@3sln/emon 0.3.0-preview.1 → 0.3.0-preview.2
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/THIRD_PARTY_NOTICES.md +163 -850
- package/emon.wasm +0 -0
- package/package.json +5 -3
- package/src/engines.js +216 -0
- package/src/index.d.ts +127 -2
- package/src/index.js +17 -2
- package/src/packfetch.js +203 -0
- package/src/packs.js +460 -0
- package/src/sources.js +38 -0
- package/src/tesseract.d.ts +4 -3
- package/src/tesseract.js +14 -12
- package/src/wasm.js +73 -0
package/src/packfetch.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// THE DEFAULT PACK LOADER, JavaScript host (D933; D913 keeps HTTP out of the pack machinery in `packs.js`, which only calls a fetcher). This is the turnkey layer: `Engines` installs it unless the
|
|
2
|
+
// app sets a fetcher of its own (`engines.packs.setFetcher(fn)`, or `setFetcher(null)` for none). It is `httpPackFetcher(packs, options)`, and an app can build one over its own `fetch`.
|
|
3
|
+
//
|
|
4
|
+
// It downloads with the platform's `fetch` (the browser's or Node's HTTPS stack and trust store), trying the file's URLs in priority order (`packs.urls`: the default mirror, the GitHub release
|
|
5
|
+
// asset, then the app's mirrors). It reports progress as the bytes arrive and stops when asked. It checks the size and SHA-256 itself and goes on to the next URL when a mirror gives other bytes;
|
|
6
|
+
// the registry verifies again. Plain `http://` is accepted only for a loopback host (a mirror on the development machine); everything else must be `https://`.
|
|
7
|
+
//
|
|
8
|
+
// THE CACHE (injected; standard types only, D940). `cache` is `{ get(pack, file) -> Promise<Uint8Array | null>, put(pack, file, bytes) -> Promise<void> }`: bytes in and out, keyed by the pack's id and rev, the file's name
|
|
9
|
+
// (and its sha, in `file`). A cache is trusted for nothing: what `get` returns is checked against the catalogue's size and SHA-256 again, and a `put` that fails is not a failed download. A cache keeps one
|
|
10
|
+
// revision of a pack apart from the others and drops the older revisions once the new one is whole (`put` knows `pack.files`: the "prune after verify"). The app can always pass its own.
|
|
11
|
+
// THE DEFAULT is chosen once, by feature detection (`detectPackCache`): Cache Storage (`caches`), else IndexedDB, in a browser or worker; else Deno's file system, else Node's or Bun's (the optional modules
|
|
12
|
+
// `@3sln/emon/deno-pack-cache` and `@3sln/emon/node-pack-cache`, loaded by dynamic `import()` only there; the `browser` condition of their `exports` is an empty stub, so a bundler for the web never sees
|
|
13
|
+
// `node:`); else NO cache (each pack is fetched and verified every time), with a note "pack cache: unavailable". This file names no file system.
|
|
14
|
+
import { sha256Hex } from './packs.js';
|
|
15
|
+
|
|
16
|
+
const isLoopback = (u) => ['localhost', '127.0.0.1', '[::1]', '::1'].includes(u.hostname);
|
|
17
|
+
|
|
18
|
+
const CACHE_ORIGIN = 'https://emon-packs.invalid';
|
|
19
|
+
const cacheUrl = (id, rev, name) => `${CACHE_ORIGIN}/${encodeURIComponent(id)}@${rev}/${encodeURIComponent(name)}`;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A pack cache over Cache Storage (the browser's, a worker's, Deno's): one `Response` per file under a synthetic URL `<id>@<rev>/<file>`. Once every file of a revision is there, the cached files of the older
|
|
23
|
+
* revisions of that pack are deleted (a newer one stays, and a failed or partial download deletes nothing). `null` where there is no `caches`.
|
|
24
|
+
* @param name the cache's name (default `emon-packs`)
|
|
25
|
+
*/
|
|
26
|
+
export function cacheStoragePackCache(name = 'emon-packs', storage = globalThis.caches) {
|
|
27
|
+
if (!storage?.open) return null;
|
|
28
|
+
const open = () => storage.open(name);
|
|
29
|
+
return {
|
|
30
|
+
kind: 'cache-storage',
|
|
31
|
+
async get(pack, file) {
|
|
32
|
+
const res = await (await open()).match(cacheUrl(pack.id, pack.rev, file.name));
|
|
33
|
+
return res ? new Uint8Array(await res.arrayBuffer()) : null;
|
|
34
|
+
},
|
|
35
|
+
async put(pack, file, bytes) {
|
|
36
|
+
const c = await open();
|
|
37
|
+
await c.put(cacheUrl(pack.id, pack.rev, file.name), new Response(bytes));
|
|
38
|
+
for (const f of pack.files) if (!(await c.match(cacheUrl(pack.id, pack.rev, f.name)))) return;
|
|
39
|
+
const prefix = `${CACHE_ORIGIN}/${encodeURIComponent(pack.id)}@`;
|
|
40
|
+
for (const req of await c.keys()) {
|
|
41
|
+
if (!req.url.startsWith(prefix)) continue;
|
|
42
|
+
const rev = req.url.slice(prefix.length).split('/')[0];
|
|
43
|
+
if (/^\d+$/.test(rev) && Number(rev) < pack.rev) await c.delete(req);
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
const keyOf = (pack, name) => `${pack.id}@${pack.rev}/${name}`;
|
|
51
|
+
const revOf = (key, id) => {
|
|
52
|
+
if (!key.startsWith(`${id}@`)) return null;
|
|
53
|
+
const r = key.slice(id.length + 1).split('/')[0];
|
|
54
|
+
return /^\d+$/.test(r) ? Number(r) : null;
|
|
55
|
+
};
|
|
56
|
+
const whole = async (pack, has) => {
|
|
57
|
+
for (const f of pack.files) if (!(await has(f))) return false;
|
|
58
|
+
return true;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** A pack cache over IndexedDB (`indexedDB`, injectable): one record per file under `<id>@<rev>/<file>`; older revisions of the pack are deleted once the new one is whole. */
|
|
62
|
+
export function indexedDBPackCache(idb = globalThis.indexedDB, name = 'emon-packs') {
|
|
63
|
+
if (!idb?.open) return null;
|
|
64
|
+
const db = new Promise((resolve, reject) => {
|
|
65
|
+
const r = idb.open(name, 1);
|
|
66
|
+
r.onupgradeneeded = () => r.result.createObjectStore('files');
|
|
67
|
+
r.onsuccess = () => resolve(r.result);
|
|
68
|
+
r.onerror = () => reject(r.error);
|
|
69
|
+
});
|
|
70
|
+
const run = async (mode, fn) => {
|
|
71
|
+
const d = await db;
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
const tx = d.transaction('files', mode);
|
|
74
|
+
const req = fn(tx.objectStore('files'));
|
|
75
|
+
tx.oncomplete = () => resolve(req.result);
|
|
76
|
+
tx.onerror = tx.onabort = () => reject(tx.error);
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
kind: 'indexeddb',
|
|
81
|
+
async get(pack, file) {
|
|
82
|
+
const v = await run('readonly', (st) => st.get(keyOf(pack, file.name)));
|
|
83
|
+
return v ? new Uint8Array(v) : null;
|
|
84
|
+
},
|
|
85
|
+
async put(pack, file, bytes) {
|
|
86
|
+
await run('readwrite', (st) => st.put(bytes.slice().buffer, keyOf(pack, file.name)));
|
|
87
|
+
const keys = await run('readonly', (st) => st.getAllKeys());
|
|
88
|
+
const have = new Set(keys);
|
|
89
|
+
if (!(await whole(pack, async (f) => have.has(keyOf(pack, f.name))))) return;
|
|
90
|
+
for (const k of keys) {
|
|
91
|
+
const r = revOf(k, pack.id);
|
|
92
|
+
if (r !== null && r < pack.rev) await run('readwrite', (st) => st.delete(k));
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The default pack cache by what the runtime has. `env` is the global object (injectable for tests); `load(name)` imports an optional file-system module (`'node'`, `'deno'`).
|
|
100
|
+
* @returns `{ kind: 'cache-storage' | 'indexeddb' | 'deno' | 'node' | 'none', cache }`
|
|
101
|
+
*/
|
|
102
|
+
export async function detectPackCache(env = globalThis, load = (n) => import(n === 'deno' ? '@3sln/emon/deno-pack-cache' : '@3sln/emon/node-pack-cache')) {
|
|
103
|
+
const cs = cacheStoragePackCache('emon-packs', env.caches);
|
|
104
|
+
if (cs) return { kind: 'cache-storage', cache: cs };
|
|
105
|
+
const idb = indexedDBPackCache(env.indexedDB);
|
|
106
|
+
if (idb) return { kind: 'indexeddb', cache: idb };
|
|
107
|
+
const tryLoad = async (kind) => {
|
|
108
|
+
try {
|
|
109
|
+
const mod = await load(kind);
|
|
110
|
+
const c = mod?.packCache?.(env);
|
|
111
|
+
return c ? { kind, cache: c } : null;
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
if (env.Deno?.version) {
|
|
117
|
+
const r = await tryLoad('deno');
|
|
118
|
+
if (r) return r;
|
|
119
|
+
}
|
|
120
|
+
if (env.Bun || env.process?.versions?.node) {
|
|
121
|
+
const r = await tryLoad('node');
|
|
122
|
+
if (r) return r;
|
|
123
|
+
}
|
|
124
|
+
return { kind: 'none', cache: null };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A fetcher `async (pack, file, progress) => Uint8Array` for `packs.setFetcher`.
|
|
129
|
+
* @param packs the registry's `Packs` (its `urls` and `noteMirror`)
|
|
130
|
+
* @param options `{ cache, fetch = globalThis.fetch, note }`: `cache` is the app's store (`null` for none); left out, `detectPackCache()` picks one on first use and `note(line)` hears "pack cache: unavailable" when there is none
|
|
131
|
+
*/
|
|
132
|
+
export function httpPackFetcher(packs, { cache, fetch = globalThis.fetch, note = () => {}, env = globalThis } = {}) {
|
|
133
|
+
let chosen = cache === undefined ? null : Promise.resolve(cache);
|
|
134
|
+
const getCache = () =>
|
|
135
|
+
(chosen ??= detectPackCache(env).then((d) => {
|
|
136
|
+
if (d.kind === 'none') note('pack cache: unavailable on this platform (no Cache Storage, IndexedDB or file system; each pack is fetched and verified every time)');
|
|
137
|
+
return d.cache;
|
|
138
|
+
}));
|
|
139
|
+
return async (pack, file, progress) => {
|
|
140
|
+
const cache = await getCache();
|
|
141
|
+
const matches = async (b) => b.length === file.bytes && (await sha256Hex(b)) === file.sha;
|
|
142
|
+
if (cache) {
|
|
143
|
+
try {
|
|
144
|
+
const have = await cache.get(pack, file);
|
|
145
|
+
if (have && (await matches(have))) {
|
|
146
|
+
progress(have.length);
|
|
147
|
+
return have;
|
|
148
|
+
}
|
|
149
|
+
} catch {
|
|
150
|
+
/* not cached */
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
let last = new Error('no pack mirrors configured');
|
|
154
|
+
for (const raw of packs.urls(pack.id, file.name)) {
|
|
155
|
+
let u;
|
|
156
|
+
try {
|
|
157
|
+
u = new URL(raw);
|
|
158
|
+
} catch {
|
|
159
|
+
last = new Error(`${raw}: not a URL`);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (!(u.protocol === 'https:' || (u.protocol === 'http:' && isLoopback(u)))) {
|
|
163
|
+
last = new Error(`${raw}: only https URLs are fetched`);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
packs.noteMirror(pack.id, raw);
|
|
167
|
+
try {
|
|
168
|
+
const res = await fetch(raw);
|
|
169
|
+
if (res.status !== 200) throw new Error(`answered ${res.status}`);
|
|
170
|
+
const chunks = [];
|
|
171
|
+
let got = 0;
|
|
172
|
+
const reader = res.body.getReader();
|
|
173
|
+
for (;;) {
|
|
174
|
+
const { done, value } = await reader.read();
|
|
175
|
+
if (done) break;
|
|
176
|
+
chunks.push(value);
|
|
177
|
+
got += value.length;
|
|
178
|
+
if (got > file.bytes) throw new Error("gave more bytes than the catalogue's size");
|
|
179
|
+
if (progress(got)) {
|
|
180
|
+
await reader.cancel();
|
|
181
|
+
throw new Error('cancelled');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const bytes = new Uint8Array(got);
|
|
185
|
+
let at = 0;
|
|
186
|
+
for (const c of chunks) {
|
|
187
|
+
bytes.set(c, at);
|
|
188
|
+
at += c.length;
|
|
189
|
+
}
|
|
190
|
+
if (!(await matches(bytes))) {
|
|
191
|
+
last = new Error(`${raw}: gave other bytes than the catalogue pins`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (cache) await cache.put(pack, file, bytes).catch(() => {}); // a cache that cannot be written is not a failed download
|
|
195
|
+
return bytes;
|
|
196
|
+
} catch (e) {
|
|
197
|
+
if (e.message === 'cancelled') throw e;
|
|
198
|
+
last = new Error(`${raw}: ${e.message}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
throw last;
|
|
202
|
+
};
|
|
203
|
+
}
|
package/src/packs.js
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
// THE PACKS, JavaScript host (DEVLOG D925/D928 P13.16; the twin of `host/rust/src/packs.rs` and the C ABI's `emon_engines_packs`/`emon_on_pack_needed`/`emon_on_pack_event`/`emon_packs_ensure`).
|
|
2
|
+
//
|
|
3
|
+
// A pack is the model files an adapter reads with. WHAT IS KIN'S: which packs exist and their SHA-256 and sizes, which a request needs (`pk-resolve`), what to do about one that
|
|
4
|
+
// is missing (`ad-asks-hook`, `ad-pack-action`), `engines()` and `prepare()`. They are asked of the module (`emon.engines().packs`). WHAT IS THIS FILE'S: holding verified bytes,
|
|
5
|
+
// the app's hook, the events, and the download, which is THE APP'S: the library ships no HTTP client (D913). With no `fetcher` a `fetch` decision is `pack-fetch-unavailable:<id>`.
|
|
6
|
+
//
|
|
7
|
+
// const engines = emon.engines();
|
|
8
|
+
// engines.packs.setMode('auto'); // 'never' (the default), 'cache' or 'auto'
|
|
9
|
+
// engines.packs.setFetcher(async (pack, file, progress) => bytes); // the app's download; progress(done) answers true to stop
|
|
10
|
+
// engines.packs.onPackNeeded(async (need) => ({ action: 'fetch' })); // or { action: 'provide', data }, { action: 'decline' }, { action: 'substitute', engine }
|
|
11
|
+
// engines.packs.onPackEvent((ev) => ...); // start, progress, done, failed, cancelled
|
|
12
|
+
// await engines.packs.ensure(['tess-fast-eng']); // ahead of time
|
|
13
|
+
//
|
|
14
|
+
// EVERY PACK IS VERIFIED against the catalogue's size and SHA-256 before an adapter sees a byte of it, wherever it came from (a hook's bytes, a download, `install`). One that does
|
|
15
|
+
// not match is never kept (`pack-hash-mismatch:<id>`). `EMON_OFFLINE=1` (Node) and mode `never` win over every hook.
|
|
16
|
+
|
|
17
|
+
const ACTION = { fetch: 1, provide: 2, decline: 3, substitute: 4 };
|
|
18
|
+
|
|
19
|
+
// ------------------------------------------------------------------------------------------------ where a pack file can be downloaded (D933)
|
|
20
|
+
//
|
|
21
|
+
// ONE DEFINITION for every host (release/packs/hosting.edn; `bb packs-hosting` checks it). The content-addressed mirror serves `<base>/sha256/<hex>`; the append-only `packs` GitHub release is the
|
|
22
|
+
// fallback and where to download by hand to host the files yourself. The app's mirrors come after (or replace them): a base URL or a template with `{sha}`, `{id}`, `{rev}`, `{file}`.
|
|
23
|
+
|
|
24
|
+
export const MIRROR_R2 = 'https://emon-packs.3sln.com';
|
|
25
|
+
export const MIRROR_GITHUB = 'https://github.com/3sln/emon/releases/download/packs/{id}@{rev}-{file}';
|
|
26
|
+
|
|
27
|
+
/** A mirror list as text: separated by commas or line breaks, empty items dropped. */
|
|
28
|
+
export function parseMirrors(text) {
|
|
29
|
+
return String(text ?? '').split(/[,\r\n]/).map((m) => m.trim()).filter(Boolean);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The URL of a file under one mirror. */
|
|
33
|
+
export function mirrorUrl(mirror, id, rev, file, shaHex) {
|
|
34
|
+
if (mirror.includes('{')) return mirror.replaceAll('{sha}', shaHex).replaceAll('{id}', id).replaceAll('{rev}', String(rev)).replaceAll('{file}', file);
|
|
35
|
+
return `${mirror.replace(/\/+$/, '')}/sha256/${shaHex}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The known URLs of a file, best first: the default mirrors (R2, then the GitHub asset), then the app's, or only the app's when `replace` and it has any. */
|
|
39
|
+
export function fileUrls(id, rev, file, shaHex, app = [], replace = false) {
|
|
40
|
+
const list = replace && app.length ? [...app] : [MIRROR_R2, MIRROR_GITHUB, ...app];
|
|
41
|
+
return [...new Set(list.map((m) => mirrorUrl(m, id, rev, file, shaHex)))];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const toHex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
45
|
+
|
|
46
|
+
/** SHA-256 of `bytes`, hex. */
|
|
47
|
+
export async function sha256Hex(bytes) {
|
|
48
|
+
return toHex(await globalThis.crypto.subtle.digest('SHA-256', bytes));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const bytesOf = (d) => (d instanceof Uint8Array ? d : d instanceof ArrayBuffer ? new Uint8Array(d) : ArrayBuffer.isView(d) ? new Uint8Array(d.buffer, d.byteOffset, d.byteLength) : null);
|
|
52
|
+
|
|
53
|
+
export class Packs {
|
|
54
|
+
#w;
|
|
55
|
+
#cat;
|
|
56
|
+
#mode;
|
|
57
|
+
#hook = null;
|
|
58
|
+
#listeners = new Set();
|
|
59
|
+
#fetcher = null;
|
|
60
|
+
#cancel = false;
|
|
61
|
+
#files = new Map(); // pack id -> Map(file name -> verified bytes)
|
|
62
|
+
#notes;
|
|
63
|
+
#fetching = Promise.resolve();
|
|
64
|
+
// the app's mirrors, and whether they replace the default ones (`$EMON_PACKS_URL` in Node is a list that replaces)
|
|
65
|
+
#mirrors = parseMirrors(globalThis.process?.env?.EMON_PACKS_URL);
|
|
66
|
+
#replace = true;
|
|
67
|
+
// the status of the packs in flight or failed (by pack id), and its subscribers
|
|
68
|
+
#status = new Map();
|
|
69
|
+
#statusListeners = new Set();
|
|
70
|
+
/** An `EventTarget` that gets a `status` event (`event.detail`: the `PackStatus`) for every change of any pack. */
|
|
71
|
+
statusTarget = new EventTarget();
|
|
72
|
+
|
|
73
|
+
/** @param w the loaded module; @param notes where `pack-hash-mismatch:<id>` and the like are noted */
|
|
74
|
+
constructor(w, notes = () => {}) {
|
|
75
|
+
this.#w = w;
|
|
76
|
+
this.#cat = w.packCatalogue();
|
|
77
|
+
this.#mode = this.#cat.pfetch.never;
|
|
78
|
+
this.#notes = notes;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** kin's catalogue: `{ class, packs: [{ code, id, rev, engine, kind, licence, bytes, files: [{ name, bytes, sha }] }], ... }`. */
|
|
82
|
+
get catalogue() {
|
|
83
|
+
return this.#cat;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `never` (the default: nothing is fetched and no hook is asked), `cache` (the hook is asked; a bare miss is not fetched) or `auto` (a miss with no hook is fetched). */
|
|
87
|
+
setMode(name) {
|
|
88
|
+
const m = this.#cat.pfetch[name];
|
|
89
|
+
if (m === undefined) throw new Error(`usage: the pack mode is never, cache or auto, not ${name}`);
|
|
90
|
+
this.#mode = m;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get mode() {
|
|
94
|
+
return Object.keys(this.#cat.pfetch).find((k) => this.#cat.pfetch[k] === this.#mode);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `EMON_OFFLINE=1`: nothing is fetched and no hook is asked, whatever the mode says (Node; a browser has no environment). */
|
|
98
|
+
get offline() {
|
|
99
|
+
return globalThis.process?.env?.EMON_OFFLINE === '1';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The app's own pack mirrors, each a base URL (`<base>/sha256/<hex>`) or a template with `{sha}`, `{id}`, `{rev}`, `{file}`: after the default ones (R2, then the GitHub release) or, with `{ replace: true }`, instead of them. */
|
|
103
|
+
setMirrors(list, { replace = false } = {}) {
|
|
104
|
+
this.#mirrors = [...list];
|
|
105
|
+
this.#replace = replace;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The known URLs of one file of a pack (`pack`: its id; `file`: `{ name }` or the name), best first: what a hook is given and what the default downloader tries in order. */
|
|
109
|
+
urls(pack, file) {
|
|
110
|
+
const info = this.#info(typeof pack === 'string' ? pack : pack.id);
|
|
111
|
+
const f = info.files.find((x) => x.name === (typeof file === 'string' ? file : file.name));
|
|
112
|
+
return fileUrls(info.id, info.rev, f.name, f.sha, this.#mirrors, this.#replace);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---------------------------------------------------------------------------------------- the status of each pack (D933)
|
|
116
|
+
//
|
|
117
|
+
// What an app's UI shows while packs load: a pack is `missing`, `queued`, `downloading` (bytes done of total, from which mirror), `verifying`, `ready` (at its revision) or `failed` (why, and whether the next
|
|
118
|
+
// request tries again). It follows the places the pack events come from, so a download the library starts, one the app starts with `ensure`, and bytes the app provides (verifying, then ready or failed) all show.
|
|
119
|
+
// `status()` and `status(id)` are snapshots; `onPackStatus(fn)`, `statusEvents(signal)` and `statusTarget` the subscription; `summary()` the aggregate; `Engines.engineReady(name)` the "OCR ready" signal.
|
|
120
|
+
|
|
121
|
+
#setStatus(info, state, done, total, app, mirror = '', reason = '', willRetry = false) {
|
|
122
|
+
const st = { id: info.id, rev: info.rev, engine: info.engine, state, done, total, mirror, reason, willRetry, byApp: app };
|
|
123
|
+
if (state === 'ready') this.#status.delete(info.id);
|
|
124
|
+
else this.#status.set(info.id, st);
|
|
125
|
+
for (const f of [...this.#statusListeners]) {
|
|
126
|
+
try {
|
|
127
|
+
f(st);
|
|
128
|
+
} catch {
|
|
129
|
+
/* a listener's failure is not the pack's */
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
this.statusTarget.dispatchEvent(new CustomEvent('status', { detail: st }));
|
|
134
|
+
} catch {
|
|
135
|
+
/* no CustomEvent here */
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Records the URL a pack is being downloaded from (the default downloader tells it for each URL it tries). */
|
|
140
|
+
noteMirror(pack, url) {
|
|
141
|
+
const info = this.#info(typeof pack === 'string' ? pack : pack.id);
|
|
142
|
+
const cur = this.#status.get(info.id);
|
|
143
|
+
if (cur?.state === 'downloading') this.#setStatus(info, 'downloading', cur.done, cur.total, cur.byApp, url);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#statusOf(info) {
|
|
147
|
+
const held = this.#status.get(info.id);
|
|
148
|
+
if (held) return held;
|
|
149
|
+
const ready = !!this.files(info.id);
|
|
150
|
+
return { id: info.id, rev: info.rev, engine: info.engine, state: ready ? 'ready' : 'missing', done: ready ? info.bytes : 0, total: info.bytes, mirror: '', reason: '', willRetry: false, byApp: false };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The state of every pack (no argument) or of one (its id): `{ id, rev, engine, state, done, total, mirror, reason, willRetry, byApp }`. */
|
|
154
|
+
status(id) {
|
|
155
|
+
if (id !== undefined) {
|
|
156
|
+
const info = this.#info(id);
|
|
157
|
+
if (!info) throw new Error(`pack-unknown:${id}`);
|
|
158
|
+
return this.#statusOf(info);
|
|
159
|
+
}
|
|
160
|
+
return this.#cat.packs.map((p) => this.#statusOf(p));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The aggregate over the packs in flight: `{ busy, activeDownloads, queued, done, total, progress }` (`progress`: 0 to 1, 1 when nothing is in flight). */
|
|
164
|
+
summary() {
|
|
165
|
+
const s = { busy: false, activeDownloads: 0, queued: 0, done: 0, total: 0, progress: 1 };
|
|
166
|
+
for (const st of this.#status.values()) {
|
|
167
|
+
if (st.state === 'downloading') s.activeDownloads++;
|
|
168
|
+
else if (st.state === 'queued') s.queued++;
|
|
169
|
+
else if (st.state !== 'verifying') continue;
|
|
170
|
+
s.busy = true;
|
|
171
|
+
s.done += st.done;
|
|
172
|
+
s.total += st.total;
|
|
173
|
+
}
|
|
174
|
+
s.progress = s.total === 0 ? 1 : s.done / s.total;
|
|
175
|
+
return s;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Listens to every state change of any pack. Answers the function that removes the listener. */
|
|
179
|
+
onPackStatus(fn) {
|
|
180
|
+
this.#statusListeners.add(fn);
|
|
181
|
+
return () => this.#statusListeners.delete(fn);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The same changes as an async iterable (`for await (const st of packs.statusEvents(signal))`): ends when `signal` aborts. */
|
|
185
|
+
statusEvents(signal) {
|
|
186
|
+
const queue = [];
|
|
187
|
+
let wake = null;
|
|
188
|
+
const off = this.onPackStatus((st) => {
|
|
189
|
+
queue.push(st);
|
|
190
|
+
wake?.();
|
|
191
|
+
});
|
|
192
|
+
const done = new Promise((res) => signal?.addEventListener('abort', res, { once: true }));
|
|
193
|
+
return (async function* () {
|
|
194
|
+
try {
|
|
195
|
+
while (!signal?.aborted) {
|
|
196
|
+
if (!queue.length) await Promise.race([new Promise((r) => (wake = r)), done]);
|
|
197
|
+
while (queue.length) yield queue.shift();
|
|
198
|
+
}
|
|
199
|
+
} finally {
|
|
200
|
+
off();
|
|
201
|
+
}
|
|
202
|
+
})();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The app's hook for a pack a conversion needs and nobody has: `(need) => decision`, sync or async. `need`: `{ pack, rev, engine, kind, licence, bytes, reason, requestEngine, files: [{ name, sha256, bytes, urls }] }` (each file's plain name, SHA-256, size and known URLs, best first, so an app can host the files itself); the decision
|
|
206
|
+
* `{ action: 'fetch' }`, `{ action: 'provide', data }` (`Uint8Array`, or `{ [fileName]: Uint8Array }` for a pack of several files), `{ action: 'decline' }` or `{ action: 'substitute', engine }`.
|
|
207
|
+
* A hook that throws declines. `null` removes it. */
|
|
208
|
+
onPackNeeded(fn) {
|
|
209
|
+
this.#hook = fn ?? null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The app's download: `async (pack, file, progress) => Uint8Array` for each file of a pack (`file`: `{ name, bytes, sha }`); `progress(done)` reports the bytes so far and answers true when the
|
|
213
|
+
* download is to stop (the app's `cancel()`, or an event listener's). `null` removes it. */
|
|
214
|
+
setFetcher(fn) {
|
|
215
|
+
this.#fetcher = fn ?? null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Listens to the one progress stream of library- and app-initiated fetches: `{ kind: 'start' | 'progress' | 'done' | 'failed' | 'cancelled', pack, engine, done, total, initiator: 'library' | 'app', message }`.
|
|
219
|
+
* A listener that returns `true` on a `progress` event cancels the fetch. Answers the function that removes the listener. */
|
|
220
|
+
onPackEvent(fn) {
|
|
221
|
+
this.#listeners.add(fn);
|
|
222
|
+
return () => this.#listeners.delete(fn);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** The same events as an async iterable (`for await (const ev of packs.events())`): ends when `signal` aborts. */
|
|
226
|
+
events(signal) {
|
|
227
|
+
const queue = [];
|
|
228
|
+
let wake = null;
|
|
229
|
+
const off = this.onPackEvent((ev) => {
|
|
230
|
+
queue.push(ev);
|
|
231
|
+
wake?.();
|
|
232
|
+
});
|
|
233
|
+
const done = new Promise((res) => signal?.addEventListener('abort', res, { once: true }));
|
|
234
|
+
return (async function* () {
|
|
235
|
+
try {
|
|
236
|
+
while (!signal?.aborted) {
|
|
237
|
+
if (!queue.length) await Promise.race([new Promise((r) => (wake = r)), done]);
|
|
238
|
+
while (queue.length) yield queue.shift();
|
|
239
|
+
}
|
|
240
|
+
} finally {
|
|
241
|
+
off();
|
|
242
|
+
}
|
|
243
|
+
})();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Asks the running fetch to stop: the pack is then missing, `pack-fetch-cancelled:<id>`. */
|
|
247
|
+
cancel() {
|
|
248
|
+
this.#cancel = true;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
#info(idOrCode) {
|
|
252
|
+
return this.#cat.packs.find((p) => p.id === idOrCode || p.code === idOrCode);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#emit(kind, info, done, total, app, message = '') {
|
|
256
|
+
const mirror = this.#status.get(info.id)?.mirror ?? '';
|
|
257
|
+
if (kind === 'start' || kind === 'progress') this.#setStatus(info, 'downloading', done, total, app, mirror);
|
|
258
|
+
else if (kind === 'done') this.#setStatus(info, 'ready', total, total, app);
|
|
259
|
+
else if (kind === 'failed') this.#setStatus(info, 'failed', done, total, app, '', message, !message.includes('pack-hash-mismatch') && !message.includes('pack-provide-failed'));
|
|
260
|
+
else if (kind === 'cancelled') this.#setStatus(info, 'failed', done, total, app, '', `pack-fetch-cancelled:${info.id}`, false);
|
|
261
|
+
let stop = false;
|
|
262
|
+
for (const f of [...this.#listeners]) {
|
|
263
|
+
try {
|
|
264
|
+
if (f({ kind, pack: info.id, engine: info.engine, done, total, initiator: app ? 'app' : 'library', message }) === true) stop = true;
|
|
265
|
+
} catch {
|
|
266
|
+
/* a listener's failure is not the fetch's */
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return stop || this.#cancel;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The verified files of a pack, or null. */
|
|
273
|
+
files(idOrCode) {
|
|
274
|
+
const info = this.#info(idOrCode);
|
|
275
|
+
const held = info && this.#files.get(info.id);
|
|
276
|
+
return held && info.files.every((f) => held.has(f.name)) ? held : null;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** The codes of the packs held. */
|
|
280
|
+
installed() {
|
|
281
|
+
return this.#cat.packs.filter((p) => this.files(p.id)).map((p) => p.code);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Verified files of every held pack an engine reads (`engine`: kin's engine name; packs of every engine included), by file name: what an adapter is given. */
|
|
285
|
+
view(engine) {
|
|
286
|
+
const out = new Map();
|
|
287
|
+
for (const p of this.#cat.packs) {
|
|
288
|
+
if (p.engine !== 'any' && p.engine !== engine) continue;
|
|
289
|
+
const held = this.files(p.id);
|
|
290
|
+
if (held) for (const [k, v] of held) out.set(k, v);
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async #matches(file, bytes) {
|
|
296
|
+
return bytes.length === file.bytes && (await sha256Hex(bytes)) === file.sha;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Verifies the app's bytes for a pack (`data`: bytes of a one-file pack, or `{ [fileName]: bytes }`) and keeps them. Throws `pack-hash-mismatch:<id>` (nothing is kept) or `pack-provide-failed:<id>`. */
|
|
300
|
+
async install(idOrCode, data) {
|
|
301
|
+
const info = this.#info(idOrCode);
|
|
302
|
+
if (!info) throw new Error(`pack-missing:${idOrCode}`);
|
|
303
|
+
this.#setStatus(info, 'verifying', info.bytes, info.bytes, true);
|
|
304
|
+
try {
|
|
305
|
+
await this.#install(info, data);
|
|
306
|
+
} catch (e) {
|
|
307
|
+
this.#setStatus(info, 'failed', 0, info.bytes, true, '', e.message, false);
|
|
308
|
+
throw e;
|
|
309
|
+
}
|
|
310
|
+
this.#setStatus(info, 'ready', info.bytes, info.bytes, true);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async #install(info, data) {
|
|
314
|
+
const staged = new Map();
|
|
315
|
+
for (const f of info.files) {
|
|
316
|
+
const raw = bytesOf(data);
|
|
317
|
+
const bytes = raw ? (info.files.length === 1 ? raw : null) : data?.[f.name] ? bytesOf(data[f.name]) : null;
|
|
318
|
+
if (!bytes) throw new Error(`pack-provide-failed:${info.id}`);
|
|
319
|
+
if (!(await this.#matches(f, bytes))) {
|
|
320
|
+
this.#notes(`pack-hash-mismatch:${info.id}`);
|
|
321
|
+
throw new Error(`pack-hash-mismatch:${info.id}`);
|
|
322
|
+
}
|
|
323
|
+
staged.set(f.name, bytes.slice());
|
|
324
|
+
}
|
|
325
|
+
this.#files.set(info.id, staged);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** What becomes of pack `idOrCode`, which a conversion needs: `{ ready: true }`, `{ unread: reason }` or `{ substitute: engine }`. Kin decides (`ad-pack-action`); this does it. */
|
|
329
|
+
async need(idOrCode, reason, requestEngine) {
|
|
330
|
+
const info = this.#info(idOrCode);
|
|
331
|
+
const present = !!this.files(info.id);
|
|
332
|
+
const { mode, offline } = { mode: this.#mode, offline: this.offline };
|
|
333
|
+
const hasHook = !!this.#hook;
|
|
334
|
+
const asks = this.#w.packAction(present, mode, offline, hasHook, 0).asks;
|
|
335
|
+
let decision = { action: 0 };
|
|
336
|
+
if (asks) {
|
|
337
|
+
try {
|
|
338
|
+
const files = info.files.map((f) => ({ name: f.name, sha256: f.sha, bytes: f.bytes, urls: this.urls(info.id, f.name) }));
|
|
339
|
+
const d = await this.#hook({ pack: info.id, rev: info.rev, engine: info.engine, kind: info.kind, licence: info.licence, bytes: info.bytes, reason, requestEngine, files });
|
|
340
|
+
decision = { action: ACTION[d?.action] ?? 0, data: d?.data, engine: d?.engine };
|
|
341
|
+
} catch {
|
|
342
|
+
decision = { action: 0 };
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const { action } = this.#w.packAction(present, mode, offline, hasHook, decision.action);
|
|
346
|
+
const c = this.#cat;
|
|
347
|
+
if (action === c.pact.use) return { ready: true };
|
|
348
|
+
if (action === c.pact.fetch) {
|
|
349
|
+
try {
|
|
350
|
+
await this.#fetch(info, false);
|
|
351
|
+
return { ready: true };
|
|
352
|
+
} catch (e) {
|
|
353
|
+
return { unread: e.message };
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (action === c.pact.provided) {
|
|
357
|
+
try {
|
|
358
|
+
await this.install(info.id, decision.data);
|
|
359
|
+
return { ready: true };
|
|
360
|
+
} catch (e) {
|
|
361
|
+
return { unread: e.message };
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (action === c.pact.substitute) return { substitute: decision.engine ?? '' };
|
|
365
|
+
if (asks && decision.action === ACTION.fetch && !this.#fetcher) {
|
|
366
|
+
const error = `pack-fetch-unavailable:${info.id}`;
|
|
367
|
+
this.#notes(error);
|
|
368
|
+
return { unread: error };
|
|
369
|
+
}
|
|
370
|
+
return { unread: `pack-missing:${info.id}` };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** The packs of `ids` (names), fetched now: progress and cancel through the events. Only when the mode lets anything be fetched. */
|
|
374
|
+
async ensure(ids) {
|
|
375
|
+
if (this.offline) throw new Error('EMON_OFFLINE=1: nothing is fetched');
|
|
376
|
+
if (this.#mode !== this.#cat.pfetch.auto) throw new Error('the pack mode does not fetch (it is `never` or `cache`)');
|
|
377
|
+
// everything that is missing is queued now, so a UI shows the whole job
|
|
378
|
+
for (const id of ids) {
|
|
379
|
+
const info = this.#info(id);
|
|
380
|
+
if (info && !this.files(info.id)) this.#setStatus(info, 'queued', 0, info.bytes, true);
|
|
381
|
+
}
|
|
382
|
+
for (const id of ids) {
|
|
383
|
+
const info = this.#info(id);
|
|
384
|
+
if (!info) throw new Error(`pack-missing:${id}`);
|
|
385
|
+
if (this.files(info.id)) continue;
|
|
386
|
+
await this.#fetch(info, true);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async #fetch(info, app) {
|
|
391
|
+
this.#setStatus(info, 'queued', 0, info.bytes, app);
|
|
392
|
+
// one fetch at a time: a second conversion needing the same pack waits for the first and finds it
|
|
393
|
+
const turn = this.#fetching;
|
|
394
|
+
let release;
|
|
395
|
+
this.#fetching = new Promise((r) => (release = r));
|
|
396
|
+
await turn;
|
|
397
|
+
try {
|
|
398
|
+
if (this.files(info.id)) {
|
|
399
|
+
this.#status.delete(info.id);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
if (!this.#fetcher) {
|
|
403
|
+
const error = `pack-fetch-unavailable:${info.id}`;
|
|
404
|
+
this.#notes(error);
|
|
405
|
+
this.#setStatus(info, 'failed', 0, info.bytes, app, '', error, false);
|
|
406
|
+
throw new Error(error);
|
|
407
|
+
}
|
|
408
|
+
this.#cancel = false;
|
|
409
|
+
this.#emit('start', info, 0, info.bytes, app);
|
|
410
|
+
let base = 0;
|
|
411
|
+
const staged = new Map();
|
|
412
|
+
for (const f of info.files) {
|
|
413
|
+
let cancelled = this.#cancel;
|
|
414
|
+
let received = 0;
|
|
415
|
+
let bytes;
|
|
416
|
+
let failure = null;
|
|
417
|
+
try {
|
|
418
|
+
const got = await this.#fetcher(info, f, (done) => {
|
|
419
|
+
done = Math.min(done, f.bytes);
|
|
420
|
+
if (done > received) {
|
|
421
|
+
received = done;
|
|
422
|
+
cancelled = this.#emit('progress', info, base + done, info.bytes, app) || cancelled;
|
|
423
|
+
}
|
|
424
|
+
cancelled = this.#cancel || cancelled;
|
|
425
|
+
return cancelled;
|
|
426
|
+
});
|
|
427
|
+
bytes = bytesOf(got);
|
|
428
|
+
if (!bytes) throw new Error('the fetcher gave no bytes');
|
|
429
|
+
} catch (e) {
|
|
430
|
+
failure = e;
|
|
431
|
+
}
|
|
432
|
+
if (cancelled || this.#cancel) {
|
|
433
|
+
this.#emit('cancelled', info, base, info.bytes, app);
|
|
434
|
+
const error = `pack-fetch-cancelled:${info.id}`;
|
|
435
|
+
this.#notes(error);
|
|
436
|
+
throw new Error(error);
|
|
437
|
+
}
|
|
438
|
+
if (failure) {
|
|
439
|
+
const error = `pack-fetch-failed:${info.id}: ${failure.message ?? failure}`;
|
|
440
|
+
this.#notes(error);
|
|
441
|
+
this.#emit('failed', info, base, info.bytes, app, error);
|
|
442
|
+
throw new Error(error);
|
|
443
|
+
}
|
|
444
|
+
this.#setStatus(info, 'verifying', base + f.bytes, info.bytes, app);
|
|
445
|
+
if (!(await this.#matches(f, bytes))) {
|
|
446
|
+
const error = `pack-hash-mismatch:${info.id}`;
|
|
447
|
+
this.#notes(error);
|
|
448
|
+
this.#emit('failed', info, base, info.bytes, app, error);
|
|
449
|
+
throw new Error(error);
|
|
450
|
+
}
|
|
451
|
+
staged.set(f.name, bytes.slice());
|
|
452
|
+
base += f.bytes;
|
|
453
|
+
}
|
|
454
|
+
this.#files.set(info.id, staged);
|
|
455
|
+
this.#emit('done', info, info.bytes, info.bytes, app);
|
|
456
|
+
} finally {
|
|
457
|
+
release();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|