browser-model-manager 0.0.0-stage → 0.1.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 +15 -0
- package/LICENSE +21 -0
- package/PROVENANCE.json +16 -0
- package/README.md +607 -2
- package/THIRD_PARTY_NOTICES +4 -0
- package/dist/acquisition/grants.d.ts +31 -0
- package/dist/acquisition/grants.js +75 -0
- package/dist/acquisition/index.d.ts +4 -0
- package/dist/acquisition/index.js +6 -0
- package/dist/acquisition/output.d.ts +12 -0
- package/dist/acquisition/output.js +19 -0
- package/dist/acquisition/phases.d.ts +3 -0
- package/dist/acquisition/phases.js +64 -0
- package/dist/acquisition/progress.d.ts +29 -0
- package/dist/acquisition/progress.js +124 -0
- package/dist/acquisition/slots.d.ts +35 -0
- package/dist/acquisition/slots.js +296 -0
- package/dist/cache/index.d.ts +3 -0
- package/dist/cache/index.js +4 -0
- package/dist/cache/model-cache.d.ts +152 -0
- package/dist/cache/model-cache.js +1585 -0
- package/dist/cache/sha256.d.ts +11 -0
- package/dist/cache/sha256.js +97 -0
- package/dist/cache/shard-store.d.ts +89 -0
- package/dist/cache/shard-store.js +204 -0
- package/dist/contracts/budgets.d.ts +41 -0
- package/dist/contracts/budgets.js +48 -0
- package/dist/contracts/errors.d.ts +43 -0
- package/dist/contracts/errors.js +2 -0
- package/dist/contracts/grant.d.ts +47 -0
- package/dist/contracts/grant.js +44 -0
- package/dist/contracts/index.d.ts +6 -0
- package/dist/contracts/index.js +7 -0
- package/dist/contracts/leases.d.ts +20 -0
- package/dist/contracts/leases.js +14 -0
- package/dist/contracts/lifecycle.d.ts +88 -0
- package/dist/contracts/lifecycle.js +12 -0
- package/dist/contracts/manifest.d.ts +95 -0
- package/dist/contracts/manifest.js +174 -0
- package/dist/handles/cross-tab.d.ts +16 -0
- package/dist/handles/cross-tab.js +29 -0
- package/dist/handles/handle.d.ts +24 -0
- package/dist/handles/handle.js +93 -0
- package/dist/handles/index.d.ts +3 -0
- package/dist/handles/index.js +4 -0
- package/dist/handles/leases.d.ts +45 -0
- package/dist/handles/leases.js +103 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +7 -0
- package/package.json +43 -4
- package/schema/model-manifest.v1.schema.json +215 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `browser-model-manager` are recorded here. Versions follow [semantic versioning](https://semver.org/);
|
|
4
|
+
while the major version is 0, a minor release may break the API and a patch release does not. A published version
|
|
5
|
+
is never changed: a fix is a new version. Each tarball carries `PROVENANCE.json`, naming the commit and the digest
|
|
6
|
+
of the `dist/` it was built from ([releasing](../../docs/packages/RELEASING.md)).
|
|
7
|
+
|
|
8
|
+
## 0.1.0 (not yet published)
|
|
9
|
+
|
|
10
|
+
First release.
|
|
11
|
+
|
|
12
|
+
- Acquisition only after the app or person authorizes it; construction and status reads make no request.
|
|
13
|
+
- Verified local storage in OPFS, with a Cache Storage fallback; quota checks, eviction and reference-counted leases.
|
|
14
|
+
- A verified local reader the engine loads models through, and typed invalidation.
|
|
15
|
+
- The model manifest schema (`schema/model-manifest.v1.schema.json`).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chris Dilger
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/PROVENANCE.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "facemorph.package-provenance/2",
|
|
3
|
+
"name": "browser-model-manager",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"sourceCommit": "59a1544aaca0cf1fedd5bc96883ffeec76e49d60",
|
|
6
|
+
"sourceTreeClean": true,
|
|
7
|
+
"sourceIdentity": "d5c5b8ee6262f039ae2f3669df0e14c829ce087416b4ee4044cde4d6d2867c8b",
|
|
8
|
+
"distSha256": "225e340e358795932e5db8ccb4e2974d63ba88e3c96ab2811daabbd9e75bc3b7",
|
|
9
|
+
"distFiles": 44,
|
|
10
|
+
"build": {
|
|
11
|
+
"repository": "facemorph-me/facemorph.me",
|
|
12
|
+
"runId": "46234816541",
|
|
13
|
+
"runAttempt": "1",
|
|
14
|
+
"workflow": "packages"
|
|
15
|
+
}
|
|
16
|
+
}
|
package/README.md
CHANGED
|
@@ -1,3 +1,608 @@
|
|
|
1
|
-
#
|
|
1
|
+
# browser-model-manager
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Consented acquisition, verification, storage and eviction of browser model assets, and the model manifest schema
|
|
4
|
+
(`schema/`). It downloads model files from the static origin you host them on, only under a grant the app or the
|
|
5
|
+
developer has approved, checks every byte against the manifest's SHA-256 pins, stores verified bytes in the Origin
|
|
6
|
+
Private File System (OPFS) or Cache Storage, and hands an engine such as `stylegan-js` a reader of
|
|
7
|
+
verified local bytes that never touches the network.
|
|
8
|
+
|
|
9
|
+
**No hidden network repair happens during engine operations.** The engine reads only through the verified local
|
|
10
|
+
reader (`cache.local`, `allowRepair: false`), which has no network path: a missing, evicted or corrupt asset is a
|
|
11
|
+
typed error, and the operations that needed it settle and release their resources. Getting the bytes back is a new
|
|
12
|
+
acquisition, which the app starts outside the engine under its own consent policy.
|
|
13
|
+
|
|
14
|
+
What the package provides: the implemented cache (`createModelCache`, `createBrowserModelCache`), grant
|
|
15
|
+
enforcement, the aggregate download budget, whole-acquisition progress, leases, loaded handles, eviction and
|
|
16
|
+
cross-tab deletion, plus the contract types (`ModelManager`, `ManagerStatus`, `ManagerError`, …) that an app's own
|
|
17
|
+
manager object is written against. The package does not decide consent, priorities or retention; the app does, and
|
|
18
|
+
these pieces enforce what it decides.
|
|
19
|
+
|
|
20
|
+
Every export is listed in the [API reference](docs/api.md). [`examples/developer-hosted`](examples/developer-hosted)
|
|
21
|
+
is the complete, tested browser example.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
<!-- docs-test: install -->
|
|
26
|
+
```sh
|
|
27
|
+
npm install browser-model-manager
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
ESM only, with `.d.ts` declarations. It depends on `stylegan-js` for the engine's types (the loaded
|
|
31
|
+
capability and compute routes); importing the manager does no I/O.
|
|
32
|
+
|
|
33
|
+
## Authorize, then acquire
|
|
34
|
+
|
|
35
|
+
Construction and status reads trigger no acquisition. Nothing is transferred until the app (or you, as the
|
|
36
|
+
developer) supplies an approved `AcquisitionGrant`:
|
|
37
|
+
|
|
38
|
+
- `createModelCache({ store, shards, fetcher, … })` makes no request and no storage call. Storage backends and the
|
|
39
|
+
fetch function are arguments. `createBrowserModelCache()` opens this origin's Cache Storage and probes OPFS with a
|
|
40
|
+
four-byte local round trip; it makes no network request either.
|
|
41
|
+
- `cache.has(asset)`, `cache.local.read(asset)` and `storageStatus()` read local state only.
|
|
42
|
+
- `cache.acquire(asset, { grant, owner, signal })` transfers bytes only when the grant names `owner`, names the
|
|
43
|
+
asset's exact digest and size, and still has the bytes. Otherwise it rejects with `GrantRefused` before any request
|
|
44
|
+
(`no-grant`, `owner-not-in-grant`, `out-of-scope`, `revision-required`).
|
|
45
|
+
|
|
46
|
+
A grant is what a person was shown: the manifest identity, the compute route, the purpose, each asset's digest and
|
|
47
|
+
bytes with its priority, the owners, and `remainingBytes`, the bytes still to transfer. Every byte received counts
|
|
48
|
+
against it: retries, alternate origins and refetched chunks included. Each chunk is reserved before it is requested,
|
|
49
|
+
so a grant that cannot cover the next chunk is refused with `revision-required` before that request. Nothing the
|
|
50
|
+
cache does adds to a grant; more scope is a new grant object after a new decision. A grant's ledger lives in the
|
|
51
|
+
JS realm that spends it (a window or one worker), so give each worker its own grant for the share it may spend.
|
|
52
|
+
`scopeCovers(grant, request)` and `inventoryAction(inventory, decision)` express the same rules for an app's policy
|
|
53
|
+
code; an `unknown` inventory means inspect, never fetch.
|
|
54
|
+
|
|
55
|
+
<!-- docs-test: run examples/readme/authorize-then-acquire.ts -->
|
|
56
|
+
```ts
|
|
57
|
+
// Construct, read status, authorize, acquire with progress, then read back verified bytes.
|
|
58
|
+
// Storage and the network are in memory here so this runs anywhere (the docs test runs it in Node with every
|
|
59
|
+
// network API refused). In a browser, use createBrowserModelCache() and the default fetch.
|
|
60
|
+
import {
|
|
61
|
+
createAcquisitionBudget,
|
|
62
|
+
createModelCache,
|
|
63
|
+
GrantRefused,
|
|
64
|
+
grantRemaining,
|
|
65
|
+
type AcquisitionGrant,
|
|
66
|
+
type BlobStore,
|
|
67
|
+
type Fetcher,
|
|
68
|
+
} from 'browser-model-manager';
|
|
69
|
+
|
|
70
|
+
const check = (ok: boolean, message: string) => {
|
|
71
|
+
if (!ok) throw new Error(message);
|
|
72
|
+
};
|
|
73
|
+
const sha256 = async (bytes: Uint8Array<ArrayBuffer>) =>
|
|
74
|
+
Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (x) =>
|
|
75
|
+
x.toString(16).padStart(2, '0'),
|
|
76
|
+
).join('');
|
|
77
|
+
|
|
78
|
+
// One model file on your own static origin, pinned by digest and exact size.
|
|
79
|
+
const file = new Uint8Array(3 * 1024 * 1024).map((_, i) => (i * 7) % 251);
|
|
80
|
+
const asset = {
|
|
81
|
+
sha256: await sha256(file),
|
|
82
|
+
size: file.byteLength,
|
|
83
|
+
url: 'https://models.example.com/demo/weights.bin',
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// The network and storage, handed in. Every request is counted.
|
|
87
|
+
const requests: string[] = [];
|
|
88
|
+
const fetcher: Fetcher = async (url) => {
|
|
89
|
+
requests.push(url);
|
|
90
|
+
let at = 0;
|
|
91
|
+
const body = new ReadableStream<Uint8Array>({
|
|
92
|
+
pull(c) {
|
|
93
|
+
if (at >= file.byteLength) return c.close();
|
|
94
|
+
c.enqueue(file.slice(at, (at += 256 * 1024))); // arrives in pieces, as over a network
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
return new Response(body);
|
|
98
|
+
};
|
|
99
|
+
const saved = new Map<string, Uint8Array<ArrayBuffer>>();
|
|
100
|
+
const store: BlobStore = {
|
|
101
|
+
get: async (hash) => (saved.has(hash) ? new Response(saved.get(hash)) : undefined),
|
|
102
|
+
// Commits only after the whole body has been read, and the cache's verifying stream fails before EOF on a wrong
|
|
103
|
+
// size or digest, so nothing partial or unverified is ever stored.
|
|
104
|
+
put: async (hash, response) => {
|
|
105
|
+
saved.set(hash, new Uint8Array(await response.arrayBuffer()));
|
|
106
|
+
},
|
|
107
|
+
remove: async (hash) => saved.delete(hash),
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// Progress for the whole acquisition: the cache reports byte-level events to it.
|
|
111
|
+
const progress = createAcquisitionBudget();
|
|
112
|
+
const bar: string[] = [];
|
|
113
|
+
progress.attach((t) => bar.push(`${t.loaded}/${t.total}`));
|
|
114
|
+
|
|
115
|
+
// 1. Construction and status reads: no request, no transfer.
|
|
116
|
+
const cache = createModelCache({ store, fetcher, report: (event) => progress.cacheEvent(event) });
|
|
117
|
+
progress.planAsset([asset]);
|
|
118
|
+
await progress.probe((a) => cache.has(a));
|
|
119
|
+
const before = await cache.local.read(asset);
|
|
120
|
+
check(!before.ok && before.error.code === 'cache-miss', 'nothing is stored yet');
|
|
121
|
+
check(requests.length === 0, 'construction and status made no request');
|
|
122
|
+
|
|
123
|
+
// 2. Without an approved grant naming this owner and digest, acquire() refuses before any request.
|
|
124
|
+
const declined: AcquisitionGrant = {
|
|
125
|
+
manifestSha256: asset.sha256,
|
|
126
|
+
route: 'cpu',
|
|
127
|
+
purpose: 'generate',
|
|
128
|
+
owners: [],
|
|
129
|
+
assets: [],
|
|
130
|
+
remainingBytes: 0,
|
|
131
|
+
};
|
|
132
|
+
const refused = await cache.acquire(asset, { grant: declined, owner: 'face:demo' }).then(
|
|
133
|
+
() => null,
|
|
134
|
+
(e: unknown) => e,
|
|
135
|
+
);
|
|
136
|
+
check(refused instanceof GrantRefused, 'refused without a grant');
|
|
137
|
+
check(requests.length === 0, 'a refusal made no request');
|
|
138
|
+
|
|
139
|
+
// 3. The person approves exactly these bytes (show `remainingBytes` in your consent UI); then acquire.
|
|
140
|
+
const grant: AcquisitionGrant = {
|
|
141
|
+
manifestSha256: asset.sha256,
|
|
142
|
+
route: 'cpu',
|
|
143
|
+
purpose: 'generate',
|
|
144
|
+
owners: ['face:demo'],
|
|
145
|
+
assets: [{ sha256: asset.sha256, bytes: asset.size, priority: 'foreground-required' }],
|
|
146
|
+
remainingBytes: asset.size,
|
|
147
|
+
};
|
|
148
|
+
await cache.acquire(asset, { grant, owner: 'face:demo' });
|
|
149
|
+
|
|
150
|
+
// 4. The verified local reader: exact-length bytes whose SHA-256 matched on this read, and never a fetch.
|
|
151
|
+
const after = await cache.local.read(asset);
|
|
152
|
+
check(after.ok && (await sha256(after.value)) === asset.sha256, 'verified bytes read back');
|
|
153
|
+
check(requests.length === 1, 'one request, made after authorization');
|
|
154
|
+
check(grantRemaining(grant) === 0, 'the grant was spent exactly');
|
|
155
|
+
|
|
156
|
+
console.log(
|
|
157
|
+
JSON.stringify({
|
|
158
|
+
refused: (refused as GrantRefused).refusal,
|
|
159
|
+
requests: requests.length,
|
|
160
|
+
progress: bar,
|
|
161
|
+
grantRemaining: grantRemaining(grant),
|
|
162
|
+
localRead: after.ok ? after.value.byteLength : after.error.code,
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Progress, abort and errors
|
|
168
|
+
|
|
169
|
+
- **Progress.** The cache reports events through its `report` option: status and digest only, never URLs or
|
|
170
|
+
credentials (`missing`, `downloading`, `progress` with `loaded`/`bytes`, `saved`, `retained`, `verified`,
|
|
171
|
+
`migrated`, `quota-exceeded`, `save-failed`, …). `progress` comes after each verified chunk on OPFS, and at
|
|
172
|
+
least every MiB (`PROGRESS_INTERVAL_BYTES`) on the Cache Storage path. `createAcquisitionBudget()` turns them into one
|
|
173
|
+
`{ loaded, total, fetched, fetchedTotal }` for the whole acquisition, so a bar crosses the download once and
|
|
174
|
+
`fetched` counts only bytes that really cross the network.
|
|
175
|
+
- **Abort.** Pass an `AbortSignal`; the acquisition rejects with the signal's reason (an `AbortError` by default).
|
|
176
|
+
Several callers acquiring the same digest share one fetch; it stops when the last of them leaves. On OPFS each
|
|
177
|
+
verified chunk is already its own committed file, so it is kept, and a later acquisition under a new approval
|
|
178
|
+
fetches only the chunks that are missing. In Cache Storage an asset commits only as a whole, after its full
|
|
179
|
+
digest matches. Either way a partly acquired asset is never readable: `local.read` reports it unavailable.
|
|
180
|
+
- **Timeouts and retries.** A pending network operation that receives nothing for `timeoutMs` (default 300 s)
|
|
181
|
+
fails with a `TimeoutError`; a chunk attempt that receives nothing for `stallMs` (default 30 s,
|
|
182
|
+
`CHUNK_STALL_MS`) is abandoned and retried. A dropped connection or an HTTP 5xx, 429 or 408 is retried after
|
|
183
|
+
1, 4, 10 and 20 s (`CHUNK_RETRY_DELAYS_MS`, `retryDelaysMs`), each retry under a fresh query string.
|
|
184
|
+
`alternateOrigins` (empty by default) sends every other retry to the same path on another HTTPS origin you
|
|
185
|
+
configure; with none configured no request leaves the asset's own origin. HTTP 404 or 410 is not retried: model
|
|
186
|
+
files are named by digest, so a missing one belongs to a version the host no longer serves, and the message asks
|
|
187
|
+
the person to reload. Every response is checked against its pin wherever it came from.
|
|
188
|
+
- **Requests** are made with `credentials: 'omit'` and `mode: 'cors'`. Asset URLs must be HTTPS without embedded
|
|
189
|
+
credentials; chunks are at most 16 MiB each and 256 per asset.
|
|
190
|
+
|
|
191
|
+
<!-- docs-test: run examples/readme/abort-and-errors.ts -->
|
|
192
|
+
```ts
|
|
193
|
+
// Abort keeps verified chunks and never yields a partial asset; refusals and failures are typed.
|
|
194
|
+
// The shard store and the network are in memory here so this runs anywhere; in a browser, openShardStore() gives
|
|
195
|
+
// the OPFS store and createBrowserModelCache() wires it up.
|
|
196
|
+
import {
|
|
197
|
+
CacheQuotaExceeded,
|
|
198
|
+
createModelCache,
|
|
199
|
+
GrantRefused,
|
|
200
|
+
type AcquisitionGrant,
|
|
201
|
+
type BlobStore,
|
|
202
|
+
type Fetcher,
|
|
203
|
+
type ShardStore,
|
|
204
|
+
} from 'browser-model-manager';
|
|
205
|
+
|
|
206
|
+
const check = (ok: boolean, message: string) => {
|
|
207
|
+
if (!ok) throw new Error(message);
|
|
208
|
+
};
|
|
209
|
+
const sha256 = async (bytes: Uint8Array<ArrayBuffer>) =>
|
|
210
|
+
Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (x) =>
|
|
211
|
+
x.toString(16).padStart(2, '0'),
|
|
212
|
+
).join('');
|
|
213
|
+
const MiB = 1024 * 1024;
|
|
214
|
+
const base = 'https://models.example.com/demo/';
|
|
215
|
+
|
|
216
|
+
// A 4 MiB asset published as four 1 MiB chunks, each pinned by its own digest.
|
|
217
|
+
const file = new Uint8Array(4 * MiB).map((_, i) => (i * 13) % 251);
|
|
218
|
+
const parts = [0, 1, 2, 3].map((i) => file.slice(i * MiB, (i + 1) * MiB));
|
|
219
|
+
const chunks = await Promise.all(
|
|
220
|
+
parts.map(async (p, i) => ({
|
|
221
|
+
sha256: await sha256(p),
|
|
222
|
+
size: p.byteLength,
|
|
223
|
+
url: `${base}part-${i}`,
|
|
224
|
+
})),
|
|
225
|
+
);
|
|
226
|
+
const asset = {
|
|
227
|
+
sha256: await sha256(file),
|
|
228
|
+
size: file.byteLength,
|
|
229
|
+
url: `${base}weights.bin`,
|
|
230
|
+
chunks,
|
|
231
|
+
};
|
|
232
|
+
const served = new Map(chunks.map((c, i) => [c.url, parts[i]!]));
|
|
233
|
+
|
|
234
|
+
const requests: string[] = [];
|
|
235
|
+
let onRequest = (_url: string) => {};
|
|
236
|
+
const fetcher: Fetcher = async (url) => {
|
|
237
|
+
requests.push(url);
|
|
238
|
+
onRequest(url);
|
|
239
|
+
return new Response(served.get(url) ?? null, { status: served.has(url) ? 200 : 404 });
|
|
240
|
+
};
|
|
241
|
+
// One file per verified unit, as OPFS keeps them.
|
|
242
|
+
const units = new Map<string, Uint8Array<ArrayBuffer>>();
|
|
243
|
+
let failWrites: DOMException | null = null;
|
|
244
|
+
const shards: ShardStore = {
|
|
245
|
+
read: async (sha, size) => (units.get(sha)?.byteLength === size ? units.get(sha) : undefined),
|
|
246
|
+
has: async (sha, size) => units.get(sha)?.byteLength === size,
|
|
247
|
+
write: async (sha, bytes) => {
|
|
248
|
+
if (failWrites) throw failWrites;
|
|
249
|
+
units.set(sha, new Uint8Array(bytes));
|
|
250
|
+
},
|
|
251
|
+
remove: async (sha) => void units.delete(sha),
|
|
252
|
+
};
|
|
253
|
+
const store: BlobStore = {
|
|
254
|
+
get: async () => undefined,
|
|
255
|
+
put: async () => {},
|
|
256
|
+
remove: async () => {},
|
|
257
|
+
};
|
|
258
|
+
const cache = createModelCache({ store, shards, fetcher, readAhead: 1 });
|
|
259
|
+
const grantFor = (remainingBytes: number, owner: `face:${string}`): AcquisitionGrant => ({
|
|
260
|
+
manifestSha256: asset.sha256,
|
|
261
|
+
route: 'cpu',
|
|
262
|
+
purpose: 'generate',
|
|
263
|
+
owners: [owner],
|
|
264
|
+
assets: [{ sha256: asset.sha256, bytes: asset.size, priority: 'foreground-required' }],
|
|
265
|
+
remainingBytes,
|
|
266
|
+
});
|
|
267
|
+
const outcome = (p: Promise<unknown>) =>
|
|
268
|
+
p.then(
|
|
269
|
+
() => null,
|
|
270
|
+
(e: unknown) => e as Error,
|
|
271
|
+
);
|
|
272
|
+
|
|
273
|
+
// Abort while the third chunk is being requested: the two verified chunks stay, the asset is not readable.
|
|
274
|
+
const controller = new AbortController();
|
|
275
|
+
onRequest = (url) => {
|
|
276
|
+
if (url === chunks[2]!.url) controller.abort();
|
|
277
|
+
};
|
|
278
|
+
const aborted = await outcome(
|
|
279
|
+
cache.acquire(asset, {
|
|
280
|
+
grant: grantFor(asset.size, 'face:a'),
|
|
281
|
+
owner: 'face:a',
|
|
282
|
+
signal: controller.signal,
|
|
283
|
+
}),
|
|
284
|
+
);
|
|
285
|
+
onRequest = () => {};
|
|
286
|
+
check(aborted?.name === 'AbortError', 'the acquisition was cancelled');
|
|
287
|
+
const partial = await cache.local.read(asset);
|
|
288
|
+
check(!partial.ok, 'a partly acquired asset is never handed out');
|
|
289
|
+
|
|
290
|
+
// Each chunk is reserved against the grant before it is requested. A grant that cannot cover the next chunk is
|
|
291
|
+
// refused before that request: more scope needs a new decision, and nothing the cache does adds to a grant.
|
|
292
|
+
const before = requests.length;
|
|
293
|
+
const short = await outcome(
|
|
294
|
+
cache.acquire(asset, { grant: grantFor(MiB - 1, 'face:b'), owner: 'face:b' }),
|
|
295
|
+
);
|
|
296
|
+
check(requests.length === before, 'refused before any request');
|
|
297
|
+
check(
|
|
298
|
+
short instanceof GrantRefused && short.refusal === 'revision-required',
|
|
299
|
+
'needs a revised grant',
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
// A new approval for the missing bytes resumes: only the two missing chunks are fetched.
|
|
303
|
+
await cache.acquire(asset, { grant: grantFor(2 * MiB, 'face:c'), owner: 'face:c' });
|
|
304
|
+
const resumed = requests.slice(before);
|
|
305
|
+
const read = await cache.local.read(asset);
|
|
306
|
+
check(read.ok && (await sha256(read.value)) === asset.sha256, 'whole asset verified');
|
|
307
|
+
|
|
308
|
+
// Bytes changed underneath are found by the next local read (every read digests what it returns).
|
|
309
|
+
units.get(chunks[1]!.sha256)![0]! ^= 0xff;
|
|
310
|
+
const corrupt = await cache.local.read(asset);
|
|
311
|
+
check(
|
|
312
|
+
!corrupt.ok && corrupt.error.code === 'corrupt',
|
|
313
|
+
'corruption is a typed error, never a fetch',
|
|
314
|
+
);
|
|
315
|
+
// The remedy is the app's: remove the bad unit, then acquire again under a new approval.
|
|
316
|
+
await shards.remove(chunks[1]!.sha256);
|
|
317
|
+
const repairFrom = requests.length;
|
|
318
|
+
await cache.acquire(asset, { grant: grantFor(MiB, 'face:e'), owner: 'face:e' });
|
|
319
|
+
const repaired = requests.slice(repairFrom);
|
|
320
|
+
check((await cache.local.read(asset)).ok, 'readable again');
|
|
321
|
+
|
|
322
|
+
// A storage refusal is a typed quota error, separate from any execution capability.
|
|
323
|
+
units.clear();
|
|
324
|
+
failWrites = new DOMException('full', 'QuotaExceededError');
|
|
325
|
+
const quota = await outcome(
|
|
326
|
+
cache.acquire(asset, { grant: grantFor(asset.size, 'face:d'), owner: 'face:d' }),
|
|
327
|
+
);
|
|
328
|
+
check(quota instanceof CacheQuotaExceeded && quota.error.code === 'quota', 'typed quota error');
|
|
329
|
+
|
|
330
|
+
console.log(
|
|
331
|
+
JSON.stringify({
|
|
332
|
+
aborted: aborted?.name,
|
|
333
|
+
partialRead: partial.ok ? 'ok' : partial.error.code,
|
|
334
|
+
shortGrant: (short as GrantRefused).refusal,
|
|
335
|
+
resumedRequests: resumed.map((u) => u.slice(base.length)),
|
|
336
|
+
corruptRead: corrupt.ok ? 'ok' : corrupt.error.code,
|
|
337
|
+
repairedRequests: repaired.map((u) => u.slice(base.length)),
|
|
338
|
+
quota: (quota as CacheQuotaExceeded).error,
|
|
339
|
+
totalRequests: requests.length,
|
|
340
|
+
}),
|
|
341
|
+
);
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
## Cache behaviour
|
|
345
|
+
|
|
346
|
+
- **OPFS shards first.** With a working OPFS (`openShardStore()`), each pinned unit, a manifest chunk or an
|
|
347
|
+
unchunked asset up to 64 MiB, is one file in the OPFS directory named by `SHARD_DIRECTORY`: the
|
|
348
|
+
payload followed by a 48-byte trailer (magic, length, digest) written last, so an interrupted write reads as
|
|
349
|
+
missing. The trailer is a commit record, not a verdict: every read digests every unit with the platform SHA-256
|
|
350
|
+
against the manifest's pin, every time.
|
|
351
|
+
- **Cache Storage fallback.** `openShardStore()` returns null where OPFS cannot be used (for example Firefox
|
|
352
|
+
private windows, older engines, non-HTTP origins such as native WebViews, denied storage, or an engine that exposes
|
|
353
|
+
`getDirectory` but refuses writes); the cache then keeps everything in the Cache Storage cache named by `MODEL_CACHE_NAME`.
|
|
354
|
+
Unchunked assets over 64 MiB stay in Cache Storage even with OPFS. Writes stream through a verifier and commit only
|
|
355
|
+
after the whole asset's size and digest match. Bytes found in Cache Storage for an asset that now belongs in OPFS
|
|
356
|
+
are moved there without a download, unit by unit, each checked against its pin.
|
|
357
|
+
- **Safari worker sync handles.** Where a file handle has no `createWritable()` (older Safari), the shard store
|
|
358
|
+
writes with `createSyncAccessHandle()`, which exists only in dedicated workers: run acquisition in a worker there.
|
|
359
|
+
The payload is flushed before the trailer, so a crash part-way leaves no valid trailer. This path is implemented
|
|
360
|
+
but unqualified: every engine in the test lanes also exposes `createWritable()`, which the store prefers. On the
|
|
361
|
+
main thread,
|
|
362
|
+
`openShardStore({ readOnly: true })` reads the shards workers wrote, never creating the directory and never
|
|
363
|
+
acquiring.
|
|
364
|
+
- **Verified local reads.** `cache.local.read(asset)` returns exact-length bytes whose SHA-256 matched on this
|
|
365
|
+
read, or a typed error: `cache-miss` (never stored, as far as this cache can tell), `evicted` (stored before, or
|
|
366
|
+
some of its units remain), `corrupt` (wrong bytes), or `unknown-status` (storage could not be read; retryable,
|
|
367
|
+
never permission to fetch). Presence alone (`has()`, a committed trailer) never vouches for bytes.
|
|
368
|
+
- **Names and identity.** Both storage names are fixed, never app-versioned or age-purged; assets are addressed by
|
|
369
|
+
SHA-256, so renaming or moving files on your host does not invalidate what is stored.
|
|
370
|
+
- **What `acquire()` returns.** `acquire()` resolves with an `AssetHandle` whose `bytes()` and `open()` may refetch
|
|
371
|
+
a vanished or corrupt unit under that caller's own grant. It is for the app's acquisition code; never hand it to
|
|
372
|
+
an engine. The engine gets `cache.local`.
|
|
373
|
+
|
|
374
|
+
## Quota and eviction
|
|
375
|
+
|
|
376
|
+
- `storageStatus()` reports `persistence` (`granted`, `not-granted` or `unavailable`), `usage` and `quota` from
|
|
377
|
+
`navigator.storage`, and `eviction: 'unknown'`: the browser does not say when it will reclaim storage. It asks for
|
|
378
|
+
persistent storage only with `{ requestPersistence: true }`; call that from your UI after the person has approved
|
|
379
|
+
the download, never at startup.
|
|
380
|
+
- A storage refusal rejects with `CacheQuotaExceeded` (`name` `QuotaExceededError`, the original `cause`, and
|
|
381
|
+
`error: { code: 'quota', requiredBytes, message }`, which is structured-clone safe). It is separate from execution
|
|
382
|
+
capability: the model can still run without durable storage.
|
|
383
|
+
- Without usable storage at all (`createBrowserModelCache()` throws where Cache Storage is unavailable),
|
|
384
|
+
`acquireUncachedBytes(asset, { grant, owner, signal })` downloads and verifies one asset for immediate use without
|
|
385
|
+
reading or writing persistent storage, still under the grant and the aggregate budget.
|
|
386
|
+
- `evictUnleased(digests, stores, registry, locks?)` removes the assets you name from the stores you pass, skipping
|
|
387
|
+
every leased one; with `navigator.locks` it also skips assets leased in other tabs. A store is anything with
|
|
388
|
+
`remove(sha256)`; remember that on OPFS each chunk is its own unit (the example's `evict()` removes an asset's
|
|
389
|
+
units). Eviction only touches the model stores you pass: app records such as exports or recovery data are never
|
|
390
|
+
part of them.
|
|
391
|
+
- Leases constrain the manager, not the browser: the browser can still clear the origin's storage. The next
|
|
392
|
+
verified read then reports `evicted` or `cache-miss`, and the lease holder is told (below).
|
|
393
|
+
|
|
394
|
+
## Leases and typed invalidation
|
|
395
|
+
|
|
396
|
+
`createLeaseRegistry({ locks: navigator.locks })` counts holders per digest; each leased asset also holds a shared
|
|
397
|
+
Web Lock until its last local lease is released, which is what other tabs' eviction checks. `createLoadedHandle({
|
|
398
|
+
manifestSha256, capability, assets, registry })` wraps an engine capability (for example a stylegan-js `Generator`)
|
|
399
|
+
with leases on the assets it reads. When a leased asset goes away, `registry.invalidate(sha256, cause)` tells every
|
|
400
|
+
holder once, with one manager error and settlement rule per cause (`LEASE_INVALIDATION`):
|
|
401
|
+
|
|
402
|
+
| Cause | Error | Settlement |
|
|
403
|
+
| --- | --- | --- |
|
|
404
|
+
| `browser-eviction` | `evicted` | `fail-pending-and-release` |
|
|
405
|
+
| `corruption` | `corrupt` | `fail-pending-and-release` |
|
|
406
|
+
| `cross-tab-deletion` | `invalidated` | `fail-pending-and-release` |
|
|
407
|
+
| `device-loss` | `invalidated` | `fail-pending-and-dispose-handle` |
|
|
408
|
+
| `worker-loss` | `invalidated` | `fail-pending-and-dispose-handle` |
|
|
409
|
+
|
|
410
|
+
`createLoadedHandle` applies both rules the same way, because the asset is gone either way: the handle rejects its
|
|
411
|
+
pending and later `map`/`synthesize` calls with `HandleUnavailable` (its `error` is the structured manager error),
|
|
412
|
+
disposes the capability's sessions, releases its leases and calls its `onInvalidated` listeners. Nothing is refetched. Explicit deletion, the person's "clear the model cache", is
|
|
413
|
+
`deleteAssets(digests, stores, channel)`: it removes the assets even while leased and announces them on a
|
|
414
|
+
`BroadcastChannel(DELETION_CHANNEL)`; `listenForDeletions(channel, registry)` in every other tab invalidates its
|
|
415
|
+
leases with `cross-tab-deletion`.
|
|
416
|
+
|
|
417
|
+
<!-- docs-test: run examples/readme/leases-and-eviction.ts -->
|
|
418
|
+
```ts
|
|
419
|
+
// Reference-counted leases, eviction that skips leased assets, and typed invalidation when an asset goes anyway.
|
|
420
|
+
// Two lease registries stand for two tabs; BroadcastChannel carries an explicit deletion between them.
|
|
421
|
+
import {
|
|
422
|
+
createLeaseRegistry,
|
|
423
|
+
deleteAssets,
|
|
424
|
+
DELETION_CHANNEL,
|
|
425
|
+
evictUnleased,
|
|
426
|
+
LEASE_INVALIDATION,
|
|
427
|
+
listenForDeletions,
|
|
428
|
+
type LeaseHolder,
|
|
429
|
+
type Removable,
|
|
430
|
+
} from 'browser-model-manager';
|
|
431
|
+
|
|
432
|
+
const check = (ok: boolean, message: string) => {
|
|
433
|
+
if (!ok) throw new Error(message);
|
|
434
|
+
};
|
|
435
|
+
const [x, y] = ['a'.repeat(64), 'b'.repeat(64)]; // asset digests
|
|
436
|
+
const stored = new Set([x, y]);
|
|
437
|
+
const store: Removable = { remove: async (sha) => stored.delete(sha) };
|
|
438
|
+
|
|
439
|
+
// A holder hears once, with the cause and the mapped manager error.
|
|
440
|
+
const heard: string[] = [];
|
|
441
|
+
const holder: LeaseHolder = {
|
|
442
|
+
invalidated: (cause, error) => heard.push(`${cause}:${error.code}`),
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
// Tab A leases x twice (two handles share it) and y once.
|
|
446
|
+
const tabA = createLeaseRegistry();
|
|
447
|
+
const [x1, y1] = tabA.lease(
|
|
448
|
+
[
|
|
449
|
+
{ sha256: x, bytes: 10 },
|
|
450
|
+
{ sha256: y, bytes: 20 },
|
|
451
|
+
],
|
|
452
|
+
holder,
|
|
453
|
+
);
|
|
454
|
+
const [x2] = tabA.lease([{ sha256: x, bytes: 10 }], holder);
|
|
455
|
+
check(tabA.refCount(x) === 2, 'x has two leases');
|
|
456
|
+
|
|
457
|
+
// Manager eviction never removes a leased asset.
|
|
458
|
+
const first = await evictUnleased([x, y], [store], tabA);
|
|
459
|
+
check(first.removed.length === 0 && stored.size === 2, 'leased assets are kept');
|
|
460
|
+
|
|
461
|
+
// Released leases make an asset evictable again; release is idempotent.
|
|
462
|
+
y1!.release();
|
|
463
|
+
y1!.release();
|
|
464
|
+
const second = await evictUnleased([x, y], [store], tabA);
|
|
465
|
+
check(second.removed[0] === y && second.kept[0] === x, 'only the unleased asset is evicted');
|
|
466
|
+
|
|
467
|
+
// The person clears the model cache in tab B: deletion removes even leased assets and tells the other tabs,
|
|
468
|
+
// whose leases are invalidated with a typed cause. Nothing is refetched.
|
|
469
|
+
const tabB = new BroadcastChannel(DELETION_CHANNEL);
|
|
470
|
+
const listening = new BroadcastChannel(DELETION_CHANNEL);
|
|
471
|
+
const delivered = new Promise<void>((resolve) =>
|
|
472
|
+
listening.addEventListener('message', () => resolve(), { once: true }),
|
|
473
|
+
);
|
|
474
|
+
const stop = listenForDeletions(listening, tabA);
|
|
475
|
+
await deleteAssets([x], [store], tabB);
|
|
476
|
+
await delivered;
|
|
477
|
+
stop();
|
|
478
|
+
tabB.close();
|
|
479
|
+
listening.close();
|
|
480
|
+
check(!stored.has(x), 'deleted');
|
|
481
|
+
check(heard[0] === 'cross-tab-deletion:invalidated', 'the holder heard a typed invalidation');
|
|
482
|
+
|
|
483
|
+
// Browser eviction or corruption found underneath a lease maps to its own error the same way.
|
|
484
|
+
tabA.invalidate(x, 'browser-eviction');
|
|
485
|
+
x1!.release();
|
|
486
|
+
x2!.release();
|
|
487
|
+
check(tabA.leased().length === 0, 'every lease released');
|
|
488
|
+
|
|
489
|
+
console.log(
|
|
490
|
+
JSON.stringify({
|
|
491
|
+
firstEviction: first,
|
|
492
|
+
secondEviction: { removed: second.removed.length, kept: second.kept.length },
|
|
493
|
+
heard,
|
|
494
|
+
mapping: LEASE_INVALIDATION,
|
|
495
|
+
}),
|
|
496
|
+
);
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
## Disposal
|
|
500
|
+
|
|
501
|
+
`handle.release()` (or the wrapped `capability.dispose()`) settles every pending operation with `HandleUnavailable`,
|
|
502
|
+
disposes the engine's sessions, then releases the leases; it is idempotent. Released assets become evictable. A
|
|
503
|
+
`LeaseRegistry` lease's own `release()` is idempotent too. The cache itself holds no sessions; dropping it is enough
|
|
504
|
+
once no acquisition is in flight (abort those first).
|
|
505
|
+
|
|
506
|
+
## Scheduling
|
|
507
|
+
|
|
508
|
+
Acquisitions are bounded per tab and per origin. `maxConcurrent` (default 2) assets download at once, each with
|
|
509
|
+
`readAhead` (default 2, at most 8) chunks in flight. `createAcquisitionSlots({ locks: navigator.locks, count })` adds
|
|
510
|
+
one aggregate budget shared by every worker and tab of the origin, sized by `slotCount(acquisitionMemoryClass(
|
|
511
|
+
navigator.deviceMemory))` (2 chunks, or 4 with 8 GiB or more); `createBrowserModelCache()` sets it up. Each grant
|
|
512
|
+
asset carries a priority (`foreground-required`, `synthesis-prerequisite`, `detector-prerequisite`, `optional`,
|
|
513
|
+
`speculative-warming`); optional work never waits in a lock queue ahead of required work. `satisfyAction(lookup,
|
|
514
|
+
acquire)` serves an action from the app's own output cache first and acquires only on a miss.
|
|
515
|
+
|
|
516
|
+
## Manifests
|
|
517
|
+
|
|
518
|
+
`parseModelManifest(json)` validates a model manifest (major version 1) and returns a typed result: an unknown or
|
|
519
|
+
newer major is rejected, asset locations must be HTTPS URLs without credentials (or relative files with
|
|
520
|
+
`{ unpublished: true }`, as a converter checks its own output), digests are lowercase hex SHA-256 and chunk sizes
|
|
521
|
+
must add up. The JSON schema producers validate against is `schema/model-manifest.v1.schema.json`.
|
|
522
|
+
|
|
523
|
+
## Errors
|
|
524
|
+
|
|
525
|
+
| Error | Where | Meaning |
|
|
526
|
+
| --- | --- | --- |
|
|
527
|
+
| `GrantRefused` (`refusal`, `sha256`) | `acquire`, `acquireUncachedBytes` | No approved scope for this transfer; thrown before the request. `revision-required` needs a new approval. |
|
|
528
|
+
| `AbortError` (`DOMException`) | `acquire` | The caller's signal aborted. |
|
|
529
|
+
| `TimeoutError` (`DOMException`) | `acquire` | A pending network operation got no data for `timeoutMs`. |
|
|
530
|
+
| `Error`, message "The model download stopped receiving data…" | `acquire` | A chunk stayed silent for `stallMs` on every retry. |
|
|
531
|
+
| `Error`, message "Asset integrity mismatch" or "Asset exceeds declared size" | `acquire` | Bytes did not match the pin; nothing was stored. |
|
|
532
|
+
| `Error` with an HTTP status in its message | `acquire` | The host refused; 5xx/429/408 were retried first, 404/410 ask for a reload. |
|
|
533
|
+
| `CacheQuotaExceeded` (`error.code: 'quota'`) | `acquire` | Storage refused the write. |
|
|
534
|
+
| `ManagerError` result: `cache-miss`, `evicted`, `corrupt`, `unknown-status` | `local.read` | Typed local outcome; never a fetch. |
|
|
535
|
+
| `HandleUnavailable` (`error`: `ManagerError`) | loaded handle operations | The handle was released or invalidated. |
|
|
536
|
+
| `ManifestError` result (`code`, `path`) | `parseModelManifest` | `not-an-object`, `newer-major`, `unsupported-major`, `invalid-field`, `invalid-asset`. |
|
|
537
|
+
|
|
538
|
+
`ManagerError` and `Result` values are plain objects, safe to post between a worker and the page.
|
|
539
|
+
|
|
540
|
+
## Example: a model from your own static origin
|
|
541
|
+
|
|
542
|
+
[`examples/developer-hosted`](examples/developer-hosted) is a page that constructs the cache and reads its status
|
|
543
|
+
with zero requests; on "Review download" fetches the two small manifests from your static origin and shows the
|
|
544
|
+
grant's exact bytes; on approval acquires the converted model and the CPU runtime with a progress bar and an Abort
|
|
545
|
+
button; reads every asset back through the verified local reader; loads `stylegan-js` on the CPU from
|
|
546
|
+
those reads alone, under leases, and synthesizes one image; and then releases and evicts. Its test
|
|
547
|
+
(`test/example.test.ts`) runs it from freshly packed tarballs in a clean project with Playwright Chromium against a
|
|
548
|
+
local static HTTPS host and checks each of those steps by the requests actually made.
|
|
549
|
+
|
|
550
|
+
## Supported browsers
|
|
551
|
+
|
|
552
|
+
Qualified by this package's own browser tests:
|
|
553
|
+
|
|
554
|
+
| Lane | Engines | What runs |
|
|
555
|
+
| --- | --- | --- |
|
|
556
|
+
| Linux, Playwright builds (`manager-cache` CI) | Chromium, Firefox, WebKit | Verified local reads on OPFS and Cache Storage, acquisition (grants, retries, slots, cancellation, deadlines), cross-tab leases and deletion, worker OPFS storage, persistence-request timing, storage refusal and uncached runs; the loaded CPU handle lifecycle |
|
|
557
|
+
| Hosted macOS (`manager-macos`) | Playwright WebKit, Firefox | The same component files, and the loaded CPU handle lifecycle |
|
|
558
|
+
| Android Emulator (`manager-mobile`) | Chrome | Native mobile component cells |
|
|
559
|
+
| iOS Simulator (`manager-mobile`) | Safari | Native mobile component cells |
|
|
560
|
+
|
|
561
|
+
Explicitly untested in those lanes, and so unqualified: the quota-override cells outside Chromium (they need
|
|
562
|
+
Chromium's quota controller), Safari's sync-handle-only write path where the engine also exposes `createWritable`
|
|
563
|
+
(current engines do, so the package uses that), physical-phone OPFS throughput and quota, and some native quota cells
|
|
564
|
+
on iOS. Every other browser, version and platform, including Edge and Windows, is unqualified.
|
|
565
|
+
|
|
566
|
+
## Troubleshooting
|
|
567
|
+
|
|
568
|
+
- **`GrantRefused` with no request.** The grant does not name this owner, digest or exact size, or it is spent. Build
|
|
569
|
+
a new grant from the current manifest and ask again; a cancelled or partly spent grant is never topped up.
|
|
570
|
+
- **The bar sits at the full size with nothing downloading.** Assets already stored are `retained`; `fetched` and
|
|
571
|
+
`fetchedTotal` from `createAcquisitionBudget()` count only real downloads.
|
|
572
|
+
- **CORS or opaque-response errors.** Serve model files with `Access-Control-Allow-Origin` for your app's origin, and
|
|
573
|
+
with `Cross-Origin-Resource-Policy: cross-origin` if the app is cross-origin isolated. An opaque response is
|
|
574
|
+
refused.
|
|
575
|
+
- **`corrupt` from `local.read`.** The bytes on disk changed. On OPFS the unit stays until you remove it: remove the
|
|
576
|
+
asset (or its units) and acquire again under a new approval, as `abort-and-errors.ts` shows.
|
|
577
|
+
- **`evicted` or `cache-miss` after a restart.** The browser reclaimed storage or a partial acquisition was
|
|
578
|
+
cancelled. Ask for persistence after approval, check `storageStatus()`, and acquire again.
|
|
579
|
+
- **No OPFS (`openShardStore()` returns null).** Expected in private windows and some WebViews; Cache Storage is used.
|
|
580
|
+
On older Safari, acquire in a dedicated worker so sync access handles exist.
|
|
581
|
+
- **Quota.** Show `CacheQuotaExceeded`'s message, free space or run uncached with `acquireUncachedBytes`.
|
|
582
|
+
- **The CPU route runs single-threaded.** That is the engine: serve the app with `Cross-Origin-Opener-Policy:
|
|
583
|
+
same-origin` and `Cross-Origin-Embedder-Policy: require-corp`.
|
|
584
|
+
|
|
585
|
+
## Related packages
|
|
586
|
+
|
|
587
|
+
- [stylegan-js](../stylegan-js/README.md) is the engine that loads the models this package acquires.
|
|
588
|
+
- [cloudflare-model-host](../cloudflare-model-host/README.md) stages converted models and writes the hosted manifest
|
|
589
|
+
this package reads, for any HTTPS static host.
|
|
590
|
+
- [model-conv](../model-conv/README.md) converts a trusted StyleGAN2 checkpoint into those files. The
|
|
591
|
+
[compatibility table](../model-conv/docs/compatibility.md) lists the checkpoints that are qualified.
|
|
592
|
+
|
|
593
|
+
## Licence and model weights
|
|
594
|
+
|
|
595
|
+
The code is MIT licensed (`LICENSE`; bundled third-party code in `THIRD_PARTY_NOTICES`). **No model weights are
|
|
596
|
+
included.** The manager downloads them from a model host only after consent, and they come under their own terms,
|
|
597
|
+
separate from this package's licence and limited to non-commercial use:
|
|
598
|
+
|
|
599
|
+
<!-- model-terms:start -->
|
|
600
|
+
- NVIDIA StyleGAN2 licence: [upstream text](https://github.com/NVlabs/stylegan2/blob/master/LICENSE.txt); served beside the weights as `notices/NVIDIA-StyleGAN2-NC.txt`
|
|
601
|
+
- NVIDIA StyleGAN2-ADA licence: [upstream text](https://github.com/NVlabs/stylegan2-ada-pytorch/blob/main/LICENSE.txt); served beside the weights as `notices/NVIDIA-StyleGAN2-ADA.txt`
|
|
602
|
+
- FFHQ dataset terms: [upstream text](https://github.com/NVlabs/ffhq-dataset#licenses); served beside the weights as `notices/FFHQ-terms.txt`
|
|
603
|
+
- e4e MIT licence: [upstream text](https://github.com/omertov/encoder4editing/blob/main/LICENSE); served beside the weights as `notices/e4e-MIT.txt`
|
|
604
|
+
- dlib landmark model notice: [upstream text](https://www.dlib.net/face_landmark_detection_ex.cpp.html); served beside the weights as `notices/index.html#dlib-landmarks`
|
|
605
|
+
<!-- model-terms:end -->
|
|
606
|
+
|
|
607
|
+
A host publishes these texts beside the weights, under `notices/` next to the runtime manifest, and the manifest's
|
|
608
|
+
`distribution.notices` points at their index. Show that link where you ask for download consent.
|