import type { EngineLoadProgress } from "@auto-hwp/engine"; import type { EngineAdapter } from "./EngineAdapter"; import type { BatchApplyOptions, BatchApplyResult, BlockHit, CaretRect, CellAddr, CellBoxItem, CellFit, HwpxExportOptions, PageUsage, UndoStats, CellCaretRect, CellHit, CellTextHit, DocProfile, FindMatch, FindOptions, FindReplaceOptions, HitResult, ImageBox, Intent, NormalizeReport, OpenResult, Outcome, OutlineItem, PageGeom, ProposalV1, ReplaceResult, RunSpec, TableBox, TableGrid } from "./types"; type WasmInput = string | URL | Request | BufferSource | WebAssembly.Module; /** Any error carrying a machine-readable engine `code` (@auto-hwp/engine EngineError). */ export interface CodedError extends Error { code?: string; } /** issue 052 — a host-supplied autosave snapshot for trap recovery: serialized HWPX bytes of the last * autosaved edit state (NOT the original file). `label` is informational (e.g. "rev 7, 3s ago"). */ export interface RecoverySnapshot { bytes: Uint8Array; label?: string; } /** issue 052 — resolves the LATEST recovery snapshot, or null when none exists. Called on every trap * recovery (never cached) so the adapter always restores the freshest autosaved state. */ export type RecoverySnapshotSource = () => RecoverySnapshot | null | Promise; /** issue 052 — how a trap recovery re-opened the document: from the autosave `snapshot` (edits up to the * last idle save survive) or from the `original` bytes (all edits lost). `reason` is the honest cause * when a snapshot existed but could not be opened (the host toasts it — no false "복구됨"). */ export interface RecoveryInfo { source: "snapshot" | "original"; label?: string; reason?: string; } /** issue 055 (FG-14) — run the engine inside a Web Worker instead of the main thread. `url` is a * self-hosted @auto-hwp/engine/worker.js MODULE-worker script (served as a static asset next to * index.js + pkg/); `factory` overrides worker creation (tests / bundler-specific recipes). W6.1: BOTH * may be omitted — the client then loads this engine version's worker.js from jsDelivr (through a * same-origin blob shim, so a strict CSP needs `worker-src blob:`). When set, open/parse/re-layout/ * export/toHwpx all run off-thread — the Promise surface of this adapter is unchanged, so consumers * need no code change. */ export interface WasmAdapterWorkerOptions { url?: string | URL; factory?: () => Worker; } export interface WasmAdapterOptions { /** Omit for the classic in-thread engine (default; e.g. jsdom tests). `{}` = worker on CDN defaults. */ worker?: WasmAdapterWorkerOptions; /** W6.2 — wasm download progress (bytes + ratio), fired while the engine is being fetched. Works in * both lanes: in-thread it wraps the loader's own fetch, in worker mode the ticks are relayed out of * the worker. Ticks stop at the last byte — wasm COMPILATION afterwards is not measurable. */ onProgress?: (progress: EngineLoadProgress) => void; /** W6.2 — override the progress denominator (uncompressed bytes) when self-hosting a custom build. * Only consulted when the transfer is content-encoded (then Content-Length counts compressed bytes). */ expectedBytes?: number; } export declare class WasmAdapter implements EngineAdapter { private doc; private bytes; private name; private fontRegistered; private wasmInput?; private ready; private recoverySource; /** issue 055 — the worker RPC bridge; null = classic in-thread engine. */ private client; /** issue 055 사후 — the IN-FLIGHT recovery, shared by every concurrent failure (single flight). */ private recovering; /** issue 052 — autosave trigger: called after every successful CONTENT mutation through this adapter * (`applyIntent`, an effective `undo`/`redo`, an effective `replace`). Read-only queries, `open`, and * `registerFont` never fire it, so a freshly-opened/un-edited document is never snapshotted (no * spurious recovery banner). Host-assigned; exceptions in the callback are swallowed (a broken * observer must not fail the edit itself). */ onMutation: (() => void) | null; /** issue 052 — trap-recovery report: which bytes the document was re-opened from (see RecoveryInfo). * Host-assigned; called AFTER the document is live again, right before the trap is rethrown. */ onRecovered: ((info: RecoveryInfo) => void) | null; /** W6.2 — the wasm download-progress observer (constructor option), kept so BOTH lanes can feed it. */ private onProgress?; private expectedBytes?; /** `wasmInput` is forwarded to initEngine/resetEngine (a wasm URL/Response/bytes). W6.1: OMIT it and * the engine loads its OWN version's wasm from jsDelivr — `npm i` is the whole setup. Pass a URL to * self-host (the classic four-file copy). With `options.worker` the input crosses into the worker * (URL objects become href strings; `Request` is unsupported). */ constructor(wasmInput?: WasmInput, options?: WasmAdapterOptions); private ensureInit; /** The loader options both lanes share (progress observer + its denominator override). */ private loadOptions; /** W6.2 — warm the engine WITHOUT a document: fetch + instantiate the wasm (spawning the worker in * worker mode) so the first `open()` is compute-only. Safe to call repeatedly (init is idempotent) * and safe to ignore — a failed prefetch is swallowed here and retried by the next real call. * Typical use: `requestIdleCallback` on a landing page, before the user picks a file. */ prefetch(): Promise; /** Reset the poisoned engine: in-thread → `resetEngine`; worker → in-worker reset or a full respawn * when the worker itself died. Either way every previously-open handle is dead afterwards. */ private resetBackend; /** Open bytes on the live backend and return the document handle (worker → RPC proxy). */ private openDoc; /** The worker-side document as an EngineDoc: every method is one whitelisted RPC (see worker.js). */ private makeWorkerDoc; /** Run an engine call (sync in-thread, or an RPC Promise in worker mode — hence the AWAIT: a sync * `return fn(...)` would let worker rejections escape this try/catch). On a poisoned instance * (wasm trap, or the worker dying), reset + reopen so the adapter survives, then rethrow (state is * lost — the caller re-renders/toasts). Ordinary engine errors pass through untouched. */ private guard; /** issue 052 — wire the autosave snapshot lane into trap recovery. Pass `null` to unwire. The source * is queried on EVERY recovery (latest snapshot wins); it may be sync or async. */ setRecoverySource(source: RecoverySnapshotSource | null): void; private notifyRecovered; private notifyMutation; /** Re-instantiate the engine and re-open the last document (its handles were poisoned). * issue 055 사후 — SINGLE FLIGHT: when the worker dies, EVERY in-flight call rejects at once and each * lands here; letting N recoveries run concurrently interleaves reset/open (the freshly-opened doc is * invalidated by the next reset → permanent dead handles) and fires onRecovered N times. So the first * failure starts ONE recovery and the rest await that same promise. */ private recover; /** issue 052: SNAPSHOT-FIRST — when a RecoverySnapshotSource is wired and yields bytes, re-open those * (the last autosaved edit state) instead of the original file; the snapshot then BECOMES the current * document bytes (a second trap recovers from it too). A failing snapshot open poisons the fresh * instance again, so the engine is reset ONCE MORE before the honest original-bytes fallback. * issue 055: the same lane serves WORKER DEATH — resetBackend respawns a fresh worker first. */ private doRecover; open(bytes: Uint8Array, name?: string): Promise; pageCount(): Promise; /** Raw (engine-sanitized) SVG — HwpPageView sanitizes AGAIN through this package's gate (R7). */ pageSvg(page: number): Promise; /** Whether "레이아웃 정리" is currently ON (the engine auto-enables it at open on a degraded * hwp→hwpx conversion — the workspace syncs its toggle from this). */ normalizeActive(): Promise; /** Toggle "레이아웃 정리" (layout normalization) — see the interface doc. Parses the engine's JSON * report into a typed `NormalizeReport` for the caller. */ setNormalize(on: boolean): Promise; hitTest(page: number, x: number, y: number): Promise; tableAt(page: number, x: number, y: number): Promise; tableCellAt(page: number, x: number, y: number): Promise; /** Every table cell placed on `page` (nested included) with address · text · own-render px box (#511). An * engine build without `cellBoxes` (older wasm) answers `[]` — the "show editable regions" overlay then * simply draws no cell regions. */ cellBoxes(page: number): Promise; /** Cell-addressed caret, hit half (issue 053) — the engine `cellTextHit` binding (the placed-cache * lane with THIS document's injected fonts, so the caret geometry agrees with the visible SVG even * after registerFont; the Intent lane would measure with default fonts). `null` off any cell text * (018 null policy — never a throw). */ hitTestCellText(page: number, x: number, y: number): Promise; /** Cell-addressed caret, geometry half (issue 053) — the engine `cellCaretRect` binding (same * injected-font placement as `hitTestCellText`, so hit → caret → typing stay on one geometry). * `null` when the address doesn't resolve; a PAST-END offset CLAMPS (a rect, never null). */ caretRectCell(section: number, block: number, row: number, col: number, para: number, offset: number, path?: CellAddr[]): Promise; /** Image click-select (issue 049) — the engine `imageAt` binding (delegates to hwp-session's * `image_at_placed`, the SAME geometry the desktop `image_at` command reads). Returns the topmost * image's own box + `(section, block)` anchor, or `null` off any image (018 null policy). */ imageAt(page: number, x: number, y: number): Promise; /** Image box by anchor (issue 049) — the engine `imageBbox` binding (delegates to `image_bbox_placed`). * Re-queried after a move/resize commit to re-place the overlay + apply-verify; `null` when that image * isn't on the queried page. */ imageBbox(page: number, section: number, block: number): Promise; blocksInRect(page: number, x0: number, y0: number, x1: number, y1: number): Promise; tableColBoundaries(page: number, section: number, block: number): Promise; tableRowBoundaries(page: number, section: number, block: number): Promise; pageGeometry(page: number): Promise; blockRuns(section: number, block: number, row?: number, col?: number): Promise; /** Styled runs of a NESTED cell by its descending CellPath (issue 064 Tier-2) — the engine * `blockRunsPath` binding, so the inline editor prefills a nested LEAF cell's runs. */ blockRunsPath(section: number, path: CellAddr[]): Promise; /** Table cell GRID (issue 066) — the engine `tableGrid` binding (a pure MODEL read, so no re-typeset * and it agrees with the edit lane's `(row, col)` on binary .hwp too). Returns the table's grid, or * `null` when the block isn't a table (018 null policy — the chat then attaches no grid). The * vibe-editing doc-context source: the model sees each cell's address + current text so it fills the * table / targets a label's value cell instead of proposing nothing. */ tableGrid(section: number, block: number): Promise; /** Document outline (issue 046) — the engine `outline()` binding (delegates to hwp-session's outline, * the SAME heading source the desktop `doc_outline` command uses). Returns an EMPTY ARRAY when the * document has no detected heading (never null — 018), so the panel's page-list fallback is a UI * decision, not a null check. */ outline(): Promise; /** Document profile (issue 067) — the engine `docProfile` binding (a pure MODEL read: no re-typeset, * ZERO LLM calls). The chat doc-context's "what IS this document" grounding: title candidate + * structure counts + heading list + table inventory (SAME `(section, block)` addresses the * `tableGrid`/`SetTableCell` lane targets) + a structure-preserving body excerpt. Cheap enough to * fetch per AI request, so it is never stale after an edit. */ docProfile(): Promise; /** WYSIWYG GLYPH caret (engine half) — the rhwp glyph-box `HitTest` intent via the applyIntent JSON * seam (issue 041: crates untouched — this is pure JSON wiring). Returns the char-precise `HitResult`, * or `null` off any glyph. `hit.node` is null for cell text / an unanchored binary-.hwp paragraph * (docs/CARET-GAP.md). `caretMiss` normalizes the `needs_rhwp` capability gate (a lean * `--no-default-features` wasm build) to `null` so the caller never sees a throw for "no caret path". */ hitTestText(page: number, x: number, y: number): Promise; /** WYSIWYG GLYPH caret (geometry half) — the `CaretRect` intent via applyIntent JSON. Returns the caret * rect (own-render PAGE px), or `null` when the paragraph isn't on `page`. A past-end `offset` is * CLAMPED by the engine (returns a rect, never null). `needs_rhwp` → null (capability gate). */ caretRect(page: number, node: number, offset: number): Promise; /** Normalize the `needs_rhwp` capability-gate error to `null` (018: no caret path ⇒ null, not a throw). * Only that ONE coded error is swallowed; traps and every other engine error propagate unchanged. */ private caretMiss; /** Find (issue 045) — the read-only `Find` Intent via applyIntent JSON. The engine's `{kind:"found"}` * outcome carries `matches` in the SAME shape as editor-core's `FindMatch` (node/start/len/section/ * block are all single-word keys — no remap). The Intent fields are snake_case (`case_sensitive`/ * `whole_word`) because the op-bus Intent enum uses `deny_unknown_fields` with no rename. */ find(query: string, opts: FindOptions): Promise; /** Replace (issue 045) — the `Replace` Intent via applyIntent JSON, ONE undo unit. The `{kind:"replaced"}` * outcome gives the count + live page count. Run formatting is preserved by the op-bus (it rebuilds runs * across the replaced range — never a plain-text collapse). */ replace(query: string, replacement: string, opts: FindReplaceOptions): Promise; applyIntent(intent: Intent): Promise; /** #371 — ATOMIC batch: one engine call, one reflow, ONE engine undo unit; on failure the engine * leaves the document and its undo/redo stacks untouched and this rejects (`batch_failed`). * `opts.coalesceKey` (#369) lets consecutive typing batches share one undo unit. */ applyIntents(intents: Intent[], opts?: BatchApplyOptions): Promise; /** #347 parity (#371) — per-cell fit / overflow of the placed table, or null. Read-only. */ tableCellFits(section: number, block: number): Promise; /** #347 parity (#371) — per-page body usage. Read-only. */ pageUsage(): Promise; /** #372 — engine undo depth + byte budget (`0` = unbounded). */ setUndoLimits(depth: number, budgetBytes?: number): Promise; /** #372 — what the engine undo stack holds now. */ undoStats(): Promise; proposeIntents(intents: Intent[]): Promise; commitProposal(proposalId: string, expectedRevision: number): Promise; undo(): Promise; redo(): Promise; registerFont(family: string, bytes: Uint8Array): Promise; hasFont(): boolean; exportPdf(): Promise; exportHtml(): Promise; /** `options` (#371 parity): `hwpRowHeights` for tables that came from a binary `.hwp`. */ toHwpx(options?: HwpxExportOptions): Promise; dispose(): void; } export {}; //# sourceMappingURL=WasmAdapter.d.ts.map