@qrcommunication/gigapdf-lib 0.107.2 → 0.109.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/dist/index.cjs +11 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -8
- package/dist/index.d.ts +11 -8
- package/dist/index.js +11 -8
- package/dist/index.js.map +1 -1
- package/gigapdf.wasm +0 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @qrcommunication/gigapdf-lib — TypeScript SDK for the gigapdf-lib Rust→WASM PDF\n * engine: no third-party PDF/Office/image library (cryptography uses RustCrypto,\n * JavaScript uses Boa). Wraps the flat `extern \"C\"` `gp_*` ABI behind a typed,\n * ergonomic class. No third-party npm deps; the `.wasm` imports a single host\n * function — `env.gp_host_random` (entropy), which `load()` supplies.\n *\n * Usage:\n * const giga = await GigaPdfEngine.load(wasmBytesOrUrl);\n * const doc = giga.open(pdfBytes);\n * const docx = doc.toDocx();\n * const png = doc.renderPage(1, 2);\n * doc.close();\n */\n\n// Node-only filesystem loaders. Swapped for a throwing browser stub via the\n// package.json `\"browser\"` field, so browser bundlers never see `node:fs`/\n// `node:url`. The specifier is a plain relative path (well-supported by\n// Turbopack/webpack/Vite), unlike the previous inline `import(\"node:...\")`.\nimport { loadDefaultWasmBytes } from \"./node-fs.js\";\n\n// FFI boundary: the wasm exports are an untyped table of `gp_*` functions\n// (numbers in, numbers out) plus `memory`. `any` here is the documented FFI\n// exception — every public method below re-imposes precise types.\nexport type Exports = {\n memory: WebAssembly.Memory;\n gp_alloc(len: number): number;\n gp_free(ptr: number, len: number): void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [k: string]: any;\n};\n\n/**\n * PDF file-version banner for the compact ({@link GigaPdfDoc.saveOptimized}) and\n * linearized ({@link GigaPdfDoc.toLinearized}) writers. Object streams,\n * cross-reference streams and linearization are valid in both, so the choice only\n * changes the `%PDF-x.y` header line. Defaults to `\"1.7\"`.\n */\nexport type PdfVersion = \"1.7\" | \"2.0\";\n\n/** Map a {@link PdfVersion} to the wasm selector (`0` = 1.7, `1` = 2.0). */\nfunction pdfVersionCode(v: PdfVersion | undefined): number {\n return v === \"2.0\" ? 1 : 0;\n}\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\n/**\n * The eight PDF access permissions carried by an `/Encrypt` dictionary's `/P`\n * entry (ISO 32000-1 §7.6.3.2, Table 22). Each flag is `true` when the action\n * is **granted** to a user opening the document with the user password; the\n * owner password always lifts every restriction.\n */\nexport type PdfPermissions = {\n /** Print the document (low resolution unless {@link printHighRes} is also set). */\n print: boolean;\n /** Modify the document contents (other than annotating, filling or assembling). */\n modify: boolean;\n /** Copy or otherwise extract text and graphics. */\n copy: boolean;\n /** Add or modify annotations and fill in interactive form fields. */\n annotate: boolean;\n /** Fill in existing interactive form fields (even if {@link annotate} is clear). */\n fillForms: boolean;\n /** Extract text and graphics for accessibility tools. */\n accessibility: boolean;\n /** Assemble the document: insert, rotate and delete pages. */\n assemble: boolean;\n /** Print to a high-resolution device (requires {@link print}). */\n printHighRes: boolean;\n};\n\n/** Every permission granted — the unrestricted baseline (`/P` = -196). */\nconst ALL_PERMISSIONS: PdfPermissions = {\n print: true,\n modify: true,\n copy: true,\n annotate: true,\n fillForms: true,\n accessibility: true,\n assemble: true,\n printHighRes: true,\n};\n\n// OCR moved host-side to the `gigapdf-ocr-rten` crate (PaddleOCR PP-OCR via RTen, 12 languages +\n// auto script selection + Hebrew). The WASM SDK no longer ships a client-side recognizer; hosts\n// call the OCR service/binary directly. The legacy `.gpocr` model-loading API was removed.\n\n/**\n * One source in a {@link GigaPdfEngine.mergePdfs} call. `pdf` is the source\n * bytes; the optional `pages` selects 1-based page numbers (in the given order)\n * to bring in — omit it to append every page.\n */\nexport type MergePart = { pdf: Uint8Array; pages?: number[] };\n\n/** Loaded engine module. Create documents with {@link open} / {@link openEncrypted}. */\nexport class GigaPdfEngine {\n private constructor(private readonly ex: Exports) {}\n\n /** Lazily-built Base64 reverse-lookup table (see {@link _fromBase64}). */\n private static _b64rev?: Int16Array;\n\n /** Instantiate from raw wasm bytes, a URL/path, or a Response. */\n static async load(source: ArrayBuffer | Uint8Array | string | Response): Promise<GigaPdfEngine> {\n let bytes: ArrayBuffer | Uint8Array;\n if (typeof source === \"string\") {\n const res = await fetch(source);\n bytes = await res.arrayBuffer();\n } else if (source instanceof Response) {\n bytes = await source.arrayBuffer();\n } else {\n bytes = source;\n }\n // The wasm imports one host function: `env.gp_host_random`. wasm32 has no OS\n // RNG, so the engine (RSA signature blinding, Boa `Math.random`) draws\n // entropy from the host's Web Crypto. This keeps the module wasm-bindgen-free.\n let ex: Exports | undefined;\n const { instance } = await WebAssembly.instantiate(\n bytes instanceof Uint8Array ? bytes.slice().buffer : bytes,\n {\n env: {\n gp_host_random: (ptr: number, len: number): void => {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (!c?.getRandomValues) {\n throw new Error(\n \"gigapdf: wasm entropy needs Web Crypto (globalThis.crypto.getRandomValues)\"\n );\n }\n const mem = new Uint8Array(ex!.memory.buffer, ptr, len);\n // getRandomValues rejects views longer than 65536 bytes; fill in chunks.\n for (let off = 0; off < len; off += 65536) {\n c.getRandomValues(mem.subarray(off, Math.min(off + 65536, len)));\n }\n },\n },\n }\n );\n ex = instance.exports as Exports;\n return new GigaPdfEngine(ex);\n }\n\n /**\n * Convenience loader for Node: instantiate from the `gigapdf.wasm` shipped\n * inside this package (resolved relative to the built module). In the browser,\n * pass a URL or bytes to {@link load} instead.\n *\n * In Next.js `output: \"standalone\"`, add the asset to `outputFileTracingIncludes`\n * for the consuming route so the `.wasm` is copied into the standalone bundle.\n */\n static async loadDefault(): Promise<GigaPdfEngine> {\n // The fs access lives in `./node-fs` (Node-only; browser-stubbed via the\n // package.json `\"browser\"` map) so browser bundlers never resolve `node:*`.\n return GigaPdfEngine.load(await loadDefaultWasmBytes());\n }\n\n // ── linear-memory ABI helpers (internal) ─────────────────────────────────\n private u8() {\n return new Uint8Array(this.ex.memory.buffer);\n }\n private dv() {\n return new DataView(this.ex.memory.buffer);\n }\n /** Copy host bytes into wasm memory; returns the pointer (caller frees). */\n _toWasm(bytes: Uint8Array): number {\n // If `bytes` aliases our own wasm memory (e.g. a buffer the caller didn't\n // copy out), `gp_alloc` may grow — and detach — that buffer mid-copy.\n // Snapshot to a host array first so the `.set` source stays valid.\n const src = bytes.buffer === this.ex.memory.buffer ? new Uint8Array(bytes) : bytes;\n const ptr = this.ex.gp_alloc(src.length);\n this.u8().set(src, ptr);\n return ptr;\n }\n _free(ptr: number, len: number) {\n this.ex.gp_free(ptr, len);\n }\n /** Call a buffer-returning export `(…, outLenPtr) -> dataPtr`; copies + frees. */\n _buffer(call: (outLenPtr: number) => number): Uint8Array {\n const lenPtr = this.ex.gp_alloc(4);\n const dataPtr = call(lenPtr);\n if (dataPtr === 0) {\n this.ex.gp_free(lenPtr, 4);\n return new Uint8Array(0);\n }\n const len = this.dv().getUint32(lenPtr, true);\n const out = this.u8().slice(dataPtr, dataPtr + len);\n this.ex.gp_free(dataPtr, len);\n this.ex.gp_free(lenPtr, 4);\n return out;\n }\n _str(call: (outLenPtr: number) => number): string {\n return dec.decode(this._buffer(call));\n }\n _json<T = unknown>(call: (outLenPtr: number) => number): T {\n const s = this._str(call);\n return (s ? JSON.parse(s) : []) as T;\n }\n /**\n * Like {@link _json} but distinguishes a **null** result (the export returned a\n * null pointer — e.g. an unrecognized container) from a present-but-empty JSON\n * payload (`[]` / `{}`). Returns `null` only for the null pointer; otherwise the\n * parsed JSON. Used where the Rust side is `Option<…>` and \"nothing\" and\n * \"unrecognized\" must stay distinct.\n */\n _jsonOrNull<T = unknown>(call: (outLenPtr: number) => number): T | null {\n const lenPtr = this.ex.gp_alloc(4);\n const dataPtr = call(lenPtr);\n if (dataPtr === 0) {\n this.ex.gp_free(lenPtr, 4);\n return null;\n }\n const len = this.dv().getUint32(lenPtr, true);\n const s = dec.decode(this.u8().slice(dataPtr, dataPtr + len));\n this.ex.gp_free(dataPtr, len);\n this.ex.gp_free(lenPtr, 4);\n return (s ? JSON.parse(s) : []) as T;\n }\n /**\n * Like {@link _str} but distinguishes a **null** result (the export returned a\n * null pointer — e.g. an `Option::None`) from a present-but-empty string.\n * Returns `null` only for the null pointer; otherwise the decoded string.\n */\n _strOrNull(call: (outLenPtr: number) => number): string | null {\n const lenPtr = this.ex.gp_alloc(4);\n const dataPtr = call(lenPtr);\n if (dataPtr === 0) {\n this.ex.gp_free(lenPtr, 4);\n return null;\n }\n const len = this.dv().getUint32(lenPtr, true);\n const s = dec.decode(this.u8().slice(dataPtr, dataPtr + len));\n this.ex.gp_free(dataPtr, len);\n this.ex.gp_free(lenPtr, 4);\n return s;\n }\n /**\n * Decode standard Base64 (RFC 4648) to bytes. Pure-JS table decode, so it\n * works identically in Node and the browser with no dependency (used to turn\n * the JSON `dataBase64` of {@link GigaPdfDoc.attachments} back into bytes).\n */\n _fromBase64(s: string): Uint8Array {\n let rev = GigaPdfEngine._b64rev;\n if (!rev) {\n rev = new Int16Array(256).fill(-1);\n const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n for (let i = 0; i < alphabet.length; i++) rev[alphabet.charCodeAt(i)] = i;\n GigaPdfEngine._b64rev = rev;\n }\n let count = s.length;\n while (count > 0 && s[count - 1] === '=') count--;\n const out = new Uint8Array((count * 3) >> 2);\n let acc = 0;\n let bits = 0;\n let oi = 0;\n for (let i = 0; i < count; i++) {\n const v = rev[s.charCodeAt(i)];\n if (v === undefined || v < 0) continue; // skip stray whitespace defensively\n acc = (acc << 6) | v;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n out[oi++] = (acc >> bits) & 0xff;\n }\n }\n return oi === out.length ? out : out.subarray(0, oi);\n }\n /** Pass a string argument; runs `fn(ptr, len)` then frees. */\n _withStr<T>(s: string, fn: (ptr: number, len: number) => T): T {\n const b = enc.encode(s);\n const ptr = this._toWasm(b);\n try {\n return fn(ptr, b.length);\n } finally {\n this._free(ptr, b.length);\n }\n }\n /** Pass an optional string; an absent/empty value runs `fn(0, 0)` (no alloc). */\n _withOptStr<T>(s: string | undefined, fn: (ptr: number, len: number) => T): T {\n return s ? this._withStr(s, fn) : fn(0, 0);\n }\n /** Pass a bytes argument; runs `fn(ptr, len)` then frees. */\n _withBytes<T>(bytes: Uint8Array, fn: (ptr: number, len: number) => T): T {\n const ptr = this._toWasm(bytes);\n try {\n return fn(ptr, bytes.length);\n } finally {\n this._free(ptr, bytes.length);\n }\n }\n /** Pass a `u32[]` argument (e.g. page numbers); runs `fn(ptr, count)` then frees. */\n _withU32<T>(values: number[], fn: (ptr: number, count: number) => T): T {\n const ptr = this.ex.gp_alloc(values.length * 4);\n const dv = this.dv();\n for (const [i, v] of values.entries()) dv.setUint32(ptr + i * 4, v >>> 0, true);\n try {\n return fn(ptr, values.length);\n } finally {\n this._free(ptr, values.length * 4);\n }\n }\n /** Pass a flat `f64[]` argument (e.g. ink x,y pairs); runs `fn(ptr, count)` then frees. */\n _withF64<T>(values: number[], fn: (ptr: number, count: number) => T): T {\n const ptr = this.ex.gp_alloc(values.length * 8);\n const dv = this.dv();\n for (const [i, v] of values.entries()) dv.setFloat64(ptr + i * 8, v, true);\n try {\n return fn(ptr, values.length);\n } finally {\n this._free(ptr, values.length * 8);\n }\n }\n get raw(): Exports {\n return this.ex;\n }\n\n // ── documents ─────────────────────────────────────────────────────────────\n /** Open a PDF. Throws if it can't be parsed. */\n open(pdf: Uint8Array): GigaPdfDoc {\n const handle = this._withBytes(pdf, (p, l) => this.ex.gp_open(p, l));\n if (handle === 0) throw new Error(\"gigapdf: failed to open PDF\");\n return new GigaPdfDoc(this, handle);\n }\n /** Open an encrypted PDF with a password. Returns null if the password is wrong. */\n openEncrypted(pdf: Uint8Array, password: string): GigaPdfDoc | null {\n const b = enc.encode(password);\n const pwPtr = this._toWasm(b);\n const handle = this._withBytes(pdf, (p, l) => this.ex.gp_open_encrypted(p, l, pwPtr, b.length));\n this._free(pwPtr, b.length);\n return handle === 0 ? null : new GigaPdfDoc(this, handle);\n }\n\n /**\n * Open a **public-key (certificate) encrypted** PDF (`/Filter /Adobe.PubSec`,\n * ISO 32000-1 §7.6.5) with a recipient's DER `certificate` + PKCS#1 RSA\n * `privateKey`. `null` if this key is not a recipient. Counterpart of\n * {@link GigaPdfDoc.encryptForRecipients}.\n */\n openWithPrivateKey(\n pdf: Uint8Array,\n certificate: Uint8Array,\n privateKey: Uint8Array\n ): GigaPdfDoc | null {\n const cP = this._toWasm(certificate);\n const kP = this._toWasm(privateKey);\n const handle = this._withBytes(pdf, (p, l) =>\n this.ex.gp_open_with_private_key(p, l, cP, certificate.length, kP, privateKey.length)\n );\n this._free(cP, certificate.length);\n this._free(kP, privateKey.length);\n return handle === 0 ? null : new GigaPdfDoc(this, handle);\n }\n\n /**\n * Inspect a PDF's encryption **without decrypting it** (no password needed):\n * whether it has an `/Encrypt` dictionary, plus its `/P` permission bitmask\n * and handler version/revision (`0` when not encrypted).\n */\n encryptionInfo(pdf: Uint8Array): {\n encrypted: boolean;\n permissions: number;\n version: number;\n revision: number;\n } {\n const json = this._withBytes(pdf, (p, l) =>\n this._buffer((o) => this.ex.gp_encryption_info(p, l, o))\n );\n return JSON.parse(dec.decode(json));\n }\n\n /**\n * Decode the eight access-permission flags from a `/P` permission bitmask\n * (ISO 32000-1 Table 22) into named booleans (`true` = the action is\n * granted). Reserved bits are ignored.\n */\n decodePermissions(p: number): PdfPermissions {\n const json = dec.decode(this._buffer((o) => this.ex.gp_permissions_from_p(p, o)));\n return JSON.parse(json) as PdfPermissions;\n }\n\n /**\n * Read a PDF's access permissions **without decrypting it** (no password\n * needed). Returns the eight named flags decoded from the `/Encrypt`\n * dictionary's `/P`; an unencrypted document grants everything.\n */\n getPermissions(pdf: Uint8Array): PdfPermissions {\n const { encrypted, permissions } = this.encryptionInfo(pdf);\n return encrypted ? this.decodePermissions(permissions) : { ...ALL_PERMISSIONS };\n }\n\n /**\n * Pack eight access-permission flags into a signed 32-bit `/P` value\n * (ISO 32000-1 Table 22). Omitted flags default to **granted**, so an empty\n * object means \"all allowed\". Feed the result to {@link GigaPdfDoc.saveEncrypted}\n * via `opts.permissions`, or pass `opts.flags` directly.\n */\n permissionsToP(flags: Partial<PdfPermissions> = {}): number {\n const f = { ...ALL_PERMISSIONS, ...flags };\n return this.ex.gp_permissions_to_p(\n f.print ? 1 : 0,\n f.modify ? 1 : 0,\n f.copy ? 1 : 0,\n f.annotate ? 1 : 0,\n f.fillForms ? 1 : 0,\n f.accessibility ? 1 : 0,\n f.assemble ? 1 : 0,\n f.printHighRes ? 1 : 0\n );\n }\n\n /**\n * Width of `text` set in standard Helvetica at `size` points (AFM metrics) —\n * place watermark/header text without embedding a font.\n */\n helveticaWidth(size: number, text: string): number {\n return this._withStr(text, (p, l) => this.ex.gp_helvetica_width(p, l, size));\n }\n\n // ── stateless <format> → PDF conversions ───────────────────────────────────\n txtToPdf(text: string): Uint8Array {\n return this._withStr(text, (p, l) => this._buffer((o) => this.ex.gp_txt_to_pdf(p, l, o)));\n }\n htmlToPdf(html: string): Uint8Array {\n return this._withStr(html, (p, l) => this._buffer((o) => this.ex.gp_html_to_pdf(p, l, o)));\n }\n rtfToPdf(rtf: string): Uint8Array {\n return this._withStr(rtf, (p, l) => this._buffer((o) => this.ex.gp_rtf_to_pdf(p, l, o)));\n }\n /** Office (DOCX/ODT/PPTX/XLSX/ODS) → PDF, auto-detected. Empty array if unrecognized. */\n officeToPdf(office: Uint8Array): Uint8Array {\n return this._withBytes(office, (p, l) =>\n this._buffer((o) => this.ex.gp_office_to_pdf(p, l, o))\n );\n }\n /**\n * Phase 1 for {@link officeToPdf} — the Google/system fonts an Office container\n * **references but doesn't embed**. Download each `url` (→ TTF) and supply the\n * bytes back to the host font cache so {@link officeToPdf}'s styled runs lay out\n * with the right metrics. Faces the container embeds itself are de-obfuscated\n * and used automatically (not listed here). Returns `null` if the bytes are not\n * a recognized Office container, `[]` if it needs no host fonts.\n */\n officeNeededFonts(office: Uint8Array): HtmlFontRequest[] | null {\n return this._withBytes(office, (p, l) =>\n this._jsonOrNull<HtmlFontRequest[]>((o) => this.ex.gp_office_needed_fonts(p, l, o))\n );\n }\n /**\n * Phase 2 for {@link officeNeededFonts} — render an Office container to PDF with\n * the host-fetched `fonts` embedded, so families the container **references but\n * doesn't embed** (reported by {@link officeNeededFonts}) lay out with the right\n * metrics (e.g. Carlito for a Calibri reference) instead of drifting onto the\n * bundled fallback. Faces the container embeds itself win on conflict, so an\n * empty `fonts` array yields exactly {@link officeToPdf}'s output. Empty array\n * if the bytes are not a recognized Office container.\n *\n * @example\n * const reqs = giga.officeNeededFonts(docx); // phase 1: what to fetch\n * const fonts = await Promise.all( // host fetches each url → TTF\n * (reqs ?? []).map(async (r) => ({ ...r, ttf: await fetchTtf(r.url) }))\n * );\n * const pdf = giga.officeToPdfWith(docx, fonts); // phase 2: render with them\n */\n officeToPdfWith(office: Uint8Array, fonts: HtmlFont[] = []): Uint8Array {\n const blob = packHtmlFonts(fonts);\n return this._withBytes(office, (op, ol) =>\n this._withBytes(blob, (fp, fl) =>\n this._buffer((o) => this.ex.gp_office_to_pdf_with_fonts(op, ol, fp, fl, o))\n )\n );\n }\n /**\n * Image (PNG/JPEG/GIF/WebP/AVIF) → one-page PDF, format auto-detected: the\n * image is centred and scaled to fit on an A4 portrait page. PNG/JPEG embed\n * directly; GIF/WebP/AVIF are transcoded to PNG first — all in pure Rust/WASM,\n * no third-party image library. Empty array if the bytes are not a recognized\n * image. To combine many images into a single document, pipe each result\n * through {@link mergePdfs}.\n */\n imageToPdf(image: Uint8Array): Uint8Array {\n return this._withBytes(image, (p, l) =>\n this._buffer((o) => this.ex.gp_image_to_pdf(p, l, o))\n );\n }\n /**\n * Merge several PDFs into one by appending their pages in order. Each input is\n * either raw bytes (every page) or a {@link MergePart} `{ pdf, pages? }` that\n * selects 1-based page numbers (ISO 32000-1 §7.7.3) — so the two forms can be\n * mixed (e.g. `[whole, { pdf: b, pages: [1, 3] }]`). Returns an empty document\n * for an empty list, or — when the only input is a whole PDF (no `pages`) —\n * that input unchanged. Each subsequent part is appended onto the first via\n * {@link GigaPdfDoc.appendPages}; the merged bytes are returned and the working\n * document is closed.\n */\n mergePdfs(parts: (Uint8Array | MergePart)[]): Uint8Array {\n if (parts.length === 0) return new Uint8Array(0);\n const part = (p: Uint8Array | MergePart): MergePart =>\n p instanceof Uint8Array ? { pdf: p } : p;\n const first = part(parts[0]!);\n if (parts.length === 1 && first.pages === undefined) return first.pdf;\n // Seed the working document from the first part — reducing it to just its\n // selected pages first, so a page-range on the first source is honoured too.\n let seed = first.pdf;\n if (first.pages !== undefined) {\n const head = this.open(first.pdf);\n try {\n seed = head.extractPages(first.pages);\n } finally {\n head.close();\n }\n }\n const base = this.open(seed);\n try {\n for (let i = 1; i < parts.length; i++) {\n const p = part(parts[i]!);\n base.appendPages(p.pdf, p.pages);\n }\n return base.save();\n } finally {\n base.close();\n }\n }\n /**\n * Write a host-built grid (`pages[rows][cells]`) to an `.xlsx` workbook — one\n * sheet per page — with the engine's native spreadsheet writer (no\n * third-party library). Supply your own table reconstruction and still emit\n * Office output. `sheetNames` (index-aligned to `grids`) overrides the default\n * `Page <n>` titles; a missing/empty name falls back to the default.\n * {@link gridsToOds} is the OpenDocument (`.ods`) counterpart.\n */\n gridsToXlsx(grids: string[][][], sheetNames: string[] = []): Uint8Array {\n return this._withStr(JSON.stringify(grids), (gp, gl) =>\n this._withStr(JSON.stringify(sheetNames), (np, nl) =>\n this._buffer((o) => this.ex.gp_grids_to_xlsx(gp, gl, np, nl, o))\n )\n );\n }\n /** Write a host-built grid (`pages[rows][cells]`) to an `.ods` spreadsheet\n * (optional `sheetNames`, default `Page <n>`). */\n gridsToOds(grids: string[][][], sheetNames: string[] = []): Uint8Array {\n return this._withStr(JSON.stringify(grids), (gp, gl) =>\n this._withStr(JSON.stringify(sheetNames), (np, nl) =>\n this._buffer((o) => this.ex.gp_grids_to_ods(gp, gl, np, nl, o))\n )\n );\n }\n /**\n * Read an `.xlsx` workbook back into per-sheet `{ name, rows }` grids — the\n * inverse of {@link gridsToXlsx} / {@link GigaPdfDoc.toXlsx}. Cell text is\n * decoded from inline strings, shared strings (`sharedStrings.xml`) or plain\n * values; sheets come in workbook order. `[]` for a non-xlsx input.\n */\n xlsxToGrids(xlsx: Uint8Array): XlsxSheet[] {\n return this._withBytes(xlsx, (p, l) =>\n this._json((o) => this.ex.gp_xlsx_to_grids(p, l, o))\n );\n }\n /**\n * Encode raw **RGBA** pixels (`width*height*4` bytes, row-major,\n * non-premultiplied) to a PNG with the engine's native encoder — no\n * third-party image library. Returns an empty array if the buffer length\n * doesn't match `width*height*4`.\n */\n rgbaToPng(rgba: Uint8Array, width: number, height: number): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_rgba_to_png(width, height, p, l, o))\n );\n }\n /**\n * Resample raw **RGBA** pixels (`sw`×`sh`) to `dw`×`dh` with the engine's\n * native alpha-correct resampler (triangle kernel, footprint scaled for\n * down/up) — no third-party image library. Returns the resized RGBA\n * (`dw*dh*4`), or an empty array on a bad input.\n */\n resizeRgba(rgba: Uint8Array, sw: number, sh: number, dw: number, dh: number): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_resize_rgba(p, l, sw, sh, dw, dh, o))\n );\n }\n /**\n * Encode raw **RGBA** pixels to a baseline JPEG at `quality` (1–100) with the\n * engine's native encoder — no third-party image library. Alpha is composited\n * onto white. Empty array on a bad input.\n */\n encodeJpeg(rgba: Uint8Array, width: number, height: number, quality = 82): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_encode_jpeg(width, height, p, l, quality, o))\n );\n }\n /** Decode a baseline JPEG to `{ width, height, rgba }`, or `null` on failure. */\n decodeJpeg(jpeg: Uint8Array): DecodedImage | null {\n return this._decodeFramed(jpeg, (p, l, o) => this.ex.gp_decode_jpeg(p, l, o));\n }\n /** Decode a PNG to `{ width, height, rgba }`, or `null` on failure. */\n decodePng(png: Uint8Array): DecodedImage | null {\n return this._decodeFramed(png, (p, l, o) => this.ex.gp_decode_png(p, l, o));\n }\n /** Decode a GIF (first frame) to `{ width, height, rgba }`, or `null`. */\n decodeGif(gif: Uint8Array): DecodedImage | null {\n return this._decodeFramed(gif, (p, l, o) => this.ex.gp_decode_gif(p, l, o));\n }\n /**\n * Encode raw RGBA pixels to a **lossless** WebP (VP8L) with the engine's native\n * encoder — no third-party image library. Empty array on a bad input.\n */\n encodeWebp(rgba: Uint8Array, width: number, height: number): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_encode_webp(width, height, p, l, o))\n );\n }\n /**\n * Decode a WebP to `{ width, height, rgba }`, or `null`. Handles both\n * **lossless** (VP8L) and **lossy** (VP8 keyframe) WebP with the engine's\n * native decoder — no third-party image library. Extended/animated WebP\n * (`VP8X`) is not handled (returns `null`).\n */\n decodeWebp(webp: Uint8Array): DecodedImage | null {\n return this._decodeFramed(webp, (p, l, o) => this.ex.gp_decode_webp(p, l, o));\n }\n /**\n * Decode a still **AVIF** (AV1 intra) to `{ width, height, rgba }`, or `null`.\n * Pure-Rust AV1 decoder — no third-party library. Supports lossy + lossless\n * transforms, in-loop deblocking (AV1 §7.14) and CDEF (§7.15, including the\n * multi-strength `cdef_bits > 0` path), screen-content **palette** mode\n * (§5.11.46-50), and both `reduced_still_picture_header` and the full\n * streaming sequence/frame headers — all validated bit-exact against dav1d.\n * Not yet covered: animated AVIF, film grain, loop restoration (§7.17), the\n * fully bit-exact directional top-right/bottom-left intra edge, and the\n * lossless WHT path at very-high quality (`q ≤ 20`).\n */\n decodeAvif(avif: Uint8Array): DecodedImage | null {\n return this._decodeFramed(avif, (p, l, o) => this.ex.gp_decode_avif(p, l, o));\n }\n /** Unpack a `[w:u32 LE][h:u32 LE][rgba]` decode buffer; `null` if empty. */\n _decodeFramed(\n bytes: Uint8Array,\n fn: (p: number, l: number, o: number) => number\n ): DecodedImage | null {\n const framed = this._withBytes(bytes, (p, l) => this._buffer((o) => fn(p, l, o)));\n if (framed.length < 8) return null;\n const dv = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);\n return { width: dv.getUint32(0, true), height: dv.getUint32(4, true), rgba: framed.subarray(8) };\n }\n\n // ── fonts (catalog / Google Fonts URL — the host performs the fetch) ───────\n fontCatalog(): FontInfo[] {\n return this._json((o) => this.ex.gp_font_catalog_json(o));\n }\n /** Google Fonts CSS2 URL for a family/weight/italic (host fetches it). */\n fontRequestUrl(family: string, weight = 400, italic = false): string {\n return this._withStr(family, (p, l) =>\n this._str((o) => this.ex.gp_font_request_url(p, l, weight, italic ? 1 : 0, o))\n );\n }\n /** Extract the trusted gstatic font URL from a Google Fonts CSS2 response. */\n parseCssFontUrl(css: string): string {\n return this._withStr(css, (p, l) => this._str((o) => this.ex.gp_parse_css_font_url(p, l, o)));\n }\n\n // ── JavaScript engine (no headless browser) ────────────────────────────────\n /**\n * Evaluate a JavaScript snippet with the built-in engine and return the\n * result value as a string (or `Uncaught …` / `SyntaxError: …`).\n */\n evalJs(src: string): string {\n return this._withStr(src, (p, l) => this._str((o) => this.ex.gp_js_eval(p, l, o)));\n }\n /**\n * Run a document's inline `<script>`s and return the resulting HTML. The\n * `htmlRender`/`htmlNeededFonts` paths already do this automatically; use this\n * only when you want the post-script HTML on its own.\n */\n runInlineScripts(html: string): string {\n return this._withStr(html, (p, l) =>\n this._str((o) => this.ex.gp_run_inline_scripts(p, l, o))\n );\n }\n\n // ── HTML rendering engine (replaces a headless browser for HTML→PDF) ───────\n /**\n * Phase 1 — the Google fonts the document references. Download each `url`\n * (→ TTF) and pass the bytes back to {@link htmlRender} for an identical render.\n */\n htmlNeededFonts(html: string): HtmlFontRequest[] {\n return this._withStr(html, (p, l) =>\n this._json((o) => this.ex.gp_html_needed_fonts(p, l, o))\n ) as HtmlFontRequest[];\n }\n\n /**\n * Phase 2 — render HTML + CSS to PDF, with the supplied fonts embedded (real\n * Google fonts, real metrics → identical or nearest match). Block, inline and\n * table layout with pagination. Page size and margin are in points\n * (US-Letter portrait, 0.5in margins by default). JavaScript is not executed.\n */\n htmlRender(\n html: string,\n fonts: HtmlFont[] = [],\n pageWidth = 612,\n pageHeight = 792,\n margin = 36\n ): Uint8Array {\n const blob = packHtmlFonts(fonts);\n return this._withStr(html, (hp, hl) =>\n this._withBytes(blob, (fp, fl) =>\n this._buffer((o) => this.ex.gp_html_render(hp, hl, fp, fl, pageWidth, pageHeight, margin, o))\n )\n );\n }\n\n /**\n * Resolve a named paper size — `\"A4\"`, `\"a3-landscape\"`, `\"letter\"`, `\"legal\"`,\n * `\"tabloid\"`, `\"b5\"`, … — to `{ w, h }` in points (portrait unless the name\n * has a `-landscape` suffix). Returns `null` for an unknown name.\n */\n pageSize(name: string): { w: number; h: number } | null {\n const outPtr = this.ex.gp_alloc(16);\n try {\n const ok = this._withStr(name, (p, l) =>\n this.ex.gp_page_size(p, l, outPtr, outPtr + 8)\n );\n if (!ok) return null;\n const dv = this.dv();\n return { w: dv.getFloat64(outPtr, true), h: dv.getFloat64(outPtr + 8, true) };\n } finally {\n this._free(outPtr, 16);\n }\n }\n\n /**\n * Phase 1 variant that also scans the running `header`/`footer` HTML, so the\n * Google fonts they reference are requested alongside the body's.\n */\n htmlNeededFontsWith(html: string, header?: string, footer?: string): HtmlFontRequest[] {\n return this._withStr(html, (hp, hl) =>\n this._withOptStr(header, (hdp, hdl) =>\n this._withOptStr(footer, (ftp, ftl) =>\n this._json((o) => this.ex.gp_html_needed_fonts_ex(hp, hl, hdp, hdl, ftp, ftl, o))\n )\n )\n ) as HtmlFontRequest[];\n }\n\n /**\n * Phase 2 with full page control: named/explicit size, per-side margins, and a\n * running header/footer painted in the page margins. `{{page}}` and `{{pages}}`\n * in the header/footer are replaced with the current / total page number.\n *\n * ```ts\n * const fonts = await fetchFonts(giga.htmlNeededFontsWith(html, header, footer));\n * const pdf = giga.htmlRenderWith(html, fonts, {\n * pageSize: \"A4\",\n * margin: { top: 72, bottom: 72, left: 54, right: 54 },\n * header: `<div style=\"text-align:center\">My Report</div>`,\n * footer: `<div style=\"text-align:center\">Page {{page}} / {{pages}}</div>`,\n * });\n * ```\n */\n htmlRenderWith(\n html: string,\n fonts: HtmlFont[] = [],\n options: HtmlRenderOptions = {}\n ): Uint8Array {\n let pw = options.pageWidth ?? 612;\n let ph = options.pageHeight ?? 792;\n if (options.pageSize) {\n const sz = this.pageSize(options.pageSize);\n if (!sz) throw new Error(`gigapdf: unknown page size \"${options.pageSize}\"`);\n pw = sz.w;\n ph = sz.h;\n }\n const m = options.margin ?? 36;\n const mg =\n typeof m === \"number\"\n ? { top: m, right: m, bottom: m, left: m }\n : { top: m.top ?? 36, right: m.right ?? 36, bottom: m.bottom ?? 36, left: m.left ?? 36 };\n const headerOffset = options.headerOffset ?? 18;\n const footerOffset = options.footerOffset ?? 18;\n const start = options.startPageNumber ?? 1;\n const blob = packHtmlFonts(fonts);\n const resBlob = packHtmlResources(options.resources ?? []);\n\n return this._withStr(html, (hp, hl) =>\n this._withBytes(blob, (fp, fl) =>\n this._withOptStr(options.header, (hdp, hdl) =>\n this._withOptStr(options.footer, (ftp, ftl) =>\n this._withBytes(resBlob, (rp, rl) =>\n this._buffer((o) =>\n this.ex.gp_html_render_opts(\n hp,\n hl,\n fp,\n fl,\n pw,\n ph,\n mg.top,\n mg.right,\n mg.bottom,\n mg.left,\n hdp,\n hdl,\n ftp,\n ftl,\n headerOffset,\n footerOffset,\n start,\n rp,\n rl,\n o\n )\n )\n )\n )\n )\n )\n );\n }\n\n /**\n * Phase 1 (unified) — every external resource the document needs the host to\n * fetch, in one list: fonts (`{kind:\"font\",family,weight,italic,url}`) and\n * external images (`{kind:\"image\",url}`). Run **one** fetch loop, then pass\n * fonts back as the `fonts` argument to {@link GigaPdfEngine.htmlRenderWith}\n * (download each `url` → TTF) and images via\n * {@link HtmlRenderOptions.resources} (`{url, bytes}`). `data:` image URIs are\n * inlined and never listed.\n */\n htmlNeededResources(html: string, header?: string, footer?: string): HtmlResourceNeed[] {\n return this._withStr(html, (hp, hl) =>\n this._withOptStr(header, (hdp, hdl) =>\n this._withOptStr(footer, (ftp, ftl) =>\n this._json((o) => this.ex.gp_html_needed_resources(hp, hl, hdp, hdl, ftp, ftl, o))\n )\n )\n ) as HtmlResourceNeed[];\n }\n\n // ── unified editable model: lower / edit / raise ───────────────────────────\n //\n // The {@link GigaDocument} model is a format-neutral tree (sections → pages →\n // blocks → runs). Lower any format into it (`*ToModel`), edit it with\n // {@link applyModelOps}, then raise it back to any format (`modelTo*`). This is\n // the substrate for a universal editor that edits every format the same way.\n\n /** Decode a model-JSON buffer returned by a `gp_model_*` export; `null` on an\n * empty (error) result. */\n private _modelOrNull(call: (outLenPtr: number) => number): GigaDocument | null {\n const s = this._str(call);\n return s ? (JSON.parse(s) as GigaDocument) : null;\n }\n\n /**\n * Lower an Office document (DOCX/XLSX/PPTX/ODT/ODS/ODP, auto-detected) into the\n * unified {@link GigaDocument} model. Returns `null` if the bytes aren't a\n * recognized Office container.\n */\n officeToModel(office: Uint8Array): GigaDocument | null {\n return this._withBytes(office, (p, l) =>\n this._modelOrNull((o) => this.ex.gp_model_from_office(p, l, o))\n );\n }\n\n /** Lower an HTML string into the unified {@link GigaDocument} model. */\n htmlToModel(html: string): GigaDocument {\n return this._withStr(html, (p, l) =>\n JSON.parse(this._str((o) => this.ex.gp_model_from_html(p, l, o)))\n ) as GigaDocument;\n }\n\n /**\n * Lower a Markdown string into the unified {@link GigaDocument} model\n * (CommonMark-ish: headings, lists, GFM tables, fenced code, emphasis/links).\n */\n mdToModel(md: string): GigaDocument {\n return this._withStr(md, (p, l) =>\n JSON.parse(this._str((o) => this.ex.gp_model_from_md(p, l, o)))\n ) as GigaDocument;\n }\n\n /**\n * Lower a CSV file (UTF-8 bytes, RFC 4180, auto-detected `,`/`;`/tab/`|`\n * delimiter) into the unified {@link GigaDocument} model as a single editable\n * table. Returns `null` if the bytes contain no parseable fields.\n */\n csvToModel(csv: Uint8Array): GigaDocument | null {\n return this._withBytes(csv, (p, l) =>\n this._modelOrNull((o) => this.ex.gp_model_from_csv(p, l, o))\n );\n }\n\n /**\n * Apply a batch of {@link ModelOp} edits to a model and return the edited\n * model. Ops run in order; out-of-range addresses (and any op that can't be\n * parsed) are silently skipped, so a partially-valid batch never throws.\n */\n applyModelOps(model: GigaDocument, ops: ModelOp[]): GigaDocument {\n return this._withStr(JSON.stringify(model), (mp, ml) =>\n this._withStr(JSON.stringify(ops), (op, ol) =>\n JSON.parse(this._str((o) => this.ex.gp_model_apply_ops(mp, ml, op, ol, o)))\n )\n ) as GigaDocument;\n }\n\n /** Raise a {@link GigaDocument} model to an editable Word document (`.docx`). */\n modelToDocx(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_docx(p, l, o))\n );\n }\n /** Raise a model to an Excel workbook (`.xlsx`). */\n modelToXlsx(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_xlsx(p, l, o))\n );\n }\n /** Raise a model to a PowerPoint presentation (`.pptx`). */\n modelToPptx(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_pptx(p, l, o))\n );\n }\n /** Raise a model to an OpenDocument Text (`.odt`). */\n modelToOdt(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_odt(p, l, o))\n );\n }\n /** Raise a model to an OpenDocument Spreadsheet (`.ods`). */\n modelToOds(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_ods(p, l, o))\n );\n }\n /** Raise a model to an OpenDocument Presentation (`.odp`). */\n modelToOdp(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_odp(p, l, o))\n );\n }\n /** Raise a model back to a PDF. */\n modelToPdf(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_pdf(p, l, o))\n );\n }\n /** Raise a model to standalone HTML (decoded UTF-8 string). */\n modelToHtml(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_html(p, l, o))\n );\n }\n /** Raise a model to RTF (decoded UTF-8 string). */\n modelToRtf(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_rtf(p, l, o))\n );\n }\n /** Raise a model to Markdown (decoded UTF-8 string). */\n modelToMarkdown(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_md(p, l, o))\n );\n }\n /** Raise a model to CSV (decoded UTF-8 string). */\n modelToCsv(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_csv(p, l, o))\n );\n }\n /** Raise a model to an EPUB e-book (`.epub`). */\n modelToEpub(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_epub(p, l, o))\n );\n }\n}\n\n/**\n * Default TSA round trip for {@link GigaPdfDoc.signTimestamped}: POST the\n * RFC 3161 `TimeStampReq` to `url` as `application/timestamp-query` and return\n * the raw `TimeStampResp` (`application/timestamp-reply`) body. Works in both\n * Node and the browser via the global `fetch`.\n *\n * No SSRF allow-listing is performed here — the URL is host-supplied. Consumers\n * that need to restrict it should pass their own `tsaFetch`.\n */\nexport async function defaultTsaPost(url: string, req: Uint8Array): Promise<Uint8Array> {\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/timestamp-query\" },\n body: req as BodyInit,\n redirect: \"error\",\n });\n if (!res.ok) {\n throw new Error(`TSA HTTP ${res.status}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/** Pack `HtmlResource[]` (host-fetched URLs) into the little-endian blob\n * `gp_html_render_opts` expects: `u32 count`, then per entry `u32 url_len, url,\n * u32 data_len, data`. */\nfunction packHtmlResources(resources: HtmlResource[]): Uint8Array {\n let size = 4;\n for (const r of resources) size += 4 + enc.encode(r.url).length + 4 + r.bytes.length;\n const buf = new Uint8Array(size);\n const dv = new DataView(buf.buffer);\n let o = 0;\n dv.setUint32(o, resources.length, true);\n o += 4;\n for (const r of resources) {\n const url = enc.encode(r.url);\n dv.setUint32(o, url.length, true);\n o += 4;\n buf.set(url, o);\n o += url.length;\n dv.setUint32(o, r.bytes.length, true);\n o += 4;\n buf.set(r.bytes, o);\n o += r.bytes.length;\n }\n return buf;\n}\n\n/** Pack `HtmlFont[]` into the little-endian blob `gp_html_render` expects. */\nfunction packHtmlFonts(fonts: HtmlFont[]): Uint8Array {\n let size = 4;\n for (const f of fonts) size += 4 + enc.encode(f.family).length + 2 + 1 + 4 + f.ttf.length;\n const buf = new Uint8Array(size);\n const dv = new DataView(buf.buffer);\n let o = 0;\n dv.setUint32(o, fonts.length, true);\n o += 4;\n for (const f of fonts) {\n const fam = enc.encode(f.family);\n dv.setUint32(o, fam.length, true);\n o += 4;\n buf.set(fam, o);\n o += fam.length;\n dv.setUint16(o, f.weight, true);\n o += 2;\n buf[o] = f.italic ? 1 : 0;\n o += 1;\n dv.setUint32(o, f.ttf.length, true);\n o += 4;\n buf.set(f.ttf, o);\n o += f.ttf.length;\n }\n return buf;\n}\n\n/** A Google font the HTML engine needs (resolved from the catalogue). */\nexport interface HtmlFontRequest {\n family: string;\n weight: number;\n italic: boolean;\n /** Google Fonts CSS URL — the host fetches it to obtain the TTF. */\n url: string;\n}\n\n/** A downloaded font handed to {@link GigaPdfEngine.htmlRender}. */\nexport interface HtmlFont {\n family: string;\n weight: number;\n italic: boolean;\n ttf: Uint8Array;\n}\n\n/**\n * A host-downloaded external resource (image) handed to\n * {@link GigaPdfEngine.htmlRenderWith} via {@link HtmlRenderOptions.resources}.\n * `url` must match the URL referenced in the HTML exactly.\n */\nexport interface HtmlResource {\n url: string;\n bytes: Uint8Array;\n}\n\n/**\n * One entry from {@link GigaPdfEngine.htmlNeededResources}: a `font` (with its\n * Google-Fonts download metadata) or an external `image` URL the host must fetch.\n */\nexport type HtmlResourceNeed =\n | { kind: \"font\"; family: string; weight: number; italic: boolean; url: string }\n | { kind: \"image\"; url: string };\n\n/** Per-side page margins in points; omitted sides default to 36pt. */\nexport interface HtmlMargins {\n top?: number;\n right?: number;\n bottom?: number;\n left?: number;\n}\n\n/** Page setup for {@link GigaPdfEngine.htmlRenderWith}. */\nexport interface HtmlRenderOptions {\n /** Named paper size (`\"A4\"`, `\"a3-landscape\"`, `\"letter\"`, …) — wins over width/height. */\n pageSize?: string;\n /** Explicit page width in points (default 612 = US Letter). Ignored if `pageSize` is set. */\n pageWidth?: number;\n /** Explicit page height in points (default 792). Ignored if `pageSize` is set. */\n pageHeight?: number;\n /** Uniform margin (points) or per-side margins. Default 36pt (0.5in). */\n margin?: number | HtmlMargins;\n /** Running header HTML painted in the top margin (`{{page}}` / `{{pages}}` tokens). */\n header?: string;\n /** Running footer HTML painted in the bottom margin (same tokens). */\n footer?: string;\n /** Distance from the top edge to the header block, in points (default 18). */\n headerOffset?: number;\n /** Distance from the bottom edge to the footer block, in points (default 18). */\n footerOffset?: number;\n /** Number assigned to the first page for `{{page}}` (default 1). */\n startPageNumber?: number;\n /**\n * Host-downloaded external images, keyed by the exact URL referenced in the\n * HTML (`<img src>`). Obtain the list with\n * {@link GigaPdfEngine.htmlNeededResources}, fetch each, and pass the bytes\n * here — the engine never touches the network. `data:` URIs need no entry.\n */\n resources?: HtmlResource[];\n}\n\nexport interface FontInfo {\n family: string;\n category: string;\n google: boolean;\n weights: number[];\n}\n/** A font embedded in a document (from {@link GigaPdfDoc.embeddedFonts}). */\nexport interface EmbeddedFont {\n /** The `/BaseFont` name (may carry a `ABCDEF+` subset prefix). */\n baseFont: string;\n /**\n * Embedded program format. `truetype` (glyf) and a full OpenType `cff`\n * (`OTTO`) re-embed directly via {@link GigaPdfDoc.embedFont}; bare `cff`\n * (Type1C) and `type1` are read-only here.\n */\n format: \"truetype\" | \"cff\" | \"type1\";\n}\nexport interface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\nexport interface Element extends Partial<Box> {\n index: number;\n kind: \"text\" | \"image\" | \"shape\";\n label: string;\n}\n/**\n * A text element from {@link GigaPdfDoc.textElements}: the decoded text plus\n * everything a host editor needs to recreate the run. `index` is the text-run\n * index accepted by {@link GigaPdfDoc.replaceText}; the bounding box is page\n * user space (origin bottom-left).\n */\nexport interface TextElementInfo {\n index: number;\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n /** Resolved `/BaseFont` family (e.g. \"Helvetica\", \"Times New Roman\"). */\n fontFamily: string;\n /**\n * The raw `/BaseFont` name with the subset prefix kept (e.g.\n * `\"ABCDEF+TimesNewRomanPSMT\"`), resolved against the run's own scope — the\n * page, or the form XObject the run is drawn inside. Lets a host target the\n * exact embedded subset rather than only the collapsed {@link fontFamily}.\n * Empty when the run's font carried no `/BaseFont` (e.g. a Type3 font).\n */\n baseFont: string;\n bold: boolean;\n italic: boolean;\n /** Effective glyph size in points. */\n fontSize: number;\n /** RGB fill colour, `0..1` per channel. */\n color: [number, number, number];\n /** Baseline rotation in degrees (0 = upright). */\n rotation: number;\n /**\n * Reading direction of this run by its strong characters: `\"rtl\"` for\n * Arabic/Hebrew, `\"ltr\"` for Latin/Greek/Cyrillic/CJK, `\"neutral\"` when the\n * run is only digits/punctuation/whitespace.\n */\n direction: 'ltr' | 'rtl' | 'neutral';\n}\n/**\n * The aggregate language signal of a document from\n * {@link GigaPdfDoc.documentLanguage}: its dominant reading {@link\n * TextElementInfo.direction | direction}, writing system, and a best-effort\n * ISO-639-1 language code (`\"ar\"`, `\"he\"`, `\"zh\"`/`\"ja\"`…), `undefined` when\n * the script does not pin a single language (e.g. plain Latin).\n */\nexport interface DocumentLanguage {\n direction: 'ltr' | 'rtl' | 'neutral';\n /** Dominant script: `\"arabic\" | \"hebrew\" | \"latin\" | \"greek\" | \"cyrillic\" | \"cjk\" | \"other\"`. */\n script: string;\n /** Best-effort ISO-639-1 code, or `undefined` when undecidable. */\n lang?: string;\n}\n\n// ── unified editable model (structural mirror of crate::model::Document JSON) ──\n//\n// These interfaces are a permissive, partial mirror of the model's stable JSON\n// envelope. They give a host enough structure to read and rebuild a model (the\n// fields it edits) without re-declaring every leaf; opaque sub-objects are typed\n// loosely. The producers ({@link GigaPdfDoc.toModel}, {@link\n// GigaPdfEngine.officeToModel}, {@link GigaPdfEngine.htmlToModel}) and the\n// consumers ({@link GigaPdfEngine.modelToDocx} …) all round-trip this shape.\n\n/** A portable font fallback class (mirrors `convert::style::Generic`). */\nexport type GigaGeneric = 'sans' | 'serif' | 'mono';\n\n/** A run's character style (mirror of `model::style::CharStyle`'s JSON). */\nexport interface GigaCharStyle {\n family: string;\n generic: GigaGeneric;\n size_pt: number;\n bold: boolean;\n italic: boolean;\n underline: boolean;\n strike: boolean;\n /** RGB `0..=1`, or `null` for default black. */\n color: [number, number, number] | null;\n valign: 'baseline' | 'super' | 'sub';\n}\n\n/** An axis-aligned placement box, lower-left `(x,y)` + size, in PDF points. */\nexport interface GigaRect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** A hyperlink destination (tagged; mirror of `model::LinkTarget`). */\nexport type GigaLinkTarget =\n | { t: 'url'; v: string }\n | { t: 'page'; v: number };\n\n/**\n * An inline (within-paragraph) node, tagged by `t` (mirror of `model::Inline`).\n * `run` carries the styled text + its `source_index` back to the editable\n * content-stream operator; `br` is a hard line break; `image` an inline image;\n * `link` wraps children with a destination.\n */\nexport type GigaInline =\n | { t: 'run'; v: GigaInlineRun }\n | { t: 'br' }\n | { t: 'image'; v: GigaImageRef }\n | { t: 'link'; href: GigaLinkTarget; children: GigaInline[] };\n\n/** A styled span of text (mirror of `model::InlineRun`). */\nexport interface GigaInlineRun {\n text: string;\n style: GigaCharStyle;\n /** Index of the source content-stream run for in-place round-tripping, or `null`. */\n source_index: number | null;\n}\n\n/** Paragraph-level formatting (mirror of `model::style::ParagraphStyle`). */\nexport interface GigaParagraphStyle {\n align: 'left' | 'center' | 'right' | 'justify';\n space_before_pt: number;\n space_after_pt: number;\n indent_left_pt: number;\n indent_right_pt: number;\n /** First-line indent (positive) or hanging indent (negative), in points. */\n first_line_pt: number;\n /** Leading policy: font-natural, a size multiple, or a fixed point value. */\n line_height:\n | { t: 'normal' }\n | { t: 'multiple'; v: number }\n | { t: 'points'; v: number };\n}\n\n/** A paragraph: its own style, an optional named-style ref, and its inline runs. */\nexport interface GigaParagraph {\n style: GigaParagraphStyle;\n /** Named style this paragraph derives from, if any. */\n style_ref: string | null;\n runs: GigaInline[];\n}\n\n/** A heading (`level` 1..=6) wrapping a paragraph (mirror of `model::Heading`). */\nexport interface GigaHeading {\n level: number;\n para: GigaParagraph;\n}\n\n/** A list bullet/number style (tagged; mirror of `model::ListMarker`). */\nexport type GigaListMarker =\n | { t: 'bullet'; v: string }\n | { t: 'decimal' }\n | { t: 'lower_alpha' }\n | { t: 'upper_alpha' }\n | { t: 'lower_roman' }\n | { t: 'upper_roman' };\n\n/** One list item: nested blocks at a given `level` (mirror of `model::ListItem`). */\nexport interface GigaListItem {\n blocks: GigaBlock[];\n level: number;\n}\n\n/** An ordered or unordered list (mirror of `model::List`). */\nexport interface GigaList {\n ordered: boolean;\n marker: GigaListMarker;\n items: GigaListItem[];\n}\n\n/** A table cell: block content, span, and optional RGB shading (`model::Cell`). */\nexport interface GigaTableCell {\n blocks: GigaBlock[];\n col_span: number;\n row_span: number;\n /** RGB `0..=1` background, or `null` for no shading. */\n shading: [number, number, number] | null;\n}\n\n/** A table row: its cells and an optional fixed height in points (`model::Row`). */\nexport interface GigaTableRow {\n cells: GigaTableCell[];\n height: number | null;\n}\n\n/** A table/cell border (mirror of `model::BorderStyle`). */\nexport interface GigaBorderStyle {\n width: number;\n color: [number, number, number];\n}\n\n/** A table: rows of cells, explicit column widths, and a border (`model::Table`). */\nexport interface GigaTable {\n rows: GigaTableRow[];\n col_widths: number[];\n border: GigaBorderStyle;\n}\n\n/** A reference to an image blob in the document's resource table (`model::ImageRef`). */\nexport interface GigaImageRef {\n /** Content-hash key into `GigaDocument.resources.images`. */\n resource: number;\n alt: string | null;\n}\n\n/** A single vector path segment (tagged; mirror of `content::vector::PathSeg`). */\nexport type GigaPathSeg =\n | { t: 'm'; x: number; y: number }\n | { t: 'l'; x: number; y: number }\n | { t: 'c'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n | { t: 'z' };\n\n/** A vector shape: a path with fill/stroke styling (mirror of `model::Shape`). */\nexport interface GigaShape {\n segments: GigaPathSeg[];\n /** RGB `0..=1` fill, or `null` when unfilled. */\n fill: [number, number, number] | null;\n /** RGB `0..=1` stroke, or `null` when unstroked. */\n stroke: [number, number, number] | null;\n stroke_width: number;\n dash: number[];\n}\n\n/** A free-floating text box holding a list of blocks (mirror of `model::TextBox`). */\nexport interface GigaTextBox {\n blocks: GigaBlock[];\n}\n\n/** A typed spreadsheet cell (mirror of `model::SheetCell`). */\nexport interface GigaSheetCell {\n value: GigaCellValue;\n number_format: string | null;\n /** RGB `0..=1` cell fill, or `null` for none. */\n fill: [number, number, number] | null;\n style: GigaCharStyle;\n}\n\n/** One spreadsheet row (mirror of `model::SheetRow`). */\nexport interface GigaSheetRow {\n cells: GigaSheetCell[];\n}\n\n/** An inclusive merged-cell rectangle `(r0,c0)..=(r1,c1)`, zero-based. */\nexport interface GigaMergeRange {\n r0: number;\n c0: number;\n r1: number;\n c1: number;\n}\n\n/** A single named worksheet (mirror of `model::Sheet`). */\nexport interface GigaSheet {\n name: string;\n rows: GigaSheetRow[];\n merges: GigaMergeRange[];\n col_widths: number[];\n}\n\n/** A block of spreadsheet content: one or more sheets (mirror of `model::SheetBlock`). */\nexport interface GigaSheetBlock {\n sheets: GigaSheet[];\n}\n\n/** A slide layout placeholder role (tagged; mirror of `model::PlaceholderRole`). */\nexport type GigaPlaceholderRole =\n | { t: 'title' }\n | { t: 'subtitle' }\n | { t: 'body' }\n | { t: 'other'; v: string };\n\n/** A slide placeholder: a block tagged with its semantic role (`model::Placeholder`). */\nexport interface GigaPlaceholder {\n role: GigaPlaceholderRole;\n block: GigaBlock;\n}\n\n/** Resolved page size + margins, in points (mirror of `model::geom::PageGeometry`). */\nexport interface GigaPageGeometry {\n width: number;\n height: number;\n margins: { top: number; right: number; bottom: number; left: number };\n}\n\n/** A single slide (mirror of `model::Slide`). */\nexport interface GigaSlide {\n geometry: GigaPageGeometry;\n shapes: GigaBlock[];\n placeholders: GigaPlaceholder[];\n notes: GigaBlock[] | null;\n}\n\n/** A block of presentation content: an ordered list of slides (`model::SlideBlock`). */\nexport interface GigaSlideBlock {\n slides: GigaSlide[];\n}\n\n/**\n * A block payload, **fully typed and discriminated by `t`** (mirror of\n * `model::BlockKind`'s JSON). Narrow on `kind.t` to read the variant body in\n * `kind.v` — e.g. a `paragraph` exposes `v.runs` (each `run` carrying\n * `style.bold`/`style.italic`/`style.size_pt`/`style.color`), a `heading` its\n * `v.level`, a `table` its `v.rows[].cells[]` (with `col_span`/`row_span`), and a\n * `list` its `v.ordered` + `v.items`. This is what lets a thin editor render the\n * recognised structure (bold, headings, tables, lists) 1:1.\n */\nexport type GigaBlockKind =\n | { t: 'paragraph'; v: GigaParagraph }\n | { t: 'heading'; v: GigaHeading }\n | { t: 'list'; v: GigaList }\n | { t: 'table'; v: GigaTable }\n | { t: 'image'; v: GigaImageRef }\n | { t: 'shape'; v: GigaShape }\n | { t: 'textbox'; v: GigaTextBox }\n | { t: 'sheet'; v: GigaSheetBlock }\n | { t: 'slide'; v: GigaSlideBlock };\n\n/** Block rotation (tagged; mirror of `model::geom::Rotation`). */\nexport type GigaRotation =\n | { t: 'd0' }\n | { t: 'd90' }\n | { t: 'd180' }\n | { t: 'd270' }\n | { t: 'deg'; v: number };\n\n/** A block: a stable id, an optional placement frame + rotation, and its kind. */\nexport interface GigaBlock {\n id: number;\n frame: GigaRect | null;\n rotation: GigaRotation;\n kind: GigaBlockKind;\n}\n\n/** A page: a list of blocks; `absolute` flags slide/form (positioned) layout. */\nexport interface GigaPage {\n blocks: GigaBlock[];\n absolute: boolean;\n}\n\n/** A section: one page geometry, optional running header/footer, and its pages. */\nexport interface GigaSection {\n geometry: GigaPageGeometry;\n header: GigaBlock[] | null;\n footer: GigaBlock[] | null;\n pages: GigaPage[];\n}\n\n/**\n * A document outline (bookmark) entry — a label, a zero-based destination page,\n * and nested children (mirror of `model::OutlineNode`). Populated by\n * {@link GigaPdfEngine.officeToModel}/reconstruction from the source's own bookmarks\n * (PDF `/Outlines`) or, lacking those, from detected headings.\n */\nexport interface GigaOutlineNode {\n /** The bookmark label. */\n title: string;\n /** Zero-based destination page in the document's flattened page sequence. */\n page: number;\n /** Nested sub-bookmarks. */\n children: GigaOutlineNode[];\n}\n\n/**\n * The unified editable document model — the format-neutral tree every format\n * lowers into and is reconstructed from. `v` is the envelope version. Leaves\n * beyond what a host typically edits (`styles`, `resources`) are carried\n * opaquely so a round-trip preserves them.\n */\nexport interface GigaDocument {\n v: number;\n meta: {\n title: string | null;\n author: string | null;\n subject: string | null;\n keywords: string[];\n lang: string | null;\n };\n styles: unknown;\n sections: GigaSection[];\n /** Bookmark / chapter hierarchy (empty when the source has none). */\n outline: GigaOutlineNode[];\n resources: unknown;\n}\n\n/**\n * A positional block address `[section, page, index]` (all zero-based) — the\n * stable handle an edit op uses to target a block (mirrors `model::BlockAddr`).\n */\nexport type GigaBlockAddr = [section: number, page: number, index: number];\n\n/**\n * A character-style patch for restyle/insert ops: only the present fields are\n * applied (mirror of `model::edit::StylePatch`). `color: null` clears the colour\n * (→ default black); omitting `color` leaves it unchanged.\n */\nexport interface GigaStylePatch {\n family?: string;\n generic?: GigaGeneric;\n size_pt?: number;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strike?: boolean;\n color?: [number, number, number] | null;\n}\n\n/**\n * A paragraph-style patch for {@link ModelOp} `setParagraphStyle`: only the\n * present fields are applied (mirror of `model::edit::ParaPatch`). Keys are the\n * op's short names (`indent_left`, not `indent_left_pt`); values in PDF points.\n * Omitting a field leaves the existing value unchanged.\n */\nexport interface GigaParaPatch {\n align?: 'left' | 'center' | 'right' | 'justify';\n indent_left?: number;\n indent_right?: number;\n /** First-line indent (positive) or hanging indent (negative), in points. */\n first_line?: number;\n space_before?: number;\n space_after?: number;\n /** Leading policy: font-natural, a size multiple, or a fixed point value. */\n line_height?: { t: 'normal' } | { t: 'multiple'; v: number } | { t: 'points'; v: number };\n}\n\n/** A typed spreadsheet cell value (tagged; mirror of `model::CellValue`). */\nexport type GigaCellValue =\n | { t: 'empty' }\n | { t: 'text'; v: string }\n | { t: 'number'; v: number }\n | { t: 'bool'; v: boolean };\n\n/**\n * A single editing operation against a {@link GigaDocument} model, mirroring the\n * JSON shape of `model::edit::ModelOp`. Pass an array to\n * {@link GigaPdfEngine.applyModelOps}; ops run in order and out-of-range\n * addresses are no-ops.\n */\nexport type ModelOp =\n | { op: 'setRunText'; addr: GigaBlockAddr; run: number; text: string }\n | { op: 'restyleRun'; addr: GigaBlockAddr; run: number; style: GigaStylePatch }\n | { op: 'insertRun'; addr: GigaBlockAddr; run: number; text: string; style?: GigaStylePatch }\n | { op: 'deleteRun'; addr: GigaBlockAddr; run: number }\n | { op: 'insertBlock'; addr: GigaBlockAddr; block: GigaBlock }\n | { op: 'deleteBlock'; addr: GigaBlockAddr }\n | { op: 'moveBlock'; addr: GigaBlockAddr; to: GigaBlockAddr }\n | { op: 'setBlockText'; addr: GigaBlockAddr; text: string }\n | { op: 'restyleBlock'; addr: GigaBlockAddr; style: GigaStylePatch }\n | { op: 'setCellText'; addr: GigaBlockAddr; row: number; col: number; text: string }\n | {\n op: 'setSheetCell';\n addr: GigaBlockAddr;\n sheet: number;\n row: number;\n col: number;\n value: GigaCellValue;\n }\n // Structural table edits. These keep the column geometry (`col_widths` +\n // per-cell spans) coherent: an inserted row spans every logical column, an\n // inserted column passes through any merge it lands inside, and deletes shrink\n // or drop the cells/spans they touch. `at` is a grid index (clamped).\n | { op: 'insertTableRow'; addr: GigaBlockAddr; at: number }\n | { op: 'deleteTableRow'; addr: GigaBlockAddr; at: number }\n | { op: 'insertTableColumn'; addr: GigaBlockAddr; at: number }\n | { op: 'deleteTableColumn'; addr: GigaBlockAddr; at: number }\n | {\n op: 'setCellSpan';\n addr: GigaBlockAddr;\n /** Row index in `rows`. */\n row: number;\n /** Cell index in `rows[row].cells` (not a grid column). */\n col: number;\n /** Columns the cell spans (clamped to ≥ 1). */\n col_span: number;\n /** Rows the cell spans (clamped to ≥ 1). */\n row_span: number;\n }\n // Structural spreadsheet edits: shift cells and re-map merge ranges. `at` is a\n // row/column index (clamped); merges that collapse are dropped.\n | { op: 'insertSheetRow'; addr: GigaBlockAddr; sheet: number; at: number }\n | { op: 'deleteSheetRow'; addr: GigaBlockAddr; sheet: number; at: number }\n | { op: 'insertSheetColumn'; addr: GigaBlockAddr; sheet: number; at: number }\n | { op: 'deleteSheetColumn'; addr: GigaBlockAddr; sheet: number; at: number }\n // ── paragraph formatting ──\n | { op: 'setParagraphStyle'; addr: GigaBlockAddr; patch: GigaParaPatch }\n // ── list ──\n | { op: 'setListLevel'; addr: GigaBlockAddr; level: number }\n | { op: 'setListMarker'; addr: GigaBlockAddr; marker: GigaListMarker }\n | { op: 'setListOrdered'; addr: GigaBlockAddr; ordered: boolean }\n // ── absolute block placement ──\n | { op: 'setBlockFrame'; addr: GigaBlockAddr; rect: GigaRect }\n /** `deg` is CCW; 0/90/180/270 snap to exact rotations, else an arbitrary angle. */\n | { op: 'setBlockRotation'; addr: GigaBlockAddr; deg: number }\n // ── table shading & geometry ──\n /** `color: null` clears the cell's shading; a triple sets it. */\n | {\n op: 'setCellShading';\n addr: GigaBlockAddr;\n row: number;\n col: number;\n color: [number, number, number] | null;\n }\n | { op: 'setRowHeight'; addr: GigaBlockAddr; row: number; height: number }\n | { op: 'setColWidth'; addr: GigaBlockAddr; col: number; width: number }\n | { op: 'setTableBorder'; addr: GigaBlockAddr; border: GigaBorderStyle };\n/**\n * An image element from {@link GigaPdfDoc.imageElements}: its placement box\n * (page user space, origin bottom-left), the embeddable encoded bytes + format,\n * and the source pixel dimensions. `data` is empty when `format` is `\"unknown\"`.\n */\nexport interface ImageElementInfo {\n /**\n * The image's **unified element index** — the same value accepted by\n * {@link GigaPdfDoc.removeElement} / {@link GigaPdfDoc.transformElement} /\n * {@link GigaPdfDoc.duplicateElement} / {@link GigaPdfDoc.moveElement}. Extract\n * an image here and pass this index to edit *that exact* image. It is **not** an\n * image-local 0,1,2 counter, so it is correct on pages that also have text/paths.\n */\n index: number;\n x: number;\n y: number;\n width: number;\n height: number;\n /** `\"jpeg\"` | `\"png\"` | `\"jp2\"` | `\"unknown\"`. */\n format: string;\n pixelWidth: number;\n pixelHeight: number;\n /** Embeddable encoded image bytes (empty when `format === \"unknown\"`). */\n data: Uint8Array;\n /** Rotation in degrees from the placement CTM (`0` = upright). */\n rotation: number;\n /** Non-stroking fill alpha (`/ExtGState` `/ca`), `0..=1` (`1` = opaque). */\n opacity: number;\n}\n/**\n * One path segment from {@link GigaPdfDoc.vectorPaths} (page user space, origin\n * bottom-left). `op` is `\"M\"` (move, 2 pts), `\"L\"` (line, 2 pts), `\"C\"` (cubic\n * Bézier, 6 pts: cp1 cp2 end) or `\"Z\"` (close, 0 pts). `pts` is the flat\n * coordinate list.\n */\nexport interface PathSegment {\n op: \"M\" | \"L\" | \"C\" | \"Z\";\n pts: number[];\n}\n/**\n * A painted vector path from {@link GigaPdfDoc.vectorPaths}: its geometry\n * (segments, bounds) plus the graphics state — fill/stroke RGB (`0..=1`, `null`\n * when the paint op doesn't fill/stroke), line width, alpha and dash. Clip-only\n * paths are omitted. The native equivalent of a reader's shape/vector layer.\n */\nexport interface VectorPathInfo {\n /**\n * The path's **unified element index** — the same value accepted by\n * {@link GigaPdfDoc.setPathStyle} / {@link GigaPdfDoc.removeElement} /\n * {@link GigaPdfDoc.transformElement}. Extract a path here and pass this index\n * to restyle or remove *that exact* path. Clip-only paths are not reported, so\n * the painted path you see is the one your index targets — not a path-local ordinal.\n */\n index: number;\n /** Whether `x0..y1` describe a real box (`false` for a degenerate path). */\n hasBounds: boolean;\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n segments: PathSegment[];\n /** Fill colour `[r,g,b]` in `0..=1`, or `null` when not filled. */\n fill: [number, number, number] | null;\n /** Stroke colour `[r,g,b]` in `0..=1`, or `null` when not stroked. */\n stroke: [number, number, number] | null;\n /** Line width (`w`) in user-space units. */\n strokeWidth: number;\n /** Non-stroking alpha (`/ca`), `0..=1`. */\n fillAlpha: number;\n /** Stroking alpha (`/CA`), `0..=1`. */\n strokeAlpha: number;\n /** Dash pattern (`d` array); empty for a solid line. */\n dash: number[];\n}\nexport interface TextLine extends Box {\n text: string;\n}\nexport interface SearchHit extends Box {\n page: number;\n text: string;\n}\nexport interface TextRunInfo {\n index: number;\n operator: string;\n text: string;\n}\n/** Signature-dictionary metadata for {@link GigaPdfDoc.signP12}. */\nexport interface SignP12Options {\n /** `/Name` — human-readable signer name. */\n name?: string;\n /** `/Reason` — why the document is being signed. */\n reason?: string;\n /** `/M` — signing time as a PDF date string, e.g. `D:20260616120000Z`. */\n date?: string;\n /** `/Location` — physical or logical signing location. */\n location?: string;\n /** `/ContactInfo` — how to reach the signer. */\n contactInfo?: string;\n}\n/**\n * Options for {@link GigaPdfDoc.signTimestamped} — a PAdES-B-T signature with an\n * RFC 3161 trusted timestamp embedded in the SignerInfo (`ETSI.CAdES.detached`\n * subfilter, `signing-certificate-v2` signed attribute, `id-aa-timeStampToken`\n * unsigned attribute).\n *\n * The signing identity is either an imported PKCS#12 (`p12` + `password`) or, if\n * `p12` is omitted, a freshly generated self-signed digital ID (`random` +\n * `notBefore`/`notAfter`).\n */\nexport interface SignTsaOptions extends SignP12Options {\n /** TSA endpoint URL, e.g. `\"https://freetsa.org/tsr\"`. */\n tsaUrl: string;\n /**\n * Optional override for the TSA round trip — lets the host add auth headers,\n * proxies, retries, **and apply its own SSRF allow-list** (the engine only\n * emits the request; the URL is host-supplied). Receives the `TimeStampReq`\n * DER and the URL, must resolve to the raw `TimeStampResp` bytes. When omitted,\n * {@link defaultTsaPost} POSTs `application/timestamp-query` via `fetch`.\n */\n tsaFetch?: (req: Uint8Array, url: string) => Promise<Uint8Array>;\n /** PKCS#12 identity bytes. Omit to sign with a generated self-signed ID. */\n p12?: Uint8Array;\n /** PKCS#12 passphrase. */\n password?: string;\n /** Self-signed path: ≥ 256 bytes from `crypto.getRandomValues`. */\n random?: Uint8Array;\n /** Self-signed path: RSA modulus size in bits (default 2048). */\n keyBits?: number;\n /** Self-signed path: certificate `notBefore`, UTCTime `YYMMDDHHMMSSZ`. */\n notBefore?: string;\n /** Self-signed path: certificate `notAfter`, UTCTime `YYMMDDHHMMSSZ`. */\n notAfter?: string;\n /** Optional 8–16 random bytes echoed by the TSA (request/response correlation). */\n nonce?: Uint8Array;\n}\n\n/**\n * Options for {@link GigaPdfDoc.signLtv} — a PAdES long-term validation\n * signature: a B-T signature, then a `/DSS` (Document Security Store) carrying\n * the certificate chain + OCSP/CRL revocation material the host fetched (B-LT),\n * optionally finished with a document timestamp over the whole file (B-LTA).\n *\n * Extends {@link SignTsaOptions}: the B-T signature is produced exactly as\n * {@link GigaPdfDoc.signTimestamped}, then the LTV material is added. The OCSP/CRL\n * URLs come from the **certificates**, so the host fetches them — supply\n * `revocationFetch`/`crlFetch` to add auth, proxies, or an SSRF allow-list (the\n * engine only computes which URLs to fetch).\n */\nexport interface SignLtvOptions extends SignTsaOptions {\n /**\n * Add a B-LTA **document timestamp** over the whole file (DSS included) after\n * the DSS. Requires a second TSA round trip. Default `false` (B-LT only).\n */\n archiveTimestamp?: boolean;\n /**\n * Override the OCSP round trip — receives the DER `OCSPRequest` and the\n * responder URL, must resolve to the raw `OCSPResponse` bytes. When omitted,\n * {@link defaultOcspPost} POSTs `application/ocsp-request` via `fetch`. Throw to\n * skip an unreachable responder (the DSS is built from whatever succeeds).\n */\n revocationFetch?: (req: Uint8Array, url: string) => Promise<Uint8Array>;\n /**\n * Override the CRL fetch — receives the CRL distribution-point URL, must\n * resolve to the raw `CertificateList` (CRL) bytes. When omitted,\n * {@link defaultCrlGet} GETs the URL. Throw to skip an unreachable CRL.\n */\n crlFetch?: (url: string) => Promise<Uint8Array>;\n}\n\n/**\n * Default OCSP round trip for {@link GigaPdfDoc.signLtv}: POST the DER\n * `OCSPRequest` to `url` as `application/ocsp-request` and return the raw\n * `OCSPResponse` body. No SSRF allow-listing — the URL comes from the\n * certificate's AIA extension; pass `revocationFetch` to restrict it.\n */\nexport async function defaultOcspPost(req: Uint8Array, url: string): Promise<Uint8Array> {\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/ocsp-request\" },\n body: req as BodyInit,\n redirect: \"error\",\n });\n if (!res.ok) {\n throw new Error(`OCSP HTTP ${res.status}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/**\n * Default CRL fetch for {@link GigaPdfDoc.signLtv}: GET the `CertificateList`\n * (CRL) from `url`. No SSRF allow-listing — the URL comes from the certificate's\n * CRL-DP extension; pass `crlFetch` to restrict it.\n */\nexport async function defaultCrlGet(url: string): Promise<Uint8Array> {\n const res = await fetch(url, { method: \"GET\", redirect: \"error\" });\n if (!res.ok) {\n throw new Error(`CRL HTTP ${res.status}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/** Decode a lowercase/uppercase hex string into bytes (LTV targets carry binary\n * fields — certificate DER, OCSP requests — as hex inside JSON). */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length >> 1);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return out;\n}\n\n/** Length-frame a list of byte blobs as `[u32 LE count]([u32 LE len][bytes])*`\n * — the binary multi-blob form `gp_apply_dss` reads for certs/OCSPs/CRLs. */\nfunction frameBlobs(blobs: Uint8Array[]): Uint8Array {\n let total = 4;\n for (const b of blobs) total += 4 + b.length;\n const out = new Uint8Array(total);\n const view = new DataView(out.buffer);\n view.setUint32(0, blobs.length, true);\n let pos = 4;\n for (const b of blobs) {\n view.setUint32(pos, b.length, true);\n pos += 4;\n out.set(b, pos);\n pos += b.length;\n }\n return out;\n}\n\n/** One certificate's LTV fetch plan, decoded from the `gp_ltv_targets` JSON. */\ninterface LtvTarget {\n certHex: string;\n sources: Array<\n | { kind: \"ocsp\"; url: string; requestHex: string }\n | { kind: \"crl\"; url: string }\n >;\n}\n/**\n * A markup annotation (rect corners in PDF user space, origin bottom-left).\n * Carries the common metadata plus the type-specific geometry a host editor\n * needs: text-markup `quadPoints`, freehand `inkList`, `stamp` name, and the\n * link target (`linkUri` / `linkPage`).\n */\nexport interface AnnotationInfo {\n index: number;\n subtype: string;\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n contents: string;\n /** `/T` — author / title. Empty when absent. */\n author: string;\n /** `/Subj` — subject. Empty when absent. */\n subject: string;\n /** `/CreationDate` — raw PDF date (`D:YYYYMMDD…`). Empty when absent. */\n created: string;\n /** `/M` — raw PDF modification date. Empty when absent. */\n modified: string;\n /** `/Name` — stamp name (e.g. `\"Approved\"`). Empty when absent. */\n name: string;\n /** `/CA` non-stroking opacity, `0..=1` (`1` = opaque). */\n opacity: number;\n /** `/C` normalised to RGB `0..=1` (`[]` when no colour). */\n color: number[];\n /** `/QuadPoints` (8 values per quad) for text-markup annotations. */\n quadPoints: number[];\n /** `/InkList` — one inner array per freehand stroke (`x y x y …`). */\n inkList: number[][];\n /** Link external URI (`/A /URI`). Empty when internal/absent. */\n linkUri: string;\n /** Link internal destination page (1-based); `0` when external/absent. */\n linkPage: number;\n}\n/** A hyperlink annotation; `kind` discriminates the target. */\nexport interface LinkInfo {\n index: number;\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n kind: \"uri\" | \"page\" | \"unknown\";\n uri?: string;\n page?: number;\n}\nexport type FieldKind =\n | \"text\"\n | \"checkbox\"\n | \"radio\"\n | \"pushbutton\"\n | \"combo\"\n | \"list\"\n | \"signature\"\n | \"unknown\";\n/** An AcroForm field with its flags and (for choices) options. */\n/** One signature on the document (a `/Sig` field's `/V`), from {@link GigaPdfDoc.signatures}. */\nexport interface SignatureInfo {\n /** The signature field's `/T` name. */\n fieldName: string;\n /** The signer name (`/Name`), or `null`. */\n signerName: string | null;\n /** The stated reason (`/Reason`), or `null`. */\n reason: string | null;\n /** The stated location (`/Location`), or `null`. */\n location: string | null;\n /** The signing date string (`/M`, e.g. `D:20260624…`), or `null`. */\n date: string | null;\n /** The `/SubFilter` (e.g. `adbe.pkcs7.detached`), or `null`. */\n subFilter: string | null;\n /** The `/ByteRange` `[a, b, c, d]` the signature covers. */\n byteRange: [number, number, number, number];\n}\n\n/** The cryptographic verdict for one signature, from {@link GigaPdfDoc.verifySignatures}. */\nexport interface SignatureReport {\n /** The signature field's `/T` name. */\n fieldName: string;\n /** The `/ByteRange` is well-formed and within the file bounds. */\n byteRangeOk: boolean;\n /** The CMS `messageDigest` equals SHA-256 of the covered bytes (integrity). */\n digestOk: boolean;\n /** The SignerInfo signature validates under the signer certificate's key. */\n signatureOk: boolean;\n /** The signature covers the **whole** current file (nothing appended after it). */\n coversWholeDocument: boolean;\n /** The signer certificate's Common Name, or `null`. */\n signerCommonName: string | null;\n /** Number of certificates embedded in the CMS. */\n certCount: number;\n /** The recognised signature algorithm (`RSA+SHA-256`) or an unsupported note. */\n algorithm: string;\n}\n\nexport interface FieldInfo {\n name: string;\n type: string;\n kind: FieldKind;\n flags: number;\n readOnly: boolean;\n required: boolean;\n multiline: boolean;\n fillable: boolean;\n /**\n * Whether this is a **comb** text field (`/Ff` bit 25): the value is laid out\n * one character per equally-spaced cell across {@link maxLen} cells (SSN, dates\n * and reference numbers on official forms). A host reproducing the field's\n * original spacing must honour this — the cells can't be inferred from the\n * value alone.\n */\n comb: boolean;\n /** Text alignment from `/Q` (AcroForm default applied): 0 = left, 1 = centre, 2 = right. */\n quadding: number;\n /**\n * Font resource name from the field's `/DA` default appearance (e.g. `\"Helv\"`,\n * `\"ZaDb\"`), resolved against the AcroForm; absent when no `Tf` is present.\n */\n daFont?: string;\n /** Font size in points from the `/DA` (`0` = auto-size), AcroForm default applied. */\n daSize: number;\n /**\n * `/MaxLen` for text fields; for a comb field this is the number of\n * equally-spaced cells the value is drawn into.\n */\n maxLen?: number;\n /** 1-based page the widget sits on (from its `/P`); absent if it has no widget. */\n page?: number;\n /**\n * Widget rectangle `[x, y, width, height]` in points, **top-left origin**\n * (already Y-flipped from the PDF's bottom-left `/Rect` for direct host use).\n * Absent when the field carries no `/Rect`.\n */\n bounds?: [number, number, number, number];\n value: string;\n options: string[];\n}\n/**\n * A view destination (ISO 32000-1 §12.3.2). `page` is 1-based; optional\n * coordinates are in the target page's user space (omit to leave unchanged).\n */\nexport type Destination =\n | { fit: \"xyz\"; page: number; left?: number; top?: number; zoom?: number }\n | { fit: \"fit\"; page: number }\n | { fit: \"fitH\"; page: number; top?: number }\n | { fit: \"fitV\"; page: number; left?: number }\n | { fit: \"fitR\"; page: number; rect: [number, number, number, number] }\n | { fit: \"fitB\"; page: number }\n | { fit: \"fitBH\"; page: number; top?: number }\n | { fit: \"fitBV\"; page: number; left?: number }\n | { fit: \"named\"; name: string };\n\n/**\n * A PDF action (ISO 32000-1 §12.6) usable on a link, the document open-action,\n * or an outline bookmark — passed to {@link GigaPdfDoc.addLink} /\n * {@link GigaPdfDoc.setOpenAction} / {@link GigaPdfDoc.setBookmarks}.\n */\nexport type Action =\n | { type: \"goto\"; dest: Destination }\n | { type: \"gotoR\"; file: string; dest: Destination }\n | { type: \"uri\"; uri: string }\n | { type: \"named\"; action: \"nextPage\" | \"prevPage\" | \"firstPage\" | \"lastPage\" }\n | { type: \"launch\"; file: string }\n | { type: \"javascript\"; js: string }\n | { type: \"submitForm\"; url: string }\n | { type: \"resetForm\" };\n\n/** One outline bookmark for {@link GigaPdfDoc.setBookmarks}. */\nexport interface Bookmark {\n /** The bookmark label. */\n title: string;\n /** Nesting depth (0 = top); deeper consecutive items become children. */\n level: number;\n /** What clicking the bookmark does (a `goto` becomes `/Dest`, else `/A`). */\n action?: Action;\n}\n\n/** One outline (bookmark) entry; `level` is the nesting depth (0 = top). */\nexport interface OutlineEntry {\n level: number;\n title: string;\n page?: number;\n /** `/F` flag bit 2 — label drawn bold (present when read via {@link GigaPdfDoc.outline}). */\n bold?: boolean;\n /** `/F` flag bit 1 — label drawn italic. */\n italic?: boolean;\n /** `/C` RGB label colour, `0..1` per channel (black when absent in the PDF). */\n color?: [number, number, number];\n /** Destination fit type, lowercased (`\"xyz\"`/`\"fit\"`/`\"fith\"`/`\"fitv\"`/…). */\n destKind?: string;\n /** `/XYZ` top-left X (when `destKind === \"xyz\"`). */\n x?: number;\n /** `/XYZ` top-left Y. */\n y?: number;\n /** `/XYZ` magnification. */\n zoom?: number;\n}\n/**\n * How a reader arranges pages on screen — the catalog `/PageLayout` name\n * (ISO 32000-1 §7.7.2). Passed to {@link GigaPdfDoc.setPageLayout}.\n */\nexport type PageLayout =\n | 'SinglePage'\n | 'OneColumn'\n | 'TwoColumnLeft'\n | 'TwoColumnRight'\n | 'TwoPageLeft'\n | 'TwoPageRight';\n\n/**\n * Which panel (if any) a reader shows on open — the catalog `/PageMode` name\n * (ISO 32000-1 §7.7.2). Passed to {@link GigaPdfDoc.setPageMode}.\n */\nexport type PageMode =\n | 'UseNone'\n | 'UseOutlines'\n | 'UseThumbs'\n | 'FullScreen'\n | 'UseOC'\n | 'UseAttachments';\n\n/**\n * Authoring options for the catalog `/ViewerPreferences` dictionary\n * (ISO 32000-1 §12.2) — UX hints a reader honours when it opens the document.\n *\n * Every field is optional: an omitted (or `undefined`) field leaves whatever\n * the document already had untouched; a boolean sets the corresponding key.\n * Passed to {@link GigaPdfDoc.setViewerPreferences}.\n */\nexport interface ViewerPreferences {\n /** `/HideToolbar` — hide the reader's tool bars. */\n hideToolbar?: boolean;\n /** `/HideMenubar` — hide the reader's menu bar. */\n hideMenubar?: boolean;\n /** `/HideWindowUI` — hide scroll bars / navigation controls, page only. */\n hideWindowUI?: boolean;\n /** `/FitWindow` — resize the window to fit the first page. */\n fitWindow?: boolean;\n /** `/CenterWindow` — centre the document window on screen. */\n centerWindow?: boolean;\n /** `/DisplayDocTitle` — show the doc title (not the file name) in the title bar. */\n displayDocTitle?: boolean;\n /** `/Direction` — predominant reading order: `\"L2R\"` or `\"R2L\"`. */\n direction?: 'L2R' | 'R2L';\n}\n\n/** A named destination from {@link GigaPdfDoc.namedDests}: a name → page anchor. */\nexport interface NamedDest {\n name: string;\n page: number;\n}\n/**\n * One document-level JavaScript read back by {@link GigaPdfDoc.documentJavascripts}:\n * the `/Names /JavaScript` name-tree key and the script source.\n */\nexport interface DocumentJavascript {\n /** The name-tree key the script is registered under. */\n name: string;\n /** The JavaScript source. */\n script: string;\n}\n/**\n * One embedded file attachment read back by {@link GigaPdfDoc.attachments}.\n * `data` is the decoded file bytes; `mime`/`description`/dates are `null` when\n * the PDF didn't record them.\n */\nexport interface Attachment {\n /** The `/EmbeddedFiles` name-tree key the file was registered under. */\n name: string;\n /** The filespec display filename (`/UF` preferred, else `/F`). */\n filename: string;\n /** The embedded stream's `/Subtype` MIME (e.g. `application/pdf`), or null. */\n mime: string | null;\n /** The filespec `/Desc` human description, or null. */\n description: string | null;\n /** The `/Params /CreationDate` PDF date string, or null. */\n creationDate: string | null;\n /** The `/Params /ModDate` PDF date string, or null. */\n modDate: string | null;\n /** The decoded (filters applied) file bytes. */\n data: Uint8Array;\n}\n\n/**\n * The relationship an **associated file** (`/AF`) bears to the document (ISO\n * 32000-2 / PDF/A-3). Hybrid e-invoices (Factur-X, ZUGFeRD, Order-X) embed their\n * XML payload as `\"alternative\"`.\n */\nexport type AfRelationship = \"source\" | \"data\" | \"alternative\" | \"supplement\" | \"unspecified\";\n\n/** Maps an {@link AfRelationship} to the discriminant the engine expects. */\nconst AF_RELATIONSHIP_CODE: Record<AfRelationship, number> = {\n source: 0,\n data: 1,\n alternative: 2,\n supplement: 3,\n unspecified: 4,\n};\n\n/** Options for embedding a file attachment (see {@link GigaPdfDoc.addAttachment}). */\nexport interface AttachmentOptions {\n /** The embedded stream `/Subtype` MIME type (e.g. `\"application/pdf\"`). */\n mime?: string;\n /** A human-readable description (`/Desc`). */\n description?: string;\n}\n\n/** The visual marker of a {@link GigaPdfDoc.addFileAttachmentAnnot} annotation. */\nexport type FileAttachmentIcon = \"PushPin\" | \"Paperclip\" | \"Graph\" | \"Tag\";\n\n/**\n * The initial navigator a PDF **portfolio** shows for its embedded files\n * (`/Collection /View`, ISO 32000-1 §7.11.6): `\"details\"` (a multi-column list),\n * `\"tile\"` (a grid of file tiles), or `\"hidden\"` (the navigator starts\n * collapsed). See {@link GigaPdfDoc.setCollection}.\n */\nexport type CollectionView = \"details\" | \"tile\" | \"hidden\";\n\n/**\n * The data type of a portfolio schema column (`/CollectionField /Subtype`). The\n * first three are **user-defined** values supplied per file via\n * {@link CollectionItem.values}; the rest are **synthetic** columns the viewer\n * derives from each file (its name, description, size, dates) and need no value.\n */\nexport type CollectionFieldSubtype =\n | \"text\"\n | \"date\"\n | \"number\"\n | \"filename\"\n | \"description\"\n | \"size\"\n | \"creationDate\"\n | \"modDate\";\n\n/** One column of a portfolio schema (a `/CollectionField`). */\nexport interface CollectionField {\n /** The schema key; per-file {@link CollectionItem.values} reference it. */\n key: string;\n /** The displayed column header (`/N`). Defaults to `key` when omitted. */\n name?: string;\n /** The column data type (`/Subtype`). Defaults to `\"text\"`. */\n subtype?: CollectionFieldSubtype;\n /** The relative ordering (`/O`); columns are shown in ascending order. */\n order?: number;\n /** `/V` — whether the column is initially visible (default `true`). */\n visible?: boolean;\n}\n\n/**\n * Per-file portfolio metadata — the `/CI` (collection item) values for one\n * embedded file, keyed by schema field {@link CollectionField.key}. Values are\n * strings (numeric columns parse the string as a number; date columns expect a\n * PDF date string `\"D:YYYYMMDD…\"`). Only user-defined columns\n * (`text`/`date`/`number`) carry a value.\n */\nexport interface CollectionItem {\n /** The embedded-file name (a key from {@link GigaPdfDoc.attachments}). */\n file: string;\n /** Schema-field `key` → value. */\n values: Record<string, string | number>;\n}\n\n/**\n * Configuration for a PDF **portfolio** / embedded-file collection — what\n * {@link GigaPdfDoc.setCollection} writes into the catalog `/Collection`\n * (ISO 32000-1 §7.11.6, §12.3.5). Marks the document as a portfolio and\n * configures its presentation.\n */\nexport interface CollectionConfig {\n /** `/View` — the initial navigator. Defaults to `\"details\"`. */\n view?: CollectionView;\n /** `/Schema` — the columns, in declaration order. May be empty/omitted. */\n schema?: CollectionField[];\n /** `/Sort` — the column to sort on and direction. Omit/`null` to leave unset. */\n sort?: { field: string; ascending?: boolean } | null;\n /** `/D` — the embedded-file name initially selected. Omit/`null` to leave unset. */\n defaultFile?: string | null;\n /** Per-file `/CI` metadata populating the schema columns. */\n items?: CollectionItem[];\n}\n\n/**\n * The standard document-information fields (ISO 32000-1 §14.3.3), shared by the\n * `/Info` dictionary and the XMP `/Metadata` packet. Passed to\n * {@link GigaPdfDoc.setInfo}, which writes both and keeps them in sync. Every\n * field is optional; on `setInfo` an omitted field is left unchanged (a partial\n * update). Dates are PDF date strings (`\"D:YYYYMMDDHHmmSS+HH'mm'\"`).\n */\nexport interface InfoFields {\n /** `/Title` → `dc:title`. */\n title?: string;\n /** `/Author` → `dc:creator`. */\n author?: string;\n /** `/Subject` → `dc:description`. */\n subject?: string;\n /** `/Keywords` → `pdf:Keywords`. */\n keywords?: string;\n /** `/Creator` (authoring app) → `xmp:CreatorTool`. */\n creator?: string;\n /** `/Producer` (PDF producer) → `pdf:Producer`. */\n producer?: string;\n /** `/CreationDate` (PDF date string) → `xmp:CreateDate`. */\n creationDate?: string;\n /** `/ModDate` (PDF date string) → `xmp:ModifyDate`. */\n modDate?: string;\n}\n\n/** One sheet read back from an `.xlsx` by {@link GigaPdfEngine.xlsxToGrids}. */\nexport interface XlsxSheet {\n name: string;\n rows: string[][];\n}\n/** A decoded raster image (`rgba` is `width*height*4`, row-major, RGBA8). */\nexport interface DecodedImage {\n width: number;\n height: number;\n rgba: Uint8Array;\n}\n/** An optional-content layer (calque): toggle `visible`/`locked` to persist in the PDF. */\nexport interface LayerInfo {\n id: number;\n name: string;\n visible: boolean;\n locked: boolean;\n order: number;\n}\n/** A page's geometry: size in points and `/Rotate` (0/90/180/270). */\nexport interface PageInfo {\n width: number;\n height: number;\n rotation: number;\n /** Raw `/MediaBox` `[x0, y0, x1, y1]` in user-space points (preserves origin). */\n mediaBox: [number, number, number, number];\n}\n\n/** Per-side page margins, in points. */\nexport interface PageMargins {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\n/**\n * The five page boundary boxes (ISO 32000-1 §14.11.2), in display/source order.\n * Used as the `kind` selector for {@link GigaPdfDoc.setPageBox} and as the keys of\n * {@link PageBoxes.declared}.\n */\nexport const PAGE_BOX_KINDS = [\"media\", \"crop\", \"bleed\", \"trim\", \"art\"] as const;\n\n/** One of the five page boundary boxes — see {@link PAGE_BOX_KINDS}. */\nexport type PageBoxKind = (typeof PAGE_BOX_KINDS)[number];\n\n/**\n * A page's five boundary boxes (see {@link GigaPdfDoc.getPageBoxes}). Each box is\n * the **effective** rectangle `[x0, y0, x1, y1]` in user-space points, with ISO\n * 32000-1 inheritance and the per-box default chain already applied — so `crop`\n * equals `media` when no `/CropBox` is declared, and `bleed`/`trim`/`art` each\n * fall back to `crop`. Values are reported verbatim (not clamped to their\n * intersection with the media box), so the source file round-trips faithfully.\n */\nexport interface PageBoxes {\n /** `/MediaBox` (inherited if absent; defaults to US Letter `[0, 0, 612, 792]`). */\n media: [number, number, number, number];\n /** `/CropBox` (inherited if absent; defaults to the media box). */\n crop: [number, number, number, number];\n /** `/BleedBox` (defaults to the crop box). */\n bleed: [number, number, number, number];\n /** `/TrimBox` (defaults to the crop box). */\n trim: [number, number, number, number];\n /** `/ArtBox` (defaults to the crop box). */\n art: [number, number, number, number];\n /**\n * Which boxes are **explicitly declared** on the page dictionary (vs inherited\n * from an ancestor `/Pages` node or defaulted by the rules above) — lets a host\n * tell a real `/TrimBox` from one defaulted to the crop box.\n */\n declared: Record<PageBoxKind, boolean>;\n}\n\n/**\n * The numbering style of a page-label range (ISO 32000-1 §12.4.2):\n * `decimal` (1,2,3…), `romanLower` (i,ii,iii…), `romanUpper` (I,II,III…),\n * `alphaLower` (a…z,aa…), `alphaUpper` (A…Z,AA…), or `none` (the prefix alone,\n * with no numeric portion).\n */\nexport type PageLabelStyle =\n | \"decimal\"\n | \"romanLower\"\n | \"romanUpper\"\n | \"alphaLower\"\n | \"alphaUpper\"\n | \"none\";\n\n/** Maps a {@link PageLabelStyle} to the single-letter token the engine expects. */\nconst PAGE_LABEL_STYLE_TOKEN: Record<PageLabelStyle, string> = {\n decimal: \"D\",\n romanLower: \"r\",\n romanUpper: \"R\",\n alphaLower: \"a\",\n alphaUpper: \"A\",\n none: \"-\",\n};\n\n/**\n * One page-label range (ISO 32000-1 §12.4.2). From {@link startPage} onward (until\n * the next range, or the end of the document), pages are labelled {@link prefix}\n * followed by the {@link style}-formatted number counting up from\n * {@link startNumber}.\n */\nexport interface PageLabelRange {\n /** 1-based page number where this labelling range begins. */\n startPage: number;\n /** The numbering style of the numeric portion. */\n style: PageLabelStyle;\n /** A label prefix prepended to every page in the range (may be empty). */\n prefix: string;\n /** The value the range's first page is numbered with (≥ 1; default 1). */\n startNumber: number;\n}\n\n/**\n * The visual style of a page transition (ISO 32000-1 §12.4.4, the `/S` entry).\n * Index order matches the engine's enum and selects which optional fields of\n * {@link PageTransition} apply.\n */\nexport const PAGE_TRANSITION_STYLES = [\n \"split\",\n \"blinds\",\n \"box\",\n \"wipe\",\n \"dissolve\",\n \"glitter\",\n \"fly\",\n \"push\",\n \"cover\",\n \"uncover\",\n \"fade\",\n \"replace\",\n] as const;\n\n/** A page transition style — see {@link PAGE_TRANSITION_STYLES}. */\nexport type PageTransitionStyle = (typeof PAGE_TRANSITION_STYLES)[number];\n\n/** Orientation of a `split`/`blinds` transition (the `/Dm` entry). */\nexport type PageTransitionDimension = \"horizontal\" | \"vertical\";\n\n/** Motion direction of a `split`/`box` transition (the `/M` entry). */\nexport type PageTransitionMotion = \"inward\" | \"outward\";\n\n/**\n * The sweep direction of a directional transition (the `/Di` entry). A number\n * of degrees — only the discrete angles `0`, `90`, `180`, `270`, `315` are\n * valid — or `\"none\"` (the `/Di /None` name, used by `fly` to mean \"fly toward\n * the viewer\").\n */\nexport type PageTransitionDirection = 0 | 90 | 180 | 270 | 315 | \"none\";\n\n/**\n * A presentation transition + auto-advance for a page (ISO 32000-1 §12.4.4),\n * passed to {@link GigaPdfDoc.setPageTransition}. {@link style} picks the\n * effect; the remaining fields are optional and only the ones that apply to the\n * chosen style are written (`dimension`/`motion` for `split`, `direction`/\n * `scale`/`flyAreaOpaque` for `fly`, …). {@link displayDuration} is the page's\n * `/Dur` auto-advance time and is independent of the transition itself.\n */\nexport interface PageTransition {\n /** The transition style (`/S`). */\n style: PageTransitionStyle;\n /** `/D` — the transition effect duration in **seconds** (viewer default: 1). */\n duration?: number;\n /** `/Dm` — orientation; `split`/`blinds` only. */\n dimension?: PageTransitionDimension;\n /** `/M` — motion direction; `split`/`box` only. */\n motion?: PageTransitionMotion;\n /** `/Di` — sweep direction; `wipe`/`glitter`/`fly`/`cover`/`uncover`/`push`. */\n direction?: PageTransitionDirection;\n /** `/SS` — starting/ending scale for `fly` (PDF 1.5; default 1.0). */\n scale?: number;\n /** `/B` — whether the `fly` area is rectangular + opaque (PDF 1.5; default false). */\n flyAreaOpaque?: boolean;\n /** `/Dur` — the page's display time in **seconds** before auto-advancing. */\n displayDuration?: number;\n}\n\n/** Horizontal alignment of header/footer text within the printable width. */\nexport type HeaderFooterAlign = \"left\" | \"center\" | \"right\";\n\n/**\n * A running header/footer to bake onto an existing PDF (see {@link GigaPdfDoc.setHeader} /\n * {@link GigaPdfDoc.setFooter}). `text` may contain the tokens `{{page}}` (1-based page\n * number) and `{{pages}}` (total page count), substituted per page. Text is drawn in\n * standard Helvetica inside the top (header) / bottom (footer) margin band.\n */\nexport interface HeaderFooterSpec {\n /** Template text, with `{{page}}` / `{{pages}}` tokens. */\n text: string;\n /** Horizontal alignment (default `\"left\"`). */\n align?: HeaderFooterAlign;\n /** Font size in points (default `10`). */\n fontSize?: number;\n /** RGB fill colour, `0..1` per channel (default black `[0,0,0]`). */\n color?: [number, number, number];\n /** Inclusive 1-based page range `[first, last]`; omit for every page. */\n pageRange?: [number, number] | null;\n /** Draw on the first page of the range too (default `true`). */\n showOnFirstPage?: boolean;\n /** Band height from the page edge, in points (default `36`). */\n bandHeight?: number;\n}\n\n/** Horizontal anchor of a rich {@link HFItem} within the printable width. */\nexport type HFAlign = HeaderFooterAlign;\n\n/**\n * One drawable element of a rich running header/footer band: a line of **text**\n * or a raster **image** (a discriminated union on `type`). Anchored within the\n * printable width by `anchor`, then nudged `(dx, dy)` points in PDF axes\n * (`+dx` → right, `+dy` → up).\n */\nexport type HFItem =\n | {\n type: \"text\";\n /** Horizontal anchor (default `\"left\"`). */\n anchor?: HFAlign;\n /** Horizontal nudge, points (default `0`). */\n dx?: number;\n /** Vertical nudge, points (default `0`). */\n dy?: number;\n /**\n * Template text — may contain `{{page}}`, `{{pages}}`, `{{date}}` and\n * `{{title}}`, substituted at bake time.\n */\n text: string;\n /**\n * An embedded-font object id (from {@link GigaPdfDoc.embedFont}); omit/`null`\n * to use the engine's bundled OFL face (a real embedded font, never base-14).\n */\n fontRef?: number | null;\n /** Font size, points (default `10`). */\n size?: number;\n /** RGB fill colour, `0..255` per channel (default black `[0,0,0]`). */\n color?: [number, number, number];\n /** Bold hint (carried with the def; honoured only by a bold `fontRef`). */\n bold?: boolean;\n /** Italic hint (carried with the def; honoured only by an italic `fontRef`). */\n italic?: boolean;\n }\n | {\n type: \"image\";\n /** Horizontal anchor (default `\"left\"`). */\n anchor?: HFAlign;\n /** Horizontal nudge, points (default `0`). */\n dx?: number;\n /** Vertical nudge, points (default `0`). */\n dy?: number;\n /** Drawn width, points. */\n w: number;\n /** Drawn height, points. */\n h: number;\n /** Key into the `images` map passed to {@link GigaPdfDoc.setRunningHeaderFooter}. */\n imageId: number;\n /** Fill opacity `0..1` (default `1`). */\n opacity?: number;\n };\n\n/** The header and footer item lists of one running-H/F {@link RunningHeaderFooter} zone. */\nexport interface HFZone {\n /** Items drawn in the top (header) band. */\n header: HFItem[];\n /** Items drawn in the bottom (footer) band. */\n footer: HFItem[];\n}\n\n/**\n * A rich, Word-like running header/footer **definition** (see\n * {@link GigaPdfDoc.setRunningHeaderFooter}). The definition is the source of\n * truth (stored in the editor-meta sidecar); the bake regenerates the visible\n * `/GPHF` band from it.\n *\n * Zone selection per 1-based page: page 1 → `firstPage` when `differentFirstPage`\n * (else `default`); otherwise, when `differentOddEven`, even pages → `evenPage`\n * and odd pages → `oddPage` (each falling back to `default` when omitted);\n * otherwise `default` everywhere.\n */\nexport interface RunningHeaderFooter {\n /** The zone every page not overridden by a more specific zone uses. */\n default: HFZone;\n /** First-page override (used when `differentFirstPage`). */\n firstPage?: HFZone | null;\n /** Even-page override (used when `differentOddEven`). */\n evenPage?: HFZone | null;\n /** Odd-page override (used when `differentOddEven`). */\n oddPage?: HFZone | null;\n /** Give page 1 its own `firstPage` zone (default `false`). */\n differentFirstPage?: boolean;\n /** Give even/odd pages their own `evenPage`/`oddPage` zones (default `false`). */\n differentOddEven?: boolean;\n /** Header band height (distance from the top edge to the baseline), points (default `36`). */\n headerBand?: number;\n /** Footer band height (distance from the bottom edge to the baseline), points (default `36`). */\n footerBand?: number;\n}\n\nconst RGB = (rgb: number) => rgb & 0xffffff;\n\n/** `n` bytes of Web Crypto randomness (for encryption seeds; the engine has none). */\nfunction cryptoRandom(n: number): Uint8Array {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (!c?.getRandomValues) {\n throw new Error(\n \"this operation needs Web Crypto (globalThis.crypto.getRandomValues) or an explicit seed\"\n );\n }\n const out = new Uint8Array(n);\n c.getRandomValues(out);\n return out;\n}\n\n/** One colour stop of a {@link GradientSpec}. */\nexport interface GradientStop {\n /** Position along the gradient axis, `0`…`1`. */\n offset: number;\n /** Colour, packed `0xRRGGBB`. */\n rgb: number;\n}\n\n/** A gradient fill for {@link GigaPdfDoc.addGradient}. */\nexport interface GradientSpec {\n /** Axial (`\"linear\"`) or radial geometry. */\n kind: \"linear\" | \"radial\";\n /** `[x0,y0,x1,y1]` for `\"linear\"`, `[x0,y0,r0,x1,y1,r1]` for `\"radial\"`. */\n coords: number[];\n /** At least two colour stops. */\n stops: GradientStop[];\n /** The rectangle `{ x, y, w, h }` filled with the gradient. */\n rect: Box;\n /** Extend before the first / after the last stop (`/Extend`; default `[true, true]`). */\n extend?: [boolean, boolean];\n /** Fill opacity `0`…`1` (default `1`). */\n opacity?: number;\n}\n\n/**\n * A fill colour in any authored colour space (ISO 32000-1 §8.6), for\n * {@link GigaPdfDoc.addFilledRectangle}/{@link GigaPdfDoc.addFilledPolygon}/\n * {@link GigaPdfDoc.addTextColor}. `cmyk`/`gray` are press-ready; `separation`\n * is a spot ink (with its `DeviceCMYK` tint approximation); `icc` embeds a\n * profile. CMYK/gray/tint components are `0`…`1`; `rgb` is packed `0xRRGGBB`.\n */\nexport type Color =\n | { space: \"rgb\"; rgb: number }\n | { space: \"cmyk\"; c: number; m: number; y: number; k: number }\n | { space: \"gray\"; gray: number }\n | {\n space: \"separation\";\n name: string;\n tint: number;\n cmyk: [number, number, number, number];\n }\n | { space: \"icc\"; components: number[]; profile: Uint8Array };\n\n/** Visual styling for a newly-created form field. */\nexport interface FieldStyle {\n /** Text size in points; `0` (default) auto-sizes to the field box. */\n fontSize?: number;\n /** Text / mark colour `0xRRGGBB` (default black). */\n color?: number;\n /** Border colour `0xRRGGBB`, or `null` for no border (default black). */\n border?: number | null;\n /** Background fill `0xRRGGBB`, or `null` for transparent (default none). */\n background?: number | null;\n /** Border width in points (default `1`). */\n borderWidth?: number;\n}\n\n/** One option of a radio group: its export value and on-page rectangle. */\nexport interface RadioOption {\n /** The export value stored in the field when this button is selected. */\n export: string;\n /** `[x0, y0, x1, y1]` in PDF user space. */\n rect: [number, number, number, number];\n}\n\n/** Expand a {@link FieldStyle} into the 7 packed ABI arguments. */\nfunction styleArgs(s: FieldStyle = {}): [number, number, number, number, number, number, number] {\n const hasBorder = s.border === null ? 0 : 1;\n const borderRgb = s.border == null ? 0x000000 : s.border;\n const hasBg = s.background == null ? 0 : 1;\n const bgRgb = s.background == null ? 0 : s.background;\n return [\n s.fontSize ?? 0,\n RGB(s.color ?? 0x000000),\n RGB(borderRgb),\n hasBorder,\n RGB(bgRgb),\n hasBg,\n s.borderWidth ?? 1,\n ];\n}\n\n/** A live document handle. Call {@link close} when done. */\nexport class GigaPdfDoc {\n constructor(\n private readonly g: GigaPdfEngine,\n private readonly h: number\n ) {}\n private ex() {\n return this.g.raw;\n }\n\n close() {\n this.ex().gp_close(this.h);\n }\n pageCount(): number {\n return this.ex().gp_page_count(this.h);\n }\n save(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_save(this.h, o));\n }\n saveCompressed(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_save_compressed(this.h, o));\n }\n\n /**\n * Serialize with PDF 1.5+ **object streams** + a **cross-reference stream**\n * (ISO 32000-1 §7.5.7 / §7.5.8) — the most compact output. `objectStreams`\n * (default `true`) packs non-stream objects into compressed `/ObjStm`s (needs\n * the xref stream); `xrefStreams` (default `true`) writes a `/XRef` stream.\n * `version` selects the `%PDF-x.y` header banner (default `\"1.7\"`).\n * Uncompressed streams are Flate-compressed first, like {@link saveCompressed}.\n * Linearization (Fast Web View) is not performed.\n */\n saveOptimized(\n opts: { objectStreams?: boolean; xrefStreams?: boolean; version?: PdfVersion } = {}\n ): Uint8Array {\n const obj = opts.objectStreams ?? true;\n const xref = opts.xrefStreams ?? true;\n const ver = pdfVersionCode(opts.version);\n return this.g._buffer((o) =>\n this.ex().gp_save_optimized(this.h, obj ? 1 : 0, xref ? 1 : 0, ver, o)\n );\n }\n\n /**\n * Serialize as a **linearized** (\"Fast Web View\") PDF (ISO 32000-1 Annex F).\n *\n * The first page and only the objects needed to render it — together with a\n * `/Linearized` parameter dictionary and a primary hint stream — are written at\n * the **front** of the file, so a web viewer can display page 1 before the rest\n * of the document has downloaded (progressive rendering / byte-range serving).\n * The remaining pages follow, then a main cross-reference table; the first-page\n * cross-reference section chains to it via `/Prev`. Streams are Flate-compressed\n * first (like {@link saveCompressed}) and embedded fonts are subset.\n *\n * Falls back to the plain {@link save} output if the document cannot be\n * linearized (no catalog / page tree / zero pages). `version` selects the\n * `%PDF-x.y` header banner (default `\"1.7\"`).\n */\n toLinearized(version: PdfVersion = \"1.7\"): Uint8Array {\n return this.g._buffer((o) =>\n this.ex().gp_to_linearized(this.h, pdfVersionCode(version), o)\n );\n }\n\n /** Alias of {@link toLinearized} — serialize as a linearized (Fast Web View) PDF. */\n saveLinearized(version: PdfVersion = \"1.7\"): Uint8Array {\n return this.toLinearized(version);\n }\n\n // text intelligence\n textRuns(page: number): TextRunInfo[] {\n return this.g._json((o) => this.ex().gp_text_runs_json(this.h, page, o));\n }\n elements(page: number): Element[] {\n return this.g._json((o) => this.ex().gp_elements_json(this.h, page, o));\n }\n /**\n * Every text element on a page, enriched for an editor: the decoded text, its\n * bounding box (user space, bottom-left), the resolved font family +\n * bold/italic, the effective point size, the RGB fill colour and the baseline\n * rotation. `index` is the text-run index for {@link replaceText}, so a host\n * can extract, render and edit text from one model — the native replacement\n * for a reader's per-run text layer (which `elements()` omits font + colour).\n */\n textElements(page: number): TextElementInfo[] {\n return this.g._json((o) => this.ex().gp_text_elements_json(this.h, page, o));\n }\n /**\n * The document's aggregate language signal — its dominant reading direction\n * (`ltr`/`rtl`/`neutral`), writing system, and a best-effort ISO-639-1\n * language code — computed across every page's decoded text. Lets a host\n * pick fonts, set the UI direction or label the document without its own bidi\n * pass (e.g. detect an Arabic/Hebrew/Japanese PDF). `lang` is omitted when the\n * script does not pin a single language.\n */\n documentLanguage(): DocumentLanguage {\n const raw = this.g._json<{ direction: 'ltr' | 'rtl' | 'neutral'; script: string; lang: string | null }>(\n (o) => this.ex().gp_document_language(this.h, o)\n );\n return {\n direction: raw.direction,\n script: raw.script,\n ...(raw.lang != null ? { lang: raw.lang } : {}),\n };\n }\n /**\n * Every image element on a page: its placement box (user space, bottom-left),\n * the embeddable encoded bytes (`data`) + `format` (`jpeg`/`png`/`jp2`/\n * `unknown`), and the source pixel dimensions. DCTDecode/JPXDecode images pass\n * through as jpeg/jp2; Flate/raw DeviceRGB|DeviceGray are re-encoded to PNG.\n * The native replacement for a reader's image extraction (bytes + placement).\n *\n * Each result's `index` is the **unified element index** usable directly with\n * {@link removeElement} / {@link transformElement} / {@link duplicateElement} /\n * {@link moveElement} — so you can extract an image and edit *that exact* image.\n */\n imageElements(page: number): ImageElementInfo[] {\n const raw = this.g._json<Array<Omit<ImageElementInfo, 'data'> & { dataBase64: string }>>((o) =>\n this.ex().gp_image_elements_json(this.h, page, o)\n );\n return raw.map(({ dataBase64, ...rest }) => ({\n ...rest,\n data: this.g._fromBase64(dataBase64),\n }));\n }\n /**\n * Every painted vector path on `page` (frames, rules, lines, filled shapes…)\n * as geometry + style: segments and bounds in user space (origin bottom-left),\n * fill/stroke RGB, line width, alpha and dash. Clip-only paths are omitted.\n * The native replacement for walking a reader's operator list to rebuild the\n * shape layer.\n *\n * Each result's `index` is the **unified element index** usable directly with\n * {@link setPathStyle} / {@link removeElement} / {@link transformElement} — so\n * you can extract a path and restyle/remove *that exact* path.\n */\n vectorPaths(page: number): VectorPathInfo[] {\n return this.g._json((o) => this.ex().gp_vector_paths_json(this.h, page, o));\n }\n structuredText(page: number): TextLine[] {\n return this.g._json((o) => this.ex().gp_structured_text_json(this.h, page, o));\n }\n /**\n * The **layout blocks** of a single page — the structural reconstruction\n * (paragraphs, headings, lists, tables, shapes, images) of the page's flat\n * glyph/path geometry, in reading order (column-major), each {@link GigaBlock}\n * keeping a top-down `frame` and every text run its `source_index` back to the\n * editable content-stream operator.\n *\n * The **per-page** counterpart of {@link GigaPdfDoc.toModel} (which\n * reconstructs the whole document at once): a continuous / lazily-virtualized\n * editor calls this one page at a time. Identifies 1- and 2-column layouts,\n * merges lines into justified/left/centred/right paragraphs, promotes large\n * isolated lines to headings, and recovers ruled tables. An out-of-range page\n * yields `[]`.\n */\n pageBlocks(page: number): GigaBlock[] {\n return this.g._json((o) => this.ex().gp_page_blocks_json(this.h, page, o));\n }\n search(query: string, caseInsensitive = true): SearchHit[] {\n return this.g._withStr(query, (p, l) =>\n this.g._json((o) => this.ex().gp_search_json(this.h, p, l, caseInsensitive ? 1 : 0, o))\n );\n }\n\n // editing\n /**\n * Replace text run `index` on `page` with `text`. Font-aware: works with\n * **any** font — a run set in an embedded Type0/Identity-H face (TrueType or\n * OpenType-CFF) is re-encoded through that font's char→glyph map; base-14 and\n * simple fonts use WinAnsi. Returns `false` if the run/page doesn't exist.\n */\n replaceText(page: number, index: number, text: string): boolean {\n return (\n this.g._withStr(text, (p, l) => this.ex().gp_replace_text(this.h, page, index, p, l)) === 0\n );\n }\n removeElement(page: number, index: number): boolean {\n return this.ex().gp_remove_element(this.h, page, index) === 0;\n }\n moveElement(page: number, index: number, dx: number, dy: number): boolean {\n return this.ex().gp_move_element(this.h, page, index, dx, dy) === 0;\n }\n /**\n * Apply a full affine transform to element `index` on `page`, wrapping it in\n * `q … cm … Q` with the matrix `m = [a, b, c, d, e, f]`. This **generalises**\n * {@link moveElement} (whose matrix is the pure translate `[1,0,0,1,dx,dy]`)\n * to scale, rotation, shear and translation in one call. Because it is purely\n * matrix-based it works identically for text, images and shapes — their\n * internal coordinates are never touched. Returns `false` if the element/page\n * doesn't exist.\n */\n transformElement(\n page: number,\n index: number,\n m: [number, number, number, number, number, number]\n ): boolean {\n return (\n this.ex().gp_transform_element(this.h, page, index, m[0], m[1], m[2], m[3], m[4], m[5]) === 0\n );\n }\n /**\n * Re-style the **path** element `index` on `page` in place: any provided field\n * overrides that part of the graphics state for the path's paint; omitted\n * fields keep the inherited state. Implemented by wrapping the path's op range\n * in `q … Q` and injecting the requested state operators (`rg`/`RG`/`w`/`d`)\n * before its construction + paint ops, so the original paint op now draws with\n * the override and following content is unaffected. RGB colours are `[r,g,b]`\n * in `0..=1`; `dash` is the PDF dash array (`[]` = solid). Returns `false` if\n * the element is not a path (or the page/index doesn't exist).\n *\n * Opacity: `fillAlpha`/`strokeAlpha` (`0..=1`) are fully supported — an\n * `/ExtGState` carrying `/ca`/`/CA` is registered on the page and a `/<gs> gs`\n * is injected into the path's `q … Q` wrap, so the alpha applies to that path\n * run only. (For non-path elements such as images, use\n * {@link setElementOpacity}.)\n */\n setPathStyle(\n page: number,\n index: number,\n style: {\n fill?: [number, number, number];\n stroke?: [number, number, number];\n strokeWidth?: number;\n fillAlpha?: number;\n strokeAlpha?: number;\n dash?: number[];\n }\n ): boolean {\n return (\n this.g._withStr(JSON.stringify(style), (p, l) =>\n this.ex().gp_set_path_style_json(this.h, page, index, p, l)\n ) === 0\n );\n }\n /**\n * Re-style **sub-ranges** of text run `index` on `page` in place — the\n * by-character-run companion of {@link setPathStyle}. Each span sets the style\n * of the `[start, end)` UTF-16 slice of the run's *decoded* text (bold / italic\n * / underline / strike / colour / size); the run is split so the rest keeps its\n * original style and **positioning is preserved** (the original glyph codes,\n * including `TJ` kerning, are sliced and re-emitted — never re-encoded — and\n * each styled slice is wrapped in `q … Q`). Spans may be given in any order and\n * are clamped to the run's length.\n *\n * Notes on each field: `color` is `[r,g,b]` in `0..=1` (text fill); `sizePt`\n * rescales the slice's font in the run's own text scale; `bold` is faux-bold\n * (fill+stroke render mode) when no bold variant font is wired; `italic` is a\n * no-op without an italic/oblique variant (a stream edit can't shear glyphs\n * without disturbing advances); `underline`/`strike` draw a thin rule in page\n * space. Returns `false` when `index` does not resolve to a top-level text run\n * (e.g. it addresses form-XObject text), like {@link setPathStyle} for a\n * non-matching element.\n */\n setTextRunStyle(\n page: number,\n index: number,\n spans: Array<{\n start: number;\n end: number;\n color?: [number, number, number];\n sizePt?: number;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strike?: boolean;\n }>\n ): boolean {\n return (\n this.g._withStr(JSON.stringify(spans), (p, l) =>\n this.ex().gp_set_text_run_style_json(this.h, page, index, p, l)\n ) === 0\n );\n }\n /**\n * Set a constant opacity on element `index` on `page` — text, image **or**\n * shape — by registering an `/ExtGState` (`/ca` = `/CA` = `fillAlpha`, clamped\n * to `0..=1`) on the page and wrapping the element's op range in\n * `q /<gs> gs … Q`. This is the way to set an **image**'s alpha in place;\n * shapes may also use {@link setPathStyle}'s `fillAlpha`/`strokeAlpha` (same\n * underlying `/ExtGState` mechanism). Returns `false` if the page/index doesn't\n * exist.\n */\n setElementOpacity(page: number, index: number, fillAlpha: number): boolean {\n return this.ex().gp_set_element_opacity(this.h, page, index, fillAlpha) === 0;\n }\n /**\n * Change the paint order (z-order) of element `index` on `page`. `toFront`\n * brings it visually on top (its op range is moved to the end of the content\n * stream, painted last); otherwise it is sent behind everything (moved to the\n * start, painted first). The moved range is re-wrapped in `q … Q` so it neither\n * inherits nor leaks graphics state. Works for text, image and shape elements.\n * The element's index changes after the move — re-read {@link GigaPdfDoc.elements}.\n * Returns `false` if the page/index doesn't exist.\n */\n reorderElement(page: number, index: number, toFront: boolean): boolean {\n return this.ex().gp_reorder_element(this.h, page, index, toFront ? 1 : 0) === 0;\n }\n duplicateElement(page: number, index: number): boolean {\n return this.ex().gp_duplicate_element(this.h, page, index) === 0;\n }\n /** Index of the element at page point `(x, y)`, or -1 if none. */\n elementAt(page: number, x: number, y: number): number {\n return this.ex().gp_element_at(this.h, page, x, y);\n }\n /**\n * Draw a vector rectangle. Pass an `0xRRGGBB` colour for `stroke`/`fill`, or\n * `null` to omit that paint. 0 → success.\n */\n addRectangle(\n page: number,\n x: number,\n y: number,\n w: number,\n h: number,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.ex().gp_add_rectangle(\n this.h,\n page,\n x,\n y,\n w,\n h,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n ) === 0\n );\n }\n\n /** Draw a straight line from `(x1,y1)` to `(x2,y2)`. `stroke` is `0xRRGGBB`. */\n drawLine(\n page: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n stroke = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.ex().gp_draw_line(this.h, page, x1, y1, x2, y2, RGB(stroke), lineWidth, opacity) === 0\n );\n }\n\n /**\n * Draw an ellipse (circle when `rx === ry`) centred at `(cx,cy)`. Pass an\n * `0xRRGGBB` colour for `stroke`/`fill`, or `null` to omit that paint.\n */\n addEllipse(\n page: number,\n cx: number,\n cy: number,\n rx: number,\n ry: number,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.ex().gp_add_ellipse(\n this.h,\n page,\n cx,\n cy,\n rx,\n ry,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n ) === 0\n );\n }\n\n /**\n * Paint a **linear** or **radial** gradient over `rect` on `page` (ISO 32000-1\n * §8.7.4 shading + §8.7.3 pattern). `coords` is `[x0,y0,x1,y1]` for `\"linear\"`\n * or `[x0,y0,r0,x1,y1,r1]` for `\"radial\"`; `stops` is ≥ 2 colour stops\n * (`offset` 0…1, `rgb` packed `0xRRGGBB`). `extend` (default `[true,true]`)\n * sets `/Extend`; `opacity` (default `1`) is the fill alpha.\n *\n * @example\n * doc.addGradient(1, {\n * kind: \"linear\", coords: [50, 50, 250, 50],\n * stops: [{ offset: 0, rgb: 0xff0000 }, { offset: 1, rgb: 0x0000ff }],\n * rect: { x: 50, y: 40, w: 200, h: 60 },\n * });\n */\n addGradient(page: number, spec: GradientSpec): boolean {\n const kind = spec.kind === \"radial\" ? 1 : 0;\n const offsets = spec.stops.map((s) => s.offset);\n const colors = spec.stops.map((s) => RGB(s.rgb));\n const [es, ee] = spec.extend ?? [true, true];\n const opacity = spec.opacity ?? 1;\n const r = spec.rect;\n return (\n this.g._withF64(spec.coords, (cp, cc) =>\n this.g._withF64(offsets, (op, _oc) =>\n this.g._withU32(colors, (clp, _clc) =>\n this.ex().gp_add_gradient(\n this.h, page, kind, cp, cc, op, clp, offsets.length,\n r.x, r.y, r.w, r.h, es ? 1 : 0, ee ? 1 : 0, opacity\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Encode a {@link Color} into the ABI's `(kind, comps, name, profile)` buffers\n * and invoke `fn` with the resulting pointers. Internal.\n */\n private _color<T>(\n color: Color,\n fn: (\n kind: number,\n compsPtr: number,\n compsCount: number,\n namePtr: number,\n nameLen: number,\n profPtr: number,\n profLen: number\n ) => T\n ): T {\n let kind: number;\n let comps: number[];\n let name = \"\";\n let profile: Uint8Array | null = null;\n switch (color.space) {\n case \"cmyk\":\n kind = 1;\n comps = [color.c, color.m, color.y, color.k];\n break;\n case \"gray\":\n kind = 2;\n comps = [color.gray];\n break;\n case \"separation\":\n kind = 3;\n comps = [color.tint, ...color.cmyk];\n name = color.name;\n break;\n case \"icc\":\n kind = 4;\n comps = color.components;\n profile = color.profile;\n break;\n default: {\n const c = RGB(color.rgb);\n kind = 0;\n comps = [((c >> 16) & 0xff) / 255, ((c >> 8) & 0xff) / 255, (c & 0xff) / 255];\n }\n }\n return this.g._withF64(comps, (cp, cc) =>\n this.g._withOptStr(name, (np, nl) =>\n profile\n ? this.g._withBytes(profile, (pp, pl) => fn(kind, cp, cc, np, nl, pp, pl))\n : fn(kind, cp, cc, np, nl, 0, 0)\n )\n );\n }\n\n /**\n * Fill a rectangle with `color` in **any** colour space — the press-ready\n * counterpart of {@link addRectangle} (CMYK, spot `Separation`, gray, ICC).\n *\n * @example\n * doc.addFilledRectangle(1, { x: 40, y: 700, w: 200, h: 40 },\n * { space: \"cmyk\", c: 0.1, m: 0.8, y: 0.9, k: 0 });\n */\n addFilledRectangle(page: number, rect: Box, color: Color, opacity = 1): boolean {\n return (\n this._color(color, (kind, cp, cc, np, nl, pp, pl) =>\n this.ex().gp_add_filled_rectangle(\n this.h, page, rect.x, rect.y, rect.w, rect.h, kind, cp, cc, np, nl, pp, pl, opacity\n )\n ) === 0\n );\n }\n\n /**\n * Fill a polygon through flat `[x0,y0,x1,y1,…]` `points` (≥ 3 vertices) with\n * `color` in any colour space. The path is closed automatically.\n */\n addFilledPolygon(page: number, points: number[], color: Color, opacity = 1): boolean {\n return (\n this.g._withF64(points, (ptsPtr, ptsCount) =>\n this._color(color, (kind, cp, cc, np, nl, pp, pl) =>\n this.ex().gp_add_filled_polygon(\n this.h, page, ptsPtr, ptsCount, kind, cp, cc, np, nl, pp, pl, opacity\n )\n )\n ) === 0\n );\n }\n\n /**\n * Draw a base-14 text run in **any** colour space — the press-ready\n * counterpart of {@link addTextStandard}. `font` is a base-14 family\n * (`Helvetica`, `Times-Roman`, `Courier`, …).\n */\n addTextColor(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n font: string,\n color: Color,\n opts: { opacity?: number; rotation?: number; underline?: boolean; strikethrough?: boolean } = {}\n ): boolean {\n const { opacity = 1, rotation = 0, underline = false, strikethrough = false } = opts;\n return (\n this.g._withStr(text, (tp, tl) =>\n this.g._withStr(font, (fp, fl) =>\n this._color(color, (kind, cp, cc, np, nl, pp, pl) =>\n this.ex().gp_add_text_color(\n this.h, page, x, y, size, tp, tl, fp, fl, kind, cp, cc, np, nl, pp, pl,\n opacity, rotation, underline ? 1 : 0, strikethrough ? 1 : 0\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Turn **overprint** on/off for content drawn **after** this call (`/op` fill,\n * `/OP` stroke, `/OPM` mode — `0` independent colorants, `1` non-erasing).\n * Essential for prepress black-overprint / trapping.\n */\n setOverprint(page: number, fill: boolean, stroke: boolean, mode = 1): boolean {\n return this.ex().gp_set_overprint(this.h, page, fill ? 1 : 0, stroke ? 1 : 0, mode) === 0;\n }\n\n /**\n * Add a document-level **OutputIntent** embedding the ICC `profile` (its `/N`\n * is read from the profile), with `condition` as the output-condition\n * identifier (e.g. `\"Coated FOGRA39\"`). Decoupled from the PDF/A path.\n */\n addOutputIntent(profile: Uint8Array, condition: string): boolean {\n return (\n this.g._withBytes(profile, (pp, pl) =>\n this.g._withStr(condition, (cp, cl) =>\n this.ex().gp_add_output_intent(this.h, pp, pl, cp, cl)\n )\n ) === 0\n );\n }\n\n /**\n * Draw a polyline/polygon through flat `[x0,y0,x1,y1,…]` points. `close` joins\n * the last vertex back to the first. `0xRRGGBB` colours, or `null` to omit.\n */\n addPolygon(\n page: number,\n points: number[],\n close = true,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.g._withF64(points, (p, c) =>\n this.ex().gp_add_polygon(\n this.h,\n page,\n p,\n c,\n close ? 1 : 0,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n )\n ) === 0\n );\n }\n\n /**\n * Draw an SVG path (`M`/`L`/`C`/`Q`/`Z`…) anchored so the SVG origin maps to\n * `(ox,oy)` with the Y axis flipped — same convention as `pdf-lib`'s\n * `drawSvgPath`. Covers freeform/polygon/triangle shapes.\n */\n addPath(\n page: number,\n svgPath: string,\n ox: number,\n oy: number,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.g._withStr(svgPath, (p, l) =>\n this.ex().gp_add_path(\n this.h,\n page,\n p,\n l,\n ox,\n oy,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n )\n ) === 0\n );\n }\n\n /**\n * Embed a raster image (PNG or JPEG bytes) at `(x,y)` sized `(w,h)` in PDF\n * user space. PNG alpha is honoured; `opacity` (0..1) sets an overall alpha.\n */\n addImage(\n page: number,\n data: Uint8Array,\n x: number,\n y: number,\n w: number,\n h: number,\n opacity = 1\n ): boolean {\n return (\n this.g._withBytes(data, (p, l) =>\n this.ex().gp_add_image(this.h, page, p, l, x, y, w, h, opacity)\n ) === 0\n );\n }\n /**\n * Replace the pixels of an **existing image XObject in place** — swap a logo or\n * photo while every reference to it stays intact (ISO 32000-1 §8.9). `index` is\n * the **unified element index** of an image on `page`, exactly the `index`\n * reported by {@link imageElements} (and accepted by {@link removeElement} /\n * {@link transformElement}); `data` is a fresh PNG or JPEG.\n *\n * Unlike a delete-then-re-add, the image keeps its object number, **every `/Do`\n * placement, and its position / scale / rotation / clip matrix** — only the\n * stream bytes and the image dictionary (`/Width`, `/Height`, `/ColorSpace`,\n * `/BitsPerComponent`, `/Filter`) are rewritten. The new raster is re-encoded\n * through the same path as {@link addImage} (PNG alpha → a fresh `/SMask`; JPEG\n * → `/DCTDecode` passthrough). It need not match the old pixel size — it is\n * drawn into the same box (transform the element first to re-fit it).\n *\n * Returns `false` if `page`/`index` doesn't resolve to a top-level image, or the\n * bytes aren't a decodable PNG/JPEG.\n */\n replaceImage(page: number, index: number, data: Uint8Array): boolean {\n return (\n this.g._withBytes(data, (p, l) => this.ex().gp_replace_image(this.h, page, index, p, l)) === 0\n );\n }\n /**\n * Stamp an **image watermark** across pages from raw image bytes. Accepts the\n * same five formats the engine decodes — **PNG, JPEG, WebP, GIF, AVIF**. The\n * image is embedded **once** and referenced on every target page.\n *\n * `opts.pages` is a list of 1-based page numbers; omit it (or pass `[]`) to\n * stamp every page. `opts.anchor` positions the image (`'center'` default, or a\n * corner) and `opts.offsetX`/`offsetY` nudge it (in points; in `tile` mode they\n * become the gaps between tiles). `opts.width`/`height` set the target size in\n * points (height keeps the source aspect ratio when omitted). `opts.rotationDeg`\n * rotates about the image centre and `opts.opacity` (0–1) sets the alpha.\n * Returns `false` if the image can't be decoded.\n */\n addImageWatermark(\n data: Uint8Array,\n opts: {\n pages?: number[];\n anchor?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n offsetX?: number;\n offsetY?: number;\n width?: number;\n height?: number;\n rotationDeg?: number;\n opacity?: number;\n tile?: boolean;\n } = {}\n ): boolean {\n const anchorTag = {\n center: 0,\n 'top-left': 1,\n 'top-right': 2,\n 'bottom-left': 3,\n 'bottom-right': 4,\n }[opts.anchor ?? 'center'];\n const pages = opts.pages ?? [];\n const call = (pp: number, pc: number) =>\n this.g._withBytes(data, (p, l) =>\n this.ex().gp_add_image_watermark(\n this.h,\n p,\n l,\n pp,\n pc,\n anchorTag,\n opts.offsetX ?? 0,\n opts.offsetY ?? 0,\n opts.width ?? 0,\n opts.height ?? 0,\n opts.rotationDeg ?? 0,\n opts.opacity ?? 0.25,\n opts.tile ? 1 : 0\n )\n );\n const rc = pages.length === 0 ? call(0, 0) : this.g._withU32(pages, (pp, pc) => call(pp, pc));\n return rc === 0;\n }\n /**\n * Draw SVG markup on a page as **native vector paths** (crisp at any zoom, not\n * rasterized), fitting its `viewBox` into the box `(x, y, w, h)` in PDF points\n * (origin bottom-left). Supports shapes, `<path>`, groups, transforms and\n * fill/stroke/opacity. Returns `false` if the SVG can't be parsed.\n */\n addSvg(page: number, svg: string, x: number, y: number, w: number, h: number): boolean {\n return (\n this.g._withStr(svg, (p, l) => this.ex().gp_add_svg(this.h, page, p, l, x, y, w, h)) === 0\n );\n }\n /** True redaction: delete content intersecting the region (no opaque cover by default). */\n redact(\n page: number,\n x: number,\n y: number,\n w: number,\n h: number,\n coverRgb = 0,\n hasCover = false\n ): number {\n return this.ex().gp_redact_region(this.h, page, x, y, w, h, RGB(coverRgb), hasCover ? 1 : 0);\n }\n\n /**\n * True **PII redaction** of one or more rectangles `(x, y, width, height)` in\n * PDF points (origin bottom-left), in a single call. For every rect this:\n *\n * - **deletes** the overlapping text/vector elements from the content stream —\n * the glyphs and their `/ToUnicode` mapping are gone, so copy/paste and text\n * extraction reveal nothing in the area;\n * - **overwrites the pixels** of any underlying image (a scan/photo) with opaque\n * black — only the intersecting sub-rectangle, so the rest of the page image\n * survives — and re-encodes the image, erasing the sensitive pixels from the\n * bytes (not merely covering them);\n * - strips overlapping annotations and clears their form-field values;\n * - paints an opaque **black** box over the rect as the visible redaction mark.\n *\n * The black cover is the default for PII (unlike {@link redact}). Pass\n * `opts.coverRgb` to change the mark colour, or `opts.cover = false` to remove\n * the content/pixels with no visible box. Returns the number of content\n * elements deleted across all rects.\n */\n redactPii(\n page: number,\n rects: { x: number; y: number; width: number; height: number }[],\n opts: { cover?: boolean; coverRgb?: number } = {}\n ): number {\n if (rects.length === 0) return 0;\n const flat: number[] = [];\n for (const r of rects) flat.push(r.x, r.y, r.width, r.height);\n const cover = opts.cover ?? true;\n const coverRgb = opts.coverRgb ?? 0x000000;\n return this.g._withF64(flat, (p, c) =>\n this.ex().gp_redact_pii(this.h, page, p, c, RGB(coverRgb), cover ? 1 : 0)\n );\n }\n\n // pages\n rotatePage(page: number, degrees: number): boolean {\n return this.ex().gp_rotate_page(this.h, page, degrees) === 0;\n }\n deletePage(page: number): boolean {\n return this.ex().gp_delete_page(this.h, page) === 0;\n }\n movePage(from: number, to: number): boolean {\n return this.ex().gp_move_page(this.h, from, to) === 0;\n }\n /**\n * Append pages of another PDF onto this document. With no `pages`, every page\n * is appended (powers *merge*). With `pages` — 1-based page numbers, in the\n * order given — only that selection is brought in (ISO 32000-1 §7.7.3), each\n * page keeping its content, resources, annotations and box geometry. Numbers\n * out of range are skipped; an empty/all-out-of-range selection returns\n * `false`.\n */\n appendPages(otherPdf: Uint8Array, pages?: number[]): boolean {\n if (pages === undefined) {\n return this.g._withBytes(otherPdf, (p, l) => this.ex().gp_append_pages(this.h, p, l)) === 0;\n }\n return (\n this.g._withBytes(otherPdf, (bp, bl) =>\n this.g._withU32(pages, (pp, pc) =>\n this.ex().gp_append_pages_subset(this.h, bp, bl, pp, pc)\n )\n ) === 0\n );\n }\n /**\n * Add an invisible (text render mode 3) standard-Helvetica text layer to\n * `page` in a SINGLE content append — for OCR. Each run is `{x, y, size,\n * text, rotation?}` (PDF user space, baseline-anchored, `rotation`° CCW).\n * Runs whose text has any non-WinAnsi glyph are skipped. Returns the number\n * of runs actually written (0 on engine error).\n */\n addTextLayer(\n page: number,\n runs: { x: number; y: number; size: number; text: string; rotation?: number }[]\n ): number {\n const parts: Uint8Array[] = [];\n let total = 0;\n for (const r of runs) {\n const t = enc.encode(r.text);\n const head = new Uint8Array(36);\n const dv = new DataView(head.buffer);\n dv.setFloat64(0, r.x, true);\n dv.setFloat64(8, r.y, true);\n dv.setFloat64(16, r.size, true);\n dv.setFloat64(24, r.rotation ?? 0, true);\n dv.setUint32(32, t.length, true);\n parts.push(head, t);\n total += 36 + t.length;\n }\n const buf = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n buf.set(p, off);\n off += p.length;\n }\n const written = this.g._withBytes(buf, (p, l) =>\n this.ex().gp_add_text_layer(this.h, page, p, l)\n );\n return written < 0 ? 0 : written;\n }\n /** Extract the given 1-based page numbers into a NEW standalone PDF. */\n extractPages(pages: number[]): Uint8Array {\n return this.g._withU32(pages, (p, c) =>\n this.g._buffer((o) => this.ex().gp_extract_pages(this.h, p, c, o))\n );\n }\n /**\n * Resize a page's `/MediaBox` to `width`×`height` points — **box geometry\n * only**. The drawn content keeps its own coordinates (it is *not* rescaled to\n * the new box, so it may clip or float). To scale the page content along with\n * the box (keeping annotations aligned) use {@link scalePageContent} or\n * {@link scalePageTo}; for large-format authoring see {@link setUserUnit}.\n */\n resizePage(page: number, width: number, height: number): boolean {\n return this.ex().gp_resize_page(this.h, page, width, height) === 0;\n }\n /**\n * Scale a page's **content** uniformly by `factor` about the page origin (ISO\n * 32000-1 §8.3.4) — a true zoom of the whole page, not just the box. Three\n * things move together: (1) the content stream is wrapped in\n * `q <factor 0 0 factor 0 0> cm … Q`; (2) `/MediaBox` and `/CropBox` (resolved\n * through inheritance) plus any locally declared `/BleedBox`/`/TrimBox`/\n * `/ArtBox` are scaled about the origin; (3) every annotation `/Rect` is scaled,\n * so widget/stamp appearances — mapped from their `/BBox` into the `/Rect` per\n * §12.5.5 — rescale to stay aligned automatically. `factor` must be finite and\n * positive. `false` on engine error (bad page number / non-positive factor).\n */\n scalePageContent(page: number, factor: number): boolean {\n return this.ex().gp_scale_page_content(this.h, page, factor) === 0;\n }\n /**\n * Anisotropic {@link scalePageContent}: scale a page's content by `sx`\n * horizontally and `sy` vertically about the origin, scaling the boxes and\n * annotation `/Rect`s by the same factors. Both must be finite and positive.\n * `false` on engine error.\n */\n scalePageContentXY(page: number, sx: number, sy: number): boolean {\n return this.ex().gp_scale_page_content_xy(this.h, page, sx, sy) === 0;\n }\n /**\n * Scale a page's content to **fit within** `width`×`height` points (shrink- or\n * grow-to-fit), preserving aspect ratio — equivalent to {@link scalePageContent}\n * with `min(width / currentWidth, height / currentHeight)` over the page's\n * displayed size (`/MediaBox` with `/Rotate` applied). Returns the uniform\n * factor applied, or `null` on engine error (bad page number, non-positive\n * target, or zero-area page).\n */\n scalePageTo(page: number, width: number, height: number): number | null {\n const factor = this.ex().gp_scale_page_to(this.h, page, width, height);\n return factor < 0 ? null : factor;\n }\n /**\n * Set a page's `/UserUnit` (ISO 32000-1 §14.11.2) for **large-format\n * authoring**: one default user-space unit becomes `unit`⁄72 inch, so the same\n * coordinates render larger (e.g. `2.0` doubles the physical size, lifting the\n * ~200-inch coordinate ceiling). `1.0` is the default and removes the key. This\n * is distinct from {@link scalePageContent}: it rescales the coordinate system\n * (a viewer-level zoom of the medium), not the content or boxes. `unit` must be\n * finite and positive. `false` on engine error.\n */\n setUserUnit(page: number, unit: number): boolean {\n return this.ex().gp_set_user_unit(this.h, page, unit) === 0;\n }\n /**\n * A page's `/UserUnit` (ISO 32000-1 §14.11.2), defaulting to `1.0` when absent.\n * Returns `null` on engine error (bad page number).\n */\n pageUserUnit(page: number): number | null {\n const unit = this.ex().gp_page_user_unit(this.h, page);\n return unit < 0 ? null : unit;\n }\n /** Insert a blank page after the 1-based `after` page (0 = front); returns its id. */\n addPage(width: number, height: number, after = 0): number {\n return this.ex().gp_add_page(this.h, width, height, after);\n }\n /** Duplicate a page, inserting the copy right after it; returns the new page's id. */\n copyPage(page: number): number {\n return this.ex().gp_copy_page(this.h, page);\n }\n /**\n * N-up imposition (ISO 32000-1 §8.10): draw the **content** of the 1-based\n * `source` page, scaled and translated, onto the 1-based `target` page — the\n * basis for 2-up/4-up, booklets, contact sheets and page-on-page stamping. The\n * source page becomes a Form XObject (its content + `/Resources`, so its fonts\n * and images come along) and is drawn with `q <cm> /Fmn Do Q` appended to the\n * target. `(x, y)` is where the visible page's lower-left corner lands and\n * `(scaleX, scaleY)` scale the page **as displayed** (its `/MediaBox` origin\n * and `/Rotate` are absorbed into the matrix). Wrapped in `q`/`Q`, so it never\n * disturbs existing target content and is **composable** — call it repeatedly\n * (different sources and/or cells) to build an N-up sheet. `source` and\n * `target` may be the same page. `false` on engine error (bad page number).\n */\n placePage(\n target: number,\n source: number,\n x: number,\n y: number,\n scaleX: number,\n scaleY: number\n ): boolean {\n return this.ex().gp_place_page(this.h, target, source, x, y, scaleX, scaleY) === 0;\n }\n /**\n * Place `source` onto `target` (both 1-based) using an explicit content-stream\n * matrix `[a, b, c, d, e, f]` — the low-level primitive behind\n * {@link placePage} for full control of the affine (shear, arbitrary rotation,\n * reflection). The matrix maps the source page's form space (its user space,\n * including the `/MediaBox` origin) to the target; unlike {@link placePage} no\n * origin/rotation normalisation is applied, so identity draws the source 1:1\n * at the target origin. `false` on engine error.\n */\n placePageMatrix(target: number, source: number, matrix: [number, number, number, number, number, number]): boolean {\n const [a, b, c, d, e, f] = matrix;\n return this.ex().gp_place_page_matrix(this.h, target, source, a, b, c, d, e, f) === 0;\n }\n /**\n * Impose **all** existing pages `cols × rows` per sheet onto freshly added\n * sheets (2-up, 4-up, booklet thumbnails, contact sheets). Pages go\n * left-to-right, top-to-bottom; each is scaled uniformly to fit its cell\n * (aspect preserved) and centred. The new sheets are appended after the last\n * original page and the **originals are removed**, leaving only the imposed\n * sheets. Returns the number of sheets produced (negative on error: `cols`/\n * `rows` 0, or an empty document). `sheetWidth`/`sheetHeight` default to A4\n * portrait; `margin`/`gutter` to 14 pt.\n */\n nUp(\n cols: number,\n rows: number,\n opts: { sheetWidth?: number; sheetHeight?: number; margin?: number; gutter?: number } = {}\n ): number {\n return this.ex().gp_n_up(\n this.h,\n cols,\n rows,\n opts.sheetWidth ?? 595.28,\n opts.sheetHeight ?? 841.89,\n opts.margin ?? 14,\n opts.gutter ?? 14\n );\n }\n /** A page's size (points) and `/Rotate` (0/90/180/270). */\n pageInfo(page: number): PageInfo {\n return this.g._json((o) => this.ex().gp_page_info_json(this.h, page, o));\n }\n\n // margins + running header/footer\n\n /**\n * A page's margins (points): the gap between `/CropBox` and `/MediaBox` when a\n * CropBox exists, else estimated from the content bounding box.\n */\n pageMargins(page: number): PageMargins {\n return this.g._json<PageMargins>((o) => this.ex().gp_page_margins(this.h, page, o));\n }\n\n /**\n * Set a page's margins (points) by insetting its `/CropBox` from the `/MediaBox`\n * — a real, visible margin change. Returns `true` on success.\n */\n setPageMargins(page: number, m: PageMargins): boolean {\n return this.ex().gp_set_page_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;\n }\n\n /**\n * Store an **opaque** JSON string as the document's GigaPDF editor-metadata\n * sidecar — private editor state that travels with the PDF (catalog\n * `/GigaPDF /EditorMeta`, a FlateDecode-compressed stream). It is ignored by\n * every standard PDF reader and the round-trip survives save/open. Pass a JSON\n * **object** if you also use {@link setEditorMargins} (which read-modify-writes\n * that object's `margins` key). Returns `true` on success.\n */\n setEditorMeta(json: string): boolean {\n return this.g._withStr(json, (p, l) => this.ex().gp_set_editor_meta(this.h, p, l)) === 0;\n }\n\n /**\n * The document's GigaPDF editor-metadata sidecar string (set by\n * {@link setEditorMeta}), or `null` when the document carries none.\n */\n editorMeta(): string | null {\n return this.g._strOrNull((o) => this.ex().gp_editor_meta(this.h, o));\n }\n\n /**\n * Record the editor's per-page **display** margins (points) in the\n * editor-metadata sidecar (under `margins`, keyed by page) **without touching\n * `/CropBox` or `/MediaBox`** — distinct from {@link setPageMargins}, which\n * performs a real visible recrop. Any other host keys in the sidecar are\n * preserved. Returns `true` on success.\n */\n setEditorMargins(page: number, m: PageMargins): boolean {\n return this.ex().gp_set_editor_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;\n }\n\n /**\n * The editor's per-page display margins (points) recorded for `page` by\n * {@link setEditorMargins}, or `null` when none were stored. Reads only the\n * sidecar — never `/CropBox`.\n */\n editorMargins(page: number): PageMargins | null {\n return this.g._jsonOrNull<PageMargins>((o) => this.ex().gp_editor_margins(this.h, page, o));\n }\n\n /**\n * All five page boundary boxes (`media`/`crop`/`bleed`/`trim`/`art`) for the\n * 1-based `page`, each as `[x0, y0, x1, y1]` in points, with ISO 32000-1\n * inheritance and defaults applied. See {@link PageBoxes} for the exact\n * default chain and the `declared` flags.\n */\n getPageBoxes(page: number): PageBoxes {\n return this.g._json<PageBoxes>((o) => this.ex().gp_page_boxes_json(this.h, page, o));\n }\n\n /**\n * Set one of a page's boundary boxes. `kind` is one of {@link PAGE_BOX_KINDS}\n * and `box` is given as `{ x, y, w, h }` (origin + size, points); it is written\n * as `[x, y, x+w, y+h]`, normalised so reversed sizes are accepted. Sibling\n * boxes are preserved. Returns `true` on success, `false` for an unknown kind,\n * a degenerate box (zero/negative area), or a bad page number.\n *\n * Setting `\"trim\"`/`\"bleed\"` is the prerequisite for PDF/X and commercial-print\n * (imposition, bleed, finished-size) pipelines.\n */\n setPageBox(page: number, kind: PageBoxKind, box: Box): boolean {\n const k = PAGE_BOX_KINDS.indexOf(kind);\n if (k < 0) return false;\n return (\n this.ex().gp_set_page_box(this.h, page, k, box.x, box.y, box.x + box.w, box.y + box.h) === 0\n );\n }\n\n /**\n * The document's page-label ranges (`/PageLabels`, ISO 32000-1 §12.4.2), sorted\n * by `startPage` (1-based). Empty when the document declares no page labels.\n */\n getPageLabels(): PageLabelRange[] {\n return this.g._json<PageLabelRange[]>((o) => this.ex().gp_page_labels_json(this.h, o));\n }\n\n /**\n * Replace the document's page labels. Pass an **empty** array to remove all\n * labels. Ranges are sorted by `startPage` and collapsed to one entry per page\n * (last wins). Returns `true` on success.\n *\n * @example\n * // Front matter in lowercase roman, body in decimal, appendix \"A-1, A-2…\".\n * doc.setPageLabels([\n * { startPage: 1, style: \"romanLower\", prefix: \"\", startNumber: 1 },\n * { startPage: 5, style: \"decimal\", prefix: \"\", startNumber: 1 },\n * { startPage: 20, style: \"decimal\", prefix: \"A-\", startNumber: 1 },\n * ]);\n */\n setPageLabels(ranges: PageLabelRange[]): boolean {\n const text = ranges\n .map(\n (r) =>\n `${r.startPage}\\t${PAGE_LABEL_STYLE_TOKEN[r.style] ?? \"-\"}\\t${r.startNumber ?? 1}\\t${\n r.prefix ?? \"\"\n }`\n )\n .join(\"\\n\");\n return this.g._withOptStr(text, (p, l) => this.ex().gp_set_page_labels(this.h, p, l)) === 0;\n }\n\n /**\n * The viewer-visible label string for the 1-based `page` (e.g. `\"iv\"`, `\"A-3\"`),\n * resolving the applicable `/PageLabels` range; the decimal page number when no\n * range applies (including a document with no page labels).\n */\n pageLabel(page: number): string {\n return this.g._str((o) => this.ex().gp_page_label(this.h, page, o));\n }\n\n /**\n * Author a presentation transition + auto-advance on `page` (1-based),\n * ISO 32000-1 §12.4.4. Writes the page's `/Trans` dictionary from\n * {@link PageTransition.style} plus only the optional sub-keys that apply to\n * that style (`dimension`/`motion` for `split`, `direction`/`scale`/\n * `flyAreaOpaque` for `fly`, …) — inapplicable fields are dropped.\n * {@link PageTransition.displayDuration} becomes the page's `/Dur`\n * (auto-advance); omitting it removes any existing `/Dur`. Re-calling replaces\n * the prior transition in full (idempotent). Returns `true` on success,\n * `false` for an unknown style, a negative/non-finite `duration`/`scale`/\n * `displayDuration`, or a bad page number.\n *\n * @example\n * // Kiosk slideshow: every page wipes in over 0.5 s, auto-advancing after 5 s.\n * for (let p = 1; p <= doc.pageCount(); p++) {\n * doc.setPageTransition(p, { style: \"wipe\", duration: 0.5, displayDuration: 5 });\n * }\n */\n setPageTransition(page: number, trans: PageTransition): boolean {\n const style = PAGE_TRANSITION_STYLES.indexOf(trans.style);\n if (style < 0) return false;\n const dimension =\n trans.dimension === \"horizontal\" ? 0 : trans.dimension === \"vertical\" ? 1 : -1;\n const motion = trans.motion === \"inward\" ? 0 : trans.motion === \"outward\" ? 1 : -1;\n const direction =\n trans.direction === undefined ? -2 : trans.direction === \"none\" ? -1 : trans.direction;\n const flyB = trans.flyAreaOpaque === undefined ? -1 : trans.flyAreaOpaque ? 1 : 0;\n return (\n this.ex().gp_set_page_transition(\n this.h,\n page,\n style,\n trans.duration ?? Number.NaN,\n dimension,\n motion,\n direction,\n trans.scale ?? Number.NaN,\n flyB,\n trans.displayDuration ?? Number.NaN\n ) === 0\n );\n }\n\n /**\n * The presentation transition declared on `page` (1-based), or `null` when the\n * page has no `/Trans` (ISO 32000-1 §12.4.4). Optional fields that do not apply\n * to the recovered style are omitted from the result.\n */\n getPageTransition(page: number): PageTransition | null {\n return this.g._jsonOrNull<PageTransition>((o) => this.ex().gp_page_transition_json(this.h, page, o));\n }\n\n /**\n * Remove any presentation transition from `page` (1-based) — drops the page's\n * `/Trans` dictionary and its `/Dur` auto-advance entry. A no-op if neither is\n * present. Returns `true` on success.\n */\n clearPageTransition(page: number): boolean {\n return this.ex().gp_clear_page_transition(this.h, page) === 0;\n }\n\n /**\n * Bake a running header onto every in-range page (idempotent: re-baking\n * replaces the prior header). Returns `true` on success.\n */\n setHeader(spec: HeaderFooterSpec): boolean {\n return (\n this.g._withStr(JSON.stringify(spec), (p, l) => this.ex().gp_set_header(this.h, p, l)) === 0\n );\n }\n\n /** Bake a running footer onto every in-range page (idempotent). */\n setFooter(spec: HeaderFooterSpec): boolean {\n return (\n this.g._withStr(JSON.stringify(spec), (p, l) => this.ex().gp_set_footer(this.h, p, l)) === 0\n );\n }\n\n /** Remove every previously-baked running header from all pages. */\n removeHeaders(): boolean {\n return this.ex().gp_remove_headers(this.h) === 0;\n }\n\n /** Remove every previously-baked running footer from all pages. */\n removeFooters(): boolean {\n return this.ex().gp_remove_footers(this.h) === 0;\n }\n\n /**\n * Detect the running header/footer already baked into this PDF — the reader\n * counterpart of {@link GigaPdfDoc.setHeader} / {@link GigaPdfDoc.setFooter}.\n * Each side is a {@link HeaderFooterSpec} (with its recovered `text`) when a\n * baked `/GPHF` span is present, or `null` when absent. The `text` is faithful\n * (the per-page-substituted text of the first matching page); `align`,\n * `fontSize`, `color`, etc. are best-effort defaults, since the bake records\n * only the drawn text. Use it to reflect existing document state (e.g. a\n * Word-like editor toggle).\n */\n headerFooter(): { header: HeaderFooterSpec | null; footer: HeaderFooterSpec | null } {\n return this.g._json<{ header: HeaderFooterSpec | null; footer: HeaderFooterSpec | null }>((o) =>\n this.ex().gp_header_footer(this.h, o),\n );\n }\n\n /**\n * Bake a **rich**, Word-like running header/footer from a {@link RunningHeaderFooter}\n * `def` (the source of truth — stored in the editor-meta sidecar, its visible\n * `/GPHF` band regenerated on every page). Text is set in an embedded font\n * (each item's `fontRef`, else the bundled OFL face — never base-14) and images\n * via the same path as {@link addImage}; both live inside the `/GPHF` span, so\n * they are excluded from {@link elements}/{@link textRuns} and masked by\n * {@link renderPageExcludingMarkedContent}. Idempotent (re-baking replaces the\n * prior band).\n *\n * `opts.date` is the bake date for `{{date}}` (the engine is clockless — pass\n * e.g. `new Date().toISOString().slice(0, 10)`); omit to fall back to the\n * document's `/Info` date. `opts.images` supplies the pixels each\n * `HFItem` of `type: \"image\"` references by `imageId` — an iterable of\n * `[imageId, bytes]` (a `Map<number, Uint8Array>` works directly); an image\n * whose id is absent is skipped. Returns `true` on success.\n *\n * @example\n * doc.setRunningHeaderFooter(\n * {\n * default: {\n * header: [{ type: \"image\", imageId: 1, w: 80, h: 24, anchor: \"left\" }],\n * footer: [{ type: \"text\", text: \"{{title}} — {{page}}/{{pages}}\", anchor: \"center\" }],\n * },\n * firstPage: { header: [], footer: [] }, // blank cover\n * differentFirstPage: true,\n * differentOddEven: true,\n * evenPage: { header: [{ type: \"text\", text: \"{{page}}\", anchor: \"left\" }], footer: [] },\n * oddPage: { header: [{ type: \"text\", text: \"{{page}}\", anchor: \"right\" }], footer: [] },\n * },\n * { date: new Date().toISOString().slice(0, 10), images: new Map([[1, logoPng]]) }\n * );\n */\n setRunningHeaderFooter(\n def: RunningHeaderFooter,\n opts?: { date?: string; images?: Iterable<[number, Uint8Array]> }\n ): boolean {\n const entries = opts?.images ? Array.from(opts.images) : [];\n // Image blob: [u32 count] then, per entry, [u32 imageId][u32 byteLen][bytes].\n let total = 4;\n for (const [, bytes] of entries) total += 8 + bytes.length;\n const blob = new Uint8Array(total);\n const dv = new DataView(blob.buffer);\n let off = 0;\n dv.setUint32(off, entries.length >>> 0, true);\n off += 4;\n for (const [id, bytes] of entries) {\n dv.setUint32(off, id >>> 0, true);\n off += 4;\n dv.setUint32(off, bytes.length >>> 0, true);\n off += 4;\n blob.set(bytes, off);\n off += bytes.length;\n }\n return (\n this.g._withStr(JSON.stringify(def), (dp, dl) =>\n this.g._withOptStr(opts?.date, (tp, tl) =>\n this.g._withBytes(blob, (ip, il) =>\n this.ex().gp_set_running_header_footer(this.h, dp, dl, tp, tl, ip, il)\n )\n )\n ) === 0\n );\n }\n\n /**\n * The rich {@link RunningHeaderFooter} definition recorded by\n * {@link setRunningHeaderFooter} (read from the editor-meta sidecar — the\n * source of truth), or a minimal one reconstructed from a legacy flat\n * {@link setHeader}/{@link setFooter} bake, or `null` when neither is present.\n */\n runningHeaderFooter(): RunningHeaderFooter | null {\n return this.g._jsonOrNull<RunningHeaderFooter>((o) =>\n this.ex().gp_running_header_footer(this.h, o)\n );\n }\n\n // render\n renderPage(page: number, scale = 1): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_render_page(this.h, page, scale, o));\n }\n\n /**\n * Rasterize a page to a PNG **without the page content stream's text** — glyphs\n * are suppressed while gradients, shadings, images, vectors and patterns are\n * preserved. Form-field **widget** appearances are omitted (the editor re-shows\n * their values as an editable overlay, so baking them in would double every\n * field); other annotation appearances (stamps, highlights, ink) are still\n * painted. Use this to paint a text-free raster background the editor can\n * overlay real, editable text on top of.\n */\n renderPageNoText(page: number, scale = 1): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_render_page_no_text(this.h, page, scale, o));\n }\n\n /**\n * Rasterize a page to a PNG while **omitting** the given top-level element\n * `indices` (from {@link GigaPdfDoc.elements}). Each excluded element paints nothing\n * — fills, strokes, shadings, images and text alike — while everything else\n * (including the non-text content of non-excluded elements) renders normally.\n * Use it to paint a background without specific elements and overlay live,\n * editable versions on top. Generalises {@link renderPageNoText} (which\n * suppresses *all* text). Like {@link renderPageNoText}, form-field **widget**\n * appearances are omitted (the editor re-shows them as an editable overlay);\n * other annotation appearances are painted. An empty `indices` renders the full\n * page; unknown indices are ignored.\n */\n renderPageExcluding(page: number, indices: number[], scale = 1): Uint8Array {\n return this.g._buffer((o) =>\n this.g._withU32(indices, (p, c) =>\n this.ex().gp_render_page_excluding(this.h, page, p, c, scale, o)\n )\n );\n }\n\n /**\n * Rasterize a page to a PNG **excluding the ops inside a baked marked-content\n * span** named `marker` — and, when `skipText` is true, the page's text too — in\n * a **single** raster pass. For `marker = \"GPHF\"` (the default) this drops the\n * baked running header/footer band: the extraction views ({@link elements},\n * {@link textRuns}) already omit that band (it is never editable body content),\n * and this render omits it from the picture so it cannot double against an\n * editable overlay. With `skipText = true` it is the editor's text-free display\n * background minus the band; with `skipText = false`, the full page minus the\n * band. Like {@link renderPageNoText}, form-field widget appearances are omitted.\n */\n renderPageExcludingMarkedContent(\n page: number,\n scale = 1,\n skipText = true,\n marker = \"GPHF\"\n ): Uint8Array {\n return this.g._buffer((o) =>\n this.g._withStr(marker, (p, l) =>\n this.ex().gp_render_page_excluding_marked_content(\n this.h,\n page,\n scale,\n skipText ? 1 : 0,\n p,\n l,\n o\n )\n )\n );\n }\n\n // fonts — embed a downloaded font, then add real selectable text\n /**\n * Embed an outline font program as a Type0 font and return its object number\n * (pass to {@link addText} / re-encoded by {@link replaceText}). Accepts\n * **any** font file — glyf **TrueType** (`.ttf`) or **OpenType-CFF**\n * (`.otf`/`OTTO`), flavour auto-detected — so `font` may be a Google Font the\n * host fetched, an `.otf` you supply, or a face pulled out of a document with\n * {@link extractFont}. Returns 0 on a malformed/unsupported program.\n */\n embedFont(family: string, font: Uint8Array): number {\n const b = enc.encode(family);\n const famPtr = this.g._toWasm(b);\n const obj = this.g._withBytes(font, (p, l) =>\n this.ex().gp_embed_font(this.h, famPtr, b.length, p, l)\n );\n this.g._free(famPtr, b.length);\n return obj;\n }\n /**\n * Draw real, selectable text at `(x, y)` (PDF points, origin bottom-left) in a\n * font embedded with {@link embedFont} (`fontObj`). Works with **any** embedded\n * face — glyf TrueType or OpenType-CFF — encoding each character through the\n * font's char→glyph map (Identity-H, 2-byte glyph ids). `rgb` is packed\n * `0xRRGGBB`; `rotationDeg` rotates CCW about `(x, y)`. For a built-in base-14\n * family with no embedding, use {@link addStandardText}.\n *\n * Pass `opts` to bake **text decorations** into the run: `{ underline: true }`\n * draws a rule just below the baseline, `{ strikethrough: true }` a rule near\n * the x-height — both span the run's advance and are filled in the text colour.\n * Omitting `opts` is fully backward-compatible (no decoration).\n */\n addText(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n fontObj: number,\n rgb = 0,\n opacity = 1,\n rotationDeg = 0,\n opts?: { underline?: boolean; strikethrough?: boolean }\n ): boolean {\n const underline = opts?.underline ? 1 : 0;\n const strikethrough = opts?.strikethrough ? 1 : 0;\n return (\n this.g._withStr(text, (p, l) =>\n this.ex().gp_add_text_styled(\n this.h,\n page,\n x,\n y,\n size,\n p,\n l,\n fontObj,\n RGB(rgb),\n opacity,\n rotationDeg,\n underline,\n strikethrough\n )\n ) === 0\n );\n }\n /**\n * Draw `text` at `(x, y)` in a built-in **base-14 standard font** (`fontName`,\n * e.g. `\"Times-Bold\"`, `\"Courier-Oblique\"`, `\"Symbol\"`) — no embedding needed,\n * every viewer ships these 14. For any other family embed a TrueType with\n * {@link embedFont} (a Google Font fetched by the host, or one pulled out of\n * the document with {@link extractFont}) and use {@link addText}. Returns\n * `false` on an unknown font name or bad page.\n *\n * Pass `opts` to bake **text decorations** into the run: `{ underline: true }`\n * and/or `{ strikethrough: true }` draw filled rules in the text colour.\n * Omitting `opts` is fully backward-compatible (no decoration).\n */\n addStandardText(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n fontName: string,\n rgb = 0,\n opacity = 1,\n rotationDeg = 0,\n opts?: { underline?: boolean; strikethrough?: boolean }\n ): boolean {\n const underline = opts?.underline ? 1 : 0;\n const strikethrough = opts?.strikethrough ? 1 : 0;\n return (\n this.g._withStr(text, (tp, tl) =>\n this.g._withStr(fontName, (fp, fl) =>\n this.ex().gp_add_text_standard_styled(\n this.h,\n page,\n x,\n y,\n size,\n tp,\n tl,\n fp,\n fl,\n RGB(rgb),\n opacity,\n rotationDeg,\n underline,\n strikethrough\n )\n )\n ) === 0\n );\n }\n /**\n * Stamp a standard-**Helvetica** watermark (no font embed needed): `text` at\n * `(x, y)`, rotated `rotationDeg`° counter-clockwise, `rgb` packed `0xRRGGBB`,\n * `opacity` 0–1. Pair with {@link GigaPdfEngine.helveticaWidth} for centring.\n */\n addWatermark(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n rgb = 0x808080,\n opacity = 0.25,\n rotationDeg = 0\n ): boolean {\n return (\n this.g._withStr(text, (p, l) =>\n this.ex().gp_add_watermark(this.h, page, x, y, size, p, l, RGB(rgb), opacity, rotationDeg)\n ) === 0\n );\n }\n neededFonts(): string[] {\n return this.g._json((o) => this.ex().gp_needed_fonts(this.h, o));\n }\n /**\n * Extract an embedded font program by (fuzzy) `/BaseFont` name — so a host\n * editor can re-embed the document's own font when re-baking edited text and\n * keep the original glyphs. Returns the raw decoded bytes and the program\n * format (`truetype` embeds directly; `cff`/`type1` need a TTF conversion),\n * or `null` when nothing embedded matches.\n */\n extractFont(\n name: string\n ): { format: \"truetype\" | \"cff\" | \"type1\"; bytes: Uint8Array } | null {\n const buf = this.g._withStr(name, (p, l) =>\n this.g._buffer((o) => this.ex().gp_extract_font(this.h, p, l, o))\n );\n if (buf.length === 0) return null;\n const format = buf[0] === 1 ? \"truetype\" : buf[0] === 2 ? \"cff\" : \"type1\";\n return { format, bytes: buf.subarray(1) };\n }\n /**\n * The fonts **embedded** in the document — each `{ baseFont, format }`. Pair\n * with {@link extractFont} to pull a font's bytes out and re-embed them via\n * {@link embedFont}, e.g. to draw new text (with {@link addText}) in a face\n * the document already carries — no external font file needed.\n */\n embeddedFonts(): EmbeddedFont[] {\n return this.g._json((o) => this.ex().gp_embedded_fonts_json(this.h, o));\n }\n\n // convert PDF → X\n toText(): string {\n return this.g._str((o) => this.ex().gp_to_text(this.h, o));\n }\n toHtml(): string {\n return this.g._str((o) => this.ex().gp_to_html(this.h, o));\n }\n /**\n * Reconstruct this PDF into the **unified editable model** — the\n * format-neutral {@link GigaDocument} tree (sections → pages → blocks → runs)\n * that every format lowers into. Edit it with\n * {@link GigaPdfEngine.applyModelOps}, then export it to any target with\n * {@link GigaPdfEngine.modelToDocx} / {@link GigaPdfEngine.modelToPdf} / … —\n * the foundation for editing any document indifferently of its source format.\n */\n toModel(): GigaDocument {\n return JSON.parse(this.g._str((o) => this.ex().gp_model_from_pdf(this.h, o))) as GigaDocument;\n }\n toDocx(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_docx(this.h, o));\n }\n toPptx(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_pptx(this.h, o));\n }\n /** Convert to an editable OpenDocument Presentation (`.odp`). */\n toOdp(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_odp(this.h, o));\n }\n toOdt(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_odt(this.h, o));\n }\n toXlsx(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_xlsx(this.h, o));\n }\n toOds(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_ods(this.h, o));\n }\n toRtf(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_rtf(this.h, o));\n }\n /**\n * Re-serialize the document as **PDF/A** (archival).\n *\n * `level` selects the conformance flavour (default `\"pdfa-2b\"`):\n * - `\"pdfa-1b\"` — ISO 19005-1, based on PDF 1.4.\n * - `\"pdfa-1a\"` — ISO 19005-1 **Tagged PDF** (level A): 1b + a logical\n * structure tree, marked content and `/Lang`. Built from the structure the\n * engine reconstructs (paragraphs, headings, tables, lists).\n * - `\"pdfa-2b\"` — ISO 19005-2 (default).\n * - `\"pdfa-2u\"` — like 2b but requires every glyph Unicode-mapped (a\n * `/ToUnicode` CMap on each font); only validator-clean when the source\n * fonts already carry one — otherwise prefer `\"pdfa-2b\"`.\n * - `\"pdfa-2a\"` — ISO 19005-2 **Tagged PDF** (level A): 2u + a logical\n * structure tree and marked content (`/StructTreeRoot`, `/MarkInfo`).\n * - `\"pdfa-3b\"` — ISO 19005-3; permits embedded file attachments.\n *\n * Full conformance also requires every font embedded — this method does not\n * embed missing fonts (see the Rust `to_pdfa_level` docs). For the level-A\n * (`1a`/`2a`) flavours the tagging is rendering-neutral: it only inserts\n * balanced marked-content operators and a structure tree, never changing the\n * page appearance.\n */\n toPdfA(\n level:\n | \"pdfa-1b\"\n | \"pdfa-1a\"\n | \"pdfa-2b\"\n | \"pdfa-2u\"\n | \"pdfa-2a\"\n | \"pdfa-3b\" = \"pdfa-2b\",\n ): Uint8Array {\n return this.g._withStr(level, (p, l) =>\n this.g._buffer((o) => this.ex().gp_to_pdfa(this.h, p, l, o)),\n );\n }\n\n /**\n * Author a **tagged (accessible) PDF** — a `/StructTreeRoot` logical-structure\n * tree (`P`/`H1`–`H6`/`Table`/`L`/`Figure` …) with marked content, `/MarkInfo`,\n * `/Lang`, `/RoleMap` and `/Alt` on figures — **without** forcing PDF/A. Pass\n * `{ pdfUa: true }` to also stamp the PDF/UA-1 identifier (ISO 14289). If the\n * document has no reconstructable structure the plain PDF is returned.\n * ISO 32000-1 §14.7/§14.8.\n */\n toTagged(opts: { pdfUa?: boolean } = {}): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_tagged(this.h, opts.pdfUa ? 1 : 0, o));\n }\n\n /**\n * The number of taggable **figures** the engine reconstructs across the whole\n * document — the valid range `0..figureCount()` for {@link setFigureAlt}'s\n * `index`. Each figure is an image the geometric reconstruction surfaces; the\n * Tagged-PDF / PDF-A-level-A export emits one `/Figure` structure element per\n * figure, in this same order.\n */\n figureCount(): number {\n return this.ex().gp_figure_count(this.h);\n }\n\n /**\n * Attach **author-supplied alternate text** (`/Alt`) to a figure so assistive\n * technology can describe the image (WCAG / PDF/UA, ISO 32000-1 §14.9.3).\n *\n * `index` is the **document-global figure index** — figures are numbered\n * `0, 1, 2, …` in page order, then in page-content order within each page (the\n * Nth image of the whole document is figure `N`; {@link figureCount} bounds the\n * range). The text lands on the matching `/Figure` structure element's `/Alt`\n * when an accessible export is produced — {@link toTagged} or {@link toPdfA}\n * with `\"pdfa-1a\"`/`\"pdfa-2a\"`. Figures with no author-supplied text keep a\n * generic non-empty placeholder, so the output stays structurally valid even\n * for unlabeled figures.\n *\n * Returns `true` on success; `false` if `alt` is empty (a `/Alt` must be\n * non-empty) or the call otherwise fails.\n */\n setFigureAlt(index: number, alt: string): boolean {\n return (\n this.g._withStr(alt, (p, l) => this.ex().gp_set_figure_alt(this.h, index, p, l)) === 0\n );\n }\n\n // security\n /**\n * Serialize the document encrypted with the PDF Standard Security Handler.\n * Defaults to **AES-256 (R6)**. `fileId` is the document `/ID` (any stable\n * hex/string). For AES-256 a **secret 32-byte key** is required — it is taken\n * from `opts.keySeed` or generated with Web Crypto; RC4/AES-128 derive their\n * key from the password and ignore it.\n */\n saveEncrypted(\n password: string,\n fileId: string,\n opts: {\n ownerPassword?: string;\n algorithm?: \"rc4\" | \"aes128\" | \"aes256\";\n /**\n * Named access permissions (ISO 32000-1 Table 22). Omitted flags default\n * to **granted**. Takes precedence over `permissions` when present.\n */\n flags?: Partial<PdfPermissions>;\n /**\n * Raw signed 32-bit `/P` bitmask. Use `flags` (above) for a readable API.\n * Defaults to all permissions granted when neither is given.\n */\n permissions?: number;\n keySeed?: Uint8Array;\n } = {}\n ): Uint8Array {\n const algo = opts.algorithm ?? \"aes256\";\n const algoCode = algo === \"rc4\" ? 0 : algo === \"aes128\" ? 1 : 2;\n // Precedence: explicit `flags` → packed /P; else raw `permissions`; else\n // the unrestricted spec-strict baseline (`/P` = -196, all eight granted).\n const permissions =\n opts.flags !== undefined\n ? this.g.permissionsToP(opts.flags)\n : opts.permissions ?? this.g.permissionsToP();\n let key = opts.keySeed ?? new Uint8Array(0);\n if (algoCode === 2 && key.length < 32) {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (!c?.getRandomValues) {\n throw new Error(\n \"AES-256 encryption needs Web Crypto (globalThis.crypto.getRandomValues) or an explicit opts.keySeed\"\n );\n }\n // `getRandomValues` requires an ArrayBuffer-backed view (not ArrayBufferLike).\n const fresh = new Uint8Array(32);\n c.getRandomValues(fresh);\n key = fresh;\n }\n return this.g._withStr(password, (pwP, pwL) =>\n this.g._withOptStr(opts.ownerPassword, (oP, oL) =>\n this.g._withStr(fileId, (idP, idL) =>\n this.g._withBytes(key, (kP, kL) =>\n this.g._buffer((o) =>\n this.ex().gp_save_encrypted(\n this.h,\n pwP,\n pwL,\n oP,\n oL,\n idP,\n idL,\n kP,\n kL,\n algoCode,\n permissions,\n o\n )\n )\n )\n )\n )\n );\n }\n\n /**\n * Re-encrypt an already-opened (decrypted) document with **new** passwords,\n * discarding the prior encryption (ISO 32000-1 §7.6). Opening with the old\n * password is what authorises the change. Mirrors {@link saveEncrypted} plus\n * `encryptMetadata` (when `false`, the metadata stream is left in the clear).\n */\n changePasswords(\n newPassword: string,\n fileId: string,\n opts: {\n ownerPassword?: string;\n algorithm?: \"rc4\" | \"aes128\" | \"aes256\";\n flags?: Partial<PdfPermissions>;\n permissions?: number;\n keySeed?: Uint8Array;\n encryptMetadata?: boolean;\n } = {}\n ): Uint8Array {\n const algo = opts.algorithm ?? \"aes256\";\n const algoCode = algo === \"rc4\" ? 0 : algo === \"aes128\" ? 1 : 2;\n const permissions =\n opts.flags !== undefined\n ? this.g.permissionsToP(opts.flags)\n : opts.permissions ?? this.g.permissionsToP();\n let key = opts.keySeed ?? new Uint8Array(0);\n if (algoCode === 2 && key.length < 32) {\n key = cryptoRandom(32);\n }\n const encMeta = opts.encryptMetadata ?? true;\n return this.g._withStr(newPassword, (pwP, pwL) =>\n this.g._withOptStr(opts.ownerPassword, (oP, oL) =>\n this.g._withStr(fileId, (idP, idL) =>\n this.g._withBytes(key, (kP, kL) =>\n this.g._buffer((o) =>\n this.ex().gp_change_passwords(\n this.h, pwP, pwL, oP, oL, idP, idL, kP, kL, algoCode, permissions,\n encMeta ? 1 : 0, o\n )\n )\n )\n )\n )\n );\n }\n\n /**\n * Strip encryption from an already-opened (decrypted) document, returning a\n * **plaintext** PDF. The document must have been opened with a valid password.\n */\n removeEncryption(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_remove_encryption(this.h, o));\n }\n\n /**\n * Encrypt the document to one or more **X.509 recipients** (public-key /\n * certificate security, ISO 32000-1 §7.6.5, `/Filter /Adobe.PubSec`): only a\n * holder of a recipient private key can open it — no shared password.\n * `certificates` are DER X.509 certs. `seed`/`rngSeed` default to Web Crypto\n * randomness. Open the result with {@link GigaPdfEngine.openWithPrivateKey}.\n */\n encryptForRecipients(\n certificates: Uint8Array[],\n opts: {\n flags?: Partial<PdfPermissions>;\n permissions?: number;\n aes256?: boolean;\n encryptMetadata?: boolean;\n seed?: Uint8Array;\n rngSeed?: Uint8Array;\n } = {}\n ): Uint8Array {\n if (certificates.length === 0) {\n throw new Error(\"encryptForRecipients needs at least one recipient certificate\");\n }\n const total = certificates.reduce((n, c) => n + c.length, 0);\n const blob = new Uint8Array(total);\n const lens: number[] = [];\n let off = 0;\n for (const c of certificates) {\n blob.set(c, off);\n off += c.length;\n lens.push(c.length);\n }\n const permissions =\n opts.flags !== undefined\n ? this.g.permissionsToP(opts.flags)\n : opts.permissions ?? this.g.permissionsToP();\n const aes256 = opts.aes256 ?? true;\n const encMeta = opts.encryptMetadata ?? true;\n const seed = opts.seed ?? cryptoRandom(20);\n const rng = opts.rngSeed ?? cryptoRandom(32);\n const out = this.g._withBytes(blob, (cP, cL) =>\n this.g._withU32(lens, (lP, lC) =>\n this.g._withBytes(seed, (sP, sL) =>\n this.g._withBytes(rng, (rP, rL) =>\n this.g._buffer((o) =>\n this.ex().gp_encrypt_for_recipients(\n this.h, cP, cL, lP, lC, permissions, aes256 ? 1 : 0, encMeta ? 1 : 0,\n sP, sL, rP, rL, o\n )\n )\n )\n )\n )\n );\n if (out.length === 0) {\n throw new Error(\"encryptForRecipients failed (invalid recipient certificate?)\");\n }\n return out;\n }\n\n /** Self-signed digital signature. `random` ≥ 256 bytes from crypto.getRandomValues. */\n sign(fields: string, random: Uint8Array, keyBits = 2048): Uint8Array {\n const rPtr = this.g._toWasm(random);\n const out = this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) => this.ex().gp_sign(this.h, fP, fL, rPtr, random.length, keyBits, o))\n );\n this.g._free(rPtr, random.length);\n return out;\n }\n\n /**\n * **Certify** the document (DocMDP) — like {@link sign} but also declares which\n * later changes are allowed: `docmdpLevel` is `1` (no changes), `2` (form-fill\n * + sign) or `3` (also annotate). `fields` is the same tab-separated string as\n * {@link sign} (`name⇥reason⇥date⇥notBefore⇥notAfter`).\n */\n certify(fields: string, random: Uint8Array, docmdpLevel: 1 | 2 | 3, keyBits = 2048): Uint8Array {\n const rPtr = this.g._toWasm(random);\n const out = this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) =>\n this.ex().gp_sign_certify(this.h, fP, fL, rPtr, random.length, keyBits, docmdpLevel, o)\n )\n );\n this.g._free(rPtr, random.length);\n return out;\n }\n\n /**\n * List every signature on the document (each `/Sig` field's `/V`) with its\n * metadata and `/ByteRange`. For cryptographic validity call\n * {@link verifySignatures}.\n */\n signatures(): SignatureInfo[] {\n return this.g._json((o) => this.ex().gp_signatures_json(this.h, o));\n }\n\n /**\n * Cryptographically verify every signature against `pdf` — the **original\n * bytes** this document was opened from. Each report carries `byteRangeOk`,\n * `digestOk` (content integrity), `signatureOk` (the RSA signature),\n * `coversWholeDocument`, the signer CN, and the algorithm.\n */\n verifySignatures(pdf: Uint8Array): SignatureReport[] {\n return this.g._withBytes(pdf, (p, l) =>\n this.g._json((o) => this.ex().gp_verify_signatures(this.h, p, l, o))\n );\n }\n /**\n * Sign with a PKCS#12 (`.p12`/`.pfx`) identity — a CA-issued / eIDAS\n * certificate and its RSA key, imported natively (no external crypto). `opts`\n * populates the signature dictionary: `name` (`/Name`), `reason` (`/Reason`),\n * `date` (`/M`, a PDF date string e.g. `D:20260616120000Z`), and the optional\n * `location` (`/Location`) and `contactInfo` (`/ContactInfo`). Throws a single\n * generic error on a wrong password, malformed file, unsupported cipher, or\n * missing certificate.\n */\n signP12(p12: Uint8Array, password: string, opts: SignP12Options = {}): Uint8Array {\n const fields = [\n opts.name ?? \"\",\n opts.reason ?? \"\",\n opts.date ?? \"\",\n opts.location ?? \"\",\n opts.contactInfo ?? \"\",\n ].join(\"\\t\");\n const p12Ptr = this.g._toWasm(p12);\n const out = this.g._withStr(password, (pwP, pwL) =>\n this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) =>\n this.ex().gp_sign_p12(this.h, p12Ptr, p12.length, pwP, pwL, fP, fL, o)\n )\n )\n );\n this.g._free(p12Ptr, p12.length);\n if (out.length === 0) {\n throw new Error(\n \"PKCS#12 signing failed: invalid certificate, password, or unsupported file\"\n );\n }\n return out;\n }\n /**\n * Sign with an embedded **RFC 3161 trusted timestamp** (PAdES-B-T). Unlike\n * {@link sign}/{@link signP12} this is `async`: the timestamp requires a\n * network round trip to a TSA, so the method runs the engine's two-phase flow\n * — build the signature → POST the `TimeStampReq` to the TSA → embed the\n * returned token — with the HTTP in between.\n *\n * The signing identity is `opts.p12` (+ `opts.password`) when supplied, else a\n * generated self-signed digital ID from `opts.random` (+ `notBefore`/\n * `notAfter`). `opts.tsaUrl` is the TSA endpoint (e.g. FreeTSA\n * `https://freetsa.org/tsr`); pass `opts.tsaFetch` to customise the request\n * (auth, proxy, SSRF allow-list). Throws a single generic error on any failure\n * (bad identity, TSA HTTP error, malformed response, or signature too large).\n */\n async signTimestamped(opts: SignTsaOptions): Promise<Uint8Array> {\n const usingP12 = opts.p12 != null && opts.p12.length > 0;\n if (!usingP12 && (opts.random == null || opts.random.length < 256)) {\n throw new Error(\n \"signTimestamped: self-signed path needs `random` ≥ 256 bytes (or pass a `p12`)\"\n );\n }\n const fields = [\n opts.name ?? \"\",\n opts.reason ?? \"\",\n opts.date ?? \"\",\n opts.location ?? \"\",\n opts.contactInfo ?? \"\",\n opts.notBefore ?? \"\",\n opts.notAfter ?? \"\",\n ].join(\"\\t\");\n\n const rand = opts.random ?? new Uint8Array(0);\n const p12 = opts.p12 ?? new Uint8Array(0);\n const nonce = opts.nonce ?? new Uint8Array(0);\n const keyBits = opts.keyBits ?? 2048;\n\n // Phase 1: build the signature, get the TimeStampReq to POST.\n const rPtr = this.g._toWasm(rand);\n const p12Ptr = this.g._toWasm(p12);\n const noncePtr = this.g._toWasm(nonce);\n let request: Uint8Array;\n try {\n request = this.g._withStr(opts.password ?? \"\", (pwP, pwL) =>\n this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) =>\n this.ex().gp_sign_prepare_tsa(\n this.h,\n fP,\n fL,\n rPtr,\n rand.length,\n keyBits,\n p12Ptr,\n p12.length,\n pwP,\n pwL,\n noncePtr,\n nonce.length,\n o\n )\n )\n )\n );\n } finally {\n this.g._free(rPtr, rand.length);\n this.g._free(p12Ptr, p12.length);\n this.g._free(noncePtr, nonce.length);\n }\n if (request.length === 0) {\n throw new Error(\n \"timestamped signing failed: invalid identity or could not build the timestamp request\"\n );\n }\n\n // Host round trip: POST the request to the TSA, read the response.\n const response = opts.tsaFetch\n ? await opts.tsaFetch(request, opts.tsaUrl)\n : await defaultTsaPost(opts.tsaUrl, request);\n\n // Phase 2: embed the timestamp token, finalize the signed PDF.\n const tokenPtr = this.g._toWasm(response);\n let out: Uint8Array;\n try {\n out = this.g._buffer((o) =>\n this.ex().gp_sign_finish_tsa(this.h, tokenPtr, response.length, o)\n );\n } finally {\n this.g._free(tokenPtr, response.length);\n }\n if (out.length === 0) {\n throw new Error(\n \"timestamped signing failed: TSA response rejected or signature too large for the reserved space\"\n );\n }\n return out;\n }\n\n /**\n * Sign with **long-term validation** material embedded (PAdES-B-LT, or B-LTA\n * with `opts.archiveTimestamp`). Builds a B-T signature ({@link signTimestamped}),\n * then fetches the certificate chain's revocation material (OCSP responses /\n * CRLs, by URL **from the certificates** — the engine computes which URLs, the\n * host fetches) and stores it in a `/DSS`, so the signature validates long after\n * the certificates expire or are revoked. With `archiveTimestamp` a document\n * timestamp over the whole file (DSS included) is added for renewable archival.\n *\n * `async`, multi-round-trip: one TSA POST for the B-T timestamp, one OCSP/CRL\n * fetch per chain certificate, and (if `archiveTimestamp`) a second TSA POST.\n * Unreachable responders are skipped — the DSS is built from whatever resolves;\n * a self-signed identity (no AIA/CRL-DP) simply yields a `/DSS/Certs`-only store.\n * Override `tsaFetch`/`revocationFetch`/`crlFetch` to add auth, proxies, or an\n * SSRF allow-list. Throws on a fatal failure (bad identity, B-T signature, or a\n * malformed PDF the DSS can't chain to).\n */\n async signLtv(opts: SignLtvOptions): Promise<Uint8Array> {\n // 1. The B-T signature is the foundation (its /Contents holds the chain).\n const signed = await this.signTimestamped(opts);\n\n // 2. Ask the engine which validation material to fetch (per certificate).\n const nonce = opts.nonce ?? new Uint8Array(0);\n const targetsJson = this.withSignedPdf(signed, (pdfPtr, pdfLen) => {\n const noncePtr = this.g._toWasm(nonce);\n try {\n return dec.decode(\n this.g._buffer((o) =>\n this.ex().gp_ltv_targets(pdfPtr, pdfLen, noncePtr, nonce.length, o)\n )\n );\n } finally {\n this.g._free(noncePtr, nonce.length);\n }\n });\n const targets: LtvTarget[] = targetsJson ? JSON.parse(targetsJson) : [];\n\n // 3. Host fetches: chain certs, plus OCSP/CRL per source (best-effort).\n const certs: Uint8Array[] = [];\n const ocsps: Uint8Array[] = [];\n const crls: Uint8Array[] = [];\n const ocspPost = opts.revocationFetch ?? defaultOcspPost;\n const crlGet = opts.crlFetch ?? defaultCrlGet;\n for (const target of targets) {\n certs.push(hexToBytes(target.certHex));\n for (const source of target.sources) {\n try {\n if (source.kind === \"ocsp\") {\n ocsps.push(await ocspPost(hexToBytes(source.requestHex), source.url));\n } else {\n crls.push(await crlGet(source.url));\n }\n } catch {\n // An unreachable responder is non-fatal: the DSS embeds what succeeds.\n }\n }\n }\n\n // 4. Embed the material in a /DSS (incremental update → B-LT).\n let lt = this.applyDss(signed, certs, ocsps, crls);\n\n // 5. Optional B-LTA: a document timestamp over the whole file (DSS included).\n if (opts.archiveTimestamp) {\n lt = await this.appendDocumentTimestamp(lt, opts);\n }\n return lt;\n }\n\n /** Run `fn` with `pdf` copied into wasm memory, freeing it afterwards. */\n private withSignedPdf<T>(pdf: Uint8Array, fn: (ptr: number, len: number) => T): T {\n const ptr = this.g._toWasm(pdf);\n try {\n return fn(ptr, pdf.length);\n } finally {\n this.g._free(ptr, pdf.length);\n }\n }\n\n /** Add the `/DSS` to `signed` as an incremental update (B-LT). */\n private applyDss(\n signed: Uint8Array,\n certs: Uint8Array[],\n ocsps: Uint8Array[],\n crls: Uint8Array[]\n ): Uint8Array {\n const certsBuf = frameBlobs(certs);\n const ocspsBuf = frameBlobs(ocsps);\n const crlsBuf = frameBlobs(crls);\n const pdfPtr = this.g._toWasm(signed);\n const cPtr = this.g._toWasm(certsBuf);\n const oPtr = this.g._toWasm(ocspsBuf);\n const rPtr = this.g._toWasm(crlsBuf);\n let out: Uint8Array;\n try {\n out = this.g._buffer((res) =>\n this.ex().gp_apply_dss(\n pdfPtr,\n signed.length,\n cPtr,\n certsBuf.length,\n oPtr,\n ocspsBuf.length,\n rPtr,\n crlsBuf.length,\n res\n )\n );\n } finally {\n this.g._free(pdfPtr, signed.length);\n this.g._free(cPtr, certsBuf.length);\n this.g._free(oPtr, ocspsBuf.length);\n this.g._free(rPtr, crlsBuf.length);\n }\n if (out.length === 0) {\n throw new Error(\"LTV failed: could not add the /DSS to the signed PDF\");\n }\n return out;\n }\n\n /** Append a document timestamp over the whole `pdf` (B-LTA), TSA round trip\n * included. */\n private async appendDocumentTimestamp(\n pdf: Uint8Array,\n opts: SignLtvOptions\n ): Promise<Uint8Array> {\n const nonce = opts.nonce ?? new Uint8Array(0);\n // Phase 1: build the timestamp shell, get the request.\n const pdfPtr = this.g._toWasm(pdf);\n const noncePtr = this.g._toWasm(nonce);\n let request: Uint8Array;\n try {\n request = this.g._buffer((o) =>\n this.ex().gp_doc_timestamp_prepare(this.h, pdfPtr, pdf.length, noncePtr, nonce.length, o)\n );\n } finally {\n this.g._free(pdfPtr, pdf.length);\n this.g._free(noncePtr, nonce.length);\n }\n if (request.length === 0) {\n throw new Error(\"LTV archive timestamp failed: could not build the timestamp request\");\n }\n\n // Host round trip: POST the request to the TSA.\n const response = opts.tsaFetch\n ? await opts.tsaFetch(request, opts.tsaUrl)\n : await defaultTsaPost(opts.tsaUrl, request);\n\n // Phase 2: embed the token, finalize B-LTA.\n const tokenPtr = this.g._toWasm(response);\n let out: Uint8Array;\n try {\n out = this.g._buffer((o) =>\n this.ex().gp_doc_timestamp_finish(this.h, tokenPtr, response.length, o)\n );\n } finally {\n this.g._free(tokenPtr, response.length);\n }\n if (out.length === 0) {\n throw new Error(\n \"LTV archive timestamp failed: TSA response rejected or token too large for the reserved space\"\n );\n }\n return out;\n }\n\n // metadata\n getMetadata(key: string): string {\n return this.g._withStr(key, (p, l) =>\n this.g._str((o) => this.ex().gp_get_metadata(this.h, p, l, o))\n );\n }\n /**\n * Set a **single** Info-dictionary entry (e.g. `\"Title\"`, `\"Author\"`). This\n * touches only `/Info`; use {@link setInfo} to update the typed fields and keep\n * the XMP `/Metadata` packet in sync.\n */\n setMetadata(key: string, value: string): boolean {\n return (\n this.g._withStr(key, (kP, kL) =>\n this.g._withStr(value, (vP, vL) => this.ex().gp_set_metadata(this.h, kP, kL, vP, vL))\n ) === 0\n );\n }\n\n /**\n * The document's XMP metadata packet (catalog `/Metadata`, ISO 32000-1 §14.3.2)\n * as raw bytes, or `null` when the document carries no XMP.\n */\n getXmp(): Uint8Array | null {\n const bytes = this.g._buffer((o) => this.ex().gp_get_xmp(this.h, o));\n return bytes.length === 0 ? null : bytes;\n }\n\n /**\n * Replace (or create) the document's XMP metadata stream (catalog `/Metadata`,\n * stored uncompressed). Accepts a UTF-8 string or raw bytes. Returns `true` on\n * success.\n */\n setXmp(xmp: Uint8Array | string): boolean {\n const bytes = typeof xmp === \"string\" ? new TextEncoder().encode(xmp) : xmp;\n return this.g._withBytes(bytes, (p, l) => this.ex().gp_set_xmp(this.h, p, l)) === 0;\n }\n\n /**\n * Set the standard document-information fields, writing **both** the `/Info`\n * dictionary and a synced XMP `/Metadata` packet so the two never drift. This is\n * a **partial** update — only the fields you provide are changed; omit a field\n * to leave it untouched. Returns `true` on success.\n *\n * @example\n * doc.setInfo({ title: \"Annual Report\", author: \"Ada Lovelace\", keywords: \"finance, 2026\" });\n */\n setInfo(fields: InfoFields): boolean {\n return (\n this.g._withStr(JSON.stringify(fields), (p, l) =>\n this.ex().gp_set_info_json(this.h, p, l)\n ) === 0\n );\n }\n\n // annotations (Acrobat-style markup)\n annotations(page: number): AnnotationInfo[] {\n return this.g._json((o) => this.ex().gp_annotations_json(this.h, page, o));\n }\n removeAnnotation(page: number, index: number): boolean {\n return this.ex().gp_remove_annotation(this.h, page, index) === 0;\n }\n addSquare(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n stroke: number | null = 0,\n fill: number | null = null,\n lineWidth = 1\n ): boolean {\n return (\n this.ex().gp_add_square(\n this.h,\n page,\n x0,\n y0,\n x1,\n y1,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth\n ) === 0\n );\n }\n addHighlight(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0xffff00): boolean {\n return this.ex().gp_add_highlight(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n /**\n * Add a `/Line` annotation from `(x1,y1)` to `(x2,y2)`. When `endArrow` is\n * `true`, an open arrowhead (`/LE [/None /OpenArrow]`) is drawn at the\n * `(x2,y2)` end — a real, editable annotation in conforming readers, ideal\n * for callouts that point at content.\n */\n addLineAnnotation(\n page: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n rgb = 0,\n lineWidth = 1,\n endArrow = false\n ): boolean {\n return (\n this.ex().gp_add_line(this.h, page, x1, y1, x2, y2, RGB(rgb), lineWidth, endArrow ? 1 : 0) === 0\n );\n }\n addFreeText(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n text: string,\n fontSize = 12,\n rgb = 0\n ): boolean {\n return (\n this.g._withStr(text, (p, l) =>\n this.ex().gp_add_free_text(this.h, page, x0, y0, x1, y1, p, l, fontSize, RGB(rgb))\n ) === 0\n );\n }\n addUnderline(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0): boolean {\n return this.ex().gp_add_underline(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n addStrikeOut(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0): boolean {\n return this.ex().gp_add_strike_out(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n /**\n * Add a text-markup annotation (`highlight` | `underline` | `strikeout` |\n * `squiggly`) spanning one or more `quads` (each `[x0, y0, x1, y1]` in PDF\n * user space, bottom-left origin — multi-quad covers wrapped text), with full\n * reviewer metadata. `date` is a PDF date string (e.g. `\"D:20260616T…Z\"`) — the\n * engine has no clock, so the host supplies it.\n */\n addMarkupAnnotation(\n page: number,\n subtype: \"highlight\" | \"underline\" | \"strikeout\" | \"squiggly\",\n quads: Array<[number, number, number, number]>,\n rgb: number,\n opacity: number,\n meta: { contents?: string; author?: string; id?: string; date?: string } = {}\n ): boolean {\n const sub =\n subtype === \"highlight\"\n ? \"Highlight\"\n : subtype === \"underline\"\n ? \"Underline\"\n : subtype === \"strikeout\"\n ? \"StrikeOut\"\n : \"Squiggly\";\n const packed = [\n sub,\n meta.contents ?? \"\",\n meta.author ?? \"\",\n meta.id ?? \"\",\n meta.date ?? \"\",\n ].join(\"\u001f\");\n const flat = quads.flat();\n return (\n this.g._withStr(packed, (mp, ml) =>\n this.g._withF64(flat, (qp, qc) =>\n this.ex().gp_add_markup_annotation(this.h, page, mp, ml, qp, qc, RGB(rgb), opacity)\n )\n ) === 0\n );\n }\n /**\n * Add a sticky-note (`/Text`) annotation: a badge at `rect` (`[x0,y0,x1,y1]`)\n * that opens a popup with `meta.contents`. `icon` is the named icon (`\"Note\"`,\n * `\"Comment\"`, …); `open` sets the initial popup state.\n */\n addTextNote(\n page: number,\n rect: [number, number, number, number],\n rgb: number,\n meta: { contents?: string; author?: string; id?: string; date?: string } = {},\n icon = \"Note\",\n open = false\n ): boolean {\n const packed = [\n meta.contents ?? \"\",\n meta.author ?? \"\",\n meta.id ?? \"\",\n meta.date ?? \"\",\n ].join(\"\u001f\");\n return (\n this.g._withStr(packed, (mp, ml) =>\n this.g._withStr(icon, (ip, il) =>\n this.ex().gp_add_text_note(\n this.h,\n page,\n rect[0],\n rect[1],\n rect[2],\n rect[3],\n mp,\n ml,\n ip,\n il,\n open ? 1 : 0,\n RGB(rgb)\n )\n )\n ) === 0\n );\n }\n /** Freehand ink annotation from one polyline (`points` = flat [x0,y0,x1,y1,…]). */\n addInk(page: number, points: number[], rgb = 0, lineWidth = 1): boolean {\n return (\n this.g._withF64(points, (p, c) => this.ex().gp_add_ink(this.h, page, p, c, RGB(rgb), lineWidth)) ===\n 0\n );\n }\n addStamp(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n label: string,\n rgb = 0xc00000\n ): boolean {\n return (\n this.g._withStr(label, (p, l) =>\n this.ex().gp_add_stamp(this.h, page, x0, y0, x1, y1, p, l, RGB(rgb))\n ) === 0\n );\n }\n\n /**\n * Add a `/Circle` (ellipse) annotation inscribed in `[x0,y0,x1,y1]`. `stroke`\n * (border) and `fill` (interior) are packed `0xRRGGBB` numbers, or `null` to\n * omit. Returns `true` on success.\n */\n addCircleAnnotation(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n stroke: number | null = 0,\n fill: number | null = null,\n lineWidth = 1\n ): boolean {\n return (\n this.ex().gp_add_circle_annot(\n this.h,\n page,\n x0,\n y0,\n x1,\n y1,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth\n ) === 0\n );\n }\n\n /**\n * Add a `/Polygon` annotation — a closed shape through `points` (a flat\n * `[x0, y0, x1, y1, …]` array, PDF user space), with optional `stroke`/`fill`\n * (`0xRRGGBB` or `null`). Returns `true` on success.\n */\n addPolygonAnnotation(\n page: number,\n points: number[],\n stroke: number | null = 0,\n fill: number | null = null,\n lineWidth = 1\n ): boolean {\n return (\n this.g._withF64(points, (p, c) =>\n this.ex().gp_add_polygon_annot(\n this.h,\n page,\n p,\n c,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth\n )\n ) === 0\n );\n }\n\n /**\n * Add a `/PolyLine` annotation — an open path through `points` (a flat\n * `[x0, y0, x1, y1, …]` array). `rgb` is packed `0xRRGGBB`.\n */\n addPolylineAnnotation(page: number, points: number[], rgb = 0, lineWidth = 1): boolean {\n return (\n this.g._withF64(points, (p, c) =>\n this.ex().gp_add_polyline_annot(this.h, page, p, c, RGB(rgb), lineWidth)\n ) === 0\n );\n }\n\n /**\n * Add a `/Caret` annotation — a small upward wedge in `[x0,y0,x1,y1]` marking\n * an insertion point. `rgb` is packed `0xRRGGBB`.\n */\n addCaretAnnotation(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0): boolean {\n return this.ex().gp_add_caret_annot(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n\n /**\n * Regenerate the appearance stream (`/AP /N`) of the 0-based `index`\n * annotation on `page` from its stored geometry, after editing its colour,\n * border or geometry. Returns `true` on success, `false` for a bad index or a\n * subtype whose appearance can't be reconstructed (FreeText/Stamp/Text/Link).\n */\n regenerateAppearance(page: number, index: number): boolean {\n return this.ex().gp_regenerate_appearance(this.h, page, index) === 0;\n }\n\n flattenAnnotations(page: number): number {\n return this.ex().gp_flatten_annotations(this.h, page);\n }\n /**\n * Flatten the interactive form: bake every field widget across all pages into\n * the page content and drop `/AcroForm`, so the document is no longer\n * fillable and {@link fields} returns empty afterwards. Returns the number of\n * widgets baked (0 when there is no form).\n */\n flattenForm(): number {\n return this.ex().gp_flatten_form(this.h);\n }\n /**\n * Inline a page's form XObjects (`/Subtype /Form` invoked via `Do`) into its\n * content stream, **de-sharing** each placement so the former form text/graphics\n * become ordinary page content with real, editable text-run indices (no form\n * sentinel) — the enabler for editing invoice/template text in place via\n * {@link replaceText} / {@link moveElement} / {@link removeElement} instead of\n * the redact+add overlay. Image XObjects are left untouched. Returns the number\n * of form XObjects inlined (every `Do` invocation, since each is de-shared).\n *\n * Distinct from {@link flattenForm}, which flattens **AcroForm** interactive\n * fields (and drops `/AcroForm`); this flattens reusable Form XObjects.\n */\n flattenFormXObjects(page: number): number {\n return this.ex().gp_flatten_form_xobjects(this.h, page);\n }\n\n // hyperlinks\n links(page: number): LinkInfo[] {\n return this.g._json((o) => this.ex().gp_links_json(this.h, page, o));\n }\n addUriLink(page: number, x0: number, y0: number, x1: number, y1: number, uri: string): boolean {\n return (\n this.g._withStr(uri, (p, l) => this.ex().gp_add_uri_link(this.h, page, x0, y0, x1, y1, p, l)) ===\n 0\n );\n }\n addGotoLink(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n targetPage: number\n ): boolean {\n return this.ex().gp_add_goto_link(this.h, page, x0, y0, x1, y1, targetPage) === 0;\n }\n /**\n * Register a named destination `name` → `targetPage` (a whole-page `/Fit`\n * view) in the catalog. Links and bookmarks can then jump by name via\n * {@link addGotoLinkNamed}; because resolution goes through the catalog (not a\n * frozen page number), the anchor survives page extraction/split as long as\n * its page is kept. Re-using a `name` overwrites its target.\n */\n addNamedDest(name: string, targetPage: number): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_add_named_dest(this.h, p, l, targetPage)) === 0\n );\n }\n /** The catalog's named destinations as `{name, page}` pairs. */\n namedDests(): NamedDest[] {\n return this.g._json((o) => this.ex().gp_named_dests_json(this.h, o));\n }\n /**\n * Every embedded file attachment in the document's `/Names /EmbeddedFiles`\n * name tree, decoded. Each {@link Attachment} carries the name-tree key, the\n * filespec display name (`/UF`/`/F`), the embedded stream's MIME (`/Subtype`)\n * and `/Params` dates, and the decoded bytes. Entries that don't resolve to a\n * readable embedded stream are skipped, so the result is only extractable\n * files (the native replacement for a reader's `getAttachments()`).\n */\n attachments(): Attachment[] {\n const raw = this.g._json<Array<Omit<Attachment, 'data'> & { dataBase64: string }>>((o) =>\n this.ex().gp_attachments_json(this.h, o)\n );\n return raw.map(({ dataBase64, ...rest }) => ({\n ...rest,\n data: this.g._fromBase64(dataBase64),\n }));\n }\n\n /**\n * Embed `bytes` as a document-level file attachment named `name`\n * (`/Names /EmbeddedFiles`, ISO 32000-1 §7.11.4). Re-using a `name` **replaces**\n * that attachment; the bytes are stored FlateDecode-compressed. Returns `true`\n * on success (`false` e.g. for an empty name).\n */\n addAttachment(name: string, bytes: Uint8Array, opts: AttachmentOptions = {}): boolean {\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withBytes(bytes, (bp, bl) =>\n this.g._withOptStr(opts.mime ?? \"\", (mp, ml) =>\n this.g._withOptStr(opts.description ?? \"\", (dp, dl) =>\n this.ex().gp_add_attachment(this.h, np, nl, bp, bl, mp, ml, dp, dl)\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Embed `bytes` as an **associated file** (`/AF`, PDF/A-3) named `name` with the\n * given {@link AfRelationship} — the mechanism Factur-X / ZUGFeRD / Order-X use\n * to carry their invoice XML (`\"alternative\"`). The file is also a normal\n * attachment, is linked from the catalog `/AF` array, and its filespec carries\n * `/AFRelationship`. Returns `true` on success.\n */\n addAssociatedFile(\n name: string,\n bytes: Uint8Array,\n relationship: AfRelationship,\n opts: AttachmentOptions = {}\n ): boolean {\n const rel = AF_RELATIONSHIP_CODE[relationship] ?? AF_RELATIONSHIP_CODE.unspecified;\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withBytes(bytes, (bp, bl) =>\n this.g._withOptStr(opts.mime ?? \"\", (mp, ml) =>\n this.g._withOptStr(opts.description ?? \"\", (dp, dl) =>\n this.ex().gp_add_associated_file(this.h, np, nl, bp, bl, mp, ml, dp, dl, rel)\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Remove the attachment named `name` (from `/Names /EmbeddedFiles` and, if\n * present, the catalog `/AF` array). Returns `true` if one was removed, `false`\n * if no attachment had that name.\n */\n removeAttachment(name: string): boolean {\n return this.g._withStr(name, (p, l) => this.ex().gp_remove_attachment(this.h, p, l)) === 1;\n }\n\n /**\n * Mark this document as an embedded-file **portfolio** and configure how its\n * attachments are presented, by writing the catalog `/Collection`\n * (ISO 32000-1 §7.11.6, §12.3.5). The files must already be embedded (add them\n * first with {@link addAttachment} / {@link addAssociatedFile}); this only adds\n * the presentation layer: the initial {@link CollectionConfig.view view}, the\n * {@link CollectionConfig.schema schema} columns, the\n * {@link CollectionConfig.sort sort} order, the\n * {@link CollectionConfig.defaultFile default file}, and per-file\n * {@link CollectionConfig.items column values} (each written as a `/CI` on the\n * matching file's filespec). An empty/omitted schema still produces a valid\n * `/Collection`. Calling again **replaces** the previous configuration. Returns\n * `true` on success (`false` on a malformed config or write error).\n */\n setCollection(config: CollectionConfig): boolean {\n return (\n this.g._withStr(JSON.stringify(config), (p, l) =>\n this.ex().gp_set_collection_json(this.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Read this document's portfolio configuration back from the catalog\n * `/Collection` — the reader counterpart of {@link setCollection}. Returns\n * `null` when the document is not a portfolio. The recovered\n * {@link CollectionConfig} carries the `view`, the `schema` columns (sorted by\n * order), the `sort`, the `defaultFile`, and each embedded file's `/CI` column\n * `values`.\n */\n collection(): CollectionConfig | null {\n return this.g._json<CollectionConfig | null>((o) => this.ex().gp_collection_json(this.h, o));\n }\n\n /**\n * Install a **document-level JavaScript** under the catalog `/Names /JavaScript`\n * name tree (ISO 32000-1 §7.7.3.4 + §12.6.4.16): a named JavaScript action\n * (`<< /S /JavaScript /JS … >>`) keyed by `name`. On open, a conforming viewer\n * runs every document-level script in **name (lexical) order** — this is where\n * form-calculation / validation helper libraries live (e.g. `AFNumber_Format`).\n * Re-using a `name` **replaces** that script; long sources are stored as a\n * FlateDecode stream, and sibling `/Names` subtrees (`/EmbeddedFiles`,\n * `/Dests`, …) are preserved. Returns `true` on success (`false` e.g. for an\n * empty name).\n */\n addDocumentJavascript(name: string, script: string): boolean {\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withStr(script, (sp, sl) =>\n this.ex().gp_add_document_javascript(this.h, np, nl, sp, sl)\n )\n ) === 0\n );\n }\n\n /**\n * Every document-level JavaScript as `{ name, script }` pairs, in name\n * (lexical) order — the read side of {@link addDocumentJavascript} (decodes\n * both a literal `/JS` string and a `/JS` stream).\n */\n documentJavascripts(): DocumentJavascript[] {\n return this.g._json((o) => this.ex().gp_document_javascripts_json(this.h, o));\n }\n\n /**\n * Remove the document-level JavaScript named `name` from `/Names /JavaScript`.\n * Returns `true` if one was removed, `false` if none had that name.\n */\n removeDocumentJavascript(name: string): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_remove_document_javascript(this.h, p, l)) === 1\n );\n }\n\n /**\n * Add a page-anchored **FileAttachment** annotation over `rect` on the 1-based\n * `page`, pointing at the already-embedded attachment `name` (add it first with\n * {@link addAttachment}). `icon` is the visual marker (default `\"PushPin\"`).\n * Returns `true` on success (`false` if no such attachment exists).\n */\n addFileAttachmentAnnot(\n page: number,\n rect: Box,\n name: string,\n icon: FileAttachmentIcon = \"PushPin\"\n ): boolean {\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withOptStr(icon, (ip, il) =>\n this.ex().gp_add_file_attachment_annot(\n this.h,\n page,\n rect.x,\n rect.y,\n rect.x + rect.w,\n rect.y + rect.h,\n np,\n nl,\n ip,\n il\n )\n )\n ) === 0\n );\n }\n\n /**\n * Add an internal hyperlink over a rectangle that jumps to the named\n * destination `name` (define it with {@link addNamedDest}). Unlike\n * {@link addGotoLink} (an explicit page), this stores `/Dest /name`, keeping\n * cross-references intact through split/extract.\n */\n addGotoLinkNamed(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n name: string\n ): boolean {\n return (\n this.g._withStr(name, (p, l) =>\n this.ex().gp_add_goto_link_named(this.h, page, x0, y0, x1, y1, p, l)\n ) === 0\n );\n }\n\n // optional-content layers (calques): list + show/hide + lock/unlock + remove\n layers(): LayerInfo[] {\n return this.g._json((o) => this.ex().gp_layers_json(this.h, o));\n }\n /** Create a new (visible, unlocked) layer; returns its id (0 on error). */\n addLayer(name: string): number {\n return this.g._withStr(name, (p, l) => this.ex().gp_add_layer(this.h, p, l));\n }\n setLayerVisibility(id: number, visible: boolean): boolean {\n return this.ex().gp_set_layer_visibility(this.h, id, visible ? 1 : 0) === 0;\n }\n setLayerLocked(id: number, locked: boolean): boolean {\n return this.ex().gp_set_layer_locked(this.h, id, locked ? 1 : 0) === 0;\n }\n removeLayer(id: number): boolean {\n return this.ex().gp_remove_layer(this.h, id) === 0;\n }\n /**\n * Begin an optional-content marked-content sequence on `page` for the layer\n * `ocg` (its id, from {@link addLayer}). Registers the OCG under the page's\n * `/Resources /Properties` and appends `/OC /OCn BDC` to the content stream;\n * every drawing call after it ({@link addText}, {@link addRectangle},\n * {@link addImage}, …) is gated on that layer's visibility until the matching\n * {@link endOptionalContent} appends `EMC`. Calls nest. Returns the `OCn`\n * property name (empty string on error).\n */\n beginOptionalContent(page: number, ocg: number): string {\n return this.g._str((o) =>\n this.ex().gp_begin_optional_content(this.h, page, ocg, o)\n );\n }\n /** End the innermost optional-content sequence on `page` (`EMC`). */\n endOptionalContent(page: number): boolean {\n return this.ex().gp_end_optional_content(this.h, page) === 0;\n }\n\n // outline (bookmarks)\n outline(): OutlineEntry[] {\n return this.g._json((o) => this.ex().gp_outline_json(this.h, o));\n }\n /** Replace the outline. Each entry: `{level, page?, title}` (page 0/undefined = no dest). */\n setOutline(entries: OutlineEntry[]): boolean {\n const text = entries.map((e) => `${e.level}\\t${e.page ?? 0}\\t${e.title}`).join(\"\\n\");\n return this.g._withStr(text, (p, l) => this.ex().gp_set_outline(this.h, p, l)) === 0;\n }\n\n /**\n * Add a `/Link` annotation over `rect` (`{ x, y, w, h }`) carrying any\n * {@link Action} — the full action & destination model (GoTo with every fit\n * mode, GoToR, URI, Named navigation, Launch, JavaScript, SubmitForm,\n * ResetForm). Returns `true` on success (`false` for a malformed action).\n *\n * @example\n * doc.addLink(1, { x: 72, y: 700, w: 120, h: 16 },\n * { type: \"goto\", dest: { fit: \"xyz\", page: 4, top: 720, zoom: 1.5 } });\n */\n addLink(page: number, rect: Box, action: Action): boolean {\n return (\n this.g._withStr(JSON.stringify(action), (p, l) =>\n this.ex().gp_add_link(this.h, page, rect.x, rect.y, rect.x + rect.w, rect.y + rect.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Set the document `/OpenAction` — the {@link Action} performed when the file\n * is opened. Returns `true` on success.\n */\n setOpenAction(action: Action): boolean {\n return (\n this.g._withStr(JSON.stringify(action), (p, l) =>\n this.ex().gp_set_open_action(this.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Remove the `linkIndex`-th `/Link` annotation on `page` (links counted in\n * order, ignoring non-link annotations). Returns `true` if one was removed.\n */\n removeLink(page: number, linkIndex: number): boolean {\n return this.ex().gp_remove_link(this.h, page, linkIndex) === 1;\n }\n\n /**\n * Replace the outline with {@link Bookmark}s that may carry actions (a `goto`\n * action becomes a `/Dest`, any other action an `/A`). An empty array clears\n * the outline. Returns `true` on success.\n */\n setBookmarks(bookmarks: Bookmark[]): boolean {\n const text = bookmarks\n .map((b) => `${b.level}\\t${b.title}\\t${b.action ? JSON.stringify(b.action) : \"\"}`)\n .join(\"\\n\");\n return this.g._withOptStr(text, (p, l) => this.ex().gp_set_bookmarks(this.h, p, l)) === 0;\n }\n\n // catalog reading / UX hints (ViewerPreferences, PageLayout, PageMode)\n /**\n * Write the catalog `/ViewerPreferences` (ISO 32000-1 §12.2). Each omitted\n * field is left unchanged; a boolean sets the key. After applying, an empty\n * dictionary is removed. Returns `false` on an invalid `direction`.\n */\n setViewerPreferences(prefs: ViewerPreferences): boolean {\n // -1 = leave unchanged, 0 = false, 1 = true.\n const tri = (v: boolean | undefined): number => (v === undefined ? -1 : v ? 1 : 0);\n return (\n this.g._withStr(prefs.direction ?? \"\", (dP, dL) =>\n this.ex().gp_set_viewer_preferences(\n this.h,\n tri(prefs.hideToolbar),\n tri(prefs.hideMenubar),\n tri(prefs.hideWindowUI),\n tri(prefs.fitWindow),\n tri(prefs.centerWindow),\n tri(prefs.displayDocTitle),\n dP,\n dL\n )\n ) === 0\n );\n }\n /** Set the catalog `/PageLayout`. `null` removes the key. Returns `false` on an unknown name. */\n setPageLayout(layout: PageLayout | null): boolean {\n return this.g._withStr(layout ?? \"\", (p, l) => this.ex().gp_set_page_layout(this.h, p, l)) === 0;\n }\n /** Set the catalog `/PageMode`. `null` removes the key. Returns `false` on an unknown name. */\n setPageMode(mode: PageMode | null): boolean {\n return this.g._withStr(mode ?? \"\", (p, l) => this.ex().gp_set_page_mode(this.h, p, l)) === 0;\n }\n\n // interactive forms (AcroForm)\n fields(): FieldInfo[] {\n return this.g._json((o) => this.ex().gp_fields_json(this.h, o));\n }\n setTextField(name: string, value: string): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(value, (vP, vL) => this.ex().gp_set_text_field(this.h, nP, nL, vP, vL))\n ) === 0\n );\n }\n setCheckbox(name: string, checked: boolean): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_set_checkbox(this.h, p, l, checked ? 1 : 0)) === 0\n );\n }\n setRadio(name: string, value: string): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(value, (vP, vL) => this.ex().gp_set_radio(this.h, nP, nL, vP, vL))\n ) === 0\n );\n }\n /** Set a choice field's selection (multi-select list boxes accept several values). */\n setChoice(name: string, values: string[]): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(values.join(\"\\n\"), (vP, vL) => this.ex().gp_set_choice(this.h, nP, nL, vP, vL))\n ) === 0\n );\n }\n\n // ── form field creation ──────────────────────────────────────────────────\n\n /**\n * Create a text field on `page` covering `rect` = `[x0, y0, x1, y1]` (PDF\n * user space). Options: `maxLen` character cap, `multiline`, `password`,\n * and visual `style`.\n */\n addTextField(\n page: number,\n name: string,\n rect: [number, number, number, number],\n value = \"\",\n opts: { maxLen?: number; multiline?: boolean; password?: boolean; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(value, (vP, vL) =>\n this.ex().gp_add_text_field(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], vP, vL,\n opts.maxLen ?? -1, opts.multiline ? 1 : 0, opts.password ? 1 : 0, ...st\n )\n )\n ) === 0\n );\n }\n\n /** Create a checkbox. `export` is the on-state name (default `On`). */\n addCheckbox(\n page: number,\n name: string,\n rect: [number, number, number, number],\n checked = false,\n opts: { export?: string; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(opts.export ?? \"On\", (eP, eL) =>\n this.ex().gp_add_checkbox(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], checked ? 1 : 0, eP, eL, ...st\n )\n )\n ) === 0\n );\n }\n\n /**\n * Create a radio-button group: one logical field whose `options` are the\n * individual buttons. `selected` is the initially-chosen export value.\n */\n addRadioGroup(\n page: number,\n name: string,\n options: RadioOption[],\n opts: { selected?: string; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n const exports = options.map((o) => o.export).join(\"\\n\");\n const rects = options.flatMap((o) => o.rect).join(\",\");\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(exports, (eP, eL) =>\n this.g._withStr(rects, (rP, rL) =>\n this.g._withStr(opts.selected ?? \"\", (sP, sL) =>\n this.ex().gp_add_radio_group(this.h, page, nP, nL, eP, eL, rP, rL, sP, sL, ...st)\n )\n )\n )\n ) === 0\n );\n }\n\n /** Create a drop-down combo box. `editable` permits values outside `options`. */\n addComboBox(\n page: number,\n name: string,\n rect: [number, number, number, number],\n options: string[],\n opts: { selected?: string; editable?: boolean; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(options.join(\"\\n\"), (oP, oL) =>\n this.g._withStr(opts.selected ?? \"\", (sP, sL) =>\n this.ex().gp_add_combo_box(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], oP, oL, sP, sL,\n opts.editable ? 1 : 0, ...st\n )\n )\n )\n ) === 0\n );\n }\n\n /** Create a scrolling list box. `multi` allows selecting several options. */\n addListBox(\n page: number,\n name: string,\n rect: [number, number, number, number],\n options: string[],\n opts: { selected?: string; multi?: boolean; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(options.join(\"\\n\"), (oP, oL) =>\n this.g._withStr(opts.selected ?? \"\", (sP, sL) =>\n this.ex().gp_add_list_box(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], oP, oL, sP, sL,\n opts.multi ? 1 : 0, ...st\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Create a **visible signature field** (`/FT /Sig`) over `rect` — an empty\n * widget the signing pipeline can later target — and flag the AcroForm\n * `/SigFlags`. Returns `true` on success.\n */\n addSignatureField(\n page: number,\n name: string,\n rect: [number, number, number, number],\n opts: { style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.ex().gp_add_signature_field(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], ...st\n )\n ) === 0\n );\n }\n\n /**\n * Attach field-level JavaScript to a field's `/AA` for the given `trigger`\n * (`\"keystroke\"` filters input, `\"format\"` formats display, `\"validate\"`\n * checks on change, `\"calculate\"` recomputes — ordered by\n * {@link setCalculationOrder}). Returns `true` if set, `false` if no field has\n * that name.\n */\n setFieldScript(\n name: string,\n trigger: \"keystroke\" | \"format\" | \"validate\" | \"calculate\",\n js: string\n ): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(trigger, (tP, tL) =>\n this.g._withStr(js, (jP, jL) =>\n this.ex().gp_set_field_script(this.h, nP, nL, tP, tL, jP, jL)\n )\n )\n ) === 1\n );\n }\n\n /**\n * Set the AcroForm calculation order (`/CO`) — the sequence in which fields\n * with a `calculate` script recompute. Unknown names are skipped.\n */\n setCalculationOrder(names: string[]): boolean {\n return (\n this.g._withOptStr(names.join(\"\\n\"), (p, l) =>\n this.ex().gp_set_calculation_order(this.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Delete a form field by name (removed from `/Fields`, `/CO` and every page's\n * annotations). Returns `true` if a field was removed.\n */\n removeField(name: string): boolean {\n return this.g._withStr(name, (p, l) => this.ex().gp_remove_field(this.h, p, l)) === 1;\n }\n\n /**\n * Rebuild a field's appearance from its current value/style — call after\n * changing a field's value programmatically. Returns `true` if regenerated\n * (`false` for an unknown name or a kind that can't be regenerated alone, e.g.\n * a radio parent with kids).\n */\n regenerateFieldAppearance(name: string): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_regenerate_field_appearance(this.h, p, l)) === 1\n );\n }\n}\n"],"mappings":";AAmBA,SAAS,4BAA4B;AAsBrC,SAAS,eAAe,GAAmC;AACzD,SAAO,MAAM,QAAQ,IAAI;AAC3B;AAEA,IAAM,MAAM,IAAI,YAAY;AAC5B,IAAM,MAAM,IAAI,YAAY;AA4B5B,IAAM,kBAAkC;AAAA,EACtC,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,eAAe;AAAA,EACf,UAAU;AAAA,EACV,cAAc;AAChB;AAcO,IAAM,gBAAN,MAAM,eAAc;AAAA,EACjB,YAA6B,IAAa;AAAb;AAAA,EAAc;AAAA,EAAd;AAAA;AAAA,EAGrC,OAAe;AAAA;AAAA,EAGf,aAAa,KAAK,QAA8E;AAC9F,QAAI;AACJ,QAAI,OAAO,WAAW,UAAU;AAC9B,YAAM,MAAM,MAAM,MAAM,MAAM;AAC9B,cAAQ,MAAM,IAAI,YAAY;AAAA,IAChC,WAAW,kBAAkB,UAAU;AACrC,cAAQ,MAAM,OAAO,YAAY;AAAA,IACnC,OAAO;AACL,cAAQ;AAAA,IACV;AAIA,QAAI;AACJ,UAAM,EAAE,SAAS,IAAI,MAAM,YAAY;AAAA,MACrC,iBAAiB,aAAa,MAAM,MAAM,EAAE,SAAS;AAAA,MACrD;AAAA,QACE,KAAK;AAAA,UACH,gBAAg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AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,MAAuB;AACjC,WAAO,KAAK,EAAE,SAAS,MAAM,CAAC,GAAG,MAAM,KAAK,GAAG,EAAE,gBAAgB,KAAK,GAAG,GAAG,CAAC,CAAC,MAAM;AAAA,EACtF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,0BAA0B,MAAuB;AAC/C,WACE,KAAK,EAAE,SAAS,MAAM,CAAC,GAAG,MAAM,KAAK,GAAG,EAAE,+BAA+B,KAAK,GAAG,GAAG,CAAC,CAAC,MAAM;AAAA,EAEhG;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @qrcommunication/gigapdf-lib — TypeScript SDK for the gigapdf-lib Rust→WASM PDF\n * engine: no third-party PDF/Office/image library (cryptography uses RustCrypto,\n * JavaScript uses Boa). Wraps the flat `extern \"C\"` `gp_*` ABI behind a typed,\n * ergonomic class. No third-party npm deps; the `.wasm` imports a single host\n * function — `env.gp_host_random` (entropy), which `load()` supplies.\n *\n * Usage:\n * const giga = await GigaPdfEngine.load(wasmBytesOrUrl);\n * const doc = giga.open(pdfBytes);\n * const docx = doc.toDocx();\n * const png = doc.renderPage(1, 2);\n * doc.close();\n */\n\n// Node-only filesystem loaders. Swapped for a throwing browser stub via the\n// package.json `\"browser\"` field, so browser bundlers never see `node:fs`/\n// `node:url`. The specifier is a plain relative path (well-supported by\n// Turbopack/webpack/Vite), unlike the previous inline `import(\"node:...\")`.\nimport { loadDefaultWasmBytes } from \"./node-fs.js\";\n\n// FFI boundary: the wasm exports are an untyped table of `gp_*` functions\n// (numbers in, numbers out) plus `memory`. `any` here is the documented FFI\n// exception — every public method below re-imposes precise types.\nexport type Exports = {\n memory: WebAssembly.Memory;\n gp_alloc(len: number): number;\n gp_free(ptr: number, len: number): void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [k: string]: any;\n};\n\n/**\n * PDF file-version banner for the compact ({@link GigaPdfDoc.saveOptimized}) and\n * linearized ({@link GigaPdfDoc.toLinearized}) writers. Object streams,\n * cross-reference streams and linearization are valid in both, so the choice only\n * changes the `%PDF-x.y` header line. Defaults to `\"1.7\"`.\n */\nexport type PdfVersion = \"1.7\" | \"2.0\";\n\n/** Map a {@link PdfVersion} to the wasm selector (`0` = 1.7, `1` = 2.0). */\nfunction pdfVersionCode(v: PdfVersion | undefined): number {\n return v === \"2.0\" ? 1 : 0;\n}\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\n/**\n * The eight PDF access permissions carried by an `/Encrypt` dictionary's `/P`\n * entry (ISO 32000-1 §7.6.3.2, Table 22). Each flag is `true` when the action\n * is **granted** to a user opening the document with the user password; the\n * owner password always lifts every restriction.\n */\nexport type PdfPermissions = {\n /** Print the document (low resolution unless {@link printHighRes} is also set). */\n print: boolean;\n /** Modify the document contents (other than annotating, filling or assembling). */\n modify: boolean;\n /** Copy or otherwise extract text and graphics. */\n copy: boolean;\n /** Add or modify annotations and fill in interactive form fields. */\n annotate: boolean;\n /** Fill in existing interactive form fields (even if {@link annotate} is clear). */\n fillForms: boolean;\n /** Extract text and graphics for accessibility tools. */\n accessibility: boolean;\n /** Assemble the document: insert, rotate and delete pages. */\n assemble: boolean;\n /** Print to a high-resolution device (requires {@link print}). */\n printHighRes: boolean;\n};\n\n/** Every permission granted — the unrestricted baseline (`/P` = -196). */\nconst ALL_PERMISSIONS: PdfPermissions = {\n print: true,\n modify: true,\n copy: true,\n annotate: true,\n fillForms: true,\n accessibility: true,\n assemble: true,\n printHighRes: true,\n};\n\n// OCR moved host-side to the `gigapdf-ocr-rten` crate (PaddleOCR PP-OCR via RTen, 12 languages +\n// auto script selection + Hebrew). The WASM SDK no longer ships a client-side recognizer; hosts\n// call the OCR service/binary directly. The legacy `.gpocr` model-loading API was removed.\n\n/**\n * One source in a {@link GigaPdfEngine.mergePdfs} call. `pdf` is the source\n * bytes; the optional `pages` selects 1-based page numbers (in the given order)\n * to bring in — omit it to append every page.\n */\nexport type MergePart = { pdf: Uint8Array; pages?: number[] };\n\n/** Loaded engine module. Create documents with {@link open} / {@link openEncrypted}. */\nexport class GigaPdfEngine {\n private constructor(private readonly ex: Exports) {}\n\n /** Lazily-built Base64 reverse-lookup table (see {@link _fromBase64}). */\n private static _b64rev?: Int16Array;\n\n /** Instantiate from raw wasm bytes, a URL/path, or a Response. */\n static async load(source: ArrayBuffer | Uint8Array | string | Response): Promise<GigaPdfEngine> {\n let bytes: ArrayBuffer | Uint8Array;\n if (typeof source === \"string\") {\n const res = await fetch(source);\n bytes = await res.arrayBuffer();\n } else if (source instanceof Response) {\n bytes = await source.arrayBuffer();\n } else {\n bytes = source;\n }\n // The wasm imports one host function: `env.gp_host_random`. wasm32 has no OS\n // RNG, so the engine (RSA signature blinding, Boa `Math.random`) draws\n // entropy from the host's Web Crypto. This keeps the module wasm-bindgen-free.\n let ex: Exports | undefined;\n const { instance } = await WebAssembly.instantiate(\n bytes instanceof Uint8Array ? bytes.slice().buffer : bytes,\n {\n env: {\n gp_host_random: (ptr: number, len: number): void => {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (!c?.getRandomValues) {\n throw new Error(\n \"gigapdf: wasm entropy needs Web Crypto (globalThis.crypto.getRandomValues)\"\n );\n }\n const mem = new Uint8Array(ex!.memory.buffer, ptr, len);\n // getRandomValues rejects views longer than 65536 bytes; fill in chunks.\n for (let off = 0; off < len; off += 65536) {\n c.getRandomValues(mem.subarray(off, Math.min(off + 65536, len)));\n }\n },\n },\n }\n );\n ex = instance.exports as Exports;\n return new GigaPdfEngine(ex);\n }\n\n /**\n * Convenience loader for Node: instantiate from the `gigapdf.wasm` shipped\n * inside this package (resolved relative to the built module). In the browser,\n * pass a URL or bytes to {@link load} instead.\n *\n * In Next.js `output: \"standalone\"`, add the asset to `outputFileTracingIncludes`\n * for the consuming route so the `.wasm` is copied into the standalone bundle.\n */\n static async loadDefault(): Promise<GigaPdfEngine> {\n // The fs access lives in `./node-fs` (Node-only; browser-stubbed via the\n // package.json `\"browser\"` map) so browser bundlers never resolve `node:*`.\n return GigaPdfEngine.load(await loadDefaultWasmBytes());\n }\n\n // ── linear-memory ABI helpers (internal) ─────────────────────────────────\n private u8() {\n return new Uint8Array(this.ex.memory.buffer);\n }\n private dv() {\n return new DataView(this.ex.memory.buffer);\n }\n /** Copy host bytes into wasm memory; returns the pointer (caller frees). */\n _toWasm(bytes: Uint8Array): number {\n // If `bytes` aliases our own wasm memory (e.g. a buffer the caller didn't\n // copy out), `gp_alloc` may grow — and detach — that buffer mid-copy.\n // Snapshot to a host array first so the `.set` source stays valid.\n const src = bytes.buffer === this.ex.memory.buffer ? new Uint8Array(bytes) : bytes;\n const ptr = this.ex.gp_alloc(src.length);\n this.u8().set(src, ptr);\n return ptr;\n }\n _free(ptr: number, len: number) {\n this.ex.gp_free(ptr, len);\n }\n /** Call a buffer-returning export `(…, outLenPtr) -> dataPtr`; copies + frees. */\n _buffer(call: (outLenPtr: number) => number): Uint8Array {\n const lenPtr = this.ex.gp_alloc(4);\n const dataPtr = call(lenPtr);\n if (dataPtr === 0) {\n this.ex.gp_free(lenPtr, 4);\n return new Uint8Array(0);\n }\n const len = this.dv().getUint32(lenPtr, true);\n const out = this.u8().slice(dataPtr, dataPtr + len);\n this.ex.gp_free(dataPtr, len);\n this.ex.gp_free(lenPtr, 4);\n return out;\n }\n _str(call: (outLenPtr: number) => number): string {\n return dec.decode(this._buffer(call));\n }\n _json<T = unknown>(call: (outLenPtr: number) => number): T {\n const s = this._str(call);\n return (s ? JSON.parse(s) : []) as T;\n }\n /**\n * Like {@link _json} but distinguishes a **null** result (the export returned a\n * null pointer — e.g. an unrecognized container) from a present-but-empty JSON\n * payload (`[]` / `{}`). Returns `null` only for the null pointer; otherwise the\n * parsed JSON. Used where the Rust side is `Option<…>` and \"nothing\" and\n * \"unrecognized\" must stay distinct.\n */\n _jsonOrNull<T = unknown>(call: (outLenPtr: number) => number): T | null {\n const lenPtr = this.ex.gp_alloc(4);\n const dataPtr = call(lenPtr);\n if (dataPtr === 0) {\n this.ex.gp_free(lenPtr, 4);\n return null;\n }\n const len = this.dv().getUint32(lenPtr, true);\n const s = dec.decode(this.u8().slice(dataPtr, dataPtr + len));\n this.ex.gp_free(dataPtr, len);\n this.ex.gp_free(lenPtr, 4);\n return (s ? JSON.parse(s) : []) as T;\n }\n /**\n * Like {@link _str} but distinguishes a **null** result (the export returned a\n * null pointer — e.g. an `Option::None`) from a present-but-empty string.\n * Returns `null` only for the null pointer; otherwise the decoded string.\n */\n _strOrNull(call: (outLenPtr: number) => number): string | null {\n const lenPtr = this.ex.gp_alloc(4);\n const dataPtr = call(lenPtr);\n if (dataPtr === 0) {\n this.ex.gp_free(lenPtr, 4);\n return null;\n }\n const len = this.dv().getUint32(lenPtr, true);\n const s = dec.decode(this.u8().slice(dataPtr, dataPtr + len));\n this.ex.gp_free(dataPtr, len);\n this.ex.gp_free(lenPtr, 4);\n return s;\n }\n /**\n * Decode standard Base64 (RFC 4648) to bytes. Pure-JS table decode, so it\n * works identically in Node and the browser with no dependency (used to turn\n * the JSON `dataBase64` of {@link GigaPdfDoc.attachments} back into bytes).\n */\n _fromBase64(s: string): Uint8Array {\n let rev = GigaPdfEngine._b64rev;\n if (!rev) {\n rev = new Int16Array(256).fill(-1);\n const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n for (let i = 0; i < alphabet.length; i++) rev[alphabet.charCodeAt(i)] = i;\n GigaPdfEngine._b64rev = rev;\n }\n let count = s.length;\n while (count > 0 && s[count - 1] === '=') count--;\n const out = new Uint8Array((count * 3) >> 2);\n let acc = 0;\n let bits = 0;\n let oi = 0;\n for (let i = 0; i < count; i++) {\n const v = rev[s.charCodeAt(i)];\n if (v === undefined || v < 0) continue; // skip stray whitespace defensively\n acc = (acc << 6) | v;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n out[oi++] = (acc >> bits) & 0xff;\n }\n }\n return oi === out.length ? out : out.subarray(0, oi);\n }\n /** Pass a string argument; runs `fn(ptr, len)` then frees. */\n _withStr<T>(s: string, fn: (ptr: number, len: number) => T): T {\n const b = enc.encode(s);\n const ptr = this._toWasm(b);\n try {\n return fn(ptr, b.length);\n } finally {\n this._free(ptr, b.length);\n }\n }\n /** Pass an optional string; an absent/empty value runs `fn(0, 0)` (no alloc). */\n _withOptStr<T>(s: string | undefined, fn: (ptr: number, len: number) => T): T {\n return s ? this._withStr(s, fn) : fn(0, 0);\n }\n /** Pass a bytes argument; runs `fn(ptr, len)` then frees. */\n _withBytes<T>(bytes: Uint8Array, fn: (ptr: number, len: number) => T): T {\n const ptr = this._toWasm(bytes);\n try {\n return fn(ptr, bytes.length);\n } finally {\n this._free(ptr, bytes.length);\n }\n }\n /** Pass a `u32[]` argument (e.g. page numbers); runs `fn(ptr, count)` then frees. */\n _withU32<T>(values: number[], fn: (ptr: number, count: number) => T): T {\n const ptr = this.ex.gp_alloc(values.length * 4);\n const dv = this.dv();\n for (const [i, v] of values.entries()) dv.setUint32(ptr + i * 4, v >>> 0, true);\n try {\n return fn(ptr, values.length);\n } finally {\n this._free(ptr, values.length * 4);\n }\n }\n /** Pass a flat `f64[]` argument (e.g. ink x,y pairs); runs `fn(ptr, count)` then frees. */\n _withF64<T>(values: number[], fn: (ptr: number, count: number) => T): T {\n const ptr = this.ex.gp_alloc(values.length * 8);\n const dv = this.dv();\n for (const [i, v] of values.entries()) dv.setFloat64(ptr + i * 8, v, true);\n try {\n return fn(ptr, values.length);\n } finally {\n this._free(ptr, values.length * 8);\n }\n }\n get raw(): Exports {\n return this.ex;\n }\n\n // ── documents ─────────────────────────────────────────────────────────────\n /** Open a PDF. Throws if it can't be parsed. */\n open(pdf: Uint8Array): GigaPdfDoc {\n const handle = this._withBytes(pdf, (p, l) => this.ex.gp_open(p, l));\n if (handle === 0) throw new Error(\"gigapdf: failed to open PDF\");\n return new GigaPdfDoc(this, handle);\n }\n /** Open an encrypted PDF with a password. Returns null if the password is wrong. */\n openEncrypted(pdf: Uint8Array, password: string): GigaPdfDoc | null {\n const b = enc.encode(password);\n const pwPtr = this._toWasm(b);\n const handle = this._withBytes(pdf, (p, l) => this.ex.gp_open_encrypted(p, l, pwPtr, b.length));\n this._free(pwPtr, b.length);\n return handle === 0 ? null : new GigaPdfDoc(this, handle);\n }\n\n /**\n * Open a **public-key (certificate) encrypted** PDF (`/Filter /Adobe.PubSec`,\n * ISO 32000-1 §7.6.5) with a recipient's DER `certificate` + PKCS#1 RSA\n * `privateKey`. `null` if this key is not a recipient. Counterpart of\n * {@link GigaPdfDoc.encryptForRecipients}.\n */\n openWithPrivateKey(\n pdf: Uint8Array,\n certificate: Uint8Array,\n privateKey: Uint8Array\n ): GigaPdfDoc | null {\n const cP = this._toWasm(certificate);\n const kP = this._toWasm(privateKey);\n const handle = this._withBytes(pdf, (p, l) =>\n this.ex.gp_open_with_private_key(p, l, cP, certificate.length, kP, privateKey.length)\n );\n this._free(cP, certificate.length);\n this._free(kP, privateKey.length);\n return handle === 0 ? null : new GigaPdfDoc(this, handle);\n }\n\n /**\n * Inspect a PDF's encryption **without decrypting it** (no password needed):\n * whether it has an `/Encrypt` dictionary, plus its `/P` permission bitmask\n * and handler version/revision (`0` when not encrypted).\n */\n encryptionInfo(pdf: Uint8Array): {\n encrypted: boolean;\n permissions: number;\n version: number;\n revision: number;\n } {\n const json = this._withBytes(pdf, (p, l) =>\n this._buffer((o) => this.ex.gp_encryption_info(p, l, o))\n );\n return JSON.parse(dec.decode(json));\n }\n\n /**\n * Decode the eight access-permission flags from a `/P` permission bitmask\n * (ISO 32000-1 Table 22) into named booleans (`true` = the action is\n * granted). Reserved bits are ignored.\n */\n decodePermissions(p: number): PdfPermissions {\n const json = dec.decode(this._buffer((o) => this.ex.gp_permissions_from_p(p, o)));\n return JSON.parse(json) as PdfPermissions;\n }\n\n /**\n * Read a PDF's access permissions **without decrypting it** (no password\n * needed). Returns the eight named flags decoded from the `/Encrypt`\n * dictionary's `/P`; an unencrypted document grants everything.\n */\n getPermissions(pdf: Uint8Array): PdfPermissions {\n const { encrypted, permissions } = this.encryptionInfo(pdf);\n return encrypted ? this.decodePermissions(permissions) : { ...ALL_PERMISSIONS };\n }\n\n /**\n * Pack eight access-permission flags into a signed 32-bit `/P` value\n * (ISO 32000-1 Table 22). Omitted flags default to **granted**, so an empty\n * object means \"all allowed\". Feed the result to {@link GigaPdfDoc.saveEncrypted}\n * via `opts.permissions`, or pass `opts.flags` directly.\n */\n permissionsToP(flags: Partial<PdfPermissions> = {}): number {\n const f = { ...ALL_PERMISSIONS, ...flags };\n return this.ex.gp_permissions_to_p(\n f.print ? 1 : 0,\n f.modify ? 1 : 0,\n f.copy ? 1 : 0,\n f.annotate ? 1 : 0,\n f.fillForms ? 1 : 0,\n f.accessibility ? 1 : 0,\n f.assemble ? 1 : 0,\n f.printHighRes ? 1 : 0\n );\n }\n\n /**\n * Width of `text` set in standard Helvetica at `size` points (AFM metrics) —\n * place watermark/header text without embedding a font.\n */\n helveticaWidth(size: number, text: string): number {\n return this._withStr(text, (p, l) => this.ex.gp_helvetica_width(p, l, size));\n }\n\n // ── stateless <format> → PDF conversions ───────────────────────────────────\n txtToPdf(text: string): Uint8Array {\n return this._withStr(text, (p, l) => this._buffer((o) => this.ex.gp_txt_to_pdf(p, l, o)));\n }\n htmlToPdf(html: string): Uint8Array {\n return this._withStr(html, (p, l) => this._buffer((o) => this.ex.gp_html_to_pdf(p, l, o)));\n }\n rtfToPdf(rtf: string): Uint8Array {\n return this._withStr(rtf, (p, l) => this._buffer((o) => this.ex.gp_rtf_to_pdf(p, l, o)));\n }\n /** Office (DOCX/ODT/PPTX/XLSX/ODS) → PDF, auto-detected. Empty array if unrecognized. */\n officeToPdf(office: Uint8Array): Uint8Array {\n return this._withBytes(office, (p, l) =>\n this._buffer((o) => this.ex.gp_office_to_pdf(p, l, o))\n );\n }\n /**\n * Phase 1 for {@link officeToPdf} — the Google/system fonts an Office container\n * **references but doesn't embed**. Download each `url` (→ TTF) and supply the\n * bytes back to the host font cache so {@link officeToPdf}'s styled runs lay out\n * with the right metrics. Faces the container embeds itself are de-obfuscated\n * and used automatically (not listed here). Returns `null` if the bytes are not\n * a recognized Office container, `[]` if it needs no host fonts.\n */\n officeNeededFonts(office: Uint8Array): HtmlFontRequest[] | null {\n return this._withBytes(office, (p, l) =>\n this._jsonOrNull<HtmlFontRequest[]>((o) => this.ex.gp_office_needed_fonts(p, l, o))\n );\n }\n /**\n * Phase 2 for {@link officeNeededFonts} — render an Office container to PDF with\n * the host-fetched `fonts` embedded, so families the container **references but\n * doesn't embed** (reported by {@link officeNeededFonts}) lay out with the right\n * metrics (e.g. Carlito for a Calibri reference) instead of drifting onto the\n * bundled fallback. Faces the container embeds itself win on conflict, so an\n * empty `fonts` array yields exactly {@link officeToPdf}'s output. Empty array\n * if the bytes are not a recognized Office container.\n *\n * @example\n * const reqs = giga.officeNeededFonts(docx); // phase 1: what to fetch\n * const fonts = await Promise.all( // host fetches each url → TTF\n * (reqs ?? []).map(async (r) => ({ ...r, ttf: await fetchTtf(r.url) }))\n * );\n * const pdf = giga.officeToPdfWith(docx, fonts); // phase 2: render with them\n */\n officeToPdfWith(office: Uint8Array, fonts: HtmlFont[] = []): Uint8Array {\n const blob = packHtmlFonts(fonts);\n return this._withBytes(office, (op, ol) =>\n this._withBytes(blob, (fp, fl) =>\n this._buffer((o) => this.ex.gp_office_to_pdf_with_fonts(op, ol, fp, fl, o))\n )\n );\n }\n /**\n * Image (PNG/JPEG/GIF/WebP/AVIF/TIFF) → one-page PDF, format auto-detected:\n * the image is centred and scaled to fit on an A4 portrait page. PNG/JPEG\n * embed directly; GIF/WebP/AVIF/TIFF are transcoded to PNG first — all in pure\n * Rust/WASM, no third-party image library. Empty array if the bytes are not a\n * recognized image. To combine many images into a single document, pipe each\n * result\n * through {@link mergePdfs}.\n */\n imageToPdf(image: Uint8Array): Uint8Array {\n return this._withBytes(image, (p, l) =>\n this._buffer((o) => this.ex.gp_image_to_pdf(p, l, o))\n );\n }\n /**\n * Merge several PDFs into one by appending their pages in order. Each input is\n * either raw bytes (every page) or a {@link MergePart} `{ pdf, pages? }` that\n * selects 1-based page numbers (ISO 32000-1 §7.7.3) — so the two forms can be\n * mixed (e.g. `[whole, { pdf: b, pages: [1, 3] }]`). Returns an empty document\n * for an empty list, or — when the only input is a whole PDF (no `pages`) —\n * that input unchanged. Each subsequent part is appended onto the first via\n * {@link GigaPdfDoc.appendPages}; the merged bytes are returned and the working\n * document is closed.\n */\n mergePdfs(parts: (Uint8Array | MergePart)[]): Uint8Array {\n if (parts.length === 0) return new Uint8Array(0);\n const part = (p: Uint8Array | MergePart): MergePart =>\n p instanceof Uint8Array ? { pdf: p } : p;\n const first = part(parts[0]!);\n if (parts.length === 1 && first.pages === undefined) return first.pdf;\n // Seed the working document from the first part — reducing it to just its\n // selected pages first, so a page-range on the first source is honoured too.\n let seed = first.pdf;\n if (first.pages !== undefined) {\n const head = this.open(first.pdf);\n try {\n seed = head.extractPages(first.pages);\n } finally {\n head.close();\n }\n }\n const base = this.open(seed);\n try {\n for (let i = 1; i < parts.length; i++) {\n const p = part(parts[i]!);\n base.appendPages(p.pdf, p.pages);\n }\n return base.save();\n } finally {\n base.close();\n }\n }\n /**\n * Write a host-built grid (`pages[rows][cells]`) to an `.xlsx` workbook — one\n * sheet per page — with the engine's native spreadsheet writer (no\n * third-party library). Supply your own table reconstruction and still emit\n * Office output. `sheetNames` (index-aligned to `grids`) overrides the default\n * `Page <n>` titles; a missing/empty name falls back to the default.\n * {@link gridsToOds} is the OpenDocument (`.ods`) counterpart.\n */\n gridsToXlsx(grids: string[][][], sheetNames: string[] = []): Uint8Array {\n return this._withStr(JSON.stringify(grids), (gp, gl) =>\n this._withStr(JSON.stringify(sheetNames), (np, nl) =>\n this._buffer((o) => this.ex.gp_grids_to_xlsx(gp, gl, np, nl, o))\n )\n );\n }\n /** Write a host-built grid (`pages[rows][cells]`) to an `.ods` spreadsheet\n * (optional `sheetNames`, default `Page <n>`). */\n gridsToOds(grids: string[][][], sheetNames: string[] = []): Uint8Array {\n return this._withStr(JSON.stringify(grids), (gp, gl) =>\n this._withStr(JSON.stringify(sheetNames), (np, nl) =>\n this._buffer((o) => this.ex.gp_grids_to_ods(gp, gl, np, nl, o))\n )\n );\n }\n /**\n * Read an `.xlsx` workbook back into per-sheet `{ name, rows }` grids — the\n * inverse of {@link gridsToXlsx} / {@link GigaPdfDoc.toXlsx}. Cell text is\n * decoded from inline strings, shared strings (`sharedStrings.xml`) or plain\n * values; sheets come in workbook order. `[]` for a non-xlsx input.\n */\n xlsxToGrids(xlsx: Uint8Array): XlsxSheet[] {\n return this._withBytes(xlsx, (p, l) =>\n this._json((o) => this.ex.gp_xlsx_to_grids(p, l, o))\n );\n }\n /**\n * Encode raw **RGBA** pixels (`width*height*4` bytes, row-major,\n * non-premultiplied) to a PNG with the engine's native encoder — no\n * third-party image library. Returns an empty array if the buffer length\n * doesn't match `width*height*4`.\n */\n rgbaToPng(rgba: Uint8Array, width: number, height: number): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_rgba_to_png(width, height, p, l, o))\n );\n }\n /**\n * Resample raw **RGBA** pixels (`sw`×`sh`) to `dw`×`dh` with the engine's\n * native alpha-correct resampler (triangle kernel, footprint scaled for\n * down/up) — no third-party image library. Returns the resized RGBA\n * (`dw*dh*4`), or an empty array on a bad input.\n */\n resizeRgba(rgba: Uint8Array, sw: number, sh: number, dw: number, dh: number): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_resize_rgba(p, l, sw, sh, dw, dh, o))\n );\n }\n /**\n * Encode raw **RGBA** pixels to a baseline JPEG at `quality` (1–100) with the\n * engine's native encoder — no third-party image library. Alpha is composited\n * onto white. Empty array on a bad input.\n */\n encodeJpeg(rgba: Uint8Array, width: number, height: number, quality = 82): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_encode_jpeg(width, height, p, l, quality, o))\n );\n }\n /** Decode a baseline JPEG to `{ width, height, rgba }`, or `null` on failure. */\n decodeJpeg(jpeg: Uint8Array): DecodedImage | null {\n return this._decodeFramed(jpeg, (p, l, o) => this.ex.gp_decode_jpeg(p, l, o));\n }\n /** Decode a PNG to `{ width, height, rgba }`, or `null` on failure. */\n decodePng(png: Uint8Array): DecodedImage | null {\n return this._decodeFramed(png, (p, l, o) => this.ex.gp_decode_png(p, l, o));\n }\n /** Decode a GIF (first frame) to `{ width, height, rgba }`, or `null`. */\n decodeGif(gif: Uint8Array): DecodedImage | null {\n return this._decodeFramed(gif, (p, l, o) => this.ex.gp_decode_gif(p, l, o));\n }\n /**\n * Encode raw RGBA pixels to a **lossless** WebP (VP8L) with the engine's native\n * encoder — no third-party image library. Empty array on a bad input.\n */\n encodeWebp(rgba: Uint8Array, width: number, height: number): Uint8Array {\n return this._withBytes(rgba, (p, l) =>\n this._buffer((o) => this.ex.gp_encode_webp(width, height, p, l, o))\n );\n }\n /**\n * Decode a WebP to `{ width, height, rgba }`, or `null`. Handles both\n * **lossless** (VP8L) and **lossy** (VP8 keyframe) WebP with the engine's\n * native decoder — no third-party image library. Extended/animated WebP\n * (`VP8X`) is not handled (returns `null`).\n */\n decodeWebp(webp: Uint8Array): DecodedImage | null {\n return this._decodeFramed(webp, (p, l, o) => this.ex.gp_decode_webp(p, l, o));\n }\n /**\n * Decode a still **AVIF** (AV1 intra) to `{ width, height, rgba }`, or `null`.\n * Pure-Rust AV1 decoder — no third-party library. Supports lossy + lossless\n * transforms, in-loop deblocking (AV1 §7.14) and CDEF (§7.15, including the\n * multi-strength `cdef_bits > 0` path), screen-content **palette** mode\n * (§5.11.46-50), and both `reduced_still_picture_header` and the full\n * streaming sequence/frame headers — all validated bit-exact against dav1d.\n * Not yet covered: animated AVIF, film grain, loop restoration (§7.17), the\n * fully bit-exact directional top-right/bottom-left intra edge, and the\n * lossless WHT path at very-high quality (`q ≤ 20`).\n */\n decodeAvif(avif: Uint8Array): DecodedImage | null {\n return this._decodeFramed(avif, (p, l, o) => this.ex.gp_decode_avif(p, l, o));\n }\n /** Unpack a `[w:u32 LE][h:u32 LE][rgba]` decode buffer; `null` if empty. */\n _decodeFramed(\n bytes: Uint8Array,\n fn: (p: number, l: number, o: number) => number\n ): DecodedImage | null {\n const framed = this._withBytes(bytes, (p, l) => this._buffer((o) => fn(p, l, o)));\n if (framed.length < 8) return null;\n const dv = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);\n return { width: dv.getUint32(0, true), height: dv.getUint32(4, true), rgba: framed.subarray(8) };\n }\n\n // ── fonts (catalog / Google Fonts URL — the host performs the fetch) ───────\n fontCatalog(): FontInfo[] {\n return this._json((o) => this.ex.gp_font_catalog_json(o));\n }\n /** Google Fonts CSS2 URL for a family/weight/italic (host fetches it). */\n fontRequestUrl(family: string, weight = 400, italic = false): string {\n return this._withStr(family, (p, l) =>\n this._str((o) => this.ex.gp_font_request_url(p, l, weight, italic ? 1 : 0, o))\n );\n }\n /** Extract the trusted gstatic font URL from a Google Fonts CSS2 response. */\n parseCssFontUrl(css: string): string {\n return this._withStr(css, (p, l) => this._str((o) => this.ex.gp_parse_css_font_url(p, l, o)));\n }\n\n // ── JavaScript engine (no headless browser) ────────────────────────────────\n /**\n * Evaluate a JavaScript snippet with the built-in engine and return the\n * result value as a string (or `Uncaught …` / `SyntaxError: …`).\n */\n evalJs(src: string): string {\n return this._withStr(src, (p, l) => this._str((o) => this.ex.gp_js_eval(p, l, o)));\n }\n /**\n * Run a document's inline `<script>`s and return the resulting HTML. The\n * `htmlRender`/`htmlNeededFonts` paths already do this automatically; use this\n * only when you want the post-script HTML on its own.\n */\n runInlineScripts(html: string): string {\n return this._withStr(html, (p, l) =>\n this._str((o) => this.ex.gp_run_inline_scripts(p, l, o))\n );\n }\n\n // ── HTML rendering engine (replaces a headless browser for HTML→PDF) ───────\n /**\n * Phase 1 — the Google fonts the document references. Download each `url`\n * (→ TTF) and pass the bytes back to {@link htmlRender} for an identical render.\n */\n htmlNeededFonts(html: string): HtmlFontRequest[] {\n return this._withStr(html, (p, l) =>\n this._json((o) => this.ex.gp_html_needed_fonts(p, l, o))\n ) as HtmlFontRequest[];\n }\n\n /**\n * Phase 2 — render HTML + CSS to PDF, with the supplied fonts embedded (real\n * Google fonts, real metrics → identical or nearest match). Block, inline and\n * table layout with pagination. Page size and margin are in points\n * (US-Letter portrait, 0.5in margins by default). JavaScript is not executed.\n */\n htmlRender(\n html: string,\n fonts: HtmlFont[] = [],\n pageWidth = 612,\n pageHeight = 792,\n margin = 36\n ): Uint8Array {\n const blob = packHtmlFonts(fonts);\n return this._withStr(html, (hp, hl) =>\n this._withBytes(blob, (fp, fl) =>\n this._buffer((o) => this.ex.gp_html_render(hp, hl, fp, fl, pageWidth, pageHeight, margin, o))\n )\n );\n }\n\n /**\n * Resolve a named paper size — `\"A4\"`, `\"a3-landscape\"`, `\"letter\"`, `\"legal\"`,\n * `\"tabloid\"`, `\"b5\"`, … — to `{ w, h }` in points (portrait unless the name\n * has a `-landscape` suffix). Returns `null` for an unknown name.\n */\n pageSize(name: string): { w: number; h: number } | null {\n const outPtr = this.ex.gp_alloc(16);\n try {\n const ok = this._withStr(name, (p, l) =>\n this.ex.gp_page_size(p, l, outPtr, outPtr + 8)\n );\n if (!ok) return null;\n const dv = this.dv();\n return { w: dv.getFloat64(outPtr, true), h: dv.getFloat64(outPtr + 8, true) };\n } finally {\n this._free(outPtr, 16);\n }\n }\n\n /**\n * Phase 1 variant that also scans the running `header`/`footer` HTML, so the\n * Google fonts they reference are requested alongside the body's.\n */\n htmlNeededFontsWith(html: string, header?: string, footer?: string): HtmlFontRequest[] {\n return this._withStr(html, (hp, hl) =>\n this._withOptStr(header, (hdp, hdl) =>\n this._withOptStr(footer, (ftp, ftl) =>\n this._json((o) => this.ex.gp_html_needed_fonts_ex(hp, hl, hdp, hdl, ftp, ftl, o))\n )\n )\n ) as HtmlFontRequest[];\n }\n\n /**\n * Phase 2 with full page control: named/explicit size, per-side margins, and a\n * running header/footer painted in the page margins. `{{page}}` and `{{pages}}`\n * in the header/footer are replaced with the current / total page number.\n *\n * ```ts\n * const fonts = await fetchFonts(giga.htmlNeededFontsWith(html, header, footer));\n * const pdf = giga.htmlRenderWith(html, fonts, {\n * pageSize: \"A4\",\n * margin: { top: 72, bottom: 72, left: 54, right: 54 },\n * header: `<div style=\"text-align:center\">My Report</div>`,\n * footer: `<div style=\"text-align:center\">Page {{page}} / {{pages}}</div>`,\n * });\n * ```\n */\n htmlRenderWith(\n html: string,\n fonts: HtmlFont[] = [],\n options: HtmlRenderOptions = {}\n ): Uint8Array {\n let pw = options.pageWidth ?? 612;\n let ph = options.pageHeight ?? 792;\n if (options.pageSize) {\n const sz = this.pageSize(options.pageSize);\n if (!sz) throw new Error(`gigapdf: unknown page size \"${options.pageSize}\"`);\n pw = sz.w;\n ph = sz.h;\n }\n const m = options.margin ?? 36;\n const mg =\n typeof m === \"number\"\n ? { top: m, right: m, bottom: m, left: m }\n : { top: m.top ?? 36, right: m.right ?? 36, bottom: m.bottom ?? 36, left: m.left ?? 36 };\n const headerOffset = options.headerOffset ?? 18;\n const footerOffset = options.footerOffset ?? 18;\n const start = options.startPageNumber ?? 1;\n const blob = packHtmlFonts(fonts);\n const resBlob = packHtmlResources(options.resources ?? []);\n\n return this._withStr(html, (hp, hl) =>\n this._withBytes(blob, (fp, fl) =>\n this._withOptStr(options.header, (hdp, hdl) =>\n this._withOptStr(options.footer, (ftp, ftl) =>\n this._withBytes(resBlob, (rp, rl) =>\n this._buffer((o) =>\n this.ex.gp_html_render_opts(\n hp,\n hl,\n fp,\n fl,\n pw,\n ph,\n mg.top,\n mg.right,\n mg.bottom,\n mg.left,\n hdp,\n hdl,\n ftp,\n ftl,\n headerOffset,\n footerOffset,\n start,\n rp,\n rl,\n o\n )\n )\n )\n )\n )\n )\n );\n }\n\n /**\n * Phase 1 (unified) — every external resource the document needs the host to\n * fetch, in one list: fonts (`{kind:\"font\",family,weight,italic,url}`) and\n * external images (`{kind:\"image\",url}`). Run **one** fetch loop, then pass\n * fonts back as the `fonts` argument to {@link GigaPdfEngine.htmlRenderWith}\n * (download each `url` → TTF) and images via\n * {@link HtmlRenderOptions.resources} (`{url, bytes}`). `data:` image URIs are\n * inlined and never listed.\n */\n htmlNeededResources(html: string, header?: string, footer?: string): HtmlResourceNeed[] {\n return this._withStr(html, (hp, hl) =>\n this._withOptStr(header, (hdp, hdl) =>\n this._withOptStr(footer, (ftp, ftl) =>\n this._json((o) => this.ex.gp_html_needed_resources(hp, hl, hdp, hdl, ftp, ftl, o))\n )\n )\n ) as HtmlResourceNeed[];\n }\n\n // ── unified editable model: lower / edit / raise ───────────────────────────\n //\n // The {@link GigaDocument} model is a format-neutral tree (sections → pages →\n // blocks → runs). Lower any format into it (`*ToModel`), edit it with\n // {@link applyModelOps}, then raise it back to any format (`modelTo*`). This is\n // the substrate for a universal editor that edits every format the same way.\n\n /** Decode a model-JSON buffer returned by a `gp_model_*` export; `null` on an\n * empty (error) result. */\n private _modelOrNull(call: (outLenPtr: number) => number): GigaDocument | null {\n const s = this._str(call);\n return s ? (JSON.parse(s) as GigaDocument) : null;\n }\n\n /**\n * Lower an Office document (DOCX/XLSX/PPTX/ODT/ODS/ODP, auto-detected) into the\n * unified {@link GigaDocument} model. Returns `null` if the bytes aren't a\n * recognized Office container.\n */\n officeToModel(office: Uint8Array): GigaDocument | null {\n return this._withBytes(office, (p, l) =>\n this._modelOrNull((o) => this.ex.gp_model_from_office(p, l, o))\n );\n }\n\n /** Lower an HTML string into the unified {@link GigaDocument} model. */\n htmlToModel(html: string): GigaDocument {\n return this._withStr(html, (p, l) =>\n JSON.parse(this._str((o) => this.ex.gp_model_from_html(p, l, o)))\n ) as GigaDocument;\n }\n\n /**\n * Lower a Markdown string into the unified {@link GigaDocument} model\n * (CommonMark-ish: headings, lists, GFM tables, fenced code, emphasis/links).\n */\n mdToModel(md: string): GigaDocument {\n return this._withStr(md, (p, l) =>\n JSON.parse(this._str((o) => this.ex.gp_model_from_md(p, l, o)))\n ) as GigaDocument;\n }\n\n /**\n * Lower a CSV file (UTF-8 bytes, RFC 4180, auto-detected `,`/`;`/tab/`|`\n * delimiter) into the unified {@link GigaDocument} model as a single editable\n * table. Returns `null` if the bytes contain no parseable fields.\n */\n csvToModel(csv: Uint8Array): GigaDocument | null {\n return this._withBytes(csv, (p, l) =>\n this._modelOrNull((o) => this.ex.gp_model_from_csv(p, l, o))\n );\n }\n\n /**\n * Apply a batch of {@link ModelOp} edits to a model and return the edited\n * model. Ops run in order; out-of-range addresses (and any op that can't be\n * parsed) are silently skipped, so a partially-valid batch never throws.\n */\n applyModelOps(model: GigaDocument, ops: ModelOp[]): GigaDocument {\n return this._withStr(JSON.stringify(model), (mp, ml) =>\n this._withStr(JSON.stringify(ops), (op, ol) =>\n JSON.parse(this._str((o) => this.ex.gp_model_apply_ops(mp, ml, op, ol, o)))\n )\n ) as GigaDocument;\n }\n\n /** Raise a {@link GigaDocument} model to an editable Word document (`.docx`). */\n modelToDocx(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_docx(p, l, o))\n );\n }\n /** Raise a model to an Excel workbook (`.xlsx`). */\n modelToXlsx(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_xlsx(p, l, o))\n );\n }\n /** Raise a model to a PowerPoint presentation (`.pptx`). */\n modelToPptx(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_pptx(p, l, o))\n );\n }\n /** Raise a model to an OpenDocument Text (`.odt`). */\n modelToOdt(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_odt(p, l, o))\n );\n }\n /** Raise a model to an OpenDocument Spreadsheet (`.ods`). */\n modelToOds(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_ods(p, l, o))\n );\n }\n /** Raise a model to an OpenDocument Presentation (`.odp`). */\n modelToOdp(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_odp(p, l, o))\n );\n }\n /** Raise a model back to a PDF. */\n modelToPdf(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_pdf(p, l, o))\n );\n }\n /** Raise a model to standalone HTML (decoded UTF-8 string). */\n modelToHtml(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_html(p, l, o))\n );\n }\n /** Raise a model to RTF (decoded UTF-8 string). */\n modelToRtf(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_rtf(p, l, o))\n );\n }\n /** Raise a model to Markdown (decoded UTF-8 string). */\n modelToMarkdown(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_md(p, l, o))\n );\n }\n /** Raise a model to CSV (decoded UTF-8 string). */\n modelToCsv(model: GigaDocument): string {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._str((o) => this.ex.gp_model_to_csv(p, l, o))\n );\n }\n /** Raise a model to an EPUB e-book (`.epub`). */\n modelToEpub(model: GigaDocument): Uint8Array {\n return this._withStr(JSON.stringify(model), (p, l) =>\n this._buffer((o) => this.ex.gp_model_to_epub(p, l, o))\n );\n }\n}\n\n/**\n * Default TSA round trip for {@link GigaPdfDoc.signTimestamped}: POST the\n * RFC 3161 `TimeStampReq` to `url` as `application/timestamp-query` and return\n * the raw `TimeStampResp` (`application/timestamp-reply`) body. Works in both\n * Node and the browser via the global `fetch`.\n *\n * No SSRF allow-listing is performed here — the URL is host-supplied. Consumers\n * that need to restrict it should pass their own `tsaFetch`.\n */\nexport async function defaultTsaPost(url: string, req: Uint8Array): Promise<Uint8Array> {\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/timestamp-query\" },\n body: req as BodyInit,\n redirect: \"error\",\n });\n if (!res.ok) {\n throw new Error(`TSA HTTP ${res.status}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/** Pack `HtmlResource[]` (host-fetched URLs) into the little-endian blob\n * `gp_html_render_opts` expects: `u32 count`, then per entry `u32 url_len, url,\n * u32 data_len, data`. */\nfunction packHtmlResources(resources: HtmlResource[]): Uint8Array {\n let size = 4;\n for (const r of resources) size += 4 + enc.encode(r.url).length + 4 + r.bytes.length;\n const buf = new Uint8Array(size);\n const dv = new DataView(buf.buffer);\n let o = 0;\n dv.setUint32(o, resources.length, true);\n o += 4;\n for (const r of resources) {\n const url = enc.encode(r.url);\n dv.setUint32(o, url.length, true);\n o += 4;\n buf.set(url, o);\n o += url.length;\n dv.setUint32(o, r.bytes.length, true);\n o += 4;\n buf.set(r.bytes, o);\n o += r.bytes.length;\n }\n return buf;\n}\n\n/** Pack `HtmlFont[]` into the little-endian blob `gp_html_render` expects. */\nfunction packHtmlFonts(fonts: HtmlFont[]): Uint8Array {\n let size = 4;\n for (const f of fonts) size += 4 + enc.encode(f.family).length + 2 + 1 + 4 + f.ttf.length;\n const buf = new Uint8Array(size);\n const dv = new DataView(buf.buffer);\n let o = 0;\n dv.setUint32(o, fonts.length, true);\n o += 4;\n for (const f of fonts) {\n const fam = enc.encode(f.family);\n dv.setUint32(o, fam.length, true);\n o += 4;\n buf.set(fam, o);\n o += fam.length;\n dv.setUint16(o, f.weight, true);\n o += 2;\n buf[o] = f.italic ? 1 : 0;\n o += 1;\n dv.setUint32(o, f.ttf.length, true);\n o += 4;\n buf.set(f.ttf, o);\n o += f.ttf.length;\n }\n return buf;\n}\n\n/** A Google font the HTML engine needs (resolved from the catalogue). */\nexport interface HtmlFontRequest {\n family: string;\n weight: number;\n italic: boolean;\n /** Google Fonts CSS URL — the host fetches it to obtain the TTF. */\n url: string;\n}\n\n/** A downloaded font handed to {@link GigaPdfEngine.htmlRender}. */\nexport interface HtmlFont {\n family: string;\n weight: number;\n italic: boolean;\n ttf: Uint8Array;\n}\n\n/**\n * A host-downloaded external resource (image) handed to\n * {@link GigaPdfEngine.htmlRenderWith} via {@link HtmlRenderOptions.resources}.\n * `url` must match the URL referenced in the HTML exactly.\n */\nexport interface HtmlResource {\n url: string;\n bytes: Uint8Array;\n}\n\n/**\n * One entry from {@link GigaPdfEngine.htmlNeededResources}: a `font` (with its\n * Google-Fonts download metadata) or an external `image` URL the host must fetch.\n */\nexport type HtmlResourceNeed =\n | { kind: \"font\"; family: string; weight: number; italic: boolean; url: string }\n | { kind: \"image\"; url: string };\n\n/** Per-side page margins in points; omitted sides default to 36pt. */\nexport interface HtmlMargins {\n top?: number;\n right?: number;\n bottom?: number;\n left?: number;\n}\n\n/** Page setup for {@link GigaPdfEngine.htmlRenderWith}. */\nexport interface HtmlRenderOptions {\n /** Named paper size (`\"A4\"`, `\"a3-landscape\"`, `\"letter\"`, …) — wins over width/height. */\n pageSize?: string;\n /** Explicit page width in points (default 612 = US Letter). Ignored if `pageSize` is set. */\n pageWidth?: number;\n /** Explicit page height in points (default 792). Ignored if `pageSize` is set. */\n pageHeight?: number;\n /** Uniform margin (points) or per-side margins. Default 36pt (0.5in). */\n margin?: number | HtmlMargins;\n /** Running header HTML painted in the top margin (`{{page}}` / `{{pages}}` tokens). */\n header?: string;\n /** Running footer HTML painted in the bottom margin (same tokens). */\n footer?: string;\n /** Distance from the top edge to the header block, in points (default 18). */\n headerOffset?: number;\n /** Distance from the bottom edge to the footer block, in points (default 18). */\n footerOffset?: number;\n /** Number assigned to the first page for `{{page}}` (default 1). */\n startPageNumber?: number;\n /**\n * Host-downloaded external images, keyed by the exact URL referenced in the\n * HTML (`<img src>`). Obtain the list with\n * {@link GigaPdfEngine.htmlNeededResources}, fetch each, and pass the bytes\n * here — the engine never touches the network. `data:` URIs need no entry.\n */\n resources?: HtmlResource[];\n}\n\nexport interface FontInfo {\n family: string;\n category: string;\n google: boolean;\n weights: number[];\n}\n/** A font embedded in a document (from {@link GigaPdfDoc.embeddedFonts}). */\nexport interface EmbeddedFont {\n /** The `/BaseFont` name (may carry a `ABCDEF+` subset prefix). */\n baseFont: string;\n /**\n * Embedded program format. `truetype` (glyf) and a full OpenType `cff`\n * (`OTTO`) re-embed directly via {@link GigaPdfDoc.embedFont}; bare `cff`\n * (Type1C) and `type1` are read-only here.\n */\n format: \"truetype\" | \"cff\" | \"type1\";\n}\nexport interface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\nexport interface Element extends Partial<Box> {\n index: number;\n kind: \"text\" | \"image\" | \"shape\";\n label: string;\n}\n/**\n * A text element from {@link GigaPdfDoc.textElements}: the decoded text plus\n * everything a host editor needs to recreate the run. `index` is the text-run\n * index accepted by {@link GigaPdfDoc.replaceText}; the bounding box is page\n * user space (origin bottom-left).\n */\nexport interface TextElementInfo {\n index: number;\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n /** Resolved `/BaseFont` family (e.g. \"Helvetica\", \"Times New Roman\"). */\n fontFamily: string;\n /**\n * The raw `/BaseFont` name with the subset prefix kept (e.g.\n * `\"ABCDEF+TimesNewRomanPSMT\"`), resolved against the run's own scope — the\n * page, or the form XObject the run is drawn inside. Lets a host target the\n * exact embedded subset rather than only the collapsed {@link fontFamily}.\n * Empty when the run's font carried no `/BaseFont` (e.g. a Type3 font).\n */\n baseFont: string;\n bold: boolean;\n italic: boolean;\n /** Effective glyph size in points. */\n fontSize: number;\n /** RGB fill colour, `0..1` per channel. */\n color: [number, number, number];\n /** Baseline rotation in degrees (0 = upright). */\n rotation: number;\n /**\n * Reading direction of this run by its strong characters: `\"rtl\"` for\n * Arabic/Hebrew, `\"ltr\"` for Latin/Greek/Cyrillic/CJK, `\"neutral\"` when the\n * run is only digits/punctuation/whitespace.\n */\n direction: 'ltr' | 'rtl' | 'neutral';\n}\n/**\n * The aggregate language signal of a document from\n * {@link GigaPdfDoc.documentLanguage}: its dominant reading {@link\n * TextElementInfo.direction | direction}, writing system, and a best-effort\n * ISO-639-1 language code (`\"ar\"`, `\"he\"`, `\"zh\"`/`\"ja\"`…), `undefined` when\n * the script does not pin a single language (e.g. plain Latin).\n */\nexport interface DocumentLanguage {\n direction: 'ltr' | 'rtl' | 'neutral';\n /** Dominant script: `\"arabic\" | \"hebrew\" | \"latin\" | \"greek\" | \"cyrillic\" | \"cjk\" | \"other\"`. */\n script: string;\n /** Best-effort ISO-639-1 code, or `undefined` when undecidable. */\n lang?: string;\n}\n\n// ── unified editable model (structural mirror of crate::model::Document JSON) ──\n//\n// These interfaces are a permissive, partial mirror of the model's stable JSON\n// envelope. They give a host enough structure to read and rebuild a model (the\n// fields it edits) without re-declaring every leaf; opaque sub-objects are typed\n// loosely. The producers ({@link GigaPdfDoc.toModel}, {@link\n// GigaPdfEngine.officeToModel}, {@link GigaPdfEngine.htmlToModel}) and the\n// consumers ({@link GigaPdfEngine.modelToDocx} …) all round-trip this shape.\n\n/** A portable font fallback class (mirrors `convert::style::Generic`). */\nexport type GigaGeneric = 'sans' | 'serif' | 'mono';\n\n/** A run's character style (mirror of `model::style::CharStyle`'s JSON). */\nexport interface GigaCharStyle {\n family: string;\n generic: GigaGeneric;\n size_pt: number;\n bold: boolean;\n italic: boolean;\n underline: boolean;\n strike: boolean;\n /** RGB `0..=1`, or `null` for default black. */\n color: [number, number, number] | null;\n valign: 'baseline' | 'super' | 'sub';\n}\n\n/** An axis-aligned placement box, lower-left `(x,y)` + size, in PDF points. */\nexport interface GigaRect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** A hyperlink destination (tagged; mirror of `model::LinkTarget`). */\nexport type GigaLinkTarget =\n | { t: 'url'; v: string }\n | { t: 'page'; v: number };\n\n/**\n * An inline (within-paragraph) node, tagged by `t` (mirror of `model::Inline`).\n * `run` carries the styled text + its `source_index` back to the editable\n * content-stream operator; `br` is a hard line break; `image` an inline image;\n * `link` wraps children with a destination.\n */\nexport type GigaInline =\n | { t: 'run'; v: GigaInlineRun }\n | { t: 'br' }\n | { t: 'image'; v: GigaImageRef }\n | { t: 'link'; href: GigaLinkTarget; children: GigaInline[] };\n\n/** A styled span of text (mirror of `model::InlineRun`). */\nexport interface GigaInlineRun {\n text: string;\n style: GigaCharStyle;\n /** Index of the source content-stream run for in-place round-tripping, or `null`. */\n source_index: number | null;\n}\n\n/** Paragraph-level formatting (mirror of `model::style::ParagraphStyle`). */\nexport interface GigaParagraphStyle {\n align: 'left' | 'center' | 'right' | 'justify';\n space_before_pt: number;\n space_after_pt: number;\n indent_left_pt: number;\n indent_right_pt: number;\n /** First-line indent (positive) or hanging indent (negative), in points. */\n first_line_pt: number;\n /** Leading policy: font-natural, a size multiple, or a fixed point value. */\n line_height:\n | { t: 'normal' }\n | { t: 'multiple'; v: number }\n | { t: 'points'; v: number };\n}\n\n/** A paragraph: its own style, an optional named-style ref, and its inline runs. */\nexport interface GigaParagraph {\n style: GigaParagraphStyle;\n /** Named style this paragraph derives from, if any. */\n style_ref: string | null;\n runs: GigaInline[];\n}\n\n/** A heading (`level` 1..=6) wrapping a paragraph (mirror of `model::Heading`). */\nexport interface GigaHeading {\n level: number;\n para: GigaParagraph;\n}\n\n/** A list bullet/number style (tagged; mirror of `model::ListMarker`). */\nexport type GigaListMarker =\n | { t: 'bullet'; v: string }\n | { t: 'decimal' }\n | { t: 'lower_alpha' }\n | { t: 'upper_alpha' }\n | { t: 'lower_roman' }\n | { t: 'upper_roman' };\n\n/** One list item: nested blocks at a given `level` (mirror of `model::ListItem`). */\nexport interface GigaListItem {\n blocks: GigaBlock[];\n level: number;\n}\n\n/** An ordered or unordered list (mirror of `model::List`). */\nexport interface GigaList {\n ordered: boolean;\n marker: GigaListMarker;\n items: GigaListItem[];\n}\n\n/** A table cell: block content, span, and optional RGB shading (`model::Cell`). */\nexport interface GigaTableCell {\n blocks: GigaBlock[];\n col_span: number;\n row_span: number;\n /** RGB `0..=1` background, or `null` for no shading. */\n shading: [number, number, number] | null;\n}\n\n/** A table row: its cells and an optional fixed height in points (`model::Row`). */\nexport interface GigaTableRow {\n cells: GigaTableCell[];\n height: number | null;\n}\n\n/** A table/cell border (mirror of `model::BorderStyle`). */\nexport interface GigaBorderStyle {\n width: number;\n color: [number, number, number];\n}\n\n/** A table: rows of cells, explicit column widths, and a border (`model::Table`). */\nexport interface GigaTable {\n rows: GigaTableRow[];\n col_widths: number[];\n border: GigaBorderStyle;\n}\n\n/** A reference to an image blob in the document's resource table (`model::ImageRef`). */\nexport interface GigaImageRef {\n /** Content-hash key into `GigaDocument.resources.images`. */\n resource: number;\n alt: string | null;\n}\n\n/** A single vector path segment (tagged; mirror of `content::vector::PathSeg`). */\nexport type GigaPathSeg =\n | { t: 'm'; x: number; y: number }\n | { t: 'l'; x: number; y: number }\n | { t: 'c'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }\n | { t: 'z' };\n\n/** A vector shape: a path with fill/stroke styling (mirror of `model::Shape`). */\nexport interface GigaShape {\n segments: GigaPathSeg[];\n /** RGB `0..=1` fill, or `null` when unfilled. */\n fill: [number, number, number] | null;\n /** RGB `0..=1` stroke, or `null` when unstroked. */\n stroke: [number, number, number] | null;\n stroke_width: number;\n dash: number[];\n}\n\n/** A free-floating text box holding a list of blocks (mirror of `model::TextBox`). */\nexport interface GigaTextBox {\n blocks: GigaBlock[];\n}\n\n/** A typed spreadsheet cell (mirror of `model::SheetCell`). */\nexport interface GigaSheetCell {\n value: GigaCellValue;\n number_format: string | null;\n /** RGB `0..=1` cell fill, or `null` for none. */\n fill: [number, number, number] | null;\n style: GigaCharStyle;\n}\n\n/** One spreadsheet row (mirror of `model::SheetRow`). */\nexport interface GigaSheetRow {\n cells: GigaSheetCell[];\n}\n\n/** An inclusive merged-cell rectangle `(r0,c0)..=(r1,c1)`, zero-based. */\nexport interface GigaMergeRange {\n r0: number;\n c0: number;\n r1: number;\n c1: number;\n}\n\n/** A single named worksheet (mirror of `model::Sheet`). */\nexport interface GigaSheet {\n name: string;\n rows: GigaSheetRow[];\n merges: GigaMergeRange[];\n col_widths: number[];\n}\n\n/** A block of spreadsheet content: one or more sheets (mirror of `model::SheetBlock`). */\nexport interface GigaSheetBlock {\n sheets: GigaSheet[];\n}\n\n/** A slide layout placeholder role (tagged; mirror of `model::PlaceholderRole`). */\nexport type GigaPlaceholderRole =\n | { t: 'title' }\n | { t: 'subtitle' }\n | { t: 'body' }\n | { t: 'other'; v: string };\n\n/** A slide placeholder: a block tagged with its semantic role (`model::Placeholder`). */\nexport interface GigaPlaceholder {\n role: GigaPlaceholderRole;\n block: GigaBlock;\n}\n\n/** Resolved page size + margins, in points (mirror of `model::geom::PageGeometry`). */\nexport interface GigaPageGeometry {\n width: number;\n height: number;\n margins: { top: number; right: number; bottom: number; left: number };\n}\n\n/** A single slide (mirror of `model::Slide`). */\nexport interface GigaSlide {\n geometry: GigaPageGeometry;\n shapes: GigaBlock[];\n placeholders: GigaPlaceholder[];\n notes: GigaBlock[] | null;\n}\n\n/** A block of presentation content: an ordered list of slides (`model::SlideBlock`). */\nexport interface GigaSlideBlock {\n slides: GigaSlide[];\n}\n\n/**\n * A block payload, **fully typed and discriminated by `t`** (mirror of\n * `model::BlockKind`'s JSON). Narrow on `kind.t` to read the variant body in\n * `kind.v` — e.g. a `paragraph` exposes `v.runs` (each `run` carrying\n * `style.bold`/`style.italic`/`style.size_pt`/`style.color`), a `heading` its\n * `v.level`, a `table` its `v.rows[].cells[]` (with `col_span`/`row_span`), and a\n * `list` its `v.ordered` + `v.items`. This is what lets a thin editor render the\n * recognised structure (bold, headings, tables, lists) 1:1.\n */\nexport type GigaBlockKind =\n | { t: 'paragraph'; v: GigaParagraph }\n | { t: 'heading'; v: GigaHeading }\n | { t: 'list'; v: GigaList }\n | { t: 'table'; v: GigaTable }\n | { t: 'image'; v: GigaImageRef }\n | { t: 'shape'; v: GigaShape }\n | { t: 'textbox'; v: GigaTextBox }\n | { t: 'sheet'; v: GigaSheetBlock }\n | { t: 'slide'; v: GigaSlideBlock };\n\n/** Block rotation (tagged; mirror of `model::geom::Rotation`). */\nexport type GigaRotation =\n | { t: 'd0' }\n | { t: 'd90' }\n | { t: 'd180' }\n | { t: 'd270' }\n | { t: 'deg'; v: number };\n\n/** A block: a stable id, an optional placement frame + rotation, and its kind. */\nexport interface GigaBlock {\n id: number;\n frame: GigaRect | null;\n rotation: GigaRotation;\n kind: GigaBlockKind;\n}\n\n/** A page: a list of blocks; `absolute` flags slide/form (positioned) layout. */\nexport interface GigaPage {\n blocks: GigaBlock[];\n absolute: boolean;\n}\n\n/** A section: one page geometry, optional running header/footer, and its pages. */\nexport interface GigaSection {\n geometry: GigaPageGeometry;\n header: GigaBlock[] | null;\n footer: GigaBlock[] | null;\n pages: GigaPage[];\n}\n\n/**\n * A document outline (bookmark) entry — a label, a zero-based destination page,\n * and nested children (mirror of `model::OutlineNode`). Populated by\n * {@link GigaPdfEngine.officeToModel}/reconstruction from the source's own bookmarks\n * (PDF `/Outlines`) or, lacking those, from detected headings.\n */\nexport interface GigaOutlineNode {\n /** The bookmark label. */\n title: string;\n /** Zero-based destination page in the document's flattened page sequence. */\n page: number;\n /** Nested sub-bookmarks. */\n children: GigaOutlineNode[];\n}\n\n/**\n * The unified editable document model — the format-neutral tree every format\n * lowers into and is reconstructed from. `v` is the envelope version. Leaves\n * beyond what a host typically edits (`styles`, `resources`) are carried\n * opaquely so a round-trip preserves them.\n */\nexport interface GigaDocument {\n v: number;\n meta: {\n title: string | null;\n author: string | null;\n subject: string | null;\n keywords: string[];\n lang: string | null;\n };\n styles: unknown;\n sections: GigaSection[];\n /** Bookmark / chapter hierarchy (empty when the source has none). */\n outline: GigaOutlineNode[];\n resources: unknown;\n}\n\n/**\n * A positional block address `[section, page, index]` (all zero-based) — the\n * stable handle an edit op uses to target a block (mirrors `model::BlockAddr`).\n */\nexport type GigaBlockAddr = [section: number, page: number, index: number];\n\n/**\n * A character-style patch for restyle/insert ops: only the present fields are\n * applied (mirror of `model::edit::StylePatch`). `color: null` clears the colour\n * (→ default black); omitting `color` leaves it unchanged.\n */\nexport interface GigaStylePatch {\n family?: string;\n generic?: GigaGeneric;\n size_pt?: number;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strike?: boolean;\n color?: [number, number, number] | null;\n}\n\n/**\n * A paragraph-style patch for {@link ModelOp} `setParagraphStyle`: only the\n * present fields are applied (mirror of `model::edit::ParaPatch`). Keys are the\n * op's short names (`indent_left`, not `indent_left_pt`); values in PDF points.\n * Omitting a field leaves the existing value unchanged.\n */\nexport interface GigaParaPatch {\n align?: 'left' | 'center' | 'right' | 'justify';\n indent_left?: number;\n indent_right?: number;\n /** First-line indent (positive) or hanging indent (negative), in points. */\n first_line?: number;\n space_before?: number;\n space_after?: number;\n /** Leading policy: font-natural, a size multiple, or a fixed point value. */\n line_height?: { t: 'normal' } | { t: 'multiple'; v: number } | { t: 'points'; v: number };\n}\n\n/** A typed spreadsheet cell value (tagged; mirror of `model::CellValue`). */\nexport type GigaCellValue =\n | { t: 'empty' }\n | { t: 'text'; v: string }\n | { t: 'number'; v: number }\n | { t: 'bool'; v: boolean };\n\n/**\n * A single editing operation against a {@link GigaDocument} model, mirroring the\n * JSON shape of `model::edit::ModelOp`. Pass an array to\n * {@link GigaPdfEngine.applyModelOps}; ops run in order and out-of-range\n * addresses are no-ops.\n */\nexport type ModelOp =\n | { op: 'setRunText'; addr: GigaBlockAddr; run: number; text: string }\n | { op: 'restyleRun'; addr: GigaBlockAddr; run: number; style: GigaStylePatch }\n | { op: 'insertRun'; addr: GigaBlockAddr; run: number; text: string; style?: GigaStylePatch }\n | { op: 'deleteRun'; addr: GigaBlockAddr; run: number }\n | { op: 'insertBlock'; addr: GigaBlockAddr; block: GigaBlock }\n | { op: 'deleteBlock'; addr: GigaBlockAddr }\n | { op: 'moveBlock'; addr: GigaBlockAddr; to: GigaBlockAddr }\n | { op: 'setBlockText'; addr: GigaBlockAddr; text: string }\n | { op: 'restyleBlock'; addr: GigaBlockAddr; style: GigaStylePatch }\n | { op: 'setCellText'; addr: GigaBlockAddr; row: number; col: number; text: string }\n | {\n op: 'setSheetCell';\n addr: GigaBlockAddr;\n sheet: number;\n row: number;\n col: number;\n value: GigaCellValue;\n }\n // Structural table edits. These keep the column geometry (`col_widths` +\n // per-cell spans) coherent: an inserted row spans every logical column, an\n // inserted column passes through any merge it lands inside, and deletes shrink\n // or drop the cells/spans they touch. `at` is a grid index (clamped).\n | { op: 'insertTableRow'; addr: GigaBlockAddr; at: number }\n | { op: 'deleteTableRow'; addr: GigaBlockAddr; at: number }\n | { op: 'insertTableColumn'; addr: GigaBlockAddr; at: number }\n | { op: 'deleteTableColumn'; addr: GigaBlockAddr; at: number }\n | {\n op: 'setCellSpan';\n addr: GigaBlockAddr;\n /** Row index in `rows`. */\n row: number;\n /** Cell index in `rows[row].cells` (not a grid column). */\n col: number;\n /** Columns the cell spans (clamped to ≥ 1). */\n col_span: number;\n /** Rows the cell spans (clamped to ≥ 1). */\n row_span: number;\n }\n // Structural spreadsheet edits: shift cells and re-map merge ranges. `at` is a\n // row/column index (clamped); merges that collapse are dropped.\n | { op: 'insertSheetRow'; addr: GigaBlockAddr; sheet: number; at: number }\n | { op: 'deleteSheetRow'; addr: GigaBlockAddr; sheet: number; at: number }\n | { op: 'insertSheetColumn'; addr: GigaBlockAddr; sheet: number; at: number }\n | { op: 'deleteSheetColumn'; addr: GigaBlockAddr; sheet: number; at: number }\n // ── paragraph formatting ──\n | { op: 'setParagraphStyle'; addr: GigaBlockAddr; patch: GigaParaPatch }\n // ── list ──\n | { op: 'setListLevel'; addr: GigaBlockAddr; level: number }\n | { op: 'setListMarker'; addr: GigaBlockAddr; marker: GigaListMarker }\n | { op: 'setListOrdered'; addr: GigaBlockAddr; ordered: boolean }\n // ── absolute block placement ──\n | { op: 'setBlockFrame'; addr: GigaBlockAddr; rect: GigaRect }\n /** `deg` is CCW; 0/90/180/270 snap to exact rotations, else an arbitrary angle. */\n | { op: 'setBlockRotation'; addr: GigaBlockAddr; deg: number }\n // ── table shading & geometry ──\n /** `color: null` clears the cell's shading; a triple sets it. */\n | {\n op: 'setCellShading';\n addr: GigaBlockAddr;\n row: number;\n col: number;\n color: [number, number, number] | null;\n }\n | { op: 'setRowHeight'; addr: GigaBlockAddr; row: number; height: number }\n | { op: 'setColWidth'; addr: GigaBlockAddr; col: number; width: number }\n | { op: 'setTableBorder'; addr: GigaBlockAddr; border: GigaBorderStyle };\n/**\n * An image element from {@link GigaPdfDoc.imageElements}: its placement box\n * (page user space, origin bottom-left), the embeddable encoded bytes + format,\n * and the source pixel dimensions. `data` is empty when `format` is `\"unknown\"`.\n */\nexport interface ImageElementInfo {\n /**\n * The image's **unified element index** — the same value accepted by\n * {@link GigaPdfDoc.removeElement} / {@link GigaPdfDoc.transformElement} /\n * {@link GigaPdfDoc.duplicateElement} / {@link GigaPdfDoc.moveElement}. Extract\n * an image here and pass this index to edit *that exact* image. It is **not** an\n * image-local 0,1,2 counter, so it is correct on pages that also have text/paths.\n */\n index: number;\n x: number;\n y: number;\n width: number;\n height: number;\n /** `\"jpeg\"` | `\"png\"` | `\"jp2\"` | `\"unknown\"`. */\n format: string;\n pixelWidth: number;\n pixelHeight: number;\n /** Embeddable encoded image bytes (empty when `format === \"unknown\"`). */\n data: Uint8Array;\n /** Rotation in degrees from the placement CTM (`0` = upright). */\n rotation: number;\n /** Non-stroking fill alpha (`/ExtGState` `/ca`), `0..=1` (`1` = opaque). */\n opacity: number;\n}\n/**\n * One path segment from {@link GigaPdfDoc.vectorPaths} (page user space, origin\n * bottom-left). `op` is `\"M\"` (move, 2 pts), `\"L\"` (line, 2 pts), `\"C\"` (cubic\n * Bézier, 6 pts: cp1 cp2 end) or `\"Z\"` (close, 0 pts). `pts` is the flat\n * coordinate list.\n */\nexport interface PathSegment {\n op: \"M\" | \"L\" | \"C\" | \"Z\";\n pts: number[];\n}\n/**\n * A painted vector path from {@link GigaPdfDoc.vectorPaths}: its geometry\n * (segments, bounds) plus the graphics state — fill/stroke RGB (`0..=1`, `null`\n * when the paint op doesn't fill/stroke), line width, alpha and dash. Clip-only\n * paths are omitted. The native equivalent of a reader's shape/vector layer.\n */\nexport interface VectorPathInfo {\n /**\n * The path's **unified element index** — the same value accepted by\n * {@link GigaPdfDoc.setPathStyle} / {@link GigaPdfDoc.removeElement} /\n * {@link GigaPdfDoc.transformElement}. Extract a path here and pass this index\n * to restyle or remove *that exact* path. Clip-only paths are not reported, so\n * the painted path you see is the one your index targets — not a path-local ordinal.\n */\n index: number;\n /** Whether `x0..y1` describe a real box (`false` for a degenerate path). */\n hasBounds: boolean;\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n segments: PathSegment[];\n /** Fill colour `[r,g,b]` in `0..=1`, or `null` when not filled. */\n fill: [number, number, number] | null;\n /** Stroke colour `[r,g,b]` in `0..=1`, or `null` when not stroked. */\n stroke: [number, number, number] | null;\n /** Line width (`w`) in user-space units. */\n strokeWidth: number;\n /** Non-stroking alpha (`/ca`), `0..=1`. */\n fillAlpha: number;\n /** Stroking alpha (`/CA`), `0..=1`. */\n strokeAlpha: number;\n /** Dash pattern (`d` array); empty for a solid line. */\n dash: number[];\n}\nexport interface TextLine extends Box {\n text: string;\n}\nexport interface SearchHit extends Box {\n page: number;\n text: string;\n}\nexport interface TextRunInfo {\n index: number;\n operator: string;\n text: string;\n}\n/** Signature-dictionary metadata for {@link GigaPdfDoc.signP12}. */\nexport interface SignP12Options {\n /** `/Name` — human-readable signer name. */\n name?: string;\n /** `/Reason` — why the document is being signed. */\n reason?: string;\n /** `/M` — signing time as a PDF date string, e.g. `D:20260616120000Z`. */\n date?: string;\n /** `/Location` — physical or logical signing location. */\n location?: string;\n /** `/ContactInfo` — how to reach the signer. */\n contactInfo?: string;\n}\n/**\n * Options for {@link GigaPdfDoc.signTimestamped} — a PAdES-B-T signature with an\n * RFC 3161 trusted timestamp embedded in the SignerInfo (`ETSI.CAdES.detached`\n * subfilter, `signing-certificate-v2` signed attribute, `id-aa-timeStampToken`\n * unsigned attribute).\n *\n * The signing identity is either an imported PKCS#12 (`p12` + `password`) or, if\n * `p12` is omitted, a freshly generated self-signed digital ID (`random` +\n * `notBefore`/`notAfter`).\n */\nexport interface SignTsaOptions extends SignP12Options {\n /** TSA endpoint URL, e.g. `\"https://freetsa.org/tsr\"`. */\n tsaUrl: string;\n /**\n * Optional override for the TSA round trip — lets the host add auth headers,\n * proxies, retries, **and apply its own SSRF allow-list** (the engine only\n * emits the request; the URL is host-supplied). Receives the `TimeStampReq`\n * DER and the URL, must resolve to the raw `TimeStampResp` bytes. When omitted,\n * {@link defaultTsaPost} POSTs `application/timestamp-query` via `fetch`.\n */\n tsaFetch?: (req: Uint8Array, url: string) => Promise<Uint8Array>;\n /** PKCS#12 identity bytes. Omit to sign with a generated self-signed ID. */\n p12?: Uint8Array;\n /** PKCS#12 passphrase. */\n password?: string;\n /** Self-signed path: ≥ 256 bytes from `crypto.getRandomValues`. */\n random?: Uint8Array;\n /** Self-signed path: RSA modulus size in bits (default 2048). */\n keyBits?: number;\n /** Self-signed path: certificate `notBefore`, UTCTime `YYMMDDHHMMSSZ`. */\n notBefore?: string;\n /** Self-signed path: certificate `notAfter`, UTCTime `YYMMDDHHMMSSZ`. */\n notAfter?: string;\n /** Optional 8–16 random bytes echoed by the TSA (request/response correlation). */\n nonce?: Uint8Array;\n}\n\n/**\n * Options for {@link GigaPdfDoc.signLtv} — a PAdES long-term validation\n * signature: a B-T signature, then a `/DSS` (Document Security Store) carrying\n * the certificate chain + OCSP/CRL revocation material the host fetched (B-LT),\n * optionally finished with a document timestamp over the whole file (B-LTA).\n *\n * Extends {@link SignTsaOptions}: the B-T signature is produced exactly as\n * {@link GigaPdfDoc.signTimestamped}, then the LTV material is added. The OCSP/CRL\n * URLs come from the **certificates**, so the host fetches them — supply\n * `revocationFetch`/`crlFetch` to add auth, proxies, or an SSRF allow-list (the\n * engine only computes which URLs to fetch).\n */\nexport interface SignLtvOptions extends SignTsaOptions {\n /**\n * Add a B-LTA **document timestamp** over the whole file (DSS included) after\n * the DSS. Requires a second TSA round trip. Default `false` (B-LT only).\n */\n archiveTimestamp?: boolean;\n /**\n * Override the OCSP round trip — receives the DER `OCSPRequest` and the\n * responder URL, must resolve to the raw `OCSPResponse` bytes. When omitted,\n * {@link defaultOcspPost} POSTs `application/ocsp-request` via `fetch`. Throw to\n * skip an unreachable responder (the DSS is built from whatever succeeds).\n */\n revocationFetch?: (req: Uint8Array, url: string) => Promise<Uint8Array>;\n /**\n * Override the CRL fetch — receives the CRL distribution-point URL, must\n * resolve to the raw `CertificateList` (CRL) bytes. When omitted,\n * {@link defaultCrlGet} GETs the URL. Throw to skip an unreachable CRL.\n */\n crlFetch?: (url: string) => Promise<Uint8Array>;\n}\n\n/**\n * Default OCSP round trip for {@link GigaPdfDoc.signLtv}: POST the DER\n * `OCSPRequest` to `url` as `application/ocsp-request` and return the raw\n * `OCSPResponse` body. No SSRF allow-listing — the URL comes from the\n * certificate's AIA extension; pass `revocationFetch` to restrict it.\n */\nexport async function defaultOcspPost(req: Uint8Array, url: string): Promise<Uint8Array> {\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/ocsp-request\" },\n body: req as BodyInit,\n redirect: \"error\",\n });\n if (!res.ok) {\n throw new Error(`OCSP HTTP ${res.status}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/**\n * Default CRL fetch for {@link GigaPdfDoc.signLtv}: GET the `CertificateList`\n * (CRL) from `url`. No SSRF allow-listing — the URL comes from the certificate's\n * CRL-DP extension; pass `crlFetch` to restrict it.\n */\nexport async function defaultCrlGet(url: string): Promise<Uint8Array> {\n const res = await fetch(url, { method: \"GET\", redirect: \"error\" });\n if (!res.ok) {\n throw new Error(`CRL HTTP ${res.status}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/** Decode a lowercase/uppercase hex string into bytes (LTV targets carry binary\n * fields — certificate DER, OCSP requests — as hex inside JSON). */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length >> 1);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return out;\n}\n\n/** Length-frame a list of byte blobs as `[u32 LE count]([u32 LE len][bytes])*`\n * — the binary multi-blob form `gp_apply_dss` reads for certs/OCSPs/CRLs. */\nfunction frameBlobs(blobs: Uint8Array[]): Uint8Array {\n let total = 4;\n for (const b of blobs) total += 4 + b.length;\n const out = new Uint8Array(total);\n const view = new DataView(out.buffer);\n view.setUint32(0, blobs.length, true);\n let pos = 4;\n for (const b of blobs) {\n view.setUint32(pos, b.length, true);\n pos += 4;\n out.set(b, pos);\n pos += b.length;\n }\n return out;\n}\n\n/** One certificate's LTV fetch plan, decoded from the `gp_ltv_targets` JSON. */\ninterface LtvTarget {\n certHex: string;\n sources: Array<\n | { kind: \"ocsp\"; url: string; requestHex: string }\n | { kind: \"crl\"; url: string }\n >;\n}\n/**\n * A markup annotation (rect corners in PDF user space, origin bottom-left).\n * Carries the common metadata plus the type-specific geometry a host editor\n * needs: text-markup `quadPoints`, freehand `inkList`, `stamp` name, and the\n * link target (`linkUri` / `linkPage`).\n */\nexport interface AnnotationInfo {\n index: number;\n subtype: string;\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n contents: string;\n /** `/T` — author / title. Empty when absent. */\n author: string;\n /** `/Subj` — subject. Empty when absent. */\n subject: string;\n /** `/CreationDate` — raw PDF date (`D:YYYYMMDD…`). Empty when absent. */\n created: string;\n /** `/M` — raw PDF modification date. Empty when absent. */\n modified: string;\n /** `/Name` — stamp name (e.g. `\"Approved\"`). Empty when absent. */\n name: string;\n /** `/CA` non-stroking opacity, `0..=1` (`1` = opaque). */\n opacity: number;\n /** `/C` normalised to RGB `0..=1` (`[]` when no colour). */\n color: number[];\n /** `/QuadPoints` (8 values per quad) for text-markup annotations. */\n quadPoints: number[];\n /** `/InkList` — one inner array per freehand stroke (`x y x y …`). */\n inkList: number[][];\n /** Link external URI (`/A /URI`). Empty when internal/absent. */\n linkUri: string;\n /** Link internal destination page (1-based); `0` when external/absent. */\n linkPage: number;\n}\n/** A hyperlink annotation; `kind` discriminates the target. */\nexport interface LinkInfo {\n index: number;\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n kind: \"uri\" | \"page\" | \"unknown\";\n uri?: string;\n page?: number;\n}\nexport type FieldKind =\n | \"text\"\n | \"checkbox\"\n | \"radio\"\n | \"pushbutton\"\n | \"combo\"\n | \"list\"\n | \"signature\"\n | \"unknown\";\n/** An AcroForm field with its flags and (for choices) options. */\n/** One signature on the document (a `/Sig` field's `/V`), from {@link GigaPdfDoc.signatures}. */\nexport interface SignatureInfo {\n /** The signature field's `/T` name. */\n fieldName: string;\n /** The signer name (`/Name`), or `null`. */\n signerName: string | null;\n /** The stated reason (`/Reason`), or `null`. */\n reason: string | null;\n /** The stated location (`/Location`), or `null`. */\n location: string | null;\n /** The signing date string (`/M`, e.g. `D:20260624…`), or `null`. */\n date: string | null;\n /** The `/SubFilter` (e.g. `adbe.pkcs7.detached`), or `null`. */\n subFilter: string | null;\n /** The `/ByteRange` `[a, b, c, d]` the signature covers. */\n byteRange: [number, number, number, number];\n}\n\n/** The cryptographic verdict for one signature, from {@link GigaPdfDoc.verifySignatures}. */\nexport interface SignatureReport {\n /** The signature field's `/T` name. */\n fieldName: string;\n /** The `/ByteRange` is well-formed and within the file bounds. */\n byteRangeOk: boolean;\n /** The CMS `messageDigest` equals SHA-256 of the covered bytes (integrity). */\n digestOk: boolean;\n /** The SignerInfo signature validates under the signer certificate's key. */\n signatureOk: boolean;\n /** The signature covers the **whole** current file (nothing appended after it). */\n coversWholeDocument: boolean;\n /** The signer certificate's Common Name, or `null`. */\n signerCommonName: string | null;\n /** Number of certificates embedded in the CMS. */\n certCount: number;\n /** The recognised signature algorithm (`RSA+SHA-256`) or an unsupported note. */\n algorithm: string;\n}\n\nexport interface FieldInfo {\n name: string;\n type: string;\n kind: FieldKind;\n flags: number;\n readOnly: boolean;\n required: boolean;\n multiline: boolean;\n fillable: boolean;\n /**\n * Whether this is a **comb** text field (`/Ff` bit 25): the value is laid out\n * one character per equally-spaced cell across {@link maxLen} cells (SSN, dates\n * and reference numbers on official forms). A host reproducing the field's\n * original spacing must honour this — the cells can't be inferred from the\n * value alone.\n */\n comb: boolean;\n /** Text alignment from `/Q` (AcroForm default applied): 0 = left, 1 = centre, 2 = right. */\n quadding: number;\n /**\n * Font resource name from the field's `/DA` default appearance (e.g. `\"Helv\"`,\n * `\"ZaDb\"`), resolved against the AcroForm; absent when no `Tf` is present.\n */\n daFont?: string;\n /** Font size in points from the `/DA` (`0` = auto-size), AcroForm default applied. */\n daSize: number;\n /**\n * `/MaxLen` for text fields; for a comb field this is the number of\n * equally-spaced cells the value is drawn into.\n */\n maxLen?: number;\n /** 1-based page the widget sits on (from its `/P`); absent if it has no widget. */\n page?: number;\n /**\n * Widget rectangle `[x, y, width, height]` in points, **top-left origin**\n * (already Y-flipped from the PDF's bottom-left `/Rect` for direct host use).\n * Absent when the field carries no `/Rect`.\n */\n bounds?: [number, number, number, number];\n value: string;\n options: string[];\n}\n/**\n * A view destination (ISO 32000-1 §12.3.2). `page` is 1-based; optional\n * coordinates are in the target page's user space (omit to leave unchanged).\n */\nexport type Destination =\n | { fit: \"xyz\"; page: number; left?: number; top?: number; zoom?: number }\n | { fit: \"fit\"; page: number }\n | { fit: \"fitH\"; page: number; top?: number }\n | { fit: \"fitV\"; page: number; left?: number }\n | { fit: \"fitR\"; page: number; rect: [number, number, number, number] }\n | { fit: \"fitB\"; page: number }\n | { fit: \"fitBH\"; page: number; top?: number }\n | { fit: \"fitBV\"; page: number; left?: number }\n | { fit: \"named\"; name: string };\n\n/**\n * A PDF action (ISO 32000-1 §12.6) usable on a link, the document open-action,\n * or an outline bookmark — passed to {@link GigaPdfDoc.addLink} /\n * {@link GigaPdfDoc.setOpenAction} / {@link GigaPdfDoc.setBookmarks}.\n */\nexport type Action =\n | { type: \"goto\"; dest: Destination }\n | { type: \"gotoR\"; file: string; dest: Destination }\n | { type: \"uri\"; uri: string }\n | { type: \"named\"; action: \"nextPage\" | \"prevPage\" | \"firstPage\" | \"lastPage\" }\n | { type: \"launch\"; file: string }\n | { type: \"javascript\"; js: string }\n | { type: \"submitForm\"; url: string }\n | { type: \"resetForm\" };\n\n/** One outline bookmark for {@link GigaPdfDoc.setBookmarks}. */\nexport interface Bookmark {\n /** The bookmark label. */\n title: string;\n /** Nesting depth (0 = top); deeper consecutive items become children. */\n level: number;\n /** What clicking the bookmark does (a `goto` becomes `/Dest`, else `/A`). */\n action?: Action;\n}\n\n/** One outline (bookmark) entry; `level` is the nesting depth (0 = top). */\nexport interface OutlineEntry {\n level: number;\n title: string;\n page?: number;\n /** `/F` flag bit 2 — label drawn bold (present when read via {@link GigaPdfDoc.outline}). */\n bold?: boolean;\n /** `/F` flag bit 1 — label drawn italic. */\n italic?: boolean;\n /** `/C` RGB label colour, `0..1` per channel (black when absent in the PDF). */\n color?: [number, number, number];\n /** Destination fit type, lowercased (`\"xyz\"`/`\"fit\"`/`\"fith\"`/`\"fitv\"`/…). */\n destKind?: string;\n /** `/XYZ` top-left X (when `destKind === \"xyz\"`). */\n x?: number;\n /** `/XYZ` top-left Y. */\n y?: number;\n /** `/XYZ` magnification. */\n zoom?: number;\n}\n/**\n * How a reader arranges pages on screen — the catalog `/PageLayout` name\n * (ISO 32000-1 §7.7.2). Passed to {@link GigaPdfDoc.setPageLayout}.\n */\nexport type PageLayout =\n | 'SinglePage'\n | 'OneColumn'\n | 'TwoColumnLeft'\n | 'TwoColumnRight'\n | 'TwoPageLeft'\n | 'TwoPageRight';\n\n/**\n * Which panel (if any) a reader shows on open — the catalog `/PageMode` name\n * (ISO 32000-1 §7.7.2). Passed to {@link GigaPdfDoc.setPageMode}.\n */\nexport type PageMode =\n | 'UseNone'\n | 'UseOutlines'\n | 'UseThumbs'\n | 'FullScreen'\n | 'UseOC'\n | 'UseAttachments';\n\n/**\n * Authoring options for the catalog `/ViewerPreferences` dictionary\n * (ISO 32000-1 §12.2) — UX hints a reader honours when it opens the document.\n *\n * Every field is optional: an omitted (or `undefined`) field leaves whatever\n * the document already had untouched; a boolean sets the corresponding key.\n * Passed to {@link GigaPdfDoc.setViewerPreferences}.\n */\nexport interface ViewerPreferences {\n /** `/HideToolbar` — hide the reader's tool bars. */\n hideToolbar?: boolean;\n /** `/HideMenubar` — hide the reader's menu bar. */\n hideMenubar?: boolean;\n /** `/HideWindowUI` — hide scroll bars / navigation controls, page only. */\n hideWindowUI?: boolean;\n /** `/FitWindow` — resize the window to fit the first page. */\n fitWindow?: boolean;\n /** `/CenterWindow` — centre the document window on screen. */\n centerWindow?: boolean;\n /** `/DisplayDocTitle` — show the doc title (not the file name) in the title bar. */\n displayDocTitle?: boolean;\n /** `/Direction` — predominant reading order: `\"L2R\"` or `\"R2L\"`. */\n direction?: 'L2R' | 'R2L';\n}\n\n/** A named destination from {@link GigaPdfDoc.namedDests}: a name → page anchor. */\nexport interface NamedDest {\n name: string;\n page: number;\n}\n/**\n * One document-level JavaScript read back by {@link GigaPdfDoc.documentJavascripts}:\n * the `/Names /JavaScript` name-tree key and the script source.\n */\nexport interface DocumentJavascript {\n /** The name-tree key the script is registered under. */\n name: string;\n /** The JavaScript source. */\n script: string;\n}\n/**\n * One embedded file attachment read back by {@link GigaPdfDoc.attachments}.\n * `data` is the decoded file bytes; `mime`/`description`/dates are `null` when\n * the PDF didn't record them.\n */\nexport interface Attachment {\n /** The `/EmbeddedFiles` name-tree key the file was registered under. */\n name: string;\n /** The filespec display filename (`/UF` preferred, else `/F`). */\n filename: string;\n /** The embedded stream's `/Subtype` MIME (e.g. `application/pdf`), or null. */\n mime: string | null;\n /** The filespec `/Desc` human description, or null. */\n description: string | null;\n /** The `/Params /CreationDate` PDF date string, or null. */\n creationDate: string | null;\n /** The `/Params /ModDate` PDF date string, or null. */\n modDate: string | null;\n /** The decoded (filters applied) file bytes. */\n data: Uint8Array;\n}\n\n/**\n * The relationship an **associated file** (`/AF`) bears to the document (ISO\n * 32000-2 / PDF/A-3). Hybrid e-invoices (Factur-X, ZUGFeRD, Order-X) embed their\n * XML payload as `\"alternative\"`.\n */\nexport type AfRelationship = \"source\" | \"data\" | \"alternative\" | \"supplement\" | \"unspecified\";\n\n/** Maps an {@link AfRelationship} to the discriminant the engine expects. */\nconst AF_RELATIONSHIP_CODE: Record<AfRelationship, number> = {\n source: 0,\n data: 1,\n alternative: 2,\n supplement: 3,\n unspecified: 4,\n};\n\n/** Options for embedding a file attachment (see {@link GigaPdfDoc.addAttachment}). */\nexport interface AttachmentOptions {\n /** The embedded stream `/Subtype` MIME type (e.g. `\"application/pdf\"`). */\n mime?: string;\n /** A human-readable description (`/Desc`). */\n description?: string;\n}\n\n/** The visual marker of a {@link GigaPdfDoc.addFileAttachmentAnnot} annotation. */\nexport type FileAttachmentIcon = \"PushPin\" | \"Paperclip\" | \"Graph\" | \"Tag\";\n\n/**\n * The initial navigator a PDF **portfolio** shows for its embedded files\n * (`/Collection /View`, ISO 32000-1 §7.11.6): `\"details\"` (a multi-column list),\n * `\"tile\"` (a grid of file tiles), or `\"hidden\"` (the navigator starts\n * collapsed). See {@link GigaPdfDoc.setCollection}.\n */\nexport type CollectionView = \"details\" | \"tile\" | \"hidden\";\n\n/**\n * The data type of a portfolio schema column (`/CollectionField /Subtype`). The\n * first three are **user-defined** values supplied per file via\n * {@link CollectionItem.values}; the rest are **synthetic** columns the viewer\n * derives from each file (its name, description, size, dates) and need no value.\n */\nexport type CollectionFieldSubtype =\n | \"text\"\n | \"date\"\n | \"number\"\n | \"filename\"\n | \"description\"\n | \"size\"\n | \"creationDate\"\n | \"modDate\";\n\n/** One column of a portfolio schema (a `/CollectionField`). */\nexport interface CollectionField {\n /** The schema key; per-file {@link CollectionItem.values} reference it. */\n key: string;\n /** The displayed column header (`/N`). Defaults to `key` when omitted. */\n name?: string;\n /** The column data type (`/Subtype`). Defaults to `\"text\"`. */\n subtype?: CollectionFieldSubtype;\n /** The relative ordering (`/O`); columns are shown in ascending order. */\n order?: number;\n /** `/V` — whether the column is initially visible (default `true`). */\n visible?: boolean;\n}\n\n/**\n * Per-file portfolio metadata — the `/CI` (collection item) values for one\n * embedded file, keyed by schema field {@link CollectionField.key}. Values are\n * strings (numeric columns parse the string as a number; date columns expect a\n * PDF date string `\"D:YYYYMMDD…\"`). Only user-defined columns\n * (`text`/`date`/`number`) carry a value.\n */\nexport interface CollectionItem {\n /** The embedded-file name (a key from {@link GigaPdfDoc.attachments}). */\n file: string;\n /** Schema-field `key` → value. */\n values: Record<string, string | number>;\n}\n\n/**\n * Configuration for a PDF **portfolio** / embedded-file collection — what\n * {@link GigaPdfDoc.setCollection} writes into the catalog `/Collection`\n * (ISO 32000-1 §7.11.6, §12.3.5). Marks the document as a portfolio and\n * configures its presentation.\n */\nexport interface CollectionConfig {\n /** `/View` — the initial navigator. Defaults to `\"details\"`. */\n view?: CollectionView;\n /** `/Schema` — the columns, in declaration order. May be empty/omitted. */\n schema?: CollectionField[];\n /** `/Sort` — the column to sort on and direction. Omit/`null` to leave unset. */\n sort?: { field: string; ascending?: boolean } | null;\n /** `/D` — the embedded-file name initially selected. Omit/`null` to leave unset. */\n defaultFile?: string | null;\n /** Per-file `/CI` metadata populating the schema columns. */\n items?: CollectionItem[];\n}\n\n/**\n * The standard document-information fields (ISO 32000-1 §14.3.3), shared by the\n * `/Info` dictionary and the XMP `/Metadata` packet. Passed to\n * {@link GigaPdfDoc.setInfo}, which writes both and keeps them in sync. Every\n * field is optional; on `setInfo` an omitted field is left unchanged (a partial\n * update). Dates are PDF date strings (`\"D:YYYYMMDDHHmmSS+HH'mm'\"`).\n */\nexport interface InfoFields {\n /** `/Title` → `dc:title`. */\n title?: string;\n /** `/Author` → `dc:creator`. */\n author?: string;\n /** `/Subject` → `dc:description`. */\n subject?: string;\n /** `/Keywords` → `pdf:Keywords`. */\n keywords?: string;\n /** `/Creator` (authoring app) → `xmp:CreatorTool`. */\n creator?: string;\n /** `/Producer` (PDF producer) → `pdf:Producer`. */\n producer?: string;\n /** `/CreationDate` (PDF date string) → `xmp:CreateDate`. */\n creationDate?: string;\n /** `/ModDate` (PDF date string) → `xmp:ModifyDate`. */\n modDate?: string;\n}\n\n/** One sheet read back from an `.xlsx` by {@link GigaPdfEngine.xlsxToGrids}. */\nexport interface XlsxSheet {\n name: string;\n rows: string[][];\n}\n/** A decoded raster image (`rgba` is `width*height*4`, row-major, RGBA8). */\nexport interface DecodedImage {\n width: number;\n height: number;\n rgba: Uint8Array;\n}\n/** An optional-content layer (calque): toggle `visible`/`locked` to persist in the PDF. */\nexport interface LayerInfo {\n id: number;\n name: string;\n visible: boolean;\n locked: boolean;\n order: number;\n}\n/** A page's geometry: size in points and `/Rotate` (0/90/180/270). */\nexport interface PageInfo {\n width: number;\n height: number;\n rotation: number;\n /** Raw `/MediaBox` `[x0, y0, x1, y1]` in user-space points (preserves origin). */\n mediaBox: [number, number, number, number];\n}\n\n/** Per-side page margins, in points. */\nexport interface PageMargins {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\n/**\n * The five page boundary boxes (ISO 32000-1 §14.11.2), in display/source order.\n * Used as the `kind` selector for {@link GigaPdfDoc.setPageBox} and as the keys of\n * {@link PageBoxes.declared}.\n */\nexport const PAGE_BOX_KINDS = [\"media\", \"crop\", \"bleed\", \"trim\", \"art\"] as const;\n\n/** One of the five page boundary boxes — see {@link PAGE_BOX_KINDS}. */\nexport type PageBoxKind = (typeof PAGE_BOX_KINDS)[number];\n\n/**\n * A page's five boundary boxes (see {@link GigaPdfDoc.getPageBoxes}). Each box is\n * the **effective** rectangle `[x0, y0, x1, y1]` in user-space points, with ISO\n * 32000-1 inheritance and the per-box default chain already applied — so `crop`\n * equals `media` when no `/CropBox` is declared, and `bleed`/`trim`/`art` each\n * fall back to `crop`. Values are reported verbatim (not clamped to their\n * intersection with the media box), so the source file round-trips faithfully.\n */\nexport interface PageBoxes {\n /** `/MediaBox` (inherited if absent; defaults to US Letter `[0, 0, 612, 792]`). */\n media: [number, number, number, number];\n /** `/CropBox` (inherited if absent; defaults to the media box). */\n crop: [number, number, number, number];\n /** `/BleedBox` (defaults to the crop box). */\n bleed: [number, number, number, number];\n /** `/TrimBox` (defaults to the crop box). */\n trim: [number, number, number, number];\n /** `/ArtBox` (defaults to the crop box). */\n art: [number, number, number, number];\n /**\n * Which boxes are **explicitly declared** on the page dictionary (vs inherited\n * from an ancestor `/Pages` node or defaulted by the rules above) — lets a host\n * tell a real `/TrimBox` from one defaulted to the crop box.\n */\n declared: Record<PageBoxKind, boolean>;\n}\n\n/**\n * The numbering style of a page-label range (ISO 32000-1 §12.4.2):\n * `decimal` (1,2,3…), `romanLower` (i,ii,iii…), `romanUpper` (I,II,III…),\n * `alphaLower` (a…z,aa…), `alphaUpper` (A…Z,AA…), or `none` (the prefix alone,\n * with no numeric portion).\n */\nexport type PageLabelStyle =\n | \"decimal\"\n | \"romanLower\"\n | \"romanUpper\"\n | \"alphaLower\"\n | \"alphaUpper\"\n | \"none\";\n\n/** Maps a {@link PageLabelStyle} to the single-letter token the engine expects. */\nconst PAGE_LABEL_STYLE_TOKEN: Record<PageLabelStyle, string> = {\n decimal: \"D\",\n romanLower: \"r\",\n romanUpper: \"R\",\n alphaLower: \"a\",\n alphaUpper: \"A\",\n none: \"-\",\n};\n\n/**\n * One page-label range (ISO 32000-1 §12.4.2). From {@link startPage} onward (until\n * the next range, or the end of the document), pages are labelled {@link prefix}\n * followed by the {@link style}-formatted number counting up from\n * {@link startNumber}.\n */\nexport interface PageLabelRange {\n /** 1-based page number where this labelling range begins. */\n startPage: number;\n /** The numbering style of the numeric portion. */\n style: PageLabelStyle;\n /** A label prefix prepended to every page in the range (may be empty). */\n prefix: string;\n /** The value the range's first page is numbered with (≥ 1; default 1). */\n startNumber: number;\n}\n\n/**\n * The visual style of a page transition (ISO 32000-1 §12.4.4, the `/S` entry).\n * Index order matches the engine's enum and selects which optional fields of\n * {@link PageTransition} apply.\n */\nexport const PAGE_TRANSITION_STYLES = [\n \"split\",\n \"blinds\",\n \"box\",\n \"wipe\",\n \"dissolve\",\n \"glitter\",\n \"fly\",\n \"push\",\n \"cover\",\n \"uncover\",\n \"fade\",\n \"replace\",\n] as const;\n\n/** A page transition style — see {@link PAGE_TRANSITION_STYLES}. */\nexport type PageTransitionStyle = (typeof PAGE_TRANSITION_STYLES)[number];\n\n/** Orientation of a `split`/`blinds` transition (the `/Dm` entry). */\nexport type PageTransitionDimension = \"horizontal\" | \"vertical\";\n\n/** Motion direction of a `split`/`box` transition (the `/M` entry). */\nexport type PageTransitionMotion = \"inward\" | \"outward\";\n\n/**\n * The sweep direction of a directional transition (the `/Di` entry). A number\n * of degrees — only the discrete angles `0`, `90`, `180`, `270`, `315` are\n * valid — or `\"none\"` (the `/Di /None` name, used by `fly` to mean \"fly toward\n * the viewer\").\n */\nexport type PageTransitionDirection = 0 | 90 | 180 | 270 | 315 | \"none\";\n\n/**\n * A presentation transition + auto-advance for a page (ISO 32000-1 §12.4.4),\n * passed to {@link GigaPdfDoc.setPageTransition}. {@link style} picks the\n * effect; the remaining fields are optional and only the ones that apply to the\n * chosen style are written (`dimension`/`motion` for `split`, `direction`/\n * `scale`/`flyAreaOpaque` for `fly`, …). {@link displayDuration} is the page's\n * `/Dur` auto-advance time and is independent of the transition itself.\n */\nexport interface PageTransition {\n /** The transition style (`/S`). */\n style: PageTransitionStyle;\n /** `/D` — the transition effect duration in **seconds** (viewer default: 1). */\n duration?: number;\n /** `/Dm` — orientation; `split`/`blinds` only. */\n dimension?: PageTransitionDimension;\n /** `/M` — motion direction; `split`/`box` only. */\n motion?: PageTransitionMotion;\n /** `/Di` — sweep direction; `wipe`/`glitter`/`fly`/`cover`/`uncover`/`push`. */\n direction?: PageTransitionDirection;\n /** `/SS` — starting/ending scale for `fly` (PDF 1.5; default 1.0). */\n scale?: number;\n /** `/B` — whether the `fly` area is rectangular + opaque (PDF 1.5; default false). */\n flyAreaOpaque?: boolean;\n /** `/Dur` — the page's display time in **seconds** before auto-advancing. */\n displayDuration?: number;\n}\n\n/** Horizontal alignment of header/footer text within the printable width. */\nexport type HeaderFooterAlign = \"left\" | \"center\" | \"right\";\n\n/**\n * A running header/footer to bake onto an existing PDF (see {@link GigaPdfDoc.setHeader} /\n * {@link GigaPdfDoc.setFooter}). `text` may contain the tokens `{{page}}` (1-based page\n * number) and `{{pages}}` (total page count), substituted per page. Text is drawn in\n * standard Helvetica inside the top (header) / bottom (footer) margin band.\n */\nexport interface HeaderFooterSpec {\n /** Template text, with `{{page}}` / `{{pages}}` tokens. */\n text: string;\n /** Horizontal alignment (default `\"left\"`). */\n align?: HeaderFooterAlign;\n /** Font size in points (default `10`). */\n fontSize?: number;\n /** RGB fill colour, `0..1` per channel (default black `[0,0,0]`). */\n color?: [number, number, number];\n /** Inclusive 1-based page range `[first, last]`; omit for every page. */\n pageRange?: [number, number] | null;\n /** Draw on the first page of the range too (default `true`). */\n showOnFirstPage?: boolean;\n /** Band height from the page edge, in points (default `36`). */\n bandHeight?: number;\n}\n\n/** Horizontal anchor of a rich {@link HFItem} within the printable width. */\nexport type HFAlign = HeaderFooterAlign;\n\n/**\n * One drawable element of a rich running header/footer band: a line of **text**\n * or a raster **image** (a discriminated union on `type`). Anchored within the\n * printable width by `anchor`, then nudged `(dx, dy)` points in PDF axes\n * (`+dx` → right, `+dy` → up).\n */\nexport type HFItem =\n | {\n type: \"text\";\n /** Horizontal anchor (default `\"left\"`). */\n anchor?: HFAlign;\n /** Horizontal nudge, points (default `0`). */\n dx?: number;\n /** Vertical nudge, points (default `0`). */\n dy?: number;\n /**\n * Template text — may contain `{{page}}`, `{{pages}}`, `{{date}}` and\n * `{{title}}`, substituted at bake time.\n */\n text: string;\n /**\n * An embedded-font object id (from {@link GigaPdfDoc.embedFont}); omit/`null`\n * to use the engine's bundled OFL face (a real embedded font, never base-14).\n */\n fontRef?: number | null;\n /** Font size, points (default `10`). */\n size?: number;\n /** RGB fill colour, `0..255` per channel (default black `[0,0,0]`). */\n color?: [number, number, number];\n /** Bold hint (carried with the def; honoured only by a bold `fontRef`). */\n bold?: boolean;\n /** Italic hint (carried with the def; honoured only by an italic `fontRef`). */\n italic?: boolean;\n }\n | {\n type: \"image\";\n /** Horizontal anchor (default `\"left\"`). */\n anchor?: HFAlign;\n /** Horizontal nudge, points (default `0`). */\n dx?: number;\n /** Vertical nudge, points (default `0`). */\n dy?: number;\n /** Drawn width, points. */\n w: number;\n /** Drawn height, points. */\n h: number;\n /** Key into the `images` map passed to {@link GigaPdfDoc.setRunningHeaderFooter}. */\n imageId: number;\n /** Fill opacity `0..1` (default `1`). */\n opacity?: number;\n };\n\n/** The header and footer item lists of one running-H/F {@link RunningHeaderFooter} zone. */\nexport interface HFZone {\n /** Items drawn in the top (header) band. */\n header: HFItem[];\n /** Items drawn in the bottom (footer) band. */\n footer: HFItem[];\n}\n\n/**\n * A rich, Word-like running header/footer **definition** (see\n * {@link GigaPdfDoc.setRunningHeaderFooter}). The definition is the source of\n * truth (stored in the editor-meta sidecar); the bake regenerates the visible\n * `/GPHF` band from it.\n *\n * Zone selection per 1-based page: page 1 → `firstPage` when `differentFirstPage`\n * (else `default`); otherwise, when `differentOddEven`, even pages → `evenPage`\n * and odd pages → `oddPage` (each falling back to `default` when omitted);\n * otherwise `default` everywhere.\n */\nexport interface RunningHeaderFooter {\n /** The zone every page not overridden by a more specific zone uses. */\n default: HFZone;\n /** First-page override (used when `differentFirstPage`). */\n firstPage?: HFZone | null;\n /** Even-page override (used when `differentOddEven`). */\n evenPage?: HFZone | null;\n /** Odd-page override (used when `differentOddEven`). */\n oddPage?: HFZone | null;\n /** Give page 1 its own `firstPage` zone (default `false`). */\n differentFirstPage?: boolean;\n /** Give even/odd pages their own `evenPage`/`oddPage` zones (default `false`). */\n differentOddEven?: boolean;\n /** Header band height (distance from the top edge to the baseline), points (default `36`). */\n headerBand?: number;\n /** Footer band height (distance from the bottom edge to the baseline), points (default `36`). */\n footerBand?: number;\n}\n\nconst RGB = (rgb: number) => rgb & 0xffffff;\n\n/** `n` bytes of Web Crypto randomness (for encryption seeds; the engine has none). */\nfunction cryptoRandom(n: number): Uint8Array {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (!c?.getRandomValues) {\n throw new Error(\n \"this operation needs Web Crypto (globalThis.crypto.getRandomValues) or an explicit seed\"\n );\n }\n const out = new Uint8Array(n);\n c.getRandomValues(out);\n return out;\n}\n\n/** One colour stop of a {@link GradientSpec}. */\nexport interface GradientStop {\n /** Position along the gradient axis, `0`…`1`. */\n offset: number;\n /** Colour, packed `0xRRGGBB`. */\n rgb: number;\n}\n\n/** A gradient fill for {@link GigaPdfDoc.addGradient}. */\nexport interface GradientSpec {\n /** Axial (`\"linear\"`) or radial geometry. */\n kind: \"linear\" | \"radial\";\n /** `[x0,y0,x1,y1]` for `\"linear\"`, `[x0,y0,r0,x1,y1,r1]` for `\"radial\"`. */\n coords: number[];\n /** At least two colour stops. */\n stops: GradientStop[];\n /** The rectangle `{ x, y, w, h }` filled with the gradient. */\n rect: Box;\n /** Extend before the first / after the last stop (`/Extend`; default `[true, true]`). */\n extend?: [boolean, boolean];\n /** Fill opacity `0`…`1` (default `1`). */\n opacity?: number;\n}\n\n/**\n * A fill colour in any authored colour space (ISO 32000-1 §8.6), for\n * {@link GigaPdfDoc.addFilledRectangle}/{@link GigaPdfDoc.addFilledPolygon}/\n * {@link GigaPdfDoc.addTextColor}. `cmyk`/`gray` are press-ready; `separation`\n * is a spot ink (with its `DeviceCMYK` tint approximation); `icc` embeds a\n * profile. CMYK/gray/tint components are `0`…`1`; `rgb` is packed `0xRRGGBB`.\n */\nexport type Color =\n | { space: \"rgb\"; rgb: number }\n | { space: \"cmyk\"; c: number; m: number; y: number; k: number }\n | { space: \"gray\"; gray: number }\n | {\n space: \"separation\";\n name: string;\n tint: number;\n cmyk: [number, number, number, number];\n }\n | { space: \"icc\"; components: number[]; profile: Uint8Array };\n\n/** Visual styling for a newly-created form field. */\nexport interface FieldStyle {\n /** Text size in points; `0` (default) auto-sizes to the field box. */\n fontSize?: number;\n /** Text / mark colour `0xRRGGBB` (default black). */\n color?: number;\n /** Border colour `0xRRGGBB`, or `null` for no border (default black). */\n border?: number | null;\n /** Background fill `0xRRGGBB`, or `null` for transparent (default none). */\n background?: number | null;\n /** Border width in points (default `1`). */\n borderWidth?: number;\n}\n\n/** One option of a radio group: its export value and on-page rectangle. */\nexport interface RadioOption {\n /** The export value stored in the field when this button is selected. */\n export: string;\n /** `[x0, y0, x1, y1]` in PDF user space. */\n rect: [number, number, number, number];\n}\n\n/** Expand a {@link FieldStyle} into the 7 packed ABI arguments. */\nfunction styleArgs(s: FieldStyle = {}): [number, number, number, number, number, number, number] {\n const hasBorder = s.border === null ? 0 : 1;\n const borderRgb = s.border == null ? 0x000000 : s.border;\n const hasBg = s.background == null ? 0 : 1;\n const bgRgb = s.background == null ? 0 : s.background;\n return [\n s.fontSize ?? 0,\n RGB(s.color ?? 0x000000),\n RGB(borderRgb),\n hasBorder,\n RGB(bgRgb),\n hasBg,\n s.borderWidth ?? 1,\n ];\n}\n\n/** A live document handle. Call {@link close} when done. */\nexport class GigaPdfDoc {\n constructor(\n private readonly g: GigaPdfEngine,\n private readonly h: number\n ) {}\n private ex() {\n return this.g.raw;\n }\n\n close() {\n this.ex().gp_close(this.h);\n }\n pageCount(): number {\n return this.ex().gp_page_count(this.h);\n }\n save(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_save(this.h, o));\n }\n saveCompressed(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_save_compressed(this.h, o));\n }\n\n /**\n * Serialize with PDF 1.5+ **object streams** + a **cross-reference stream**\n * (ISO 32000-1 §7.5.7 / §7.5.8) — the most compact output. `objectStreams`\n * (default `true`) packs non-stream objects into compressed `/ObjStm`s (needs\n * the xref stream); `xrefStreams` (default `true`) writes a `/XRef` stream.\n * `version` selects the `%PDF-x.y` header banner (default `\"1.7\"`).\n * Uncompressed streams are Flate-compressed first, like {@link saveCompressed}.\n * Linearization (Fast Web View) is not performed.\n */\n saveOptimized(\n opts: { objectStreams?: boolean; xrefStreams?: boolean; version?: PdfVersion } = {}\n ): Uint8Array {\n const obj = opts.objectStreams ?? true;\n const xref = opts.xrefStreams ?? true;\n const ver = pdfVersionCode(opts.version);\n return this.g._buffer((o) =>\n this.ex().gp_save_optimized(this.h, obj ? 1 : 0, xref ? 1 : 0, ver, o)\n );\n }\n\n /**\n * Serialize as a **linearized** (\"Fast Web View\") PDF (ISO 32000-1 Annex F).\n *\n * The first page and only the objects needed to render it — together with a\n * `/Linearized` parameter dictionary and a primary hint stream — are written at\n * the **front** of the file, so a web viewer can display page 1 before the rest\n * of the document has downloaded (progressive rendering / byte-range serving).\n * The remaining pages follow, then a main cross-reference table; the first-page\n * cross-reference section chains to it via `/Prev`. Streams are Flate-compressed\n * first (like {@link saveCompressed}) and embedded fonts are subset.\n *\n * Falls back to the plain {@link save} output if the document cannot be\n * linearized (no catalog / page tree / zero pages). `version` selects the\n * `%PDF-x.y` header banner (default `\"1.7\"`).\n */\n toLinearized(version: PdfVersion = \"1.7\"): Uint8Array {\n return this.g._buffer((o) =>\n this.ex().gp_to_linearized(this.h, pdfVersionCode(version), o)\n );\n }\n\n /** Alias of {@link toLinearized} — serialize as a linearized (Fast Web View) PDF. */\n saveLinearized(version: PdfVersion = \"1.7\"): Uint8Array {\n return this.toLinearized(version);\n }\n\n // text intelligence\n textRuns(page: number): TextRunInfo[] {\n return this.g._json((o) => this.ex().gp_text_runs_json(this.h, page, o));\n }\n elements(page: number): Element[] {\n return this.g._json((o) => this.ex().gp_elements_json(this.h, page, o));\n }\n /**\n * Every text element on a page, enriched for an editor: the decoded text, its\n * bounding box (user space, bottom-left), the resolved font family +\n * bold/italic, the effective point size, the RGB fill colour and the baseline\n * rotation. `index` is the text-run index for {@link replaceText}, so a host\n * can extract, render and edit text from one model — the native replacement\n * for a reader's per-run text layer (which `elements()` omits font + colour).\n */\n textElements(page: number): TextElementInfo[] {\n return this.g._json((o) => this.ex().gp_text_elements_json(this.h, page, o));\n }\n /**\n * The document's aggregate language signal — its dominant reading direction\n * (`ltr`/`rtl`/`neutral`), writing system, and a best-effort ISO-639-1\n * language code — computed across every page's decoded text. Lets a host\n * pick fonts, set the UI direction or label the document without its own bidi\n * pass (e.g. detect an Arabic/Hebrew/Japanese PDF). `lang` is omitted when the\n * script does not pin a single language.\n */\n documentLanguage(): DocumentLanguage {\n const raw = this.g._json<{ direction: 'ltr' | 'rtl' | 'neutral'; script: string; lang: string | null }>(\n (o) => this.ex().gp_document_language(this.h, o)\n );\n return {\n direction: raw.direction,\n script: raw.script,\n ...(raw.lang != null ? { lang: raw.lang } : {}),\n };\n }\n /**\n * Every image element on a page: its placement box (user space, bottom-left),\n * the embeddable encoded bytes (`data`) + `format` (`jpeg`/`png`/`jp2`/\n * `unknown`), and the source pixel dimensions. DCTDecode/JPXDecode images pass\n * through as jpeg/jp2; Flate/raw DeviceRGB|DeviceGray are re-encoded to PNG.\n * The native replacement for a reader's image extraction (bytes + placement).\n *\n * Each result's `index` is the **unified element index** usable directly with\n * {@link removeElement} / {@link transformElement} / {@link duplicateElement} /\n * {@link moveElement} — so you can extract an image and edit *that exact* image.\n */\n imageElements(page: number): ImageElementInfo[] {\n const raw = this.g._json<Array<Omit<ImageElementInfo, 'data'> & { dataBase64: string }>>((o) =>\n this.ex().gp_image_elements_json(this.h, page, o)\n );\n return raw.map(({ dataBase64, ...rest }) => ({\n ...rest,\n data: this.g._fromBase64(dataBase64),\n }));\n }\n /**\n * Every painted vector path on `page` (frames, rules, lines, filled shapes…)\n * as geometry + style: segments and bounds in user space (origin bottom-left),\n * fill/stroke RGB, line width, alpha and dash. Clip-only paths are omitted.\n * The native replacement for walking a reader's operator list to rebuild the\n * shape layer.\n *\n * Each result's `index` is the **unified element index** usable directly with\n * {@link setPathStyle} / {@link removeElement} / {@link transformElement} — so\n * you can extract a path and restyle/remove *that exact* path.\n */\n vectorPaths(page: number): VectorPathInfo[] {\n return this.g._json((o) => this.ex().gp_vector_paths_json(this.h, page, o));\n }\n structuredText(page: number): TextLine[] {\n return this.g._json((o) => this.ex().gp_structured_text_json(this.h, page, o));\n }\n /**\n * The **layout blocks** of a single page — the structural reconstruction\n * (paragraphs, headings, lists, tables, shapes, images) of the page's flat\n * glyph/path geometry, in reading order (column-major), each {@link GigaBlock}\n * keeping a top-down `frame` and every text run its `source_index` back to the\n * editable content-stream operator.\n *\n * The **per-page** counterpart of {@link GigaPdfDoc.toModel} (which\n * reconstructs the whole document at once): a continuous / lazily-virtualized\n * editor calls this one page at a time. Identifies 1- and 2-column layouts,\n * merges lines into justified/left/centred/right paragraphs, promotes large\n * isolated lines to headings, and recovers ruled tables. An out-of-range page\n * yields `[]`.\n */\n pageBlocks(page: number): GigaBlock[] {\n return this.g._json((o) => this.ex().gp_page_blocks_json(this.h, page, o));\n }\n search(query: string, caseInsensitive = true): SearchHit[] {\n return this.g._withStr(query, (p, l) =>\n this.g._json((o) => this.ex().gp_search_json(this.h, p, l, caseInsensitive ? 1 : 0, o))\n );\n }\n\n // editing\n /**\n * Replace text run `index` on `page` with `text`. Font-aware: works with\n * **any** font — a run set in an embedded Type0/Identity-H face (TrueType or\n * OpenType-CFF) is re-encoded through that font's char→glyph map; base-14 and\n * simple fonts use WinAnsi. Returns `false` if the run/page doesn't exist.\n */\n replaceText(page: number, index: number, text: string): boolean {\n return (\n this.g._withStr(text, (p, l) => this.ex().gp_replace_text(this.h, page, index, p, l)) === 0\n );\n }\n removeElement(page: number, index: number): boolean {\n return this.ex().gp_remove_element(this.h, page, index) === 0;\n }\n moveElement(page: number, index: number, dx: number, dy: number): boolean {\n return this.ex().gp_move_element(this.h, page, index, dx, dy) === 0;\n }\n /**\n * Apply a full affine transform to element `index` on `page`, wrapping it in\n * `q … cm … Q` with the matrix `m = [a, b, c, d, e, f]`. This **generalises**\n * {@link moveElement} (whose matrix is the pure translate `[1,0,0,1,dx,dy]`)\n * to scale, rotation, shear and translation in one call. Because it is purely\n * matrix-based it works identically for text, images and shapes — their\n * internal coordinates are never touched. Returns `false` if the element/page\n * doesn't exist.\n */\n transformElement(\n page: number,\n index: number,\n m: [number, number, number, number, number, number]\n ): boolean {\n return (\n this.ex().gp_transform_element(this.h, page, index, m[0], m[1], m[2], m[3], m[4], m[5]) === 0\n );\n }\n /**\n * Re-style the **path** element `index` on `page` in place: any provided field\n * overrides that part of the graphics state for the path's paint; omitted\n * fields keep the inherited state. Implemented by wrapping the path's op range\n * in `q … Q` and injecting the requested state operators (`rg`/`RG`/`w`/`d`)\n * before its construction + paint ops, so the original paint op now draws with\n * the override and following content is unaffected. RGB colours are `[r,g,b]`\n * in `0..=1`; `dash` is the PDF dash array (`[]` = solid). Returns `false` if\n * the element is not a path (or the page/index doesn't exist).\n *\n * Opacity: `fillAlpha`/`strokeAlpha` (`0..=1`) are fully supported — an\n * `/ExtGState` carrying `/ca`/`/CA` is registered on the page and a `/<gs> gs`\n * is injected into the path's `q … Q` wrap, so the alpha applies to that path\n * run only. (For non-path elements such as images, use\n * {@link setElementOpacity}.)\n */\n setPathStyle(\n page: number,\n index: number,\n style: {\n fill?: [number, number, number];\n stroke?: [number, number, number];\n strokeWidth?: number;\n fillAlpha?: number;\n strokeAlpha?: number;\n dash?: number[];\n }\n ): boolean {\n return (\n this.g._withStr(JSON.stringify(style), (p, l) =>\n this.ex().gp_set_path_style_json(this.h, page, index, p, l)\n ) === 0\n );\n }\n /**\n * Re-style **sub-ranges** of text run `index` on `page` in place — the\n * by-character-run companion of {@link setPathStyle}. Each span sets the style\n * of the `[start, end)` UTF-16 slice of the run's *decoded* text (bold / italic\n * / underline / strike / colour / size); the run is split so the rest keeps its\n * original style and **positioning is preserved** (the original glyph codes,\n * including `TJ` kerning, are sliced and re-emitted — never re-encoded — and\n * each styled slice is wrapped in `q … Q`). Spans may be given in any order and\n * are clamped to the run's length.\n *\n * Notes on each field: `color` is `[r,g,b]` in `0..=1` (text fill); `sizePt`\n * rescales the slice's font in the run's own text scale; `bold` is faux-bold\n * (fill+stroke render mode) when no bold variant font is wired; `italic` is a\n * no-op without an italic/oblique variant (a stream edit can't shear glyphs\n * without disturbing advances); `underline`/`strike` draw a thin rule in page\n * space. Returns `false` when `index` does not resolve to a top-level text run\n * (e.g. it addresses form-XObject text), like {@link setPathStyle} for a\n * non-matching element.\n */\n setTextRunStyle(\n page: number,\n index: number,\n spans: Array<{\n start: number;\n end: number;\n color?: [number, number, number];\n sizePt?: number;\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strike?: boolean;\n }>\n ): boolean {\n return (\n this.g._withStr(JSON.stringify(spans), (p, l) =>\n this.ex().gp_set_text_run_style_json(this.h, page, index, p, l)\n ) === 0\n );\n }\n /**\n * Set a constant opacity on element `index` on `page` — text, image **or**\n * shape — by registering an `/ExtGState` (`/ca` = `/CA` = `fillAlpha`, clamped\n * to `0..=1`) on the page and wrapping the element's op range in\n * `q /<gs> gs … Q`. This is the way to set an **image**'s alpha in place;\n * shapes may also use {@link setPathStyle}'s `fillAlpha`/`strokeAlpha` (same\n * underlying `/ExtGState` mechanism). Returns `false` if the page/index doesn't\n * exist.\n */\n setElementOpacity(page: number, index: number, fillAlpha: number): boolean {\n return this.ex().gp_set_element_opacity(this.h, page, index, fillAlpha) === 0;\n }\n /**\n * Change the paint order (z-order) of element `index` on `page`. `toFront`\n * brings it visually on top (its op range is moved to the end of the content\n * stream, painted last); otherwise it is sent behind everything (moved to the\n * start, painted first). The moved range is re-wrapped in `q … Q` so it neither\n * inherits nor leaks graphics state. Works for text, image and shape elements.\n * The element's index changes after the move — re-read {@link GigaPdfDoc.elements}.\n * Returns `false` if the page/index doesn't exist.\n */\n reorderElement(page: number, index: number, toFront: boolean): boolean {\n return this.ex().gp_reorder_element(this.h, page, index, toFront ? 1 : 0) === 0;\n }\n duplicateElement(page: number, index: number): boolean {\n return this.ex().gp_duplicate_element(this.h, page, index) === 0;\n }\n /** Index of the element at page point `(x, y)`, or -1 if none. */\n elementAt(page: number, x: number, y: number): number {\n return this.ex().gp_element_at(this.h, page, x, y);\n }\n /**\n * Draw a vector rectangle. Pass an `0xRRGGBB` colour for `stroke`/`fill`, or\n * `null` to omit that paint. 0 → success.\n */\n addRectangle(\n page: number,\n x: number,\n y: number,\n w: number,\n h: number,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.ex().gp_add_rectangle(\n this.h,\n page,\n x,\n y,\n w,\n h,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n ) === 0\n );\n }\n\n /** Draw a straight line from `(x1,y1)` to `(x2,y2)`. `stroke` is `0xRRGGBB`. */\n drawLine(\n page: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n stroke = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.ex().gp_draw_line(this.h, page, x1, y1, x2, y2, RGB(stroke), lineWidth, opacity) === 0\n );\n }\n\n /**\n * Draw an ellipse (circle when `rx === ry`) centred at `(cx,cy)`. Pass an\n * `0xRRGGBB` colour for `stroke`/`fill`, or `null` to omit that paint.\n */\n addEllipse(\n page: number,\n cx: number,\n cy: number,\n rx: number,\n ry: number,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.ex().gp_add_ellipse(\n this.h,\n page,\n cx,\n cy,\n rx,\n ry,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n ) === 0\n );\n }\n\n /**\n * Paint a **linear** or **radial** gradient over `rect` on `page` (ISO 32000-1\n * §8.7.4 shading + §8.7.3 pattern). `coords` is `[x0,y0,x1,y1]` for `\"linear\"`\n * or `[x0,y0,r0,x1,y1,r1]` for `\"radial\"`; `stops` is ≥ 2 colour stops\n * (`offset` 0…1, `rgb` packed `0xRRGGBB`). `extend` (default `[true,true]`)\n * sets `/Extend`; `opacity` (default `1`) is the fill alpha.\n *\n * @example\n * doc.addGradient(1, {\n * kind: \"linear\", coords: [50, 50, 250, 50],\n * stops: [{ offset: 0, rgb: 0xff0000 }, { offset: 1, rgb: 0x0000ff }],\n * rect: { x: 50, y: 40, w: 200, h: 60 },\n * });\n */\n addGradient(page: number, spec: GradientSpec): boolean {\n const kind = spec.kind === \"radial\" ? 1 : 0;\n const offsets = spec.stops.map((s) => s.offset);\n const colors = spec.stops.map((s) => RGB(s.rgb));\n const [es, ee] = spec.extend ?? [true, true];\n const opacity = spec.opacity ?? 1;\n const r = spec.rect;\n return (\n this.g._withF64(spec.coords, (cp, cc) =>\n this.g._withF64(offsets, (op, _oc) =>\n this.g._withU32(colors, (clp, _clc) =>\n this.ex().gp_add_gradient(\n this.h, page, kind, cp, cc, op, clp, offsets.length,\n r.x, r.y, r.w, r.h, es ? 1 : 0, ee ? 1 : 0, opacity\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Encode a {@link Color} into the ABI's `(kind, comps, name, profile)` buffers\n * and invoke `fn` with the resulting pointers. Internal.\n */\n private _color<T>(\n color: Color,\n fn: (\n kind: number,\n compsPtr: number,\n compsCount: number,\n namePtr: number,\n nameLen: number,\n profPtr: number,\n profLen: number\n ) => T\n ): T {\n let kind: number;\n let comps: number[];\n let name = \"\";\n let profile: Uint8Array | null = null;\n switch (color.space) {\n case \"cmyk\":\n kind = 1;\n comps = [color.c, color.m, color.y, color.k];\n break;\n case \"gray\":\n kind = 2;\n comps = [color.gray];\n break;\n case \"separation\":\n kind = 3;\n comps = [color.tint, ...color.cmyk];\n name = color.name;\n break;\n case \"icc\":\n kind = 4;\n comps = color.components;\n profile = color.profile;\n break;\n default: {\n const c = RGB(color.rgb);\n kind = 0;\n comps = [((c >> 16) & 0xff) / 255, ((c >> 8) & 0xff) / 255, (c & 0xff) / 255];\n }\n }\n return this.g._withF64(comps, (cp, cc) =>\n this.g._withOptStr(name, (np, nl) =>\n profile\n ? this.g._withBytes(profile, (pp, pl) => fn(kind, cp, cc, np, nl, pp, pl))\n : fn(kind, cp, cc, np, nl, 0, 0)\n )\n );\n }\n\n /**\n * Fill a rectangle with `color` in **any** colour space — the press-ready\n * counterpart of {@link addRectangle} (CMYK, spot `Separation`, gray, ICC).\n *\n * @example\n * doc.addFilledRectangle(1, { x: 40, y: 700, w: 200, h: 40 },\n * { space: \"cmyk\", c: 0.1, m: 0.8, y: 0.9, k: 0 });\n */\n addFilledRectangle(page: number, rect: Box, color: Color, opacity = 1): boolean {\n return (\n this._color(color, (kind, cp, cc, np, nl, pp, pl) =>\n this.ex().gp_add_filled_rectangle(\n this.h, page, rect.x, rect.y, rect.w, rect.h, kind, cp, cc, np, nl, pp, pl, opacity\n )\n ) === 0\n );\n }\n\n /**\n * Fill a polygon through flat `[x0,y0,x1,y1,…]` `points` (≥ 3 vertices) with\n * `color` in any colour space. The path is closed automatically.\n */\n addFilledPolygon(page: number, points: number[], color: Color, opacity = 1): boolean {\n return (\n this.g._withF64(points, (ptsPtr, ptsCount) =>\n this._color(color, (kind, cp, cc, np, nl, pp, pl) =>\n this.ex().gp_add_filled_polygon(\n this.h, page, ptsPtr, ptsCount, kind, cp, cc, np, nl, pp, pl, opacity\n )\n )\n ) === 0\n );\n }\n\n /**\n * Draw a base-14 text run in **any** colour space — the press-ready\n * counterpart of {@link addTextStandard}. `font` is a base-14 family\n * (`Helvetica`, `Times-Roman`, `Courier`, …).\n */\n addTextColor(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n font: string,\n color: Color,\n opts: { opacity?: number; rotation?: number; underline?: boolean; strikethrough?: boolean } = {}\n ): boolean {\n const { opacity = 1, rotation = 0, underline = false, strikethrough = false } = opts;\n return (\n this.g._withStr(text, (tp, tl) =>\n this.g._withStr(font, (fp, fl) =>\n this._color(color, (kind, cp, cc, np, nl, pp, pl) =>\n this.ex().gp_add_text_color(\n this.h, page, x, y, size, tp, tl, fp, fl, kind, cp, cc, np, nl, pp, pl,\n opacity, rotation, underline ? 1 : 0, strikethrough ? 1 : 0\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Turn **overprint** on/off for content drawn **after** this call (`/op` fill,\n * `/OP` stroke, `/OPM` mode — `0` independent colorants, `1` non-erasing).\n * Essential for prepress black-overprint / trapping.\n */\n setOverprint(page: number, fill: boolean, stroke: boolean, mode = 1): boolean {\n return this.ex().gp_set_overprint(this.h, page, fill ? 1 : 0, stroke ? 1 : 0, mode) === 0;\n }\n\n /**\n * Add a document-level **OutputIntent** embedding the ICC `profile` (its `/N`\n * is read from the profile), with `condition` as the output-condition\n * identifier (e.g. `\"Coated FOGRA39\"`). Decoupled from the PDF/A path.\n */\n addOutputIntent(profile: Uint8Array, condition: string): boolean {\n return (\n this.g._withBytes(profile, (pp, pl) =>\n this.g._withStr(condition, (cp, cl) =>\n this.ex().gp_add_output_intent(this.h, pp, pl, cp, cl)\n )\n ) === 0\n );\n }\n\n /**\n * Draw a polyline/polygon through flat `[x0,y0,x1,y1,…]` points. `close` joins\n * the last vertex back to the first. `0xRRGGBB` colours, or `null` to omit.\n */\n addPolygon(\n page: number,\n points: number[],\n close = true,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.g._withF64(points, (p, c) =>\n this.ex().gp_add_polygon(\n this.h,\n page,\n p,\n c,\n close ? 1 : 0,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n )\n ) === 0\n );\n }\n\n /**\n * Draw an SVG path (`M`/`L`/`C`/`Q`/`Z`…) anchored so the SVG origin maps to\n * `(ox,oy)` with the Y axis flipped — same convention as `pdf-lib`'s\n * `drawSvgPath`. Covers freeform/polygon/triangle shapes.\n */\n addPath(\n page: number,\n svgPath: string,\n ox: number,\n oy: number,\n stroke: number | null = null,\n fill: number | null = 0,\n lineWidth = 1,\n opacity = 1\n ): boolean {\n return (\n this.g._withStr(svgPath, (p, l) =>\n this.ex().gp_add_path(\n this.h,\n page,\n p,\n l,\n ox,\n oy,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth,\n opacity\n )\n ) === 0\n );\n }\n\n /**\n * Embed a raster image at `(x,y)` sized `(w,h)` in PDF user space. Format\n * auto-detected: **PNG, JPEG, GIF, WebP, AVIF, TIFF** (non-PNG/JPEG decoded to\n * RGBA in pure Rust/WASM). PNG alpha is honoured; `opacity` (0..1) sets an\n * overall alpha.\n */\n addImage(\n page: number,\n data: Uint8Array,\n x: number,\n y: number,\n w: number,\n h: number,\n opacity = 1\n ): boolean {\n return (\n this.g._withBytes(data, (p, l) =>\n this.ex().gp_add_image(this.h, page, p, l, x, y, w, h, opacity)\n ) === 0\n );\n }\n /**\n * Replace the pixels of an **existing image XObject in place** — swap a logo or\n * photo while every reference to it stays intact (ISO 32000-1 §8.9). `index` is\n * the **unified element index** of an image on `page`, exactly the `index`\n * reported by {@link imageElements} (and accepted by {@link removeElement} /\n * {@link transformElement}); `data` is a fresh PNG or JPEG.\n *\n * Unlike a delete-then-re-add, the image keeps its object number, **every `/Do`\n * placement, and its position / scale / rotation / clip matrix** — only the\n * stream bytes and the image dictionary (`/Width`, `/Height`, `/ColorSpace`,\n * `/BitsPerComponent`, `/Filter`) are rewritten. The new raster is re-encoded\n * through the same path as {@link addImage} (PNG alpha → a fresh `/SMask`; JPEG\n * → `/DCTDecode` passthrough). It need not match the old pixel size — it is\n * drawn into the same box (transform the element first to re-fit it).\n *\n * Returns `false` if `page`/`index` doesn't resolve to a top-level image, or the\n * bytes aren't a decodable PNG/JPEG.\n */\n replaceImage(page: number, index: number, data: Uint8Array): boolean {\n return (\n this.g._withBytes(data, (p, l) => this.ex().gp_replace_image(this.h, page, index, p, l)) === 0\n );\n }\n /**\n * Stamp an **image watermark** across pages from raw image bytes. Accepts the\n * formats the engine decodes — **PNG, JPEG, WebP, GIF, AVIF, TIFF**. The\n * image is embedded **once** and referenced on every target page.\n *\n * `opts.pages` is a list of 1-based page numbers; omit it (or pass `[]`) to\n * stamp every page. `opts.anchor` positions the image (`'center'` default, or a\n * corner) and `opts.offsetX`/`offsetY` nudge it (in points; in `tile` mode they\n * become the gaps between tiles). `opts.width`/`height` set the target size in\n * points (height keeps the source aspect ratio when omitted). `opts.rotationDeg`\n * rotates about the image centre and `opts.opacity` (0–1) sets the alpha.\n * Returns `false` if the image can't be decoded.\n */\n addImageWatermark(\n data: Uint8Array,\n opts: {\n pages?: number[];\n anchor?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n offsetX?: number;\n offsetY?: number;\n width?: number;\n height?: number;\n rotationDeg?: number;\n opacity?: number;\n tile?: boolean;\n } = {}\n ): boolean {\n const anchorTag = {\n center: 0,\n 'top-left': 1,\n 'top-right': 2,\n 'bottom-left': 3,\n 'bottom-right': 4,\n }[opts.anchor ?? 'center'];\n const pages = opts.pages ?? [];\n const call = (pp: number, pc: number) =>\n this.g._withBytes(data, (p, l) =>\n this.ex().gp_add_image_watermark(\n this.h,\n p,\n l,\n pp,\n pc,\n anchorTag,\n opts.offsetX ?? 0,\n opts.offsetY ?? 0,\n opts.width ?? 0,\n opts.height ?? 0,\n opts.rotationDeg ?? 0,\n opts.opacity ?? 0.25,\n opts.tile ? 1 : 0\n )\n );\n const rc = pages.length === 0 ? call(0, 0) : this.g._withU32(pages, (pp, pc) => call(pp, pc));\n return rc === 0;\n }\n /**\n * Draw SVG markup on a page as **native vector paths** (crisp at any zoom, not\n * rasterized), fitting its `viewBox` into the box `(x, y, w, h)` in PDF points\n * (origin bottom-left). Supports shapes, `<path>`, groups, transforms and\n * fill/stroke/opacity. Returns `false` if the SVG can't be parsed.\n */\n addSvg(page: number, svg: string, x: number, y: number, w: number, h: number): boolean {\n return (\n this.g._withStr(svg, (p, l) => this.ex().gp_add_svg(this.h, page, p, l, x, y, w, h)) === 0\n );\n }\n /** True redaction: delete content intersecting the region (no opaque cover by default). */\n redact(\n page: number,\n x: number,\n y: number,\n w: number,\n h: number,\n coverRgb = 0,\n hasCover = false\n ): number {\n return this.ex().gp_redact_region(this.h, page, x, y, w, h, RGB(coverRgb), hasCover ? 1 : 0);\n }\n\n /**\n * True **PII redaction** of one or more rectangles `(x, y, width, height)` in\n * PDF points (origin bottom-left), in a single call. For every rect this:\n *\n * - **deletes** the overlapping text/vector elements from the content stream —\n * the glyphs and their `/ToUnicode` mapping are gone, so copy/paste and text\n * extraction reveal nothing in the area;\n * - **overwrites the pixels** of any underlying image (a scan/photo) with opaque\n * black — only the intersecting sub-rectangle, so the rest of the page image\n * survives — and re-encodes the image, erasing the sensitive pixels from the\n * bytes (not merely covering them);\n * - strips overlapping annotations and clears their form-field values;\n * - paints an opaque **black** box over the rect as the visible redaction mark.\n *\n * The black cover is the default for PII (unlike {@link redact}). Pass\n * `opts.coverRgb` to change the mark colour, or `opts.cover = false` to remove\n * the content/pixels with no visible box. Returns the number of content\n * elements deleted across all rects.\n */\n redactPii(\n page: number,\n rects: { x: number; y: number; width: number; height: number }[],\n opts: { cover?: boolean; coverRgb?: number } = {}\n ): number {\n if (rects.length === 0) return 0;\n const flat: number[] = [];\n for (const r of rects) flat.push(r.x, r.y, r.width, r.height);\n const cover = opts.cover ?? true;\n const coverRgb = opts.coverRgb ?? 0x000000;\n return this.g._withF64(flat, (p, c) =>\n this.ex().gp_redact_pii(this.h, page, p, c, RGB(coverRgb), cover ? 1 : 0)\n );\n }\n\n // pages\n rotatePage(page: number, degrees: number): boolean {\n return this.ex().gp_rotate_page(this.h, page, degrees) === 0;\n }\n deletePage(page: number): boolean {\n return this.ex().gp_delete_page(this.h, page) === 0;\n }\n movePage(from: number, to: number): boolean {\n return this.ex().gp_move_page(this.h, from, to) === 0;\n }\n /**\n * Append pages of another PDF onto this document. With no `pages`, every page\n * is appended (powers *merge*). With `pages` — 1-based page numbers, in the\n * order given — only that selection is brought in (ISO 32000-1 §7.7.3), each\n * page keeping its content, resources, annotations and box geometry. Numbers\n * out of range are skipped; an empty/all-out-of-range selection returns\n * `false`.\n */\n appendPages(otherPdf: Uint8Array, pages?: number[]): boolean {\n if (pages === undefined) {\n return this.g._withBytes(otherPdf, (p, l) => this.ex().gp_append_pages(this.h, p, l)) === 0;\n }\n return (\n this.g._withBytes(otherPdf, (bp, bl) =>\n this.g._withU32(pages, (pp, pc) =>\n this.ex().gp_append_pages_subset(this.h, bp, bl, pp, pc)\n )\n ) === 0\n );\n }\n /**\n * Add an invisible (text render mode 3) standard-Helvetica text layer to\n * `page` in a SINGLE content append — for OCR. Each run is `{x, y, size,\n * text, rotation?}` (PDF user space, baseline-anchored, `rotation`° CCW).\n * Runs whose text has any non-WinAnsi glyph are skipped. Returns the number\n * of runs actually written (0 on engine error).\n */\n addTextLayer(\n page: number,\n runs: { x: number; y: number; size: number; text: string; rotation?: number }[]\n ): number {\n const parts: Uint8Array[] = [];\n let total = 0;\n for (const r of runs) {\n const t = enc.encode(r.text);\n const head = new Uint8Array(36);\n const dv = new DataView(head.buffer);\n dv.setFloat64(0, r.x, true);\n dv.setFloat64(8, r.y, true);\n dv.setFloat64(16, r.size, true);\n dv.setFloat64(24, r.rotation ?? 0, true);\n dv.setUint32(32, t.length, true);\n parts.push(head, t);\n total += 36 + t.length;\n }\n const buf = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n buf.set(p, off);\n off += p.length;\n }\n const written = this.g._withBytes(buf, (p, l) =>\n this.ex().gp_add_text_layer(this.h, page, p, l)\n );\n return written < 0 ? 0 : written;\n }\n /** Extract the given 1-based page numbers into a NEW standalone PDF. */\n extractPages(pages: number[]): Uint8Array {\n return this.g._withU32(pages, (p, c) =>\n this.g._buffer((o) => this.ex().gp_extract_pages(this.h, p, c, o))\n );\n }\n /**\n * Resize a page's `/MediaBox` to `width`×`height` points — **box geometry\n * only**. The drawn content keeps its own coordinates (it is *not* rescaled to\n * the new box, so it may clip or float). To scale the page content along with\n * the box (keeping annotations aligned) use {@link scalePageContent} or\n * {@link scalePageTo}; for large-format authoring see {@link setUserUnit}.\n */\n resizePage(page: number, width: number, height: number): boolean {\n return this.ex().gp_resize_page(this.h, page, width, height) === 0;\n }\n /**\n * Scale a page's **content** uniformly by `factor` about the page origin (ISO\n * 32000-1 §8.3.4) — a true zoom of the whole page, not just the box. Three\n * things move together: (1) the content stream is wrapped in\n * `q <factor 0 0 factor 0 0> cm … Q`; (2) `/MediaBox` and `/CropBox` (resolved\n * through inheritance) plus any locally declared `/BleedBox`/`/TrimBox`/\n * `/ArtBox` are scaled about the origin; (3) every annotation `/Rect` is scaled,\n * so widget/stamp appearances — mapped from their `/BBox` into the `/Rect` per\n * §12.5.5 — rescale to stay aligned automatically. `factor` must be finite and\n * positive. `false` on engine error (bad page number / non-positive factor).\n */\n scalePageContent(page: number, factor: number): boolean {\n return this.ex().gp_scale_page_content(this.h, page, factor) === 0;\n }\n /**\n * Anisotropic {@link scalePageContent}: scale a page's content by `sx`\n * horizontally and `sy` vertically about the origin, scaling the boxes and\n * annotation `/Rect`s by the same factors. Both must be finite and positive.\n * `false` on engine error.\n */\n scalePageContentXY(page: number, sx: number, sy: number): boolean {\n return this.ex().gp_scale_page_content_xy(this.h, page, sx, sy) === 0;\n }\n /**\n * Scale a page's content to **fit within** `width`×`height` points (shrink- or\n * grow-to-fit), preserving aspect ratio — equivalent to {@link scalePageContent}\n * with `min(width / currentWidth, height / currentHeight)` over the page's\n * displayed size (`/MediaBox` with `/Rotate` applied). Returns the uniform\n * factor applied, or `null` on engine error (bad page number, non-positive\n * target, or zero-area page).\n */\n scalePageTo(page: number, width: number, height: number): number | null {\n const factor = this.ex().gp_scale_page_to(this.h, page, width, height);\n return factor < 0 ? null : factor;\n }\n /**\n * Set a page's `/UserUnit` (ISO 32000-1 §14.11.2) for **large-format\n * authoring**: one default user-space unit becomes `unit`⁄72 inch, so the same\n * coordinates render larger (e.g. `2.0` doubles the physical size, lifting the\n * ~200-inch coordinate ceiling). `1.0` is the default and removes the key. This\n * is distinct from {@link scalePageContent}: it rescales the coordinate system\n * (a viewer-level zoom of the medium), not the content or boxes. `unit` must be\n * finite and positive. `false` on engine error.\n */\n setUserUnit(page: number, unit: number): boolean {\n return this.ex().gp_set_user_unit(this.h, page, unit) === 0;\n }\n /**\n * A page's `/UserUnit` (ISO 32000-1 §14.11.2), defaulting to `1.0` when absent.\n * Returns `null` on engine error (bad page number).\n */\n pageUserUnit(page: number): number | null {\n const unit = this.ex().gp_page_user_unit(this.h, page);\n return unit < 0 ? null : unit;\n }\n /** Insert a blank page after the 1-based `after` page (0 = front); returns its id. */\n addPage(width: number, height: number, after = 0): number {\n return this.ex().gp_add_page(this.h, width, height, after);\n }\n /** Duplicate a page, inserting the copy right after it; returns the new page's id. */\n copyPage(page: number): number {\n return this.ex().gp_copy_page(this.h, page);\n }\n /**\n * N-up imposition (ISO 32000-1 §8.10): draw the **content** of the 1-based\n * `source` page, scaled and translated, onto the 1-based `target` page — the\n * basis for 2-up/4-up, booklets, contact sheets and page-on-page stamping. The\n * source page becomes a Form XObject (its content + `/Resources`, so its fonts\n * and images come along) and is drawn with `q <cm> /Fmn Do Q` appended to the\n * target. `(x, y)` is where the visible page's lower-left corner lands and\n * `(scaleX, scaleY)` scale the page **as displayed** (its `/MediaBox` origin\n * and `/Rotate` are absorbed into the matrix). Wrapped in `q`/`Q`, so it never\n * disturbs existing target content and is **composable** — call it repeatedly\n * (different sources and/or cells) to build an N-up sheet. `source` and\n * `target` may be the same page. `false` on engine error (bad page number).\n */\n placePage(\n target: number,\n source: number,\n x: number,\n y: number,\n scaleX: number,\n scaleY: number\n ): boolean {\n return this.ex().gp_place_page(this.h, target, source, x, y, scaleX, scaleY) === 0;\n }\n /**\n * Place `source` onto `target` (both 1-based) using an explicit content-stream\n * matrix `[a, b, c, d, e, f]` — the low-level primitive behind\n * {@link placePage} for full control of the affine (shear, arbitrary rotation,\n * reflection). The matrix maps the source page's form space (its user space,\n * including the `/MediaBox` origin) to the target; unlike {@link placePage} no\n * origin/rotation normalisation is applied, so identity draws the source 1:1\n * at the target origin. `false` on engine error.\n */\n placePageMatrix(target: number, source: number, matrix: [number, number, number, number, number, number]): boolean {\n const [a, b, c, d, e, f] = matrix;\n return this.ex().gp_place_page_matrix(this.h, target, source, a, b, c, d, e, f) === 0;\n }\n /**\n * Impose **all** existing pages `cols × rows` per sheet onto freshly added\n * sheets (2-up, 4-up, booklet thumbnails, contact sheets). Pages go\n * left-to-right, top-to-bottom; each is scaled uniformly to fit its cell\n * (aspect preserved) and centred. The new sheets are appended after the last\n * original page and the **originals are removed**, leaving only the imposed\n * sheets. Returns the number of sheets produced (negative on error: `cols`/\n * `rows` 0, or an empty document). `sheetWidth`/`sheetHeight` default to A4\n * portrait; `margin`/`gutter` to 14 pt.\n */\n nUp(\n cols: number,\n rows: number,\n opts: { sheetWidth?: number; sheetHeight?: number; margin?: number; gutter?: number } = {}\n ): number {\n return this.ex().gp_n_up(\n this.h,\n cols,\n rows,\n opts.sheetWidth ?? 595.28,\n opts.sheetHeight ?? 841.89,\n opts.margin ?? 14,\n opts.gutter ?? 14\n );\n }\n /** A page's size (points) and `/Rotate` (0/90/180/270). */\n pageInfo(page: number): PageInfo {\n return this.g._json((o) => this.ex().gp_page_info_json(this.h, page, o));\n }\n\n // margins + running header/footer\n\n /**\n * A page's margins (points): the gap between `/CropBox` and `/MediaBox` when a\n * CropBox exists, else estimated from the content bounding box.\n */\n pageMargins(page: number): PageMargins {\n return this.g._json<PageMargins>((o) => this.ex().gp_page_margins(this.h, page, o));\n }\n\n /**\n * Set a page's margins (points) by insetting its `/CropBox` from the `/MediaBox`\n * — a real, visible margin change. Returns `true` on success.\n */\n setPageMargins(page: number, m: PageMargins): boolean {\n return this.ex().gp_set_page_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;\n }\n\n /**\n * Store an **opaque** JSON string as the document's GigaPDF editor-metadata\n * sidecar — private editor state that travels with the PDF (catalog\n * `/GigaPDF /EditorMeta`, a FlateDecode-compressed stream). It is ignored by\n * every standard PDF reader and the round-trip survives save/open. Pass a JSON\n * **object** if you also use {@link setEditorMargins} (which read-modify-writes\n * that object's `margins` key). Returns `true` on success.\n */\n setEditorMeta(json: string): boolean {\n return this.g._withStr(json, (p, l) => this.ex().gp_set_editor_meta(this.h, p, l)) === 0;\n }\n\n /**\n * The document's GigaPDF editor-metadata sidecar string (set by\n * {@link setEditorMeta}), or `null` when the document carries none.\n */\n editorMeta(): string | null {\n return this.g._strOrNull((o) => this.ex().gp_editor_meta(this.h, o));\n }\n\n /**\n * Record the editor's per-page **display** margins (points) in the\n * editor-metadata sidecar (under `margins`, keyed by page) **without touching\n * `/CropBox` or `/MediaBox`** — distinct from {@link setPageMargins}, which\n * performs a real visible recrop. Any other host keys in the sidecar are\n * preserved. Returns `true` on success.\n */\n setEditorMargins(page: number, m: PageMargins): boolean {\n return this.ex().gp_set_editor_margins(this.h, page, m.top, m.right, m.bottom, m.left) === 0;\n }\n\n /**\n * The editor's per-page display margins (points) recorded for `page` by\n * {@link setEditorMargins}, or `null` when none were stored. Reads only the\n * sidecar — never `/CropBox`.\n */\n editorMargins(page: number): PageMargins | null {\n return this.g._jsonOrNull<PageMargins>((o) => this.ex().gp_editor_margins(this.h, page, o));\n }\n\n /**\n * All five page boundary boxes (`media`/`crop`/`bleed`/`trim`/`art`) for the\n * 1-based `page`, each as `[x0, y0, x1, y1]` in points, with ISO 32000-1\n * inheritance and defaults applied. See {@link PageBoxes} for the exact\n * default chain and the `declared` flags.\n */\n getPageBoxes(page: number): PageBoxes {\n return this.g._json<PageBoxes>((o) => this.ex().gp_page_boxes_json(this.h, page, o));\n }\n\n /**\n * Set one of a page's boundary boxes. `kind` is one of {@link PAGE_BOX_KINDS}\n * and `box` is given as `{ x, y, w, h }` (origin + size, points); it is written\n * as `[x, y, x+w, y+h]`, normalised so reversed sizes are accepted. Sibling\n * boxes are preserved. Returns `true` on success, `false` for an unknown kind,\n * a degenerate box (zero/negative area), or a bad page number.\n *\n * Setting `\"trim\"`/`\"bleed\"` is the prerequisite for PDF/X and commercial-print\n * (imposition, bleed, finished-size) pipelines.\n */\n setPageBox(page: number, kind: PageBoxKind, box: Box): boolean {\n const k = PAGE_BOX_KINDS.indexOf(kind);\n if (k < 0) return false;\n return (\n this.ex().gp_set_page_box(this.h, page, k, box.x, box.y, box.x + box.w, box.y + box.h) === 0\n );\n }\n\n /**\n * The document's page-label ranges (`/PageLabels`, ISO 32000-1 §12.4.2), sorted\n * by `startPage` (1-based). Empty when the document declares no page labels.\n */\n getPageLabels(): PageLabelRange[] {\n return this.g._json<PageLabelRange[]>((o) => this.ex().gp_page_labels_json(this.h, o));\n }\n\n /**\n * Replace the document's page labels. Pass an **empty** array to remove all\n * labels. Ranges are sorted by `startPage` and collapsed to one entry per page\n * (last wins). Returns `true` on success.\n *\n * @example\n * // Front matter in lowercase roman, body in decimal, appendix \"A-1, A-2…\".\n * doc.setPageLabels([\n * { startPage: 1, style: \"romanLower\", prefix: \"\", startNumber: 1 },\n * { startPage: 5, style: \"decimal\", prefix: \"\", startNumber: 1 },\n * { startPage: 20, style: \"decimal\", prefix: \"A-\", startNumber: 1 },\n * ]);\n */\n setPageLabels(ranges: PageLabelRange[]): boolean {\n const text = ranges\n .map(\n (r) =>\n `${r.startPage}\\t${PAGE_LABEL_STYLE_TOKEN[r.style] ?? \"-\"}\\t${r.startNumber ?? 1}\\t${\n r.prefix ?? \"\"\n }`\n )\n .join(\"\\n\");\n return this.g._withOptStr(text, (p, l) => this.ex().gp_set_page_labels(this.h, p, l)) === 0;\n }\n\n /**\n * The viewer-visible label string for the 1-based `page` (e.g. `\"iv\"`, `\"A-3\"`),\n * resolving the applicable `/PageLabels` range; the decimal page number when no\n * range applies (including a document with no page labels).\n */\n pageLabel(page: number): string {\n return this.g._str((o) => this.ex().gp_page_label(this.h, page, o));\n }\n\n /**\n * Author a presentation transition + auto-advance on `page` (1-based),\n * ISO 32000-1 §12.4.4. Writes the page's `/Trans` dictionary from\n * {@link PageTransition.style} plus only the optional sub-keys that apply to\n * that style (`dimension`/`motion` for `split`, `direction`/`scale`/\n * `flyAreaOpaque` for `fly`, …) — inapplicable fields are dropped.\n * {@link PageTransition.displayDuration} becomes the page's `/Dur`\n * (auto-advance); omitting it removes any existing `/Dur`. Re-calling replaces\n * the prior transition in full (idempotent). Returns `true` on success,\n * `false` for an unknown style, a negative/non-finite `duration`/`scale`/\n * `displayDuration`, or a bad page number.\n *\n * @example\n * // Kiosk slideshow: every page wipes in over 0.5 s, auto-advancing after 5 s.\n * for (let p = 1; p <= doc.pageCount(); p++) {\n * doc.setPageTransition(p, { style: \"wipe\", duration: 0.5, displayDuration: 5 });\n * }\n */\n setPageTransition(page: number, trans: PageTransition): boolean {\n const style = PAGE_TRANSITION_STYLES.indexOf(trans.style);\n if (style < 0) return false;\n const dimension =\n trans.dimension === \"horizontal\" ? 0 : trans.dimension === \"vertical\" ? 1 : -1;\n const motion = trans.motion === \"inward\" ? 0 : trans.motion === \"outward\" ? 1 : -1;\n const direction =\n trans.direction === undefined ? -2 : trans.direction === \"none\" ? -1 : trans.direction;\n const flyB = trans.flyAreaOpaque === undefined ? -1 : trans.flyAreaOpaque ? 1 : 0;\n return (\n this.ex().gp_set_page_transition(\n this.h,\n page,\n style,\n trans.duration ?? Number.NaN,\n dimension,\n motion,\n direction,\n trans.scale ?? Number.NaN,\n flyB,\n trans.displayDuration ?? Number.NaN\n ) === 0\n );\n }\n\n /**\n * The presentation transition declared on `page` (1-based), or `null` when the\n * page has no `/Trans` (ISO 32000-1 §12.4.4). Optional fields that do not apply\n * to the recovered style are omitted from the result.\n */\n getPageTransition(page: number): PageTransition | null {\n return this.g._jsonOrNull<PageTransition>((o) => this.ex().gp_page_transition_json(this.h, page, o));\n }\n\n /**\n * Remove any presentation transition from `page` (1-based) — drops the page's\n * `/Trans` dictionary and its `/Dur` auto-advance entry. A no-op if neither is\n * present. Returns `true` on success.\n */\n clearPageTransition(page: number): boolean {\n return this.ex().gp_clear_page_transition(this.h, page) === 0;\n }\n\n /**\n * Bake a running header onto every in-range page (idempotent: re-baking\n * replaces the prior header). Returns `true` on success.\n */\n setHeader(spec: HeaderFooterSpec): boolean {\n return (\n this.g._withStr(JSON.stringify(spec), (p, l) => this.ex().gp_set_header(this.h, p, l)) === 0\n );\n }\n\n /** Bake a running footer onto every in-range page (idempotent). */\n setFooter(spec: HeaderFooterSpec): boolean {\n return (\n this.g._withStr(JSON.stringify(spec), (p, l) => this.ex().gp_set_footer(this.h, p, l)) === 0\n );\n }\n\n /** Remove every previously-baked running header from all pages. */\n removeHeaders(): boolean {\n return this.ex().gp_remove_headers(this.h) === 0;\n }\n\n /** Remove every previously-baked running footer from all pages. */\n removeFooters(): boolean {\n return this.ex().gp_remove_footers(this.h) === 0;\n }\n\n /**\n * Detect the running header/footer already baked into this PDF — the reader\n * counterpart of {@link GigaPdfDoc.setHeader} / {@link GigaPdfDoc.setFooter}.\n * Each side is a {@link HeaderFooterSpec} (with its recovered `text`) when a\n * baked `/GPHF` span is present, or `null` when absent. The `text` is faithful\n * (the per-page-substituted text of the first matching page); `align`,\n * `fontSize`, `color`, etc. are best-effort defaults, since the bake records\n * only the drawn text. Use it to reflect existing document state (e.g. a\n * Word-like editor toggle).\n */\n headerFooter(): { header: HeaderFooterSpec | null; footer: HeaderFooterSpec | null } {\n return this.g._json<{ header: HeaderFooterSpec | null; footer: HeaderFooterSpec | null }>((o) =>\n this.ex().gp_header_footer(this.h, o),\n );\n }\n\n /**\n * Bake a **rich**, Word-like running header/footer from a {@link RunningHeaderFooter}\n * `def` (the source of truth — stored in the editor-meta sidecar, its visible\n * `/GPHF` band regenerated on every page). Text is set in an embedded font\n * (each item's `fontRef`, else the bundled OFL face — never base-14) and images\n * via the same path as {@link addImage}; both live inside the `/GPHF` span, so\n * they are excluded from {@link elements}/{@link textRuns} and masked by\n * {@link renderPageExcludingMarkedContent}. Idempotent (re-baking replaces the\n * prior band).\n *\n * `opts.date` is the bake date for `{{date}}` (the engine is clockless — pass\n * e.g. `new Date().toISOString().slice(0, 10)`); omit to fall back to the\n * document's `/Info` date. `opts.images` supplies the pixels each\n * `HFItem` of `type: \"image\"` references by `imageId` — an iterable of\n * `[imageId, bytes]` (a `Map<number, Uint8Array>` works directly); an image\n * whose id is absent is skipped. Returns `true` on success.\n *\n * @example\n * doc.setRunningHeaderFooter(\n * {\n * default: {\n * header: [{ type: \"image\", imageId: 1, w: 80, h: 24, anchor: \"left\" }],\n * footer: [{ type: \"text\", text: \"{{title}} — {{page}}/{{pages}}\", anchor: \"center\" }],\n * },\n * firstPage: { header: [], footer: [] }, // blank cover\n * differentFirstPage: true,\n * differentOddEven: true,\n * evenPage: { header: [{ type: \"text\", text: \"{{page}}\", anchor: \"left\" }], footer: [] },\n * oddPage: { header: [{ type: \"text\", text: \"{{page}}\", anchor: \"right\" }], footer: [] },\n * },\n * { date: new Date().toISOString().slice(0, 10), images: new Map([[1, logoPng]]) }\n * );\n */\n setRunningHeaderFooter(\n def: RunningHeaderFooter,\n opts?: { date?: string; images?: Iterable<[number, Uint8Array]> }\n ): boolean {\n const entries = opts?.images ? Array.from(opts.images) : [];\n // Image blob: [u32 count] then, per entry, [u32 imageId][u32 byteLen][bytes].\n let total = 4;\n for (const [, bytes] of entries) total += 8 + bytes.length;\n const blob = new Uint8Array(total);\n const dv = new DataView(blob.buffer);\n let off = 0;\n dv.setUint32(off, entries.length >>> 0, true);\n off += 4;\n for (const [id, bytes] of entries) {\n dv.setUint32(off, id >>> 0, true);\n off += 4;\n dv.setUint32(off, bytes.length >>> 0, true);\n off += 4;\n blob.set(bytes, off);\n off += bytes.length;\n }\n return (\n this.g._withStr(JSON.stringify(def), (dp, dl) =>\n this.g._withOptStr(opts?.date, (tp, tl) =>\n this.g._withBytes(blob, (ip, il) =>\n this.ex().gp_set_running_header_footer(this.h, dp, dl, tp, tl, ip, il)\n )\n )\n ) === 0\n );\n }\n\n /**\n * The rich {@link RunningHeaderFooter} definition recorded by\n * {@link setRunningHeaderFooter} (read from the editor-meta sidecar — the\n * source of truth), or a minimal one reconstructed from a legacy flat\n * {@link setHeader}/{@link setFooter} bake, or `null` when neither is present.\n */\n runningHeaderFooter(): RunningHeaderFooter | null {\n return this.g._jsonOrNull<RunningHeaderFooter>((o) =>\n this.ex().gp_running_header_footer(this.h, o)\n );\n }\n\n // render\n renderPage(page: number, scale = 1): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_render_page(this.h, page, scale, o));\n }\n\n /**\n * Rasterize a page to a PNG **without the page content stream's text** — glyphs\n * are suppressed while gradients, shadings, images, vectors and patterns are\n * preserved. Form-field **widget** appearances are omitted (the editor re-shows\n * their values as an editable overlay, so baking them in would double every\n * field); other annotation appearances (stamps, highlights, ink) are still\n * painted. Use this to paint a text-free raster background the editor can\n * overlay real, editable text on top of.\n */\n renderPageNoText(page: number, scale = 1): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_render_page_no_text(this.h, page, scale, o));\n }\n\n /**\n * Rasterize a page to a PNG while **omitting** the given top-level element\n * `indices` (from {@link GigaPdfDoc.elements}). Each excluded element paints nothing\n * — fills, strokes, shadings, images and text alike — while everything else\n * (including the non-text content of non-excluded elements) renders normally.\n * Use it to paint a background without specific elements and overlay live,\n * editable versions on top. Generalises {@link renderPageNoText} (which\n * suppresses *all* text). Like {@link renderPageNoText}, form-field **widget**\n * appearances are omitted (the editor re-shows them as an editable overlay);\n * other annotation appearances are painted. An empty `indices` renders the full\n * page; unknown indices are ignored.\n */\n renderPageExcluding(page: number, indices: number[], scale = 1): Uint8Array {\n return this.g._buffer((o) =>\n this.g._withU32(indices, (p, c) =>\n this.ex().gp_render_page_excluding(this.h, page, p, c, scale, o)\n )\n );\n }\n\n /**\n * Rasterize a page to a PNG **excluding the ops inside a baked marked-content\n * span** named `marker` — and, when `skipText` is true, the page's text too — in\n * a **single** raster pass. For `marker = \"GPHF\"` (the default) this drops the\n * baked running header/footer band: the extraction views ({@link elements},\n * {@link textRuns}) already omit that band (it is never editable body content),\n * and this render omits it from the picture so it cannot double against an\n * editable overlay. With `skipText = true` it is the editor's text-free display\n * background minus the band; with `skipText = false`, the full page minus the\n * band. Like {@link renderPageNoText}, form-field widget appearances are omitted.\n */\n renderPageExcludingMarkedContent(\n page: number,\n scale = 1,\n skipText = true,\n marker = \"GPHF\"\n ): Uint8Array {\n return this.g._buffer((o) =>\n this.g._withStr(marker, (p, l) =>\n this.ex().gp_render_page_excluding_marked_content(\n this.h,\n page,\n scale,\n skipText ? 1 : 0,\n p,\n l,\n o\n )\n )\n );\n }\n\n // fonts — embed a downloaded font, then add real selectable text\n /**\n * Embed an outline font program as a Type0 font and return its object number\n * (pass to {@link addText} / re-encoded by {@link replaceText}). Accepts\n * **any** font file — glyf **TrueType** (`.ttf`) or **OpenType-CFF**\n * (`.otf`/`OTTO`), flavour auto-detected — so `font` may be a Google Font the\n * host fetched, an `.otf` you supply, or a face pulled out of a document with\n * {@link extractFont}. Returns 0 on a malformed/unsupported program.\n */\n embedFont(family: string, font: Uint8Array): number {\n const b = enc.encode(family);\n const famPtr = this.g._toWasm(b);\n const obj = this.g._withBytes(font, (p, l) =>\n this.ex().gp_embed_font(this.h, famPtr, b.length, p, l)\n );\n this.g._free(famPtr, b.length);\n return obj;\n }\n /**\n * Draw real, selectable text at `(x, y)` (PDF points, origin bottom-left) in a\n * font embedded with {@link embedFont} (`fontObj`). Works with **any** embedded\n * face — glyf TrueType or OpenType-CFF — encoding each character through the\n * font's char→glyph map (Identity-H, 2-byte glyph ids). `rgb` is packed\n * `0xRRGGBB`; `rotationDeg` rotates CCW about `(x, y)`. For a built-in base-14\n * family with no embedding, use {@link addStandardText}.\n *\n * Pass `opts` to bake **text decorations** into the run: `{ underline: true }`\n * draws a rule just below the baseline, `{ strikethrough: true }` a rule near\n * the x-height — both span the run's advance and are filled in the text colour.\n * Omitting `opts` is fully backward-compatible (no decoration).\n */\n addText(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n fontObj: number,\n rgb = 0,\n opacity = 1,\n rotationDeg = 0,\n opts?: { underline?: boolean; strikethrough?: boolean }\n ): boolean {\n const underline = opts?.underline ? 1 : 0;\n const strikethrough = opts?.strikethrough ? 1 : 0;\n return (\n this.g._withStr(text, (p, l) =>\n this.ex().gp_add_text_styled(\n this.h,\n page,\n x,\n y,\n size,\n p,\n l,\n fontObj,\n RGB(rgb),\n opacity,\n rotationDeg,\n underline,\n strikethrough\n )\n ) === 0\n );\n }\n /**\n * Draw `text` at `(x, y)` in a built-in **base-14 standard font** (`fontName`,\n * e.g. `\"Times-Bold\"`, `\"Courier-Oblique\"`, `\"Symbol\"`) — no embedding needed,\n * every viewer ships these 14. For any other family embed a TrueType with\n * {@link embedFont} (a Google Font fetched by the host, or one pulled out of\n * the document with {@link extractFont}) and use {@link addText}. Returns\n * `false` on an unknown font name or bad page.\n *\n * Pass `opts` to bake **text decorations** into the run: `{ underline: true }`\n * and/or `{ strikethrough: true }` draw filled rules in the text colour.\n * Omitting `opts` is fully backward-compatible (no decoration).\n */\n addStandardText(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n fontName: string,\n rgb = 0,\n opacity = 1,\n rotationDeg = 0,\n opts?: { underline?: boolean; strikethrough?: boolean }\n ): boolean {\n const underline = opts?.underline ? 1 : 0;\n const strikethrough = opts?.strikethrough ? 1 : 0;\n return (\n this.g._withStr(text, (tp, tl) =>\n this.g._withStr(fontName, (fp, fl) =>\n this.ex().gp_add_text_standard_styled(\n this.h,\n page,\n x,\n y,\n size,\n tp,\n tl,\n fp,\n fl,\n RGB(rgb),\n opacity,\n rotationDeg,\n underline,\n strikethrough\n )\n )\n ) === 0\n );\n }\n /**\n * Stamp a standard-**Helvetica** watermark (no font embed needed): `text` at\n * `(x, y)`, rotated `rotationDeg`° counter-clockwise, `rgb` packed `0xRRGGBB`,\n * `opacity` 0–1. Pair with {@link GigaPdfEngine.helveticaWidth} for centring.\n */\n addWatermark(\n page: number,\n x: number,\n y: number,\n size: number,\n text: string,\n rgb = 0x808080,\n opacity = 0.25,\n rotationDeg = 0\n ): boolean {\n return (\n this.g._withStr(text, (p, l) =>\n this.ex().gp_add_watermark(this.h, page, x, y, size, p, l, RGB(rgb), opacity, rotationDeg)\n ) === 0\n );\n }\n neededFonts(): string[] {\n return this.g._json((o) => this.ex().gp_needed_fonts(this.h, o));\n }\n /**\n * Extract an embedded font program by (fuzzy) `/BaseFont` name — so a host\n * editor can re-embed the document's own font when re-baking edited text and\n * keep the original glyphs. Returns the raw decoded bytes and the program\n * format (`truetype` embeds directly; `cff`/`type1` need a TTF conversion),\n * or `null` when nothing embedded matches.\n */\n extractFont(\n name: string\n ): { format: \"truetype\" | \"cff\" | \"type1\"; bytes: Uint8Array } | null {\n const buf = this.g._withStr(name, (p, l) =>\n this.g._buffer((o) => this.ex().gp_extract_font(this.h, p, l, o))\n );\n if (buf.length === 0) return null;\n const format = buf[0] === 1 ? \"truetype\" : buf[0] === 2 ? \"cff\" : \"type1\";\n return { format, bytes: buf.subarray(1) };\n }\n /**\n * The fonts **embedded** in the document — each `{ baseFont, format }`. Pair\n * with {@link extractFont} to pull a font's bytes out and re-embed them via\n * {@link embedFont}, e.g. to draw new text (with {@link addText}) in a face\n * the document already carries — no external font file needed.\n */\n embeddedFonts(): EmbeddedFont[] {\n return this.g._json((o) => this.ex().gp_embedded_fonts_json(this.h, o));\n }\n\n // convert PDF → X\n toText(): string {\n return this.g._str((o) => this.ex().gp_to_text(this.h, o));\n }\n toHtml(): string {\n return this.g._str((o) => this.ex().gp_to_html(this.h, o));\n }\n /**\n * Reconstruct this PDF into the **unified editable model** — the\n * format-neutral {@link GigaDocument} tree (sections → pages → blocks → runs)\n * that every format lowers into. Edit it with\n * {@link GigaPdfEngine.applyModelOps}, then export it to any target with\n * {@link GigaPdfEngine.modelToDocx} / {@link GigaPdfEngine.modelToPdf} / … —\n * the foundation for editing any document indifferently of its source format.\n */\n toModel(): GigaDocument {\n return JSON.parse(this.g._str((o) => this.ex().gp_model_from_pdf(this.h, o))) as GigaDocument;\n }\n toDocx(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_docx(this.h, o));\n }\n toPptx(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_pptx(this.h, o));\n }\n /** Convert to an editable OpenDocument Presentation (`.odp`). */\n toOdp(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_odp(this.h, o));\n }\n toOdt(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_odt(this.h, o));\n }\n toXlsx(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_xlsx(this.h, o));\n }\n toOds(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_ods(this.h, o));\n }\n toRtf(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_rtf(this.h, o));\n }\n /**\n * Re-serialize the document as **PDF/A** (archival).\n *\n * `level` selects the conformance flavour (default `\"pdfa-2b\"`):\n * - `\"pdfa-1b\"` — ISO 19005-1, based on PDF 1.4.\n * - `\"pdfa-1a\"` — ISO 19005-1 **Tagged PDF** (level A): 1b + a logical\n * structure tree, marked content and `/Lang`. Built from the structure the\n * engine reconstructs (paragraphs, headings, tables, lists).\n * - `\"pdfa-2b\"` — ISO 19005-2 (default).\n * - `\"pdfa-2u\"` — like 2b but requires every glyph Unicode-mapped (a\n * `/ToUnicode` CMap on each font); only validator-clean when the source\n * fonts already carry one — otherwise prefer `\"pdfa-2b\"`.\n * - `\"pdfa-2a\"` — ISO 19005-2 **Tagged PDF** (level A): 2u + a logical\n * structure tree and marked content (`/StructTreeRoot`, `/MarkInfo`).\n * - `\"pdfa-3b\"` — ISO 19005-3; permits embedded file attachments.\n *\n * Full conformance also requires every font embedded — this method does not\n * embed missing fonts (see the Rust `to_pdfa_level` docs). For the level-A\n * (`1a`/`2a`) flavours the tagging is rendering-neutral: it only inserts\n * balanced marked-content operators and a structure tree, never changing the\n * page appearance.\n */\n toPdfA(\n level:\n | \"pdfa-1b\"\n | \"pdfa-1a\"\n | \"pdfa-2b\"\n | \"pdfa-2u\"\n | \"pdfa-2a\"\n | \"pdfa-3b\" = \"pdfa-2b\",\n ): Uint8Array {\n return this.g._withStr(level, (p, l) =>\n this.g._buffer((o) => this.ex().gp_to_pdfa(this.h, p, l, o)),\n );\n }\n\n /**\n * Author a **tagged (accessible) PDF** — a `/StructTreeRoot` logical-structure\n * tree (`P`/`H1`–`H6`/`Table`/`L`/`Figure` …) with marked content, `/MarkInfo`,\n * `/Lang`, `/RoleMap` and `/Alt` on figures — **without** forcing PDF/A. Pass\n * `{ pdfUa: true }` to also stamp the PDF/UA-1 identifier (ISO 14289). If the\n * document has no reconstructable structure the plain PDF is returned.\n * ISO 32000-1 §14.7/§14.8.\n */\n toTagged(opts: { pdfUa?: boolean } = {}): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_to_tagged(this.h, opts.pdfUa ? 1 : 0, o));\n }\n\n /**\n * The number of taggable **figures** the engine reconstructs across the whole\n * document — the valid range `0..figureCount()` for {@link setFigureAlt}'s\n * `index`. Each figure is an image the geometric reconstruction surfaces; the\n * Tagged-PDF / PDF-A-level-A export emits one `/Figure` structure element per\n * figure, in this same order.\n */\n figureCount(): number {\n return this.ex().gp_figure_count(this.h);\n }\n\n /**\n * Attach **author-supplied alternate text** (`/Alt`) to a figure so assistive\n * technology can describe the image (WCAG / PDF/UA, ISO 32000-1 §14.9.3).\n *\n * `index` is the **document-global figure index** — figures are numbered\n * `0, 1, 2, …` in page order, then in page-content order within each page (the\n * Nth image of the whole document is figure `N`; {@link figureCount} bounds the\n * range). The text lands on the matching `/Figure` structure element's `/Alt`\n * when an accessible export is produced — {@link toTagged} or {@link toPdfA}\n * with `\"pdfa-1a\"`/`\"pdfa-2a\"`. Figures with no author-supplied text keep a\n * generic non-empty placeholder, so the output stays structurally valid even\n * for unlabeled figures.\n *\n * Returns `true` on success; `false` if `alt` is empty (a `/Alt` must be\n * non-empty) or the call otherwise fails.\n */\n setFigureAlt(index: number, alt: string): boolean {\n return (\n this.g._withStr(alt, (p, l) => this.ex().gp_set_figure_alt(this.h, index, p, l)) === 0\n );\n }\n\n // security\n /**\n * Serialize the document encrypted with the PDF Standard Security Handler.\n * Defaults to **AES-256 (R6)**. `fileId` is the document `/ID` (any stable\n * hex/string). For AES-256 a **secret 32-byte key** is required — it is taken\n * from `opts.keySeed` or generated with Web Crypto; RC4/AES-128 derive their\n * key from the password and ignore it.\n */\n saveEncrypted(\n password: string,\n fileId: string,\n opts: {\n ownerPassword?: string;\n algorithm?: \"rc4\" | \"aes128\" | \"aes256\";\n /**\n * Named access permissions (ISO 32000-1 Table 22). Omitted flags default\n * to **granted**. Takes precedence over `permissions` when present.\n */\n flags?: Partial<PdfPermissions>;\n /**\n * Raw signed 32-bit `/P` bitmask. Use `flags` (above) for a readable API.\n * Defaults to all permissions granted when neither is given.\n */\n permissions?: number;\n keySeed?: Uint8Array;\n } = {}\n ): Uint8Array {\n const algo = opts.algorithm ?? \"aes256\";\n const algoCode = algo === \"rc4\" ? 0 : algo === \"aes128\" ? 1 : 2;\n // Precedence: explicit `flags` → packed /P; else raw `permissions`; else\n // the unrestricted spec-strict baseline (`/P` = -196, all eight granted).\n const permissions =\n opts.flags !== undefined\n ? this.g.permissionsToP(opts.flags)\n : opts.permissions ?? this.g.permissionsToP();\n let key = opts.keySeed ?? new Uint8Array(0);\n if (algoCode === 2 && key.length < 32) {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (!c?.getRandomValues) {\n throw new Error(\n \"AES-256 encryption needs Web Crypto (globalThis.crypto.getRandomValues) or an explicit opts.keySeed\"\n );\n }\n // `getRandomValues` requires an ArrayBuffer-backed view (not ArrayBufferLike).\n const fresh = new Uint8Array(32);\n c.getRandomValues(fresh);\n key = fresh;\n }\n return this.g._withStr(password, (pwP, pwL) =>\n this.g._withOptStr(opts.ownerPassword, (oP, oL) =>\n this.g._withStr(fileId, (idP, idL) =>\n this.g._withBytes(key, (kP, kL) =>\n this.g._buffer((o) =>\n this.ex().gp_save_encrypted(\n this.h,\n pwP,\n pwL,\n oP,\n oL,\n idP,\n idL,\n kP,\n kL,\n algoCode,\n permissions,\n o\n )\n )\n )\n )\n )\n );\n }\n\n /**\n * Re-encrypt an already-opened (decrypted) document with **new** passwords,\n * discarding the prior encryption (ISO 32000-1 §7.6). Opening with the old\n * password is what authorises the change. Mirrors {@link saveEncrypted} plus\n * `encryptMetadata` (when `false`, the metadata stream is left in the clear).\n */\n changePasswords(\n newPassword: string,\n fileId: string,\n opts: {\n ownerPassword?: string;\n algorithm?: \"rc4\" | \"aes128\" | \"aes256\";\n flags?: Partial<PdfPermissions>;\n permissions?: number;\n keySeed?: Uint8Array;\n encryptMetadata?: boolean;\n } = {}\n ): Uint8Array {\n const algo = opts.algorithm ?? \"aes256\";\n const algoCode = algo === \"rc4\" ? 0 : algo === \"aes128\" ? 1 : 2;\n const permissions =\n opts.flags !== undefined\n ? this.g.permissionsToP(opts.flags)\n : opts.permissions ?? this.g.permissionsToP();\n let key = opts.keySeed ?? new Uint8Array(0);\n if (algoCode === 2 && key.length < 32) {\n key = cryptoRandom(32);\n }\n const encMeta = opts.encryptMetadata ?? true;\n return this.g._withStr(newPassword, (pwP, pwL) =>\n this.g._withOptStr(opts.ownerPassword, (oP, oL) =>\n this.g._withStr(fileId, (idP, idL) =>\n this.g._withBytes(key, (kP, kL) =>\n this.g._buffer((o) =>\n this.ex().gp_change_passwords(\n this.h, pwP, pwL, oP, oL, idP, idL, kP, kL, algoCode, permissions,\n encMeta ? 1 : 0, o\n )\n )\n )\n )\n )\n );\n }\n\n /**\n * Strip encryption from an already-opened (decrypted) document, returning a\n * **plaintext** PDF. The document must have been opened with a valid password.\n */\n removeEncryption(): Uint8Array {\n return this.g._buffer((o) => this.ex().gp_remove_encryption(this.h, o));\n }\n\n /**\n * Encrypt the document to one or more **X.509 recipients** (public-key /\n * certificate security, ISO 32000-1 §7.6.5, `/Filter /Adobe.PubSec`): only a\n * holder of a recipient private key can open it — no shared password.\n * `certificates` are DER X.509 certs. `seed`/`rngSeed` default to Web Crypto\n * randomness. Open the result with {@link GigaPdfEngine.openWithPrivateKey}.\n */\n encryptForRecipients(\n certificates: Uint8Array[],\n opts: {\n flags?: Partial<PdfPermissions>;\n permissions?: number;\n aes256?: boolean;\n encryptMetadata?: boolean;\n seed?: Uint8Array;\n rngSeed?: Uint8Array;\n } = {}\n ): Uint8Array {\n if (certificates.length === 0) {\n throw new Error(\"encryptForRecipients needs at least one recipient certificate\");\n }\n const total = certificates.reduce((n, c) => n + c.length, 0);\n const blob = new Uint8Array(total);\n const lens: number[] = [];\n let off = 0;\n for (const c of certificates) {\n blob.set(c, off);\n off += c.length;\n lens.push(c.length);\n }\n const permissions =\n opts.flags !== undefined\n ? this.g.permissionsToP(opts.flags)\n : opts.permissions ?? this.g.permissionsToP();\n const aes256 = opts.aes256 ?? true;\n const encMeta = opts.encryptMetadata ?? true;\n const seed = opts.seed ?? cryptoRandom(20);\n const rng = opts.rngSeed ?? cryptoRandom(32);\n const out = this.g._withBytes(blob, (cP, cL) =>\n this.g._withU32(lens, (lP, lC) =>\n this.g._withBytes(seed, (sP, sL) =>\n this.g._withBytes(rng, (rP, rL) =>\n this.g._buffer((o) =>\n this.ex().gp_encrypt_for_recipients(\n this.h, cP, cL, lP, lC, permissions, aes256 ? 1 : 0, encMeta ? 1 : 0,\n sP, sL, rP, rL, o\n )\n )\n )\n )\n )\n );\n if (out.length === 0) {\n throw new Error(\"encryptForRecipients failed (invalid recipient certificate?)\");\n }\n return out;\n }\n\n /** Self-signed digital signature. `random` ≥ 256 bytes from crypto.getRandomValues. */\n sign(fields: string, random: Uint8Array, keyBits = 2048): Uint8Array {\n const rPtr = this.g._toWasm(random);\n const out = this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) => this.ex().gp_sign(this.h, fP, fL, rPtr, random.length, keyBits, o))\n );\n this.g._free(rPtr, random.length);\n return out;\n }\n\n /**\n * **Certify** the document (DocMDP) — like {@link sign} but also declares which\n * later changes are allowed: `docmdpLevel` is `1` (no changes), `2` (form-fill\n * + sign) or `3` (also annotate). `fields` is the same tab-separated string as\n * {@link sign} (`name⇥reason⇥date⇥notBefore⇥notAfter`).\n */\n certify(fields: string, random: Uint8Array, docmdpLevel: 1 | 2 | 3, keyBits = 2048): Uint8Array {\n const rPtr = this.g._toWasm(random);\n const out = this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) =>\n this.ex().gp_sign_certify(this.h, fP, fL, rPtr, random.length, keyBits, docmdpLevel, o)\n )\n );\n this.g._free(rPtr, random.length);\n return out;\n }\n\n /**\n * List every signature on the document (each `/Sig` field's `/V`) with its\n * metadata and `/ByteRange`. For cryptographic validity call\n * {@link verifySignatures}.\n */\n signatures(): SignatureInfo[] {\n return this.g._json((o) => this.ex().gp_signatures_json(this.h, o));\n }\n\n /**\n * Cryptographically verify every signature against `pdf` — the **original\n * bytes** this document was opened from. Each report carries `byteRangeOk`,\n * `digestOk` (content integrity), `signatureOk` (the RSA signature),\n * `coversWholeDocument`, the signer CN, and the algorithm.\n */\n verifySignatures(pdf: Uint8Array): SignatureReport[] {\n return this.g._withBytes(pdf, (p, l) =>\n this.g._json((o) => this.ex().gp_verify_signatures(this.h, p, l, o))\n );\n }\n /**\n * Sign with a PKCS#12 (`.p12`/`.pfx`) identity — a CA-issued / eIDAS\n * certificate and its RSA key, imported natively (no external crypto). `opts`\n * populates the signature dictionary: `name` (`/Name`), `reason` (`/Reason`),\n * `date` (`/M`, a PDF date string e.g. `D:20260616120000Z`), and the optional\n * `location` (`/Location`) and `contactInfo` (`/ContactInfo`). Throws a single\n * generic error on a wrong password, malformed file, unsupported cipher, or\n * missing certificate.\n */\n signP12(p12: Uint8Array, password: string, opts: SignP12Options = {}): Uint8Array {\n const fields = [\n opts.name ?? \"\",\n opts.reason ?? \"\",\n opts.date ?? \"\",\n opts.location ?? \"\",\n opts.contactInfo ?? \"\",\n ].join(\"\\t\");\n const p12Ptr = this.g._toWasm(p12);\n const out = this.g._withStr(password, (pwP, pwL) =>\n this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) =>\n this.ex().gp_sign_p12(this.h, p12Ptr, p12.length, pwP, pwL, fP, fL, o)\n )\n )\n );\n this.g._free(p12Ptr, p12.length);\n if (out.length === 0) {\n throw new Error(\n \"PKCS#12 signing failed: invalid certificate, password, or unsupported file\"\n );\n }\n return out;\n }\n /**\n * Sign with an embedded **RFC 3161 trusted timestamp** (PAdES-B-T). Unlike\n * {@link sign}/{@link signP12} this is `async`: the timestamp requires a\n * network round trip to a TSA, so the method runs the engine's two-phase flow\n * — build the signature → POST the `TimeStampReq` to the TSA → embed the\n * returned token — with the HTTP in between.\n *\n * The signing identity is `opts.p12` (+ `opts.password`) when supplied, else a\n * generated self-signed digital ID from `opts.random` (+ `notBefore`/\n * `notAfter`). `opts.tsaUrl` is the TSA endpoint (e.g. FreeTSA\n * `https://freetsa.org/tsr`); pass `opts.tsaFetch` to customise the request\n * (auth, proxy, SSRF allow-list). Throws a single generic error on any failure\n * (bad identity, TSA HTTP error, malformed response, or signature too large).\n */\n async signTimestamped(opts: SignTsaOptions): Promise<Uint8Array> {\n const usingP12 = opts.p12 != null && opts.p12.length > 0;\n if (!usingP12 && (opts.random == null || opts.random.length < 256)) {\n throw new Error(\n \"signTimestamped: self-signed path needs `random` ≥ 256 bytes (or pass a `p12`)\"\n );\n }\n const fields = [\n opts.name ?? \"\",\n opts.reason ?? \"\",\n opts.date ?? \"\",\n opts.location ?? \"\",\n opts.contactInfo ?? \"\",\n opts.notBefore ?? \"\",\n opts.notAfter ?? \"\",\n ].join(\"\\t\");\n\n const rand = opts.random ?? new Uint8Array(0);\n const p12 = opts.p12 ?? new Uint8Array(0);\n const nonce = opts.nonce ?? new Uint8Array(0);\n const keyBits = opts.keyBits ?? 2048;\n\n // Phase 1: build the signature, get the TimeStampReq to POST.\n const rPtr = this.g._toWasm(rand);\n const p12Ptr = this.g._toWasm(p12);\n const noncePtr = this.g._toWasm(nonce);\n let request: Uint8Array;\n try {\n request = this.g._withStr(opts.password ?? \"\", (pwP, pwL) =>\n this.g._withStr(fields, (fP, fL) =>\n this.g._buffer((o) =>\n this.ex().gp_sign_prepare_tsa(\n this.h,\n fP,\n fL,\n rPtr,\n rand.length,\n keyBits,\n p12Ptr,\n p12.length,\n pwP,\n pwL,\n noncePtr,\n nonce.length,\n o\n )\n )\n )\n );\n } finally {\n this.g._free(rPtr, rand.length);\n this.g._free(p12Ptr, p12.length);\n this.g._free(noncePtr, nonce.length);\n }\n if (request.length === 0) {\n throw new Error(\n \"timestamped signing failed: invalid identity or could not build the timestamp request\"\n );\n }\n\n // Host round trip: POST the request to the TSA, read the response.\n const response = opts.tsaFetch\n ? await opts.tsaFetch(request, opts.tsaUrl)\n : await defaultTsaPost(opts.tsaUrl, request);\n\n // Phase 2: embed the timestamp token, finalize the signed PDF.\n const tokenPtr = this.g._toWasm(response);\n let out: Uint8Array;\n try {\n out = this.g._buffer((o) =>\n this.ex().gp_sign_finish_tsa(this.h, tokenPtr, response.length, o)\n );\n } finally {\n this.g._free(tokenPtr, response.length);\n }\n if (out.length === 0) {\n throw new Error(\n \"timestamped signing failed: TSA response rejected or signature too large for the reserved space\"\n );\n }\n return out;\n }\n\n /**\n * Sign with **long-term validation** material embedded (PAdES-B-LT, or B-LTA\n * with `opts.archiveTimestamp`). Builds a B-T signature ({@link signTimestamped}),\n * then fetches the certificate chain's revocation material (OCSP responses /\n * CRLs, by URL **from the certificates** — the engine computes which URLs, the\n * host fetches) and stores it in a `/DSS`, so the signature validates long after\n * the certificates expire or are revoked. With `archiveTimestamp` a document\n * timestamp over the whole file (DSS included) is added for renewable archival.\n *\n * `async`, multi-round-trip: one TSA POST for the B-T timestamp, one OCSP/CRL\n * fetch per chain certificate, and (if `archiveTimestamp`) a second TSA POST.\n * Unreachable responders are skipped — the DSS is built from whatever resolves;\n * a self-signed identity (no AIA/CRL-DP) simply yields a `/DSS/Certs`-only store.\n * Override `tsaFetch`/`revocationFetch`/`crlFetch` to add auth, proxies, or an\n * SSRF allow-list. Throws on a fatal failure (bad identity, B-T signature, or a\n * malformed PDF the DSS can't chain to).\n */\n async signLtv(opts: SignLtvOptions): Promise<Uint8Array> {\n // 1. The B-T signature is the foundation (its /Contents holds the chain).\n const signed = await this.signTimestamped(opts);\n\n // 2. Ask the engine which validation material to fetch (per certificate).\n const nonce = opts.nonce ?? new Uint8Array(0);\n const targetsJson = this.withSignedPdf(signed, (pdfPtr, pdfLen) => {\n const noncePtr = this.g._toWasm(nonce);\n try {\n return dec.decode(\n this.g._buffer((o) =>\n this.ex().gp_ltv_targets(pdfPtr, pdfLen, noncePtr, nonce.length, o)\n )\n );\n } finally {\n this.g._free(noncePtr, nonce.length);\n }\n });\n const targets: LtvTarget[] = targetsJson ? JSON.parse(targetsJson) : [];\n\n // 3. Host fetches: chain certs, plus OCSP/CRL per source (best-effort).\n const certs: Uint8Array[] = [];\n const ocsps: Uint8Array[] = [];\n const crls: Uint8Array[] = [];\n const ocspPost = opts.revocationFetch ?? defaultOcspPost;\n const crlGet = opts.crlFetch ?? defaultCrlGet;\n for (const target of targets) {\n certs.push(hexToBytes(target.certHex));\n for (const source of target.sources) {\n try {\n if (source.kind === \"ocsp\") {\n ocsps.push(await ocspPost(hexToBytes(source.requestHex), source.url));\n } else {\n crls.push(await crlGet(source.url));\n }\n } catch {\n // An unreachable responder is non-fatal: the DSS embeds what succeeds.\n }\n }\n }\n\n // 4. Embed the material in a /DSS (incremental update → B-LT).\n let lt = this.applyDss(signed, certs, ocsps, crls);\n\n // 5. Optional B-LTA: a document timestamp over the whole file (DSS included).\n if (opts.archiveTimestamp) {\n lt = await this.appendDocumentTimestamp(lt, opts);\n }\n return lt;\n }\n\n /** Run `fn` with `pdf` copied into wasm memory, freeing it afterwards. */\n private withSignedPdf<T>(pdf: Uint8Array, fn: (ptr: number, len: number) => T): T {\n const ptr = this.g._toWasm(pdf);\n try {\n return fn(ptr, pdf.length);\n } finally {\n this.g._free(ptr, pdf.length);\n }\n }\n\n /** Add the `/DSS` to `signed` as an incremental update (B-LT). */\n private applyDss(\n signed: Uint8Array,\n certs: Uint8Array[],\n ocsps: Uint8Array[],\n crls: Uint8Array[]\n ): Uint8Array {\n const certsBuf = frameBlobs(certs);\n const ocspsBuf = frameBlobs(ocsps);\n const crlsBuf = frameBlobs(crls);\n const pdfPtr = this.g._toWasm(signed);\n const cPtr = this.g._toWasm(certsBuf);\n const oPtr = this.g._toWasm(ocspsBuf);\n const rPtr = this.g._toWasm(crlsBuf);\n let out: Uint8Array;\n try {\n out = this.g._buffer((res) =>\n this.ex().gp_apply_dss(\n pdfPtr,\n signed.length,\n cPtr,\n certsBuf.length,\n oPtr,\n ocspsBuf.length,\n rPtr,\n crlsBuf.length,\n res\n )\n );\n } finally {\n this.g._free(pdfPtr, signed.length);\n this.g._free(cPtr, certsBuf.length);\n this.g._free(oPtr, ocspsBuf.length);\n this.g._free(rPtr, crlsBuf.length);\n }\n if (out.length === 0) {\n throw new Error(\"LTV failed: could not add the /DSS to the signed PDF\");\n }\n return out;\n }\n\n /** Append a document timestamp over the whole `pdf` (B-LTA), TSA round trip\n * included. */\n private async appendDocumentTimestamp(\n pdf: Uint8Array,\n opts: SignLtvOptions\n ): Promise<Uint8Array> {\n const nonce = opts.nonce ?? new Uint8Array(0);\n // Phase 1: build the timestamp shell, get the request.\n const pdfPtr = this.g._toWasm(pdf);\n const noncePtr = this.g._toWasm(nonce);\n let request: Uint8Array;\n try {\n request = this.g._buffer((o) =>\n this.ex().gp_doc_timestamp_prepare(this.h, pdfPtr, pdf.length, noncePtr, nonce.length, o)\n );\n } finally {\n this.g._free(pdfPtr, pdf.length);\n this.g._free(noncePtr, nonce.length);\n }\n if (request.length === 0) {\n throw new Error(\"LTV archive timestamp failed: could not build the timestamp request\");\n }\n\n // Host round trip: POST the request to the TSA.\n const response = opts.tsaFetch\n ? await opts.tsaFetch(request, opts.tsaUrl)\n : await defaultTsaPost(opts.tsaUrl, request);\n\n // Phase 2: embed the token, finalize B-LTA.\n const tokenPtr = this.g._toWasm(response);\n let out: Uint8Array;\n try {\n out = this.g._buffer((o) =>\n this.ex().gp_doc_timestamp_finish(this.h, tokenPtr, response.length, o)\n );\n } finally {\n this.g._free(tokenPtr, response.length);\n }\n if (out.length === 0) {\n throw new Error(\n \"LTV archive timestamp failed: TSA response rejected or token too large for the reserved space\"\n );\n }\n return out;\n }\n\n // metadata\n getMetadata(key: string): string {\n return this.g._withStr(key, (p, l) =>\n this.g._str((o) => this.ex().gp_get_metadata(this.h, p, l, o))\n );\n }\n /**\n * Set a **single** Info-dictionary entry (e.g. `\"Title\"`, `\"Author\"`). This\n * touches only `/Info`; use {@link setInfo} to update the typed fields and keep\n * the XMP `/Metadata` packet in sync.\n */\n setMetadata(key: string, value: string): boolean {\n return (\n this.g._withStr(key, (kP, kL) =>\n this.g._withStr(value, (vP, vL) => this.ex().gp_set_metadata(this.h, kP, kL, vP, vL))\n ) === 0\n );\n }\n\n /**\n * The document's XMP metadata packet (catalog `/Metadata`, ISO 32000-1 §14.3.2)\n * as raw bytes, or `null` when the document carries no XMP.\n */\n getXmp(): Uint8Array | null {\n const bytes = this.g._buffer((o) => this.ex().gp_get_xmp(this.h, o));\n return bytes.length === 0 ? null : bytes;\n }\n\n /**\n * Replace (or create) the document's XMP metadata stream (catalog `/Metadata`,\n * stored uncompressed). Accepts a UTF-8 string or raw bytes. Returns `true` on\n * success.\n */\n setXmp(xmp: Uint8Array | string): boolean {\n const bytes = typeof xmp === \"string\" ? new TextEncoder().encode(xmp) : xmp;\n return this.g._withBytes(bytes, (p, l) => this.ex().gp_set_xmp(this.h, p, l)) === 0;\n }\n\n /**\n * Set the standard document-information fields, writing **both** the `/Info`\n * dictionary and a synced XMP `/Metadata` packet so the two never drift. This is\n * a **partial** update — only the fields you provide are changed; omit a field\n * to leave it untouched. Returns `true` on success.\n *\n * @example\n * doc.setInfo({ title: \"Annual Report\", author: \"Ada Lovelace\", keywords: \"finance, 2026\" });\n */\n setInfo(fields: InfoFields): boolean {\n return (\n this.g._withStr(JSON.stringify(fields), (p, l) =>\n this.ex().gp_set_info_json(this.h, p, l)\n ) === 0\n );\n }\n\n // annotations (Acrobat-style markup)\n annotations(page: number): AnnotationInfo[] {\n return this.g._json((o) => this.ex().gp_annotations_json(this.h, page, o));\n }\n removeAnnotation(page: number, index: number): boolean {\n return this.ex().gp_remove_annotation(this.h, page, index) === 0;\n }\n addSquare(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n stroke: number | null = 0,\n fill: number | null = null,\n lineWidth = 1\n ): boolean {\n return (\n this.ex().gp_add_square(\n this.h,\n page,\n x0,\n y0,\n x1,\n y1,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth\n ) === 0\n );\n }\n addHighlight(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0xffff00): boolean {\n return this.ex().gp_add_highlight(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n /**\n * Add a `/Line` annotation from `(x1,y1)` to `(x2,y2)`. When `endArrow` is\n * `true`, an open arrowhead (`/LE [/None /OpenArrow]`) is drawn at the\n * `(x2,y2)` end — a real, editable annotation in conforming readers, ideal\n * for callouts that point at content.\n */\n addLineAnnotation(\n page: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n rgb = 0,\n lineWidth = 1,\n endArrow = false\n ): boolean {\n return (\n this.ex().gp_add_line(this.h, page, x1, y1, x2, y2, RGB(rgb), lineWidth, endArrow ? 1 : 0) === 0\n );\n }\n addFreeText(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n text: string,\n fontSize = 12,\n rgb = 0\n ): boolean {\n return (\n this.g._withStr(text, (p, l) =>\n this.ex().gp_add_free_text(this.h, page, x0, y0, x1, y1, p, l, fontSize, RGB(rgb))\n ) === 0\n );\n }\n addUnderline(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0): boolean {\n return this.ex().gp_add_underline(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n addStrikeOut(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0): boolean {\n return this.ex().gp_add_strike_out(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n /**\n * Add a text-markup annotation (`highlight` | `underline` | `strikeout` |\n * `squiggly`) spanning one or more `quads` (each `[x0, y0, x1, y1]` in PDF\n * user space, bottom-left origin — multi-quad covers wrapped text), with full\n * reviewer metadata. `date` is a PDF date string (e.g. `\"D:20260616T…Z\"`) — the\n * engine has no clock, so the host supplies it.\n */\n addMarkupAnnotation(\n page: number,\n subtype: \"highlight\" | \"underline\" | \"strikeout\" | \"squiggly\",\n quads: Array<[number, number, number, number]>,\n rgb: number,\n opacity: number,\n meta: { contents?: string; author?: string; id?: string; date?: string } = {}\n ): boolean {\n const sub =\n subtype === \"highlight\"\n ? \"Highlight\"\n : subtype === \"underline\"\n ? \"Underline\"\n : subtype === \"strikeout\"\n ? \"StrikeOut\"\n : \"Squiggly\";\n const packed = [\n sub,\n meta.contents ?? \"\",\n meta.author ?? \"\",\n meta.id ?? \"\",\n meta.date ?? \"\",\n ].join(\"\u001f\");\n const flat = quads.flat();\n return (\n this.g._withStr(packed, (mp, ml) =>\n this.g._withF64(flat, (qp, qc) =>\n this.ex().gp_add_markup_annotation(this.h, page, mp, ml, qp, qc, RGB(rgb), opacity)\n )\n ) === 0\n );\n }\n /**\n * Add a sticky-note (`/Text`) annotation: a badge at `rect` (`[x0,y0,x1,y1]`)\n * that opens a popup with `meta.contents`. `icon` is the named icon (`\"Note\"`,\n * `\"Comment\"`, …); `open` sets the initial popup state.\n */\n addTextNote(\n page: number,\n rect: [number, number, number, number],\n rgb: number,\n meta: { contents?: string; author?: string; id?: string; date?: string } = {},\n icon = \"Note\",\n open = false\n ): boolean {\n const packed = [\n meta.contents ?? \"\",\n meta.author ?? \"\",\n meta.id ?? \"\",\n meta.date ?? \"\",\n ].join(\"\u001f\");\n return (\n this.g._withStr(packed, (mp, ml) =>\n this.g._withStr(icon, (ip, il) =>\n this.ex().gp_add_text_note(\n this.h,\n page,\n rect[0],\n rect[1],\n rect[2],\n rect[3],\n mp,\n ml,\n ip,\n il,\n open ? 1 : 0,\n RGB(rgb)\n )\n )\n ) === 0\n );\n }\n /** Freehand ink annotation from one polyline (`points` = flat [x0,y0,x1,y1,…]). */\n addInk(page: number, points: number[], rgb = 0, lineWidth = 1): boolean {\n return (\n this.g._withF64(points, (p, c) => this.ex().gp_add_ink(this.h, page, p, c, RGB(rgb), lineWidth)) ===\n 0\n );\n }\n addStamp(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n label: string,\n rgb = 0xc00000\n ): boolean {\n return (\n this.g._withStr(label, (p, l) =>\n this.ex().gp_add_stamp(this.h, page, x0, y0, x1, y1, p, l, RGB(rgb))\n ) === 0\n );\n }\n\n /**\n * Add a `/Circle` (ellipse) annotation inscribed in `[x0,y0,x1,y1]`. `stroke`\n * (border) and `fill` (interior) are packed `0xRRGGBB` numbers, or `null` to\n * omit. Returns `true` on success.\n */\n addCircleAnnotation(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n stroke: number | null = 0,\n fill: number | null = null,\n lineWidth = 1\n ): boolean {\n return (\n this.ex().gp_add_circle_annot(\n this.h,\n page,\n x0,\n y0,\n x1,\n y1,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth\n ) === 0\n );\n }\n\n /**\n * Add a `/Polygon` annotation — a closed shape through `points` (a flat\n * `[x0, y0, x1, y1, …]` array, PDF user space), with optional `stroke`/`fill`\n * (`0xRRGGBB` or `null`). Returns `true` on success.\n */\n addPolygonAnnotation(\n page: number,\n points: number[],\n stroke: number | null = 0,\n fill: number | null = null,\n lineWidth = 1\n ): boolean {\n return (\n this.g._withF64(points, (p, c) =>\n this.ex().gp_add_polygon_annot(\n this.h,\n page,\n p,\n c,\n RGB(stroke ?? 0),\n stroke === null ? 0 : 1,\n RGB(fill ?? 0),\n fill === null ? 0 : 1,\n lineWidth\n )\n ) === 0\n );\n }\n\n /**\n * Add a `/PolyLine` annotation — an open path through `points` (a flat\n * `[x0, y0, x1, y1, …]` array). `rgb` is packed `0xRRGGBB`.\n */\n addPolylineAnnotation(page: number, points: number[], rgb = 0, lineWidth = 1): boolean {\n return (\n this.g._withF64(points, (p, c) =>\n this.ex().gp_add_polyline_annot(this.h, page, p, c, RGB(rgb), lineWidth)\n ) === 0\n );\n }\n\n /**\n * Add a `/Caret` annotation — a small upward wedge in `[x0,y0,x1,y1]` marking\n * an insertion point. `rgb` is packed `0xRRGGBB`.\n */\n addCaretAnnotation(page: number, x0: number, y0: number, x1: number, y1: number, rgb = 0): boolean {\n return this.ex().gp_add_caret_annot(this.h, page, x0, y0, x1, y1, RGB(rgb)) === 0;\n }\n\n /**\n * Regenerate the appearance stream (`/AP /N`) of the 0-based `index`\n * annotation on `page` from its stored geometry, after editing its colour,\n * border or geometry. Returns `true` on success, `false` for a bad index or a\n * subtype whose appearance can't be reconstructed (FreeText/Stamp/Text/Link).\n */\n regenerateAppearance(page: number, index: number): boolean {\n return this.ex().gp_regenerate_appearance(this.h, page, index) === 0;\n }\n\n flattenAnnotations(page: number): number {\n return this.ex().gp_flatten_annotations(this.h, page);\n }\n /**\n * Flatten the interactive form: bake every field widget across all pages into\n * the page content and drop `/AcroForm`, so the document is no longer\n * fillable and {@link fields} returns empty afterwards. Returns the number of\n * widgets baked (0 when there is no form).\n */\n flattenForm(): number {\n return this.ex().gp_flatten_form(this.h);\n }\n /**\n * Inline a page's form XObjects (`/Subtype /Form` invoked via `Do`) into its\n * content stream, **de-sharing** each placement so the former form text/graphics\n * become ordinary page content with real, editable text-run indices (no form\n * sentinel) — the enabler for editing invoice/template text in place via\n * {@link replaceText} / {@link moveElement} / {@link removeElement} instead of\n * the redact+add overlay. Image XObjects are left untouched. Returns the number\n * of form XObjects inlined (every `Do` invocation, since each is de-shared).\n *\n * Distinct from {@link flattenForm}, which flattens **AcroForm** interactive\n * fields (and drops `/AcroForm`); this flattens reusable Form XObjects.\n */\n flattenFormXObjects(page: number): number {\n return this.ex().gp_flatten_form_xobjects(this.h, page);\n }\n\n // hyperlinks\n links(page: number): LinkInfo[] {\n return this.g._json((o) => this.ex().gp_links_json(this.h, page, o));\n }\n addUriLink(page: number, x0: number, y0: number, x1: number, y1: number, uri: string): boolean {\n return (\n this.g._withStr(uri, (p, l) => this.ex().gp_add_uri_link(this.h, page, x0, y0, x1, y1, p, l)) ===\n 0\n );\n }\n addGotoLink(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n targetPage: number\n ): boolean {\n return this.ex().gp_add_goto_link(this.h, page, x0, y0, x1, y1, targetPage) === 0;\n }\n /**\n * Register a named destination `name` → `targetPage` (a whole-page `/Fit`\n * view) in the catalog. Links and bookmarks can then jump by name via\n * {@link addGotoLinkNamed}; because resolution goes through the catalog (not a\n * frozen page number), the anchor survives page extraction/split as long as\n * its page is kept. Re-using a `name` overwrites its target.\n */\n addNamedDest(name: string, targetPage: number): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_add_named_dest(this.h, p, l, targetPage)) === 0\n );\n }\n /** The catalog's named destinations as `{name, page}` pairs. */\n namedDests(): NamedDest[] {\n return this.g._json((o) => this.ex().gp_named_dests_json(this.h, o));\n }\n /**\n * Every embedded file attachment in the document's `/Names /EmbeddedFiles`\n * name tree, decoded. Each {@link Attachment} carries the name-tree key, the\n * filespec display name (`/UF`/`/F`), the embedded stream's MIME (`/Subtype`)\n * and `/Params` dates, and the decoded bytes. Entries that don't resolve to a\n * readable embedded stream are skipped, so the result is only extractable\n * files (the native replacement for a reader's `getAttachments()`).\n */\n attachments(): Attachment[] {\n const raw = this.g._json<Array<Omit<Attachment, 'data'> & { dataBase64: string }>>((o) =>\n this.ex().gp_attachments_json(this.h, o)\n );\n return raw.map(({ dataBase64, ...rest }) => ({\n ...rest,\n data: this.g._fromBase64(dataBase64),\n }));\n }\n\n /**\n * Embed `bytes` as a document-level file attachment named `name`\n * (`/Names /EmbeddedFiles`, ISO 32000-1 §7.11.4). Re-using a `name` **replaces**\n * that attachment; the bytes are stored FlateDecode-compressed. Returns `true`\n * on success (`false` e.g. for an empty name).\n */\n addAttachment(name: string, bytes: Uint8Array, opts: AttachmentOptions = {}): boolean {\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withBytes(bytes, (bp, bl) =>\n this.g._withOptStr(opts.mime ?? \"\", (mp, ml) =>\n this.g._withOptStr(opts.description ?? \"\", (dp, dl) =>\n this.ex().gp_add_attachment(this.h, np, nl, bp, bl, mp, ml, dp, dl)\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Embed `bytes` as an **associated file** (`/AF`, PDF/A-3) named `name` with the\n * given {@link AfRelationship} — the mechanism Factur-X / ZUGFeRD / Order-X use\n * to carry their invoice XML (`\"alternative\"`). The file is also a normal\n * attachment, is linked from the catalog `/AF` array, and its filespec carries\n * `/AFRelationship`. Returns `true` on success.\n */\n addAssociatedFile(\n name: string,\n bytes: Uint8Array,\n relationship: AfRelationship,\n opts: AttachmentOptions = {}\n ): boolean {\n const rel = AF_RELATIONSHIP_CODE[relationship] ?? AF_RELATIONSHIP_CODE.unspecified;\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withBytes(bytes, (bp, bl) =>\n this.g._withOptStr(opts.mime ?? \"\", (mp, ml) =>\n this.g._withOptStr(opts.description ?? \"\", (dp, dl) =>\n this.ex().gp_add_associated_file(this.h, np, nl, bp, bl, mp, ml, dp, dl, rel)\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Remove the attachment named `name` (from `/Names /EmbeddedFiles` and, if\n * present, the catalog `/AF` array). Returns `true` if one was removed, `false`\n * if no attachment had that name.\n */\n removeAttachment(name: string): boolean {\n return this.g._withStr(name, (p, l) => this.ex().gp_remove_attachment(this.h, p, l)) === 1;\n }\n\n /**\n * Mark this document as an embedded-file **portfolio** and configure how its\n * attachments are presented, by writing the catalog `/Collection`\n * (ISO 32000-1 §7.11.6, §12.3.5). The files must already be embedded (add them\n * first with {@link addAttachment} / {@link addAssociatedFile}); this only adds\n * the presentation layer: the initial {@link CollectionConfig.view view}, the\n * {@link CollectionConfig.schema schema} columns, the\n * {@link CollectionConfig.sort sort} order, the\n * {@link CollectionConfig.defaultFile default file}, and per-file\n * {@link CollectionConfig.items column values} (each written as a `/CI` on the\n * matching file's filespec). An empty/omitted schema still produces a valid\n * `/Collection`. Calling again **replaces** the previous configuration. Returns\n * `true` on success (`false` on a malformed config or write error).\n */\n setCollection(config: CollectionConfig): boolean {\n return (\n this.g._withStr(JSON.stringify(config), (p, l) =>\n this.ex().gp_set_collection_json(this.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Read this document's portfolio configuration back from the catalog\n * `/Collection` — the reader counterpart of {@link setCollection}. Returns\n * `null` when the document is not a portfolio. The recovered\n * {@link CollectionConfig} carries the `view`, the `schema` columns (sorted by\n * order), the `sort`, the `defaultFile`, and each embedded file's `/CI` column\n * `values`.\n */\n collection(): CollectionConfig | null {\n return this.g._json<CollectionConfig | null>((o) => this.ex().gp_collection_json(this.h, o));\n }\n\n /**\n * Install a **document-level JavaScript** under the catalog `/Names /JavaScript`\n * name tree (ISO 32000-1 §7.7.3.4 + §12.6.4.16): a named JavaScript action\n * (`<< /S /JavaScript /JS … >>`) keyed by `name`. On open, a conforming viewer\n * runs every document-level script in **name (lexical) order** — this is where\n * form-calculation / validation helper libraries live (e.g. `AFNumber_Format`).\n * Re-using a `name` **replaces** that script; long sources are stored as a\n * FlateDecode stream, and sibling `/Names` subtrees (`/EmbeddedFiles`,\n * `/Dests`, …) are preserved. Returns `true` on success (`false` e.g. for an\n * empty name).\n */\n addDocumentJavascript(name: string, script: string): boolean {\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withStr(script, (sp, sl) =>\n this.ex().gp_add_document_javascript(this.h, np, nl, sp, sl)\n )\n ) === 0\n );\n }\n\n /**\n * Every document-level JavaScript as `{ name, script }` pairs, in name\n * (lexical) order — the read side of {@link addDocumentJavascript} (decodes\n * both a literal `/JS` string and a `/JS` stream).\n */\n documentJavascripts(): DocumentJavascript[] {\n return this.g._json((o) => this.ex().gp_document_javascripts_json(this.h, o));\n }\n\n /**\n * Remove the document-level JavaScript named `name` from `/Names /JavaScript`.\n * Returns `true` if one was removed, `false` if none had that name.\n */\n removeDocumentJavascript(name: string): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_remove_document_javascript(this.h, p, l)) === 1\n );\n }\n\n /**\n * Add a page-anchored **FileAttachment** annotation over `rect` on the 1-based\n * `page`, pointing at the already-embedded attachment `name` (add it first with\n * {@link addAttachment}). `icon` is the visual marker (default `\"PushPin\"`).\n * Returns `true` on success (`false` if no such attachment exists).\n */\n addFileAttachmentAnnot(\n page: number,\n rect: Box,\n name: string,\n icon: FileAttachmentIcon = \"PushPin\"\n ): boolean {\n return (\n this.g._withStr(name, (np, nl) =>\n this.g._withOptStr(icon, (ip, il) =>\n this.ex().gp_add_file_attachment_annot(\n this.h,\n page,\n rect.x,\n rect.y,\n rect.x + rect.w,\n rect.y + rect.h,\n np,\n nl,\n ip,\n il\n )\n )\n ) === 0\n );\n }\n\n /**\n * Add an internal hyperlink over a rectangle that jumps to the named\n * destination `name` (define it with {@link addNamedDest}). Unlike\n * {@link addGotoLink} (an explicit page), this stores `/Dest /name`, keeping\n * cross-references intact through split/extract.\n */\n addGotoLinkNamed(\n page: number,\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n name: string\n ): boolean {\n return (\n this.g._withStr(name, (p, l) =>\n this.ex().gp_add_goto_link_named(this.h, page, x0, y0, x1, y1, p, l)\n ) === 0\n );\n }\n\n // optional-content layers (calques): list + show/hide + lock/unlock + remove\n layers(): LayerInfo[] {\n return this.g._json((o) => this.ex().gp_layers_json(this.h, o));\n }\n /** Create a new (visible, unlocked) layer; returns its id (0 on error). */\n addLayer(name: string): number {\n return this.g._withStr(name, (p, l) => this.ex().gp_add_layer(this.h, p, l));\n }\n setLayerVisibility(id: number, visible: boolean): boolean {\n return this.ex().gp_set_layer_visibility(this.h, id, visible ? 1 : 0) === 0;\n }\n setLayerLocked(id: number, locked: boolean): boolean {\n return this.ex().gp_set_layer_locked(this.h, id, locked ? 1 : 0) === 0;\n }\n removeLayer(id: number): boolean {\n return this.ex().gp_remove_layer(this.h, id) === 0;\n }\n /**\n * Begin an optional-content marked-content sequence on `page` for the layer\n * `ocg` (its id, from {@link addLayer}). Registers the OCG under the page's\n * `/Resources /Properties` and appends `/OC /OCn BDC` to the content stream;\n * every drawing call after it ({@link addText}, {@link addRectangle},\n * {@link addImage}, …) is gated on that layer's visibility until the matching\n * {@link endOptionalContent} appends `EMC`. Calls nest. Returns the `OCn`\n * property name (empty string on error).\n */\n beginOptionalContent(page: number, ocg: number): string {\n return this.g._str((o) =>\n this.ex().gp_begin_optional_content(this.h, page, ocg, o)\n );\n }\n /** End the innermost optional-content sequence on `page` (`EMC`). */\n endOptionalContent(page: number): boolean {\n return this.ex().gp_end_optional_content(this.h, page) === 0;\n }\n\n // outline (bookmarks)\n outline(): OutlineEntry[] {\n return this.g._json((o) => this.ex().gp_outline_json(this.h, o));\n }\n /** Replace the outline. Each entry: `{level, page?, title}` (page 0/undefined = no dest). */\n setOutline(entries: OutlineEntry[]): boolean {\n const text = entries.map((e) => `${e.level}\\t${e.page ?? 0}\\t${e.title}`).join(\"\\n\");\n return this.g._withStr(text, (p, l) => this.ex().gp_set_outline(this.h, p, l)) === 0;\n }\n\n /**\n * Add a `/Link` annotation over `rect` (`{ x, y, w, h }`) carrying any\n * {@link Action} — the full action & destination model (GoTo with every fit\n * mode, GoToR, URI, Named navigation, Launch, JavaScript, SubmitForm,\n * ResetForm). Returns `true` on success (`false` for a malformed action).\n *\n * @example\n * doc.addLink(1, { x: 72, y: 700, w: 120, h: 16 },\n * { type: \"goto\", dest: { fit: \"xyz\", page: 4, top: 720, zoom: 1.5 } });\n */\n addLink(page: number, rect: Box, action: Action): boolean {\n return (\n this.g._withStr(JSON.stringify(action), (p, l) =>\n this.ex().gp_add_link(this.h, page, rect.x, rect.y, rect.x + rect.w, rect.y + rect.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Set the document `/OpenAction` — the {@link Action} performed when the file\n * is opened. Returns `true` on success.\n */\n setOpenAction(action: Action): boolean {\n return (\n this.g._withStr(JSON.stringify(action), (p, l) =>\n this.ex().gp_set_open_action(this.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Remove the `linkIndex`-th `/Link` annotation on `page` (links counted in\n * order, ignoring non-link annotations). Returns `true` if one was removed.\n */\n removeLink(page: number, linkIndex: number): boolean {\n return this.ex().gp_remove_link(this.h, page, linkIndex) === 1;\n }\n\n /**\n * Replace the outline with {@link Bookmark}s that may carry actions (a `goto`\n * action becomes a `/Dest`, any other action an `/A`). An empty array clears\n * the outline. Returns `true` on success.\n */\n setBookmarks(bookmarks: Bookmark[]): boolean {\n const text = bookmarks\n .map((b) => `${b.level}\\t${b.title}\\t${b.action ? JSON.stringify(b.action) : \"\"}`)\n .join(\"\\n\");\n return this.g._withOptStr(text, (p, l) => this.ex().gp_set_bookmarks(this.h, p, l)) === 0;\n }\n\n // catalog reading / UX hints (ViewerPreferences, PageLayout, PageMode)\n /**\n * Write the catalog `/ViewerPreferences` (ISO 32000-1 §12.2). Each omitted\n * field is left unchanged; a boolean sets the key. After applying, an empty\n * dictionary is removed. Returns `false` on an invalid `direction`.\n */\n setViewerPreferences(prefs: ViewerPreferences): boolean {\n // -1 = leave unchanged, 0 = false, 1 = true.\n const tri = (v: boolean | undefined): number => (v === undefined ? -1 : v ? 1 : 0);\n return (\n this.g._withStr(prefs.direction ?? \"\", (dP, dL) =>\n this.ex().gp_set_viewer_preferences(\n this.h,\n tri(prefs.hideToolbar),\n tri(prefs.hideMenubar),\n tri(prefs.hideWindowUI),\n tri(prefs.fitWindow),\n tri(prefs.centerWindow),\n tri(prefs.displayDocTitle),\n dP,\n dL\n )\n ) === 0\n );\n }\n /** Set the catalog `/PageLayout`. `null` removes the key. Returns `false` on an unknown name. */\n setPageLayout(layout: PageLayout | null): boolean {\n return this.g._withStr(layout ?? \"\", (p, l) => this.ex().gp_set_page_layout(this.h, p, l)) === 0;\n }\n /** Set the catalog `/PageMode`. `null` removes the key. Returns `false` on an unknown name. */\n setPageMode(mode: PageMode | null): boolean {\n return this.g._withStr(mode ?? \"\", (p, l) => this.ex().gp_set_page_mode(this.h, p, l)) === 0;\n }\n\n // interactive forms (AcroForm)\n fields(): FieldInfo[] {\n return this.g._json((o) => this.ex().gp_fields_json(this.h, o));\n }\n setTextField(name: string, value: string): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(value, (vP, vL) => this.ex().gp_set_text_field(this.h, nP, nL, vP, vL))\n ) === 0\n );\n }\n setCheckbox(name: string, checked: boolean): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_set_checkbox(this.h, p, l, checked ? 1 : 0)) === 0\n );\n }\n setRadio(name: string, value: string): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(value, (vP, vL) => this.ex().gp_set_radio(this.h, nP, nL, vP, vL))\n ) === 0\n );\n }\n /** Set a choice field's selection (multi-select list boxes accept several values). */\n setChoice(name: string, values: string[]): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(values.join(\"\\n\"), (vP, vL) => this.ex().gp_set_choice(this.h, nP, nL, vP, vL))\n ) === 0\n );\n }\n\n // ── form field creation ──────────────────────────────────────────────────\n\n /**\n * Create a text field on `page` covering `rect` = `[x0, y0, x1, y1]` (PDF\n * user space). Options: `maxLen` character cap, `multiline`, `password`,\n * and visual `style`.\n */\n addTextField(\n page: number,\n name: string,\n rect: [number, number, number, number],\n value = \"\",\n opts: { maxLen?: number; multiline?: boolean; password?: boolean; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(value, (vP, vL) =>\n this.ex().gp_add_text_field(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], vP, vL,\n opts.maxLen ?? -1, opts.multiline ? 1 : 0, opts.password ? 1 : 0, ...st\n )\n )\n ) === 0\n );\n }\n\n /** Create a checkbox. `export` is the on-state name (default `On`). */\n addCheckbox(\n page: number,\n name: string,\n rect: [number, number, number, number],\n checked = false,\n opts: { export?: string; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(opts.export ?? \"On\", (eP, eL) =>\n this.ex().gp_add_checkbox(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], checked ? 1 : 0, eP, eL, ...st\n )\n )\n ) === 0\n );\n }\n\n /**\n * Create a radio-button group: one logical field whose `options` are the\n * individual buttons. `selected` is the initially-chosen export value.\n */\n addRadioGroup(\n page: number,\n name: string,\n options: RadioOption[],\n opts: { selected?: string; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n const exports = options.map((o) => o.export).join(\"\\n\");\n const rects = options.flatMap((o) => o.rect).join(\",\");\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(exports, (eP, eL) =>\n this.g._withStr(rects, (rP, rL) =>\n this.g._withStr(opts.selected ?? \"\", (sP, sL) =>\n this.ex().gp_add_radio_group(this.h, page, nP, nL, eP, eL, rP, rL, sP, sL, ...st)\n )\n )\n )\n ) === 0\n );\n }\n\n /** Create a drop-down combo box. `editable` permits values outside `options`. */\n addComboBox(\n page: number,\n name: string,\n rect: [number, number, number, number],\n options: string[],\n opts: { selected?: string; editable?: boolean; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(options.join(\"\\n\"), (oP, oL) =>\n this.g._withStr(opts.selected ?? \"\", (sP, sL) =>\n this.ex().gp_add_combo_box(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], oP, oL, sP, sL,\n opts.editable ? 1 : 0, ...st\n )\n )\n )\n ) === 0\n );\n }\n\n /** Create a scrolling list box. `multi` allows selecting several options. */\n addListBox(\n page: number,\n name: string,\n rect: [number, number, number, number],\n options: string[],\n opts: { selected?: string; multi?: boolean; style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(options.join(\"\\n\"), (oP, oL) =>\n this.g._withStr(opts.selected ?? \"\", (sP, sL) =>\n this.ex().gp_add_list_box(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], oP, oL, sP, sL,\n opts.multi ? 1 : 0, ...st\n )\n )\n )\n ) === 0\n );\n }\n\n /**\n * Create a **visible signature field** (`/FT /Sig`) over `rect` — an empty\n * widget the signing pipeline can later target — and flag the AcroForm\n * `/SigFlags`. Returns `true` on success.\n */\n addSignatureField(\n page: number,\n name: string,\n rect: [number, number, number, number],\n opts: { style?: FieldStyle } = {}\n ): boolean {\n const st = styleArgs(opts.style);\n return (\n this.g._withStr(name, (nP, nL) =>\n this.ex().gp_add_signature_field(\n this.h, page, nP, nL, rect[0], rect[1], rect[2], rect[3], ...st\n )\n ) === 0\n );\n }\n\n /**\n * Attach field-level JavaScript to a field's `/AA` for the given `trigger`\n * (`\"keystroke\"` filters input, `\"format\"` formats display, `\"validate\"`\n * checks on change, `\"calculate\"` recomputes — ordered by\n * {@link setCalculationOrder}). Returns `true` if set, `false` if no field has\n * that name.\n */\n setFieldScript(\n name: string,\n trigger: \"keystroke\" | \"format\" | \"validate\" | \"calculate\",\n js: string\n ): boolean {\n return (\n this.g._withStr(name, (nP, nL) =>\n this.g._withStr(trigger, (tP, tL) =>\n this.g._withStr(js, (jP, jL) =>\n this.ex().gp_set_field_script(this.h, nP, nL, tP, tL, jP, jL)\n )\n )\n ) === 1\n );\n }\n\n /**\n * Set the AcroForm calculation order (`/CO`) — the sequence in which fields\n * with a `calculate` script recompute. Unknown names are skipped.\n */\n setCalculationOrder(names: string[]): boolean {\n return (\n this.g._withOptStr(names.join(\"\\n\"), (p, l) =>\n this.ex().gp_set_calculation_order(this.h, p, l)\n ) === 0\n );\n }\n\n /**\n * Delete a form field by name (removed from `/Fields`, `/CO` and every page's\n * annotations). Returns `true` if a field was removed.\n */\n removeField(name: string): boolean {\n return this.g._withStr(name, (p, l) => this.ex().gp_remove_field(this.h, p, l)) === 1;\n }\n\n /**\n * Rebuild a field's appearance from its current value/style — call after\n * changing a field's value programmatically. Returns `true` if regenerated\n * (`false` for an unknown name or a kind that can't be regenerated alone, e.g.\n * a radio parent with kids).\n */\n regenerateFieldAppearance(name: string): boolean {\n return (\n this.g._withStr(name, (p, l) => this.ex().gp_regenerate_field_appearance(this.h, p, l)) === 1\n );\n }\n}\n"],"mappings":";AAmBA,SAAS,4BAA4B;AAsBrC,SAAS,eAAe,GAAmC;AACzD,SAAO,MAAM,QAAQ,IAAI;AAC3B;AAEA,IAAM,MAAM,IAAI,YAAY;AAC5B,IAAM,MAAM,IAAI,YAAY;AA4B5B,IAAM,kBAAkC;AAAA,EACtC,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,eAAe;AAAA,EACf,UAAU;AAAA,EACV,cAAc;AAChB;AAcO,IAAM,gBAAN,MAAM,eAAc;AAAA,EACjB,YAA6B,IAAa;AAAb;AAAA,EAAc;AAAA,EAAd;AAAA;AAAA,EAGrC,OAAe;AAAA;AAAA,EAGf,aAAa,KAAK,QAA8E;AAC9F,QAAI;AACJ,QAAI,OAAO,WAAW,UAAU;AAC9B,YAAM,MAAM,MAAM,MAAM,MAAM;AAC9B,cAAQ,MAAM,IAAI,YAAY;AAAA,IAChC,WAAW,kBAAkB,UAAU;AACrC,cAAQ,MAAM,OAAO,YAAY;AAAA,IACnC,OAAO;AACL,cAAQ;AAAA,IACV;AAIA,QAAI;AACJ,UAAM,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