@3sln/emon 0.3.0-preview.1 → 0.3.0-preview.3

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/emon.wasm CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@3sln/emon",
3
- "version": "0.3.0-preview.1",
3
+ "version": "0.3.0-preview.3",
4
4
  "license": "MIT",
5
5
  "description": "emon's JavaScript SDK: PDFs and images to semantic HTML in the browser, over the WASM binding (DEVLOG P9.3). The library has no dependencies; the devDependencies are the browser test harness and the tesseract.js engine the OCR adapter drives.",
6
6
  "keywords": ["pdf", "html", "semantic-html", "ocr", "document-conversion", "scraping", "wasm", "webassembly", "tables"],
@@ -15,15 +15,17 @@
15
15
  ".": "./src/index.js",
16
16
  "./tesseract": "./src/tesseract.js",
17
17
  "./pdfium": "./src/pdfium.js",
18
+ "./node-pack-cache": { "types": "./node/pack-cache.d.ts", "browser": "./node/unavailable.js", "default": "./node/pack-cache.js" },
19
+ "./deno-pack-cache": { "types": "./node/pack-cache-deno.d.ts", "browser": "./node/unavailable.js", "default": "./node/pack-cache-deno.js" },
18
20
  "./emon.wasm": "./emon.wasm",
19
21
  "./package.json": "./package.json"
20
22
  },
21
- "files": ["src", "emon.wasm", "LICENSE", "THIRD_PARTY_NOTICES.md", "README.md"],
23
+ "files": ["src", "node", "emon.wasm", "LICENSE", "THIRD_PARTY_NOTICES.md", "README.md"],
22
24
  "sideEffects": false,
23
25
  "publishConfig": { "access": "public" },
24
26
  "engines": { "node": ">=22" },
25
27
  "peerDependencies": {
26
- "@3sln/pdfium-wasm": "^0.3.0-preview.1"
28
+ "@3sln/pdfium-wasm": "^0.3.0-preview.3"
27
29
  },
28
30
  "peerDependenciesMeta": {
29
31
  "@3sln/pdfium-wasm": { "optional": true }
package/src/engines.js ADDED
@@ -0,0 +1,216 @@
1
+ // THE ENGINE REGISTRY, JavaScript host (DEVLOG D925, K3; the twin of `host/go/engines.go` and `host/rust/src/adapter.rs`: read those for the reasoning).
2
+ //
3
+ // An OCR engine is an ADAPTER that is registered, never wired. `emon.engines()` is an empty registry bound to the loaded module; `engines.add(adapter)` registers one
4
+ // (`tesseractAdapter` of `@3sln/emon/tesseract`, `ppocrEngine` of `@3sln/emon/ppocr`, or the embedder's own), and `engines.port()` is the `ports.ocr` of a conversion: the registry
5
+ // routes each request to the adapter registered for the engine it names. Kin decides every rule and this file asks the module for them: what an adapter may declare
6
+ // (`ad-register-check`, against the engine table) and which adapter a request goes to (`ad-route`: the first registered for the OIL engine the request names). An engine nobody
7
+ // registered answers `unsupported`; a rejection from an adapter answers `failed`, and either way the page is unread, never blank.
8
+ //
9
+ // An adapter is an object:
10
+ //
11
+ // { name: 'tesseract', // the engine's name in kin's table, or the embedder's own
12
+ // engine: 1, // the OIL engine it answers as: 1 tesseract, 2 ppocr, 3 apple-vision, 4 mlkit-text, 5 windows-media-ocr
13
+ // caps, measured, needs, flags, // optional (0): what it declares, what it measures, the pack kinds it reads with (1 recognizer, 2 osd, 4 detector, 8 classifier), its flags
14
+ // producer: { engine: '...' }, // optional: what the transcript says produced it
15
+ // read(request, { signal, packs }) { ... }, // `ocr.js`'s port form: a result, `null` (unsupported) or a rejection (failed)
16
+ // close() { ... } } // optional
17
+ //
18
+ // A result here is `ocr.js`'s form, which the module's own builders turn into the OIL record (so its layout is held by kin, not by this file); the canonical answers of the
19
+ // Rust-built PP-OCR module come back through `canonicalOcr` and are checked by the module. Every adapter here answers with a Promise, so `read` is async by nature; the flag `1`
20
+ // (async) says that it may take a while, and `2` (remote: the pixels leave the device; app code, usually a `fetch`, this library does none) is refused unless `allowRemote(true)` came
21
+ // first (D935). An adapter that says `1` or `2` is held to `setTimeout(ms)` (kin's `ocr.timeout-ms`, default 60 s) and `cancel()`: its second argument holds `signal`, an `AbortSignal`
22
+ // that aborts at the timeout or the cancel (pass it to `fetch`), the request is left unread (`failed timeout`, `failed cancelled` noted) and the adapter's late answer is dropped. Adapters in this host are in-process values: there are no adapter libraries to load, so there is no `defaults()`; a page that registers
23
+ // no Tesseract adapter has none (D920).
24
+
25
+ import { EmonError } from './sources.js';
26
+ import { Packs } from './packs.js';
27
+ import { httpPackFetcher } from './packfetch.js';
28
+
29
+ const ASYNC = 1;
30
+ const REMOTE = 2;
31
+ const DEFAULT_TIMEOUT_MS = 60000;
32
+
33
+ export class Engines {
34
+ #w;
35
+ #entries = [];
36
+ #allowRemote = false;
37
+ #notes = [];
38
+ #timeoutMs = DEFAULT_TIMEOUT_MS;
39
+ #flights = new Set();
40
+ #optionLines;
41
+ /** The packs (D896, P13.16): the mode, the app's hook, download and events, `ensure`. See `packs.js`. */
42
+ packs;
43
+
44
+ /** @param w the loaded module (`emon.w`): use `emon.engines()`. */
45
+ constructor(w, optionLines = () => '') {
46
+ this.#w = w;
47
+ this.#optionLines = optionLines;
48
+ this.packs = new Packs(w, (line) => this.#notes.push(line));
49
+ // D933: the turnkey downloads with the platform's `fetch` unless the app sets a fetcher of its own (`packs.setFetcher(fn)`; `null` for none). The mode is still `never` until the app says otherwise.
50
+ this.packs.setFetcher(httpPackFetcher(this.packs, { note: (l) => this.#notes.push(l) }));
51
+ }
52
+
53
+ /** D933: whether the engine (kin's name: `tesseract`, `ppocr`) can read now: registered, and its packs here (its state is `built-in` or `installed`). The signal behind an "OCR ready" indicator. */
54
+ engineReady(name, { renderer = false } = {}) {
55
+ const e = this.state({ renderer }).engines.find((x) => x.name === name);
56
+ return !!e && (e.state === 'built-in' || e.state === 'installed');
57
+ }
58
+
59
+ /** D896's `engines()`: every engine of kin's table that runs here, with its state (`built-in`, `installed`, `downloadable` or `unavailable`) and why, as the C ABI's `emon_engines_describe` JSON
60
+ * (`{ platform, mode, offline, store, engines: [{ name, kind, impl, state, registered, calibrated, caps, oen, role, needs, download_bytes, reason }] }`). `renderer`: say a renderer port is in use. */
61
+ state({ renderer = false } = {}) {
62
+ const p = this.packs;
63
+ const cat = p.catalogue.pfetch;
64
+ return this.#w.packDescribe(this.#entries.map((e) => e.engine | 0), renderer, p.installed(), cat[p.mode], p.offline, 'memory');
65
+ }
66
+
67
+ /** D896's `prepare(options)`: the packs a conversion with these options (`ocr`, `ocrEngine`, `locale`) needs and which are missing, as the C ABI's `emon_prepare` JSON
68
+ * (`{ verdict, mode, offline, engines, languages, osd, packs, unsupported, missing, missing_bytes, conditional, conditional_bytes }`). */
69
+ prepare(options = {}) {
70
+ const p = this.packs;
71
+ return this.#w.packPrepare(this.#optionLines(options), p.installed(), p.catalogue.pfetch[p.mode], p.offline);
72
+ }
73
+
74
+ // The packs a request needs, made present or refused (D896), for an adapter that reads its models from them (`adapter.packs: true`): `{ ok: adapter }`, `{ ok: other }` (the app's substitute)
75
+ // or `{ unread: reason }`. An adapter without `packs: true` brings its own models (tesseract.js's `langPath`, PP-OCR's URLs) and no pack is asked for.
76
+ async #ensure(adapter, req) {
77
+ if (!adapter.packs || !(adapter.needs | 0)) return { ok: adapter };
78
+ const w = this.#w;
79
+ const eng = w.packOenEng(adapter.engine | 0);
80
+ if (eng < 0) return { ok: adapter };
81
+ const packs = this.packs;
82
+ const langs = adapter.engine === 1 ? (req.langs ?? []).filter((l) => /^[a-z]{3}$/.test(l)).map((l) => ((l.charCodeAt(0) << 24) | (l.charCodeAt(1) << 16) | (l.charCodeAt(2) << 8)) | 0) : [];
83
+ const osd = !!req.osd && ((adapter.needs | 0) & 2) !== 0;
84
+ let rows;
85
+ try {
86
+ rows = w.packResolve(osd, langs, [eng], packs.installed());
87
+ } catch (e) {
88
+ return { unread: `engine-unavailable: ${e.message}` };
89
+ }
90
+ const c = packs.catalogue;
91
+ const unreadable = rows.filter((r) => r[0] === c.pstate.unsupported);
92
+ if (langs.length && unreadable.length >= langs.length) return { unread: `lang-unavailable:${req.langs[0]}` };
93
+ const engineName = adapter.name ?? 'adapter';
94
+ const kindOf = (code) => packs.catalogue.packs.find((x) => x.code === code)?.kind;
95
+ for (const r of rows.filter((x) => x[0] === c.pstate.missing)) {
96
+ const got = await packs.need(r[2], 'conversion', engineName);
97
+ if (got.ready) continue;
98
+ // orientation detection degrades to kin's own policy without its model; it never leaves the page unread
99
+ if (got.unread !== undefined && kindOf(r[2]) === 'osd') continue;
100
+ if (got.unread !== undefined) return { unread: got.unread };
101
+ // another engine would answer under its own name: kin's plan chose this engine, so the request stays unread
102
+ const named = this.#entries.find((e) => (e.name ?? 'adapter') === got.substitute);
103
+ if (named && named.engine !== adapter.engine) return { unread: `pack-substitute-differs:${got.substitute}` };
104
+ const other = this.#entries.find((e) => e !== adapter && e.packs && e.engine === adapter.engine && (!named || e === named));
105
+ return other ? { ok: other } : { unread: `pack-substitute-unavailable:${got.substitute}` };
106
+ }
107
+ return { ok: adapter };
108
+ }
109
+
110
+ /** How long a request waits for an async or remote adapter (kin's `ocr.timeout-ms`; default 60 s; `0` restores it). A request that ran out of time is unread, never blank. */
111
+ setTimeout(ms) {
112
+ this.#timeoutMs = ms > 0 ? ms : DEFAULT_TIMEOUT_MS;
113
+ }
114
+
115
+ /** Ends every request now waiting for an async or remote adapter: each is unread (`failed cancelled`) and its `signal` aborts. Later requests are not affected. */
116
+ cancel() {
117
+ for (const abort of [...this.#flights]) abort('cancelled');
118
+ }
119
+
120
+ // One read of an adapter that may take a while: its `signal` aborts at the timeout or a cancel, and the request stops waiting then.
121
+ async #guarded(adapter, req, context) {
122
+ const ac = new AbortController();
123
+ let abort;
124
+ const gone = new Promise((_, reject) => {
125
+ abort = (why) => {
126
+ ac.abort(new Error(why));
127
+ reject(new Error(why));
128
+ };
129
+ });
130
+ gone.catch(() => {});
131
+ this.#flights.add(abort);
132
+ const timer = setTimeout(() => abort('timeout'), this.#timeoutMs);
133
+ try {
134
+ const reading = Promise.resolve(adapter.read(req, { ...context, signal: ac.signal }));
135
+ reading.catch(() => {}); // a late rejection, after the request gave up, is nobody's
136
+ return await Promise.race([reading, gone]);
137
+ } finally {
138
+ clearTimeout(timer);
139
+ this.#flights.delete(abort);
140
+ }
141
+ }
142
+
143
+ /** Lets adapters that send the pixels off the device register (default no: documents may hold personal data). Call it before registering them. */
144
+ allowRemote(allow) {
145
+ this.#allowRemote = !!allow;
146
+ }
147
+
148
+ /** Registers an adapter, held to kin's engine table; it is closed when refused, and the error's message is the refusal's name and sentence. */
149
+ async add(adapter) {
150
+ const { name = 'adapter', engine, caps = 0, measured = 0, needs = 0, flags = 0 } = adapter;
151
+ const code = this.#w.adapterCheck(1, engine | 0, caps | 0, measured | 0, needs | 0, flags | 0);
152
+ const refuse = async (reason, sentence) => {
153
+ try { await adapter.close?.(); } catch { /* the adapter is refused whatever it says */ }
154
+ throw new EmonError('usage', `${reason}: ${name}${sentence ? ` ${sentence}` : ''} (engine ${engine}, caps ${caps}, needs ${needs}, flags ${flags})`);
155
+ };
156
+ if (typeof adapter.read !== 'function') await refuse('adapter-abi-unsupported', 'has no `read`');
157
+ if (code !== 0) await refuse(this.#w.adapterReason(code));
158
+ if (flags & REMOTE && !this.#allowRemote) await refuse('adapter-remote-refused', 'sends the pixels off the device; call allowRemote(true) first');
159
+ this.#entries.push(adapter);
160
+ }
161
+
162
+ /** The registered adapters, in registration order. */
163
+ describe() {
164
+ return this.#entries.map(({ name = 'adapter', engine, caps = 0, measured = 0, needs = 0, flags = 0, producer = {} }) => ({ name, engine, caps, measured, needs, flags, producer: { ...producer } }));
165
+ }
166
+
167
+ /** Why requests were left unread since the last call, one line each. */
168
+ notes() {
169
+ return this.#notes.splice(0);
170
+ }
171
+
172
+ /** The first adapter's pairs, the combined engine name when there are several (`tesseract+ppocr`), then the other adapters' further keys. */
173
+ producer() {
174
+ const out = {};
175
+ const combined = this.#entries.length > 1 ? this.#entries.map((e) => e.name ?? 'adapter').join('+') : null;
176
+ this.#entries.forEach((e, i) => {
177
+ for (const [k, v] of Object.entries(e.producer ?? {})) if (!(combined && k === 'ocr-engine') && !(k in out)) out[k] = v;
178
+ if (i === 0 && combined) out['ocr-engine'] = combined;
179
+ });
180
+ return out;
181
+ }
182
+
183
+ /** The `ports.ocr` of a conversion: routes each request by the engine it names. */
184
+ port() {
185
+ const port = async (req) => {
186
+ const at = this.#w.adapterRoute(req.engine ?? 0, this.#entries.map((e) => e.engine | 0));
187
+ if (at < 0) return null;
188
+ let adapter = this.#entries[at];
189
+ try {
190
+ const got = await this.#ensure(adapter, req);
191
+ if (got.unread !== undefined) {
192
+ this.#notes.push(`${adapter.name ?? 'adapter'}: unsupported ${got.unread}`);
193
+ return null;
194
+ }
195
+ adapter = got.ok;
196
+ const context = adapter.packs ? { packs: this.packs.view(adapter.name ?? 'adapter') } : undefined;
197
+ const r = (adapter.flags | 0) & (ASYNC | REMOTE) ? await this.#guarded(adapter, req, context) : await adapter.read(req, context);
198
+ if (r === null || r === undefined) this.#notes.push(`${adapter.name ?? 'adapter'}: unsupported`);
199
+ return r;
200
+ } catch (e) {
201
+ this.#notes.push(`${adapter.name ?? 'adapter'}: failed ${(e && e.message) || e}`);
202
+ throw e;
203
+ }
204
+ };
205
+ Object.defineProperty(port, 'producer', { get: () => this.producer(), enumerable: true });
206
+ port.terminate = () => this.close();
207
+ return port;
208
+ }
209
+
210
+ /** Closes every adapter; the registry is empty after it. */
211
+ async close() {
212
+ this.cancel();
213
+ const es = this.#entries.splice(0);
214
+ for (const e of es) await e.close?.();
215
+ }
216
+ }
package/src/index.d.ts CHANGED
@@ -36,7 +36,7 @@ export function urlSource(
36
36
  url: string | URL,
37
37
  options?: { fetch?: typeof fetch; headers?: Record<string, string>; signal?: AbortSignal; fetchOptions?: RequestInit },
38
38
  ): Promise<ByteSource>;
39
- export function toSource(input: Input, options?: { lazy?: boolean; max?: number }): Promise<ByteSource>;
39
+ export function toSource(input: Input | readonly Input[], options?: { lazy?: boolean; max?: number }): Promise<ByteSource>;
40
40
 
41
41
  /** A request for the OCR port (`ports.ocr`): see `@3sln/emon/tesseract`. */
42
42
  export interface OcrRequest {
@@ -58,6 +58,102 @@ export interface OcrRequest {
58
58
  /** An OCR port: `null` or `undefined` answers `unsupported`; a rejection answers `failed`. */
59
59
  export type OcrPort = (request: OcrRequest) => Promise<object | null | undefined>;
60
60
 
61
+ /**
62
+ * An OCR engine, registered with `emon.engines().add(...)` (D925): the OIL engine it answers as (1 tesseract, 2 ppocr, 3 apple-vision, 4 mlkit-text, 5 windows-media-ocr), what it
63
+ * declares, and `read`, in the OCR port's form. `@3sln/emon/tesseract` and `@3sln/emon/ppocr` make them.
64
+ */
65
+ export interface OcrAdapter {
66
+ name?: string;
67
+ engine: number;
68
+ caps?: number;
69
+ measured?: number;
70
+ /** the pack kinds it reads with: 1 recognizer, 2 osd, 4 detector, 8 classifier */
71
+ needs?: number;
72
+ /** 1: may take a while; 2: sends the pixels off the device (refused unless `allowRemote(true)`). An adapter that sets either is held to `setTimeout` and `cancel` and gets `signal` in `read`'s second argument. */
73
+ flags?: number;
74
+ /** true: the adapter reads its models from packs (`engines.packs`): a request that needs one the app has not provided or fetched is left unread (`pack-missing:<id>`), and `read`'s second argument holds the verified files. Default false: the adapter brings its own models. */
75
+ packs?: boolean;
76
+ producer?: Record<string, string>;
77
+ read(request: OcrRequest, context?: { packs?: Map<string, Uint8Array>; signal?: AbortSignal }): Promise<object | null | undefined>;
78
+ close?(): void | Promise<void>;
79
+ }
80
+
81
+ /** What the library tells the app's hook about a pack a conversion needs. */
82
+ export interface PackNeed { pack: string; rev: number; engine: string; kind: string; licence: string; bytes: number; reason: string; requestEngine: string; files: PackFileNeed[] }
83
+ /** One file of a requested pack (D933): its plain name, SHA-256 (lower-case hex), size and the known URLs in priority order (the default mirror, the GitHub `packs` release asset, then the app's mirrors). */
84
+ export interface PackFileNeed { name: string; sha256: string; bytes: number; urls: string[] }
85
+ export type PackState = 'missing' | 'queued' | 'downloading' | 'verifying' | 'ready' | 'failed';
86
+ /** The state of one pack. `done`/`total` are bytes of the whole pack; `mirror` the URL being downloaded from; `reason` why, when failed; `willRetry`: failed, and the next request that needs the pack tries again. */
87
+ export interface PackStatus { id: string; rev: number; engine: string; state: PackState; done: number; total: number; mirror: string; reason: string; willRetry: boolean; byApp: boolean }
88
+ export interface PackSummary { busy: boolean; activeDownloads: number; queued: number; done: number; total: number; progress: number }
89
+ /** What the hook decides: fetch (the app's `fetcher`), provide bytes (a one-file pack) or `{ [fileName]: bytes }`, decline (unread, `pack-missing:<id>`), or substitute another adapter of the same engine. */
90
+ export type PackDecision = { action: 'fetch' } | { action: 'provide'; data: Uint8Array | Record<string, Uint8Array> } | { action: 'decline' } | { action: 'substitute'; engine: string };
91
+ export interface PackFile { name: string; bytes: number; sha: string }
92
+ export interface PackEvent { kind: 'start' | 'progress' | 'done' | 'failed' | 'cancelled'; pack: string; engine: string; done: number; total: number; initiator: 'library' | 'app'; message: string }
93
+ /** Packs (D896, P13.16): verified model bytes, the app's hook, download and progress events. The library ships no HTTP client: `setFetcher` is the app's download. */
94
+ export interface Packs {
95
+ readonly catalogue: { class: string; packs: Array<{ code: number; id: string; rev: number; engine: string; kind: string; licence: string; bytes: number; files: PackFile[] }> };
96
+ setMode(mode: 'never' | 'cache' | 'auto'): void;
97
+ readonly mode: 'never' | 'cache' | 'auto';
98
+ /** `EMON_OFFLINE=1` in Node. */
99
+ readonly offline: boolean;
100
+ onPackNeeded(hook: ((need: PackNeed) => PackDecision | Promise<PackDecision>) | null): void;
101
+ /** The app's download. The turnkey installs `httpPackFetcher` (the platform's `fetch`, the file's URLs in order, Cache Storage where the page has it); `null` removes it. */
102
+ setFetcher(fetcher: ((pack: { id: string; rev: number; files: PackFile[] }, file: PackFile, progress: (done: number) => boolean) => Promise<Uint8Array>) | null): void;
103
+ /** The app's own mirrors, each a base URL (`<base>/sha256/<hex>`) or a template with `{sha}` `{id}` `{rev}` `{file}`: after the default ones, or instead of them with `replace`. */
104
+ setMirrors(list: string[], options?: { replace?: boolean }): void;
105
+ /** The known URLs of one file of a pack, best first. */
106
+ urls(pack: string, file: string | { name: string }): string[];
107
+ /** Records the URL a pack is being downloaded from (for a downloader of your own). */
108
+ noteMirror(pack: string, url: string): void;
109
+ /** The state of every pack, or of one by id. */
110
+ status(): PackStatus[];
111
+ status(id: string): PackStatus;
112
+ /** The aggregate over the packs in flight. */
113
+ summary(): PackSummary;
114
+ /** Listens to every state change of any pack; answers the function that removes the listener. */
115
+ onPackStatus(listener: (status: PackStatus) => void): () => void;
116
+ statusEvents(signal?: AbortSignal): AsyncIterable<PackStatus>;
117
+ /** Gets a `status` event (`event.detail`: the `PackStatus`) for every change. */
118
+ readonly statusTarget: EventTarget;
119
+ onPackEvent(listener: (event: PackEvent) => boolean | void): () => void;
120
+ events(signal?: AbortSignal): AsyncIterable<PackEvent>;
121
+ cancel(): void;
122
+ /** Verifies and keeps the app's bytes for a pack; rejects `pack-hash-mismatch:<id>` / `pack-provide-failed:<id>`. */
123
+ install(id: string, data: Uint8Array | Record<string, Uint8Array>): Promise<void>;
124
+ /** Fetches packs ahead of time (mode `auto`, not offline, a fetcher set). */
125
+ ensure(ids: string[]): Promise<void>;
126
+ installed(): number[];
127
+ files(id: string): Map<string, Uint8Array> | null;
128
+ }
129
+
130
+ /** The engine registry: kin's rules (`ad-register-check`, `ad-route`) over the adapters you register. */
131
+ export class Engines {
132
+ /** Lets adapters that send the pixels off the device register (default no). Call it before registering them. */
133
+ allowRemote(allow: boolean): void;
134
+ /** How long a request waits for an async or remote adapter (kin's `ocr.timeout-ms`; default 60 s; `0` restores it). */
135
+ setTimeout(ms: number): void;
136
+ /** Ends every request now waiting for an async or remote adapter: each is unread and its `signal` aborts. */
137
+ cancel(): void;
138
+ /** The pack mode, hook, download and events. */
139
+ readonly packs: Packs;
140
+ /** Whether the engine can read now: registered, and its packs here. */
141
+ engineReady(name: string, options?: { renderer?: boolean }): boolean;
142
+ /** D896's `engines()`: every engine of kin's table with its state and why (the C ABI's JSON shape). */
143
+ state(options?: { renderer?: boolean }): { platform: string; mode: string; offline: boolean; store: string; engines: Array<{ name: string; kind: string; impl: string; state: string; registered: boolean; calibrated: boolean; caps: number; oen: number; role: string; needs: Array<{ id: string; kind: string; bytes: number; licence: string; installed: boolean }>; download_bytes: number; reason: string }> };
144
+ /** D896's `prepare(options)`: the packs a conversion needs and which are missing (the C ABI's JSON shape). */
145
+ prepare(options?: { ocr?: string; ocrEngine?: string; locale?: string }): { verdict: string; mode: string; offline: boolean; engines: string[]; languages: string[]; osd: boolean; packs: object[]; unsupported: object[]; missing: number; missing_bytes: number; conditional: number; conditional_bytes: number };
146
+ /** Registers an adapter, held to kin's engine table; rejects with `usage` and the refusal's name (`adapter-engine-unknown`, `adapter-caps-beyond-engine`, ...). */
147
+ add(adapter: OcrAdapter): Promise<void>;
148
+ describe(): Array<{ name: string; engine: number; caps: number; measured: number; needs: number; flags: number; producer: Record<string, string> }>;
149
+ /** Why requests were left unread since the last call. */
150
+ notes(): string[];
151
+ producer(): Record<string, string>;
152
+ /** The `ports.ocr` of a conversion: routes each request by the engine it names. */
153
+ port(): OcrPort & { terminate(): Promise<void>; readonly producer: Record<string, string> };
154
+ close(): Promise<void>;
155
+ }
156
+
61
157
  /** One page of a renderer's document. */
62
158
  export interface Rendered {
63
159
  width: number;
@@ -100,6 +196,11 @@ export interface ConvertOptions {
100
196
  assetsBytes?: number;
101
197
  assetSignatures?: boolean | 'on' | 'off';
102
198
  ocrScope?: 'full' | 'witness' | string;
199
+ capture?: 'auto' | 'scan' | 'photos';
200
+ /** Where engines that read a page disagree, whether the Model says so (P13.9): `disagree` (the default), `off`, or `all` (adds segmentation-only differences). */
201
+ ocrReadings?: 'disagree' | 'off' | 'all';
202
+ /** Whether the composition of the engines' readings changes the page (P13.9): `keep` (the default) or `vote`. */
203
+ ocrCompose?: 'keep' | 'vote';
103
204
  keepEvidence?: boolean;
104
205
  maxRounds?: number;
105
206
  fetchRounds?: number;
@@ -128,6 +229,8 @@ export interface HtmlOptions {
128
229
  milestones?: boolean;
129
230
  initialsPlain?: boolean;
130
231
  alignStyle?: boolean;
232
+ /** Writes the readings that disagree as inert `<template>`s inside a `variant` span (P13.9). */
233
+ readings?: boolean;
131
234
  assets?: 'inline' | 'external' | 'omit';
132
235
  assetPrefix?: string;
133
236
  }
@@ -192,7 +295,29 @@ export class Emon {
192
295
  defaults?: { chunk?: number },
193
296
  ): Promise<Emon>;
194
297
  readonly defaults: { chunk?: number };
195
- convert(input: Input | InputWithPassword, options?: ConvertOptions): Promise<Model>;
298
+ convert(input: Input | InputWithPassword | readonly Input[], options?: ConvertOptions): Promise<Model>;
299
+ /** An empty engine registry bound to this module; register each OCR engine with `add`, then pass `engines.port()` as `ports.ocr`. */
300
+ engines(): Engines;
196
301
  /** Stage 0 of each input, cheap. */
197
302
  intake(inputs: Input | InputWithPassword | Array<Input | InputWithPassword>, options?: ConvertOptions): Promise<IntakeResult[]>;
198
303
  }
304
+
305
+ /** An injected pack store of standard types: bytes in and out by the pack's id and rev and the file's name. What `get` returns is verified again; a failed `put` is not a failed download. */
306
+ export interface PackCache {
307
+ get(pack: { id: string; rev: number; files: { name: string; bytes: number; sha: string }[] }, file: { name: string; bytes: number; sha: string }): Promise<Uint8Array | null>;
308
+ put(pack: { id: string; rev: number; files: { name: string; bytes: number; sha: string }[] }, file: { name: string; bytes: number; sha: string }, bytes: Uint8Array): Promise<void>;
309
+ }
310
+ /** A pack cache over Cache Storage (`caches`): one Response per file, older revisions dropped once a new one is whole. `null` where there is no Cache Storage. */
311
+ export function cacheStoragePackCache(name?: string, storage?: CacheStorage): PackCache | null;
312
+ /** The default pack loader (D933): downloads with `fetch`, trying the file's URLs in order, verifying, and keeping files in `cache` (default: `detectPackCache()`; `null` for none; the file stores are the optional `@3sln/emon/node-pack-cache` and `@3sln/emon/deno-pack-cache`). */
313
+ /** A pack cache over IndexedDB; null where there is none. */
314
+ export function indexedDBPackCache(idb?: IDBFactory, name?: string): PackCache | null;
315
+ /** The default store by what the runtime has: Cache Storage, IndexedDB, Deno's or Node/Bun's file system (optional modules), else none. */
316
+ export function detectPackCache(env?: object, load?: (kind: 'node' | 'deno') => Promise<{ packCache?: (env?: object) => PackCache | null }>): Promise<{ kind: 'cache-storage' | 'indexeddb' | 'deno' | 'node' | 'none'; cache: PackCache | null }>;
317
+ export function httpPackFetcher(packs: Packs, options?: { cache?: PackCache | null; fetch?: typeof fetch; note?: (line: string) => void }): NonNullable<Parameters<Packs['setFetcher']>[0]>;
318
+ /** The default places a pack file can be downloaded from (one definition for every host). */
319
+ export const MIRROR_R2: string;
320
+ export const MIRROR_GITHUB: string;
321
+ export function fileUrls(id: string, rev: number, file: string, shaHex: string, app?: string[], replace?: boolean): string[];
322
+ export function mirrorUrl(mirror: string, id: string, rev: number, file: string, shaHex: string): string;
323
+ export function parseMirrors(text: string): string[];
package/src/index.js CHANGED
@@ -26,8 +26,11 @@
26
26
  import { Wasm } from './wasm.js';
27
27
  import { toSource, bytesSource, blobSource, urlSource, streamSource, SourceChangedError, EmonError } from './sources.js';
28
28
  import { ocrRequest, encodeOcr, canonicalOcr } from './ocr.js';
29
+ import { Engines } from './engines.js';
29
30
 
30
- export { bytesSource, blobSource, urlSource, streamSource, toSource, SourceChangedError, EmonError };
31
+ export { httpPackFetcher, cacheStoragePackCache, indexedDBPackCache, detectPackCache } from './packfetch.js';
32
+ export { MIRROR_R2, MIRROR_GITHUB, fileUrls, mirrorUrl, parseMirrors } from './packs.js';
33
+ export { bytesSource, blobSource, urlSource, streamSource, toSource, SourceChangedError, EmonError, Engines };
31
34
 
32
35
  // The WASM instance (`w`), a Model's handle (`h`) and an Asset's Model (`model`) are NOT public API (P11.4, D542): they are defined
33
36
  // non-enumerable, so they are not in `Object.keys`, a spread, `JSON.stringify` or a `for...in`, and `index.d.ts` does not declare them.
@@ -53,6 +56,9 @@ const optionLines = (o, chunk, record) => {
53
56
  if (o.assetSignatures !== undefined) put('asset-signatures', o.assetSignatures === true || o.assetSignatures === 'on' ? 'on' : 'off');
54
57
  if (o.keepEvidence) put('keep-evidence', 1);
55
58
  put('ocr-scope', o.ocrScope);
59
+ put('capture', o.capture);
60
+ put('ocr-readings', o.ocrReadings);
61
+ put('ocr-compose', o.ocrCompose);
56
62
  put('max-rounds', o.maxRounds);
57
63
  put('fetch-rounds', o.fetchRounds);
58
64
  for (const [k, v] of Object.entries(o.limits || {})) put(`limit.${k}`, v);
@@ -139,7 +145,7 @@ export class Model {
139
145
 
140
146
  /**
141
147
  * SPEC 5: HTML. Options: `ids`, `geometry`, `confidenceBelow` (0..1000), `ledger`, `pretty`, `furnitureDrop`, `milestones`
142
- * (default true), `initialsPlain`, `alignStyle`, `assets`: `inline` (data: URIs, the default), `external` (the HTML names each
148
+ * (default true), `initialsPlain`, `alignStyle`, `readings`, `assets`: `inline` (data: URIs, the default), `external` (the HTML names each
143
149
  * asset file by `assetPrefix + name`, and the caller serves them: `model.assets[i].blob()`) or `omit`; `assetPrefix`.
144
150
  */
145
151
  html(o = {}) {
@@ -153,6 +159,7 @@ export class Model {
153
159
  if (o.milestones === false) L.push('no-milestones');
154
160
  if (o.initialsPlain) L.push('initials-plain');
155
161
  if (o.alignStyle) L.push('align-style');
162
+ if (o.readings) L.push('readings');
156
163
  if (o.assets) L.push(`assets=${o.assets}`);
157
164
  if (o.assetPrefix) L.push(`prefix=${o.assetPrefix}`);
158
165
  const w = this.w;
@@ -229,6 +236,14 @@ export class Emon {
229
236
  this.defaults = defaults;
230
237
  }
231
238
 
239
+ /**
240
+ * An empty engine registry bound to this module (D925): `await engines.add(adapter)` for each OCR engine (`tesseractAdapter`, `ppocrEngine`, your own), then
241
+ * `{ ports: { ocr: engines.port() } }`. Nothing is registered unless you add it.
242
+ */
243
+ engines() {
244
+ return new Engines(this.w, (o) => optionLines(o ?? {}, this.defaults?.chunk ?? 65536, false));
245
+ }
246
+
232
247
  _open(source, password, mode, options) {
233
248
  const w = this.w;
234
249
  const chunk = options.chunk ?? this.defaults.chunk ?? 65536;