@nojaja/sqlite-vec1-embeddinggemma2-wasm 0.0.0-stage → 0.0.1-build1

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.
Files changed (47) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +90 -2
  3. package/dist/image/jpeg.wasm +0 -0
  4. package/dist/image/png.wasm +0 -0
  5. package/dist/image/resize.wasm +0 -0
  6. package/dist/index-browser.d.ts +3 -0
  7. package/dist/index-browser.mjs +16371 -0
  8. package/dist/index.bundle.js +2170 -0
  9. package/dist/index.d.mts +3 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/node/index.js +2170 -0
  12. package/dist/node/index.mjs +2135 -0
  13. package/dist/official/types.d.ts +144 -0
  14. package/dist/ort/ort-wasm-simd-threaded.jsep.mjs +108 -0
  15. package/dist/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
  16. package/dist/ort/ort-wasm-simd-threaded.jspi.mjs +120 -0
  17. package/dist/ort/ort-wasm-simd-threaded.jspi.wasm +0 -0
  18. package/dist/reports/build-content.json +185 -0
  19. package/dist/reports/esbuild-metafile.json +2255 -0
  20. package/dist/reports/sbom.cdx.json +374 -0
  21. package/dist/runtime-lock.json +96 -0
  22. package/dist/samples/browser/index.mjs +48 -0
  23. package/dist/samples/browser/owner.mjs +16228 -0
  24. package/dist/samples/browser/server.js +69 -0
  25. package/dist/samples/node/index.js +2389 -0
  26. package/dist/sqlite3-bundler-friendly.mjs +21851 -0
  27. package/dist/sqlite3-node.mjs +16572 -0
  28. package/dist/sqlite3-opfs-async-proxy.js +1105 -0
  29. package/dist/sqlite3-worker1-bundler-friendly.mjs +35 -0
  30. package/dist/sqlite3-worker1-promiser.mjs +320 -0
  31. package/dist/sqlite3-worker1.mjs +35 -0
  32. package/dist/sqlite3.mjs +21940 -0
  33. package/dist/sqlite3.wasm +0 -0
  34. package/dist/vendor/transformers-directml-node.js +37007 -0
  35. package/dist/vendor/transformers-portable-node.js +36983 -0
  36. package/dist/vendor/transformers-portable.mjs +37001 -0
  37. package/dist/workers/inference-browser.mjs +1379 -0
  38. package/dist/workers/inference-node.js +7344 -0
  39. package/manifests/embeddinggemma2-q4.json +127 -0
  40. package/manifests/runtime-lock.json +96 -0
  41. package/package.json +143 -4
  42. package/samples/browser/index.ts +80 -0
  43. package/samples/browser/owner.ts +50 -0
  44. package/samples/browser/server.ts +50 -0
  45. package/samples/cli-demo.ts +58 -0
  46. package/samples/node/index.ts +144 -0
  47. package/samples/official-scenario.ts +117 -0
@@ -0,0 +1,1379 @@
1
+ // src/errors.ts
2
+ var VectorError = class extends Error {
3
+ code;
4
+ /**
5
+ * 処理名: VectorErrorコンストラクタ
6
+ * 処理概要: エラーコードを受け取り、nameをVectorError、messageをcodeに設定して初期化する。
7
+ * 実装理由: 仕様に定められたエラーコード形式(messageとcodeが同一)を厳格に保持するため。
8
+ * @param code - 設定するエラーコード。
9
+ */
10
+ constructor(code) {
11
+ super(code);
12
+ this.name = "VectorError";
13
+ this.code = code;
14
+ Object.setPrototypeOf(this, new.target.prototype);
15
+ }
16
+ };
17
+
18
+ // src/bridge/inference-health.ts
19
+ var HEALTH_READY = 1;
20
+ var HEALTH_FAILED = 2;
21
+ var HEALTH_CLOSED = 3;
22
+ function publishInferenceHealth(buffer, state) {
23
+ if (buffer === void 0) {
24
+ return;
25
+ }
26
+ const view = new Int32Array(buffer, 0, 1);
27
+ Atomics.store(view, 0, state);
28
+ Atomics.notify(view, 0);
29
+ }
30
+
31
+ // src/bridge/protocol.ts
32
+ var BUFFER_BYTE_LENGTH = 8192;
33
+ var HEADER_INT32_COUNT = 8;
34
+ var HEADER_BYTE_LENGTH = 32;
35
+ var PROTOCOL_VERSION = 1;
36
+ var STATE_PENDING = 0;
37
+ var STATE_WRITING = 1;
38
+ var STATE_OK = 2;
39
+ var STATE_ERROR = 3;
40
+ function publishResponse(buffer, payload, errorId = 0) {
41
+ if (buffer.byteLength !== BUFFER_BYTE_LENGTH) {
42
+ throw new VectorError("E_PROTOCOL");
43
+ }
44
+ if (errorId === 0) {
45
+ if (payload.byteLength !== 3072) {
46
+ throw new VectorError("E_PROTOCOL");
47
+ }
48
+ } else {
49
+ if (errorId < 1 || errorId > 10 || payload.byteLength > 4096) {
50
+ throw new VectorError("E_PROTOCOL");
51
+ }
52
+ }
53
+ const header = new Int32Array(buffer, 0, HEADER_INT32_COUNT);
54
+ const acquired = Atomics.compareExchange(header, 0, STATE_PENDING, STATE_WRITING);
55
+ if (acquired !== STATE_PENDING) {
56
+ return false;
57
+ }
58
+ new Uint8Array(buffer, HEADER_BYTE_LENGTH).set(payload);
59
+ header[1] = payload.byteLength;
60
+ header[2] = errorId;
61
+ header[3] = errorId === 0 ? 768 : 0;
62
+ header[4] = PROTOCOL_VERSION;
63
+ header[5] = 0;
64
+ header[6] = 0;
65
+ header[7] = 0;
66
+ const targetState = errorId === 0 ? STATE_OK : STATE_ERROR;
67
+ const committed = Atomics.compareExchange(header, 0, STATE_WRITING, targetState);
68
+ if (committed !== STATE_WRITING) {
69
+ return false;
70
+ }
71
+ Atomics.notify(header, 0);
72
+ return true;
73
+ }
74
+
75
+ // src/workers/inference.ts
76
+ var CODE_TO_ERROR_ID = {
77
+ E_INPUT: 1,
78
+ E_TOKEN_LIMIT: 2,
79
+ E_IMAGE_FORMAT: 3,
80
+ E_IMAGE_LIMIT: 4,
81
+ E_EMBEDDING_VALUE: 5,
82
+ E_INFERENCE: 6,
83
+ E_TIMEOUT: 7,
84
+ E_CANCELLED: 8,
85
+ E_MEMORY: 9,
86
+ E_PROTOCOL: 10
87
+ };
88
+ async function handleInferenceRequest(engine, message, generation) {
89
+ const msg = message;
90
+ if (!msg || typeof msg !== "object") {
91
+ return true;
92
+ }
93
+ if (msg.generation !== generation) {
94
+ return false;
95
+ }
96
+ const responseBuffer = msg.responseBuffer;
97
+ if (msg.protocolVersion !== 1 || !responseBuffer) {
98
+ if (responseBuffer instanceof SharedArrayBuffer && responseBuffer.byteLength === 8192) {
99
+ publishResponse(responseBuffer, new Uint8Array(0), 10);
100
+ }
101
+ return true;
102
+ }
103
+ const operation = msg.operation;
104
+ const input = msg.input;
105
+ let engineReq;
106
+ if (operation === "image") {
107
+ let rawBytes = input?.bytes;
108
+ if (rawBytes instanceof ArrayBuffer) {
109
+ rawBytes = new Uint8Array(rawBytes);
110
+ }
111
+ engineReq = {
112
+ operation: "image",
113
+ bytes: rawBytes,
114
+ mime: input?.mime
115
+ };
116
+ } else if (operation === "query" || operation === "document") {
117
+ engineReq = {
118
+ operation,
119
+ body: input?.text,
120
+ title: input?.title
121
+ };
122
+ } else {
123
+ publishResponse(responseBuffer, new Uint8Array(0), 10);
124
+ return true;
125
+ }
126
+ try {
127
+ const res = await engine.embed(engineReq);
128
+ if (res === null) {
129
+ publishResponse(responseBuffer, new Uint8Array(0), 10);
130
+ return true;
131
+ }
132
+ publishResponse(responseBuffer, res);
133
+ return false;
134
+ } catch (err) {
135
+ const code = err?.code ?? "E_INFERENCE";
136
+ const errorId = CODE_TO_ERROR_ID[code] ?? 6;
137
+ publishResponse(responseBuffer, new Uint8Array(0), errorId);
138
+ const isFatal = errorId === 5 || errorId === 6 || errorId === 9 || errorId === 10;
139
+ return isFatal;
140
+ }
141
+ }
142
+
143
+ // src/workers/inference-browser-controller.ts
144
+ var BrowserInferenceController = class {
145
+ host;
146
+ createEngine;
147
+ queue = Promise.resolve();
148
+ engine = null;
149
+ port = null;
150
+ healthBuffer;
151
+ generation = 0;
152
+ closed = false;
153
+ /**
154
+ * 処理名: BrowserInferenceController コンストラクタ
155
+ * 処理概要: ホスト境界およびエンジン生成ファクトリを注入する。
156
+ * @param host - ワーカーホスト境界。
157
+ * @param createEngine - エンジン生成ファクトリ。
158
+ */
159
+ constructor(host, createEngine) {
160
+ this.host = host;
161
+ this.createEngine = createEngine;
162
+ }
163
+ /**
164
+ * 処理名: 制御メッセージ受信
165
+ * 処理概要: 初期化またはクローズメッセージをキューに直列投入して実行する。
166
+ * 実装理由: 非同期タスクの実行順序を保証し、競合状態を排除するため。
167
+ * @param message - 制御メッセージ。
168
+ */
169
+ receiveControl(message) {
170
+ this.queue = this.queue.then(async () => {
171
+ if (message.kind === "initialize") {
172
+ if (this.closed) return;
173
+ await this.handleInitialize(message);
174
+ } else if (message.kind === "close") {
175
+ await this.handleClose();
176
+ }
177
+ });
178
+ }
179
+ /**
180
+ * 処理名: アイドル待機
181
+ * 処理概要: 現在キューに入っているすべての非同期タスクの完了を待機する。
182
+ * 実装理由: テストおよび終了処理で非同期完了を決定論的に同期するため。
183
+ * @returns 完了 Promise。
184
+ */
185
+ async whenIdle() {
186
+ await this.queue;
187
+ }
188
+ /**
189
+ * 処理名: 初期化処理
190
+ * 処理概要: バックエンド検証、エンジン生成、MessagePort 接続、READY 公開を行う。
191
+ * @param init - 初期化パラメーター。
192
+ */
193
+ async handleInitialize(init) {
194
+ this.healthBuffer = init.healthBuffer;
195
+ this.generation = init.generation;
196
+ if (init.backend !== "wasm" && init.backend !== "webgpu") {
197
+ this.host.postMessage({ kind: "failed", code: "E_INPUT" });
198
+ return;
199
+ }
200
+ try {
201
+ this.engine = await this.createEngine(init);
202
+ this.port = init.inferencePort;
203
+ this.port.onmessage = (event) => {
204
+ this.queue = this.queue.then(async () => {
205
+ if (this.closed || !this.engine) return;
206
+ await this.handlePortMessage(event.data);
207
+ });
208
+ };
209
+ if (typeof this.port.start === "function") {
210
+ this.port.start();
211
+ }
212
+ publishInferenceHealth(this.healthBuffer, HEALTH_READY);
213
+ this.host.postMessage({
214
+ kind: "ready",
215
+ backend: init.backend,
216
+ numThreads: 1
217
+ });
218
+ } catch (err) {
219
+ console.error("Browser handleInitialize error:", err);
220
+ this.host.postMessage({
221
+ kind: "progress",
222
+ stage: "init-error",
223
+ errorName: err?.stack ?? String(err)
224
+ });
225
+ publishInferenceHealth(this.healthBuffer, HEALTH_FAILED);
226
+ this.host.postMessage({ kind: "failed", code: "E_INFERENCE" });
227
+ await this.cleanup();
228
+ }
229
+ }
230
+ /**
231
+ * 処理名: ポートメッセージ処理
232
+ * 処理概要: 推論要求を処理し、致命的エラー発生時にはセッションを破棄して FAILED を通知する。
233
+ * @param data - メッセージデータ。
234
+ */
235
+ async handlePortMessage(data) {
236
+ if (!this.engine) return;
237
+ let isFatal = false;
238
+ try {
239
+ isFatal = await handleInferenceRequest(this.engine, data, this.generation);
240
+ } catch {
241
+ isFatal = true;
242
+ }
243
+ if (isFatal) {
244
+ publishInferenceHealth(this.healthBuffer, HEALTH_FAILED);
245
+ this.host.postMessage({ kind: "failed", code: "E_INFERENCE" });
246
+ await this.cleanup();
247
+ }
248
+ }
249
+ /**
250
+ * 処理名: クローズ処理
251
+ * 処理概要: CLOSED ヘルス公開、リソース解放、ホスト終了を実行する。
252
+ */
253
+ async handleClose() {
254
+ publishInferenceHealth(this.healthBuffer, HEALTH_CLOSED);
255
+ await this.cleanup();
256
+ this.host.postMessage({ kind: "closed" });
257
+ this.host.close();
258
+ }
259
+ /**
260
+ * 処理名: 内部リソース解放
261
+ * 処理概要: 推論エンジンおよび MessagePort を安全にクローズする。
262
+ */
263
+ async cleanup() {
264
+ this.closed = true;
265
+ if (this.engine) {
266
+ try {
267
+ await this.engine.close();
268
+ } catch {
269
+ }
270
+ this.engine = null;
271
+ }
272
+ if (this.port) {
273
+ try {
274
+ this.port.close();
275
+ } catch {
276
+ }
277
+ this.port = null;
278
+ }
279
+ }
280
+ };
281
+
282
+ // src/runtime-assets/model-contract.ts
283
+ var MODEL_REPOSITORY = "onnx-community/embeddinggemma-2-ONNX";
284
+ var MODEL_REVISION = "daa72c51243991dfcaf9f9137d2c573d8f7790c0";
285
+ var MODEL_ASSET_FILES = [
286
+ { path: "onnx/model_q4.onnx", source: "model_q4.onnx", mime: "application/octet-stream" },
287
+ { path: "onnx/model_q4.onnx_data", source: "model_q4.onnx_data", mime: "application/octet-stream" },
288
+ { path: "onnx/vision_encoder_q4.onnx", source: "vision_encoder_q4.onnx", mime: "application/octet-stream" },
289
+ { path: "onnx/vision_encoder_q4.onnx_data", source: "vision_encoder_q4.onnx_data", mime: "application/octet-stream" },
290
+ { path: "config.json", source: "config.json", mime: "application/json" },
291
+ { path: "processor_config.json", source: "processor_config.json", mime: "application/json" },
292
+ { path: "preprocessor_config.json", source: "preprocessor_config.json", mime: "application/json" },
293
+ { path: "tokenizer.json", source: "tokenizer.json", mime: "application/json" },
294
+ { path: "tokenizer_config.json", source: "tokenizer_config.json", mime: "application/json" },
295
+ { path: "config_sentence_transformers.json", source: "config_sentence_transformers.json", mime: "application/json" },
296
+ { path: "chat_template.jinja", source: "chat_template.jinja", mime: "text/plain" }
297
+ ];
298
+ var ALLOWED_PATH_SET = new Set(MODEL_ASSET_FILES.map((a) => a.path));
299
+ var SHA256_REGEX = /^[0-9a-f]{64}$/;
300
+ function validateModelAssets(assets) {
301
+ if (!Array.isArray(assets) || assets.length !== 11) {
302
+ throw new VectorError("E_ASSET_INTEGRITY");
303
+ }
304
+ const seenPaths = /* @__PURE__ */ new Set();
305
+ for (const asset of assets) {
306
+ if (!asset || typeof asset.path !== "string" || !ALLOWED_PATH_SET.has(asset.path)) {
307
+ throw new VectorError("E_ASSET_INTEGRITY");
308
+ }
309
+ if (seenPaths.has(asset.path)) {
310
+ throw new VectorError("E_ASSET_INTEGRITY");
311
+ }
312
+ seenPaths.add(asset.path);
313
+ if (typeof asset.bytes !== "number" || !Number.isSafeInteger(asset.bytes) || asset.bytes <= 0 || asset.bytes > Number.MAX_SAFE_INTEGER) {
314
+ throw new VectorError("E_ASSET_INTEGRITY");
315
+ }
316
+ if (typeof asset.sha256 !== "string" || !SHA256_REGEX.test(asset.sha256)) {
317
+ throw new VectorError("E_ASSET_INTEGRITY");
318
+ }
319
+ }
320
+ if (seenPaths.size !== 11) {
321
+ throw new VectorError("E_ASSET_INTEGRITY");
322
+ }
323
+ }
324
+
325
+ // src/runtime-assets/verified-cache.ts
326
+ async function sha256Hex(data) {
327
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
328
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
329
+ }
330
+ var PREFIX_LOCAL = `/models/${MODEL_REPOSITORY}/`;
331
+ var PREFIX_REMOTE = `https://huggingface.co/${MODEL_REPOSITORY}/resolve/${MODEL_REVISION}/`;
332
+ var VerifiedModelCache = class {
333
+ assetMap = /* @__PURE__ */ new Map();
334
+ reader;
335
+ /**
336
+ * 処理名: VerifiedModelCache コンストラクタ
337
+ * 処理概要: 資材一覧を検証し、パスごとの期待サイズおよびハッシュ値をマップに保持する。
338
+ * 実装理由: 読み取りごとのハッシュ検証基盤を構築するため。
339
+ * @param assets - 検証対象の資材ダイジェスト一覧。
340
+ * @param reader - 実資材読み込み非同期関数。
341
+ */
342
+ constructor(assets, reader) {
343
+ validateModelAssets(assets);
344
+ for (const a of assets) {
345
+ this.assetMap.set(a.path, a);
346
+ }
347
+ this.reader = reader;
348
+ }
349
+ /**
350
+ * 処理名: 要求キーの論理パス解決
351
+ * 処理概要: URL またはローカルパスから正規化されたマニフェスト論理パスを抽出する。
352
+ * 実装理由: 許可された 2 プレフィックス以外の任意リクエストやパストラバーサルを遮断するため。
353
+ * @param request - リクエスト文字列または Request オブジェクト。
354
+ * @returns 解決された論理パス、または未許可キーの場合 undefined。
355
+ */
356
+ resolveLogicalPath(request) {
357
+ const urlStr = typeof request === "string" ? request : request.url;
358
+ let relPath;
359
+ if (urlStr.startsWith(PREFIX_LOCAL)) {
360
+ relPath = urlStr.slice(PREFIX_LOCAL.length);
361
+ } else if (urlStr.startsWith(PREFIX_REMOTE)) {
362
+ relPath = urlStr.slice(PREFIX_REMOTE.length);
363
+ } else {
364
+ return void 0;
365
+ }
366
+ if (relPath.includes("..") || relPath.includes("%2e") || relPath.includes("%2E")) {
367
+ return void 0;
368
+ }
369
+ if (!this.assetMap.has(relPath)) {
370
+ return void 0;
371
+ }
372
+ return relPath;
373
+ }
374
+ /**
375
+ * 処理名: キャッシュマッチング (読み込み)
376
+ * 処理概要: リクエストに対応する資材を reader から読み取り、サイズとハッシュを検証して Response を返す。
377
+ * 実装理由: 読み取りごとに毎度完全性を照合し、破損資材の混入を防ぐため。
378
+ * @param request - リクエストキー。
379
+ * @returns 検証済み Response、またはキャッシュミスの場合は undefined。
380
+ */
381
+ async match(request) {
382
+ const logicalPath = this.resolveLogicalPath(request);
383
+ if (!logicalPath) {
384
+ return void 0;
385
+ }
386
+ const expected = this.assetMap.get(logicalPath);
387
+ const data = await this.reader(logicalPath);
388
+ if (data === void 0) {
389
+ return void 0;
390
+ }
391
+ if (data.byteLength !== expected.bytes) {
392
+ throw new VectorError("E_ASSET_INTEGRITY");
393
+ }
394
+ const sha = await sha256Hex(data);
395
+ if (sha.toLowerCase() !== expected.sha256.toLowerCase()) {
396
+ throw new VectorError("E_ASSET_INTEGRITY");
397
+ }
398
+ let mime = "application/octet-stream";
399
+ if (logicalPath.endsWith(".json")) {
400
+ mime = "application/json";
401
+ } else if (logicalPath.endsWith(".jinja")) {
402
+ mime = "text/plain";
403
+ }
404
+ const copy = new Uint8Array(data);
405
+ return new Response(copy, {
406
+ headers: {
407
+ "Content-Length": String(copy.byteLength),
408
+ "Content-Type": mime
409
+ }
410
+ });
411
+ }
412
+ /**
413
+ * 処理名: キャッシュ格納検証 (put)
414
+ * 処理概要: 格納対象の Response 内容が定義されたダイジェストと完全に一致することを検証する。
415
+ * 実装理由: 不正なレスポンスによるキャッシュ汚染を防止するため。
416
+ * @param request - 格納先リクエストキー。
417
+ * @param response - 格納対象 Response。
418
+ * @returns 完了 Promise。
419
+ */
420
+ async put(request, response) {
421
+ const logicalPath = this.resolveLogicalPath(request);
422
+ if (!logicalPath) {
423
+ throw new VectorError("E_ASSET_INTEGRITY");
424
+ }
425
+ const expected = this.assetMap.get(logicalPath);
426
+ const buf = new Uint8Array(await response.arrayBuffer());
427
+ if (buf.byteLength !== expected.bytes) {
428
+ throw new VectorError("E_ASSET_INTEGRITY");
429
+ }
430
+ const sha = await sha256Hex(buf);
431
+ if (sha.toLowerCase() !== expected.sha256.toLowerCase()) {
432
+ throw new VectorError("E_ASSET_INTEGRITY");
433
+ }
434
+ }
435
+ };
436
+
437
+ // src/runtime-assets/browser-model.ts
438
+ async function sha256Hex2(data) {
439
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
440
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
441
+ }
442
+ function isSecureBrowserUrl(parsedUrl) {
443
+ if (parsedUrl.username || parsedUrl.password || parsedUrl.search || parsedUrl.hash) {
444
+ return false;
445
+ }
446
+ if (parsedUrl.protocol === "https:") {
447
+ return true;
448
+ }
449
+ if (parsedUrl.protocol === "http:") {
450
+ const host = parsedUrl.hostname;
451
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]";
452
+ }
453
+ return false;
454
+ }
455
+ function createBrowserModelReader(assets, baseUrl, expectedOriginOrFetcher, fetcher = fetch) {
456
+ const activeFetcher = typeof expectedOriginOrFetcher === "function" ? expectedOriginOrFetcher : fetcher;
457
+ if (!baseUrl.endsWith("/")) {
458
+ throw new VectorError("E_ASSET_INTEGRITY");
459
+ }
460
+ let parsed;
461
+ try {
462
+ parsed = new URL(baseUrl);
463
+ } catch {
464
+ throw new VectorError("E_ASSET_INTEGRITY");
465
+ }
466
+ if (!isSecureBrowserUrl(parsed)) {
467
+ throw new VectorError("E_ASSET_INTEGRITY");
468
+ }
469
+ const assetMap = /* @__PURE__ */ new Map();
470
+ for (const a of assets) {
471
+ assetMap.set(a.path, a);
472
+ }
473
+ return async (logicalPath) => {
474
+ const expected = assetMap.get(logicalPath);
475
+ if (!expected) {
476
+ return void 0;
477
+ }
478
+ const targetUrl = `${baseUrl}${logicalPath}`;
479
+ const res = await activeFetcher(targetUrl, {
480
+ mode: "cors",
481
+ cache: "no-store",
482
+ credentials: "omit"
483
+ });
484
+ if (!res.ok) {
485
+ throw new VectorError("E_ASSET_INTEGRITY");
486
+ }
487
+ const ab = await res.arrayBuffer();
488
+ const bytes = new Uint8Array(ab);
489
+ if (bytes.byteLength !== expected.bytes) {
490
+ throw new VectorError("E_ASSET_INTEGRITY");
491
+ }
492
+ const sha = await sha256Hex2(bytes);
493
+ if (sha.toLowerCase() !== expected.sha256.toLowerCase()) {
494
+ throw new VectorError("E_ASSET_INTEGRITY");
495
+ }
496
+ return new Uint8Array(bytes);
497
+ };
498
+ }
499
+
500
+ // src/inference/browser-initialize.ts
501
+ async function prepareBrowserInference(options) {
502
+ let workerParsed;
503
+ let modelBaseParsed;
504
+ try {
505
+ workerParsed = new URL(options.workerUrl);
506
+ modelBaseParsed = new URL(options.modelBaseUrl);
507
+ } catch {
508
+ throw new VectorError("E_ASSET_INTEGRITY");
509
+ }
510
+ if (!isSecureBrowserUrl(workerParsed) || !isSecureBrowserUrl(modelBaseParsed)) {
511
+ throw new VectorError("E_ASSET_INTEGRITY");
512
+ }
513
+ if (!options.modelBaseUrl.endsWith("/")) {
514
+ throw new VectorError("E_ASSET_INTEGRITY");
515
+ }
516
+ const packageBaseUrl = new URL("../..", workerParsed);
517
+ if (!packageBaseUrl.href.endsWith("/")) {
518
+ packageBaseUrl.href += "/";
519
+ }
520
+ let wasmFileName;
521
+ let factoryFileName;
522
+ if (options.backend === "webgpu") {
523
+ wasmFileName = "dist/ort/ort-wasm-simd-threaded.jspi.wasm";
524
+ factoryFileName = "dist/ort/ort-wasm-simd-threaded.jspi.mjs";
525
+ } else {
526
+ wasmFileName = "dist/ort/ort-wasm-simd-threaded.jsep.wasm";
527
+ factoryFileName = "dist/ort/ort-wasm-simd-threaded.jsep.mjs";
528
+ }
529
+ const wasmUrl = new URL(wasmFileName, packageBaseUrl).href;
530
+ const factoryUrl = new URL(factoryFileName, packageBaseUrl).href;
531
+ const fetcher = options.fetcher ?? fetch;
532
+ async function fetchPackageAsset(relPath) {
533
+ const assetUrl = new URL(relPath, packageBaseUrl).href;
534
+ const res = await fetcher(assetUrl, { cache: "no-store", credentials: "omit" });
535
+ if (!res.ok) {
536
+ throw new VectorError("E_ASSET_INTEGRITY");
537
+ }
538
+ const ab = await res.arrayBuffer();
539
+ return new Uint8Array(ab);
540
+ }
541
+ let jpeg;
542
+ let png;
543
+ let resize;
544
+ try {
545
+ [jpeg, png, resize] = await Promise.all([
546
+ fetchPackageAsset("dist/image/jpeg.wasm"),
547
+ fetchPackageAsset("dist/image/png.wasm"),
548
+ fetchPackageAsset("dist/image/resize.wasm")
549
+ ]);
550
+ } catch (err) {
551
+ if (err instanceof VectorError) throw err;
552
+ throw new VectorError("E_ASSET_INTEGRITY");
553
+ }
554
+ if (!options.persistentCache) {
555
+ throw new VectorError("E_ASSET_INTEGRITY");
556
+ }
557
+ await options.persistentCache.initialize(options.network === "allow" ? "online" : "offline");
558
+ const verifiedCache = new VerifiedModelCache(
559
+ options.assets,
560
+ (logicalPath) => options.persistentCache.read(logicalPath)
561
+ );
562
+ return {
563
+ cache: verifiedCache,
564
+ wasmUrl,
565
+ factoryUrl,
566
+ codecs: { jpeg, png, resize }
567
+ };
568
+ }
569
+ async function configureBrowserGpu(runtime, backend, gpu) {
570
+ if (backend !== "webgpu") {
571
+ return;
572
+ }
573
+ const gpuApi = gpu ?? (typeof navigator !== "undefined" ? navigator.gpu : void 0);
574
+ if (!gpuApi || typeof gpuApi.requestAdapter !== "function") {
575
+ throw new VectorError("E_ENVIRONMENT");
576
+ }
577
+ const adapter = await gpuApi.requestAdapter();
578
+ if (!adapter) {
579
+ throw new VectorError("E_ENVIRONMENT");
580
+ }
581
+ const onnxBackends = runtime.env.backends?.onnx;
582
+ const webgpuEnv = onnxBackends?.webgpu ?? {};
583
+ webgpuEnv.adapter = adapter;
584
+ onnxBackends.webgpu = webgpuEnv;
585
+ }
586
+
587
+ // src/inference/profile.ts
588
+ var EMBEDDING_DIMENSION = 768;
589
+ var EMBEDDING_BYTES = 3072;
590
+ var MAX_TEXT_BYTES = 1024 * 1024;
591
+ var MAX_TITLE_LENGTH = 1024;
592
+ function assertTokenLimit(count) {
593
+ if (!Number.isSafeInteger(count) || count < 0) {
594
+ throw new VectorError("E_PROTOCOL");
595
+ }
596
+ if (count > 2048) {
597
+ throw new VectorError("E_TOKEN_LIMIT");
598
+ }
599
+ }
600
+ function embeddingToBlob(values, shape) {
601
+ if (shape.length !== 2 || shape[0] !== 1 || shape[1] !== EMBEDDING_DIMENSION) {
602
+ throw new VectorError("E_EMBEDDING_VALUE");
603
+ }
604
+ if (values.length !== EMBEDDING_DIMENSION) {
605
+ throw new VectorError("E_EMBEDDING_VALUE");
606
+ }
607
+ let sumSquares = 0;
608
+ for (let i = 0; i < EMBEDDING_DIMENSION; i++) {
609
+ const val = values[i];
610
+ if (!Number.isFinite(val)) {
611
+ throw new VectorError("E_EMBEDDING_VALUE");
612
+ }
613
+ sumSquares += val * val;
614
+ }
615
+ const norm = Math.sqrt(sumSquares);
616
+ if (!Number.isFinite(norm) || norm < 1e-12) {
617
+ throw new VectorError("E_EMBEDDING_VALUE");
618
+ }
619
+ const result = new Uint8Array(EMBEDDING_BYTES);
620
+ const view = new DataView(result.buffer, result.byteOffset, result.byteLength);
621
+ for (let i = 0; i < EMBEDDING_DIMENSION; i++) {
622
+ const normalized = values[i] / norm;
623
+ view.setFloat32(i * 4, normalized, true);
624
+ }
625
+ return result;
626
+ }
627
+ function validateTextContent(text, specialTokens) {
628
+ if (text.includes("\0")) {
629
+ throw new VectorError("E_INPUT");
630
+ }
631
+ for (const token of specialTokens) {
632
+ if (token.length > 0 && text.includes(token)) {
633
+ throw new VectorError("E_INPUT");
634
+ }
635
+ }
636
+ const byteLength = typeof Buffer !== "undefined" ? Buffer.byteLength(text, "utf8") : new TextEncoder().encode(text).length;
637
+ if (byteLength > MAX_TEXT_BYTES) {
638
+ throw new VectorError("E_INPUT");
639
+ }
640
+ }
641
+ function formatTextInput(operation, body, title, specialTokens) {
642
+ if (body === null) {
643
+ return null;
644
+ }
645
+ if (typeof body !== "string") {
646
+ throw new VectorError("E_INPUT");
647
+ }
648
+ if (body.trim().length === 0) {
649
+ throw new VectorError("E_INPUT");
650
+ }
651
+ validateTextContent(body, specialTokens);
652
+ if (operation === "query") {
653
+ return `task: search result | query: ${body}`;
654
+ }
655
+ if (operation === "document") {
656
+ let resolvedTitle = "none";
657
+ if (title !== void 0 && title !== null && title !== "") {
658
+ if (typeof title !== "string" || title.length > MAX_TITLE_LENGTH) {
659
+ throw new VectorError("E_INPUT");
660
+ }
661
+ validateTextContent(title, specialTokens);
662
+ resolvedTitle = title;
663
+ }
664
+ return `title: ${resolvedTitle} | text: ${body}`;
665
+ }
666
+ throw new VectorError("E_INPUT");
667
+ }
668
+
669
+ // src/inference/engine.ts
670
+ var InferenceEngine = class {
671
+ runtime;
672
+ processor = null;
673
+ model = null;
674
+ isClosed = false;
675
+ /**
676
+ * 処理名: InferenceEngine コンストラクタ
677
+ * 処理概要: ランタイムを保持して初期化する。
678
+ * 実装理由: テスト用モックおよび実ランタイムを注入可能にするため。
679
+ * @param runtime - ポータブルランタイムインスタンス。
680
+ */
681
+ constructor(runtime) {
682
+ this.runtime = runtime;
683
+ }
684
+ /**
685
+ * 処理名: プロセッサおよびモデルのアタッチ
686
+ * 処理概要: プロセッサとモデルインスタンスをエンジンへ一度だけバインドする。
687
+ * 実装理由: 二重初期化やクローズ後のアタッチを環境エラーとして拒否するため。
688
+ * @param processor - ランタイムプロセッサ。
689
+ * @param model - ランタイムモデル。
690
+ */
691
+ attach(processor, model) {
692
+ if (this.isClosed || this.processor !== null || this.model !== null) {
693
+ throw new VectorError("E_ENVIRONMENT");
694
+ }
695
+ this.processor = processor;
696
+ this.model = model;
697
+ }
698
+ /**
699
+ * 処理名: 埋め込み推論実行
700
+ * 処理概要: 入力前処理、トークン数制限検査、モデル推論、L2 正規化、テンソル破棄を一貫して行う。
701
+ * 実装理由: メモリリークを防止しつつ決定論的な Float32 ベクトル BLOB を生成するため。
702
+ * @param request - 推論要求。
703
+ * @returns 3072 バイトの Float32 BLOB、または NULL。
704
+ */
705
+ async embed(request) {
706
+ if (this.isClosed || !this.processor || !this.model) {
707
+ throw new VectorError("E_ENVIRONMENT");
708
+ }
709
+ let formattedText = null;
710
+ let decodedImage = null;
711
+ if (request.operation === "query" || request.operation === "document") {
712
+ formattedText = formatTextInput(
713
+ request.operation,
714
+ request.body,
715
+ request.title,
716
+ this.processor.tokenizer.all_special_tokens
717
+ );
718
+ if (formattedText === null) {
719
+ return null;
720
+ }
721
+ } else if (request.operation === "image") {
722
+ try {
723
+ decodedImage = await this.runtime.decodeRawImage(
724
+ request.bytes,
725
+ request.mime
726
+ );
727
+ } catch (err) {
728
+ const code = err?.code;
729
+ if (code === "E_IMAGE_FORMAT" || code === "E_IMAGE_LIMIT") {
730
+ throw new VectorError(code);
731
+ }
732
+ if (err instanceof VectorError) {
733
+ throw err;
734
+ }
735
+ throw new VectorError("E_INFERENCE");
736
+ }
737
+ } else {
738
+ throw new VectorError("E_INPUT");
739
+ }
740
+ let inputs;
741
+ try {
742
+ if (decodedImage) {
743
+ inputs = await this.processor(null, decodedImage);
744
+ } else {
745
+ inputs = await this.processor(formattedText, null);
746
+ }
747
+ } catch (err) {
748
+ if (err instanceof VectorError) {
749
+ throw err;
750
+ }
751
+ throw new VectorError("E_INFERENCE");
752
+ }
753
+ const disposables = /* @__PURE__ */ new Set();
754
+ for (const key of Object.keys(inputs)) {
755
+ const val = inputs[key];
756
+ if (typeof val?.dispose === "function") {
757
+ disposables.add(val);
758
+ }
759
+ }
760
+ try {
761
+ if (!inputs.input_ids || !inputs.input_ids.data) {
762
+ throw new VectorError("E_EMBEDDING_VALUE");
763
+ }
764
+ assertTokenLimit(inputs.input_ids.data.length);
765
+ } catch (tokenErr) {
766
+ for (const d of disposables) {
767
+ try {
768
+ d.dispose?.();
769
+ } catch {
770
+ }
771
+ }
772
+ throw tokenErr;
773
+ }
774
+ try {
775
+ const output = await this.model(inputs);
776
+ for (const key of Object.keys(output)) {
777
+ const val = output[key];
778
+ if (typeof val?.dispose === "function") {
779
+ disposables.add(val);
780
+ }
781
+ }
782
+ const emb = output.sentence_embedding;
783
+ if (!emb || !emb.data || !(emb.data instanceof Float32Array) || !Array.isArray(emb.dims) || emb.dims.length !== 2 || emb.dims[0] !== 1 || emb.dims[1] !== 768) {
784
+ throw new VectorError("E_EMBEDDING_VALUE");
785
+ }
786
+ return embeddingToBlob(emb.data, emb.dims);
787
+ } catch (err) {
788
+ if (err instanceof VectorError) {
789
+ throw err;
790
+ }
791
+ throw new VectorError("E_INFERENCE");
792
+ } finally {
793
+ for (const d of disposables) {
794
+ try {
795
+ d.dispose?.();
796
+ } catch {
797
+ }
798
+ }
799
+ }
800
+ }
801
+ /**
802
+ * 処理名: エンジン安全クローズ
803
+ * 処理概要: モデルリソースを破棄し、プロセッサ・モデルへの参照を解除する。
804
+ * 実装理由: セッション終了時の確実なリソース回収と再クローズの安全性を保証するため。
805
+ */
806
+ async close() {
807
+ if (this.isClosed) {
808
+ return;
809
+ }
810
+ this.isClosed = true;
811
+ if (this.model) {
812
+ try {
813
+ await this.model.dispose();
814
+ } catch {
815
+ }
816
+ }
817
+ this.processor = null;
818
+ this.model = null;
819
+ }
820
+ };
821
+
822
+ // src/inference/initialize.ts
823
+ function warmupImageBytes() {
824
+ const base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==";
825
+ if (typeof Buffer !== "undefined") {
826
+ return Uint8Array.from(Buffer.from(base64, "base64"));
827
+ }
828
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
829
+ }
830
+ async function initializeInferenceEngine(runtime, options) {
831
+ const env = runtime.env;
832
+ env.useCustomCache = true;
833
+ env.customCache = options.cache;
834
+ env.useBrowserCache = false;
835
+ env.useFSCache = false;
836
+ env.useFS = false;
837
+ env.allowLocalModels = true;
838
+ env.allowRemoteModels = false;
839
+ env.localModelPath = "/models/";
840
+ env.useWasmCache = false;
841
+ if (options.wasmUrl && options.factoryUrl) {
842
+ const onnx = env.backends?.onnx ?? {};
843
+ onnx.wasm = {
844
+ numThreads: 1,
845
+ proxy: false,
846
+ wasmPaths: {
847
+ wasm: options.wasmUrl,
848
+ mjs: options.factoryUrl
849
+ }
850
+ };
851
+ }
852
+ if (typeof runtime.initializeImageCodecs === "function" && options.codecs) {
853
+ await runtime.initializeImageCodecs(options.codecs);
854
+ }
855
+ const config = await runtime.AutoConfig.from_pretrained(MODEL_REPOSITORY, {
856
+ revision: MODEL_REVISION,
857
+ local_files_only: true
858
+ });
859
+ config.audio_config = null;
860
+ const processor = await runtime.AutoProcessor.from_pretrained(MODEL_REPOSITORY, {
861
+ config,
862
+ revision: MODEL_REVISION,
863
+ local_files_only: true
864
+ });
865
+ const sessionOptions = {
866
+ enableMemPattern: false
867
+ };
868
+ if (options.backend === "directml") {
869
+ sessionOptions.executionMode = "sequential";
870
+ sessionOptions.freeDimensionOverrides = { s11: 1, s35: 2520 };
871
+ sessionOptions.graphOptimizationLevel = options.graphOptimizationLevel ?? "all";
872
+ sessionOptions.logSeverityLevel = 4;
873
+ }
874
+ const modelOptions = {
875
+ device: options.backend === "directml" ? "dml" : options.backend,
876
+ dtype: { model: "q4", vision_encoder: "q4" },
877
+ config,
878
+ revision: MODEL_REVISION,
879
+ local_files_only: true,
880
+ session_options: sessionOptions
881
+ };
882
+ const model = await runtime.AutoModel.from_pretrained(
883
+ MODEL_REPOSITORY,
884
+ modelOptions
885
+ );
886
+ const engine = new InferenceEngine(runtime);
887
+ engine.attach(processor, model);
888
+ try {
889
+ await engine.embed({ operation: "query", body: "warm up" });
890
+ const imgBytes = options.warmupImage ?? warmupImageBytes();
891
+ await engine.embed({ operation: "image", bytes: imgBytes, mime: "image/png" });
892
+ } catch (err) {
893
+ await engine.close();
894
+ if (err instanceof VectorError) {
895
+ throw err;
896
+ }
897
+ throw new VectorError("E_INFERENCE");
898
+ }
899
+ return engine;
900
+ }
901
+
902
+ // src/runtime-assets/browser-opfs-cache-storage.ts
903
+ async function sha256Hex3(data) {
904
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
905
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
906
+ }
907
+ var BrowserOpfsPersistentCacheStorage = class {
908
+ root;
909
+ locks;
910
+ maxWriteBytes;
911
+ /**
912
+ * 処理名: BrowserOpfsPersistentCacheStorage コンストラクタ
913
+ * 処理概要: ルートディレクトリハンドル、Web Locks マネージャー、最大書き込み容量を初期化する。
914
+ * 実装理由: ブラウザ環境下でのモデルキャッシュ I/O 基盤を構築するため。
915
+ * @param root - OPFS ルートディレクトリハンドル。
916
+ * @param locks - Web Locks マネージャー。
917
+ * @param options - ストレージオプション。
918
+ */
919
+ constructor(root, locks, options) {
920
+ this.root = root;
921
+ this.locks = locks;
922
+ this.maxWriteBytes = options?.maxWriteBytes ?? 1024 * 1024;
923
+ }
924
+ /**
925
+ * 処理名: 論理パスセグメント検証
926
+ * 処理概要: 論理パスを検証してセグメント配列へ分解する。traversal や空文字は拒絶する。
927
+ * 実装理由: OPFS ルート外へのエスケープや不正なファイル名を防ぐため。
928
+ * @param logicalPath - 論理パス。
929
+ * @returns 有効なパスセグメント配列。
930
+ */
931
+ parseSegments(logicalPath) {
932
+ if (typeof logicalPath !== "string" || logicalPath.trim().length === 0) {
933
+ throw new VectorError("E_ASSET_INTEGRITY");
934
+ }
935
+ if (logicalPath.includes("\\")) {
936
+ throw new VectorError("E_ASSET_INTEGRITY");
937
+ }
938
+ const segments = logicalPath.split("/");
939
+ for (const seg of segments) {
940
+ if (seg === "" || seg === "." || seg === ".." || !/^[A-Za-z0-9._-]+$/.test(seg)) {
941
+ throw new VectorError("E_ASSET_INTEGRITY");
942
+ }
943
+ }
944
+ return segments;
945
+ }
946
+ /**
947
+ * 処理名: 親ディレクトリおよびファイル名解決
948
+ * 処理概要: セグメントを辿って親ディレクトリハンドルと最終ファイル名を取得する。
949
+ * 実装理由: 階層的な OPFS ハンドル操作を共通化するため。
950
+ * @param segments - パスセグメント配列。
951
+ * @param create - ディレクトリが存在しない場合に自動生成するかどうか。
952
+ * @returns 親ディレクトリハンドルとファイル名。
953
+ */
954
+ async resolveParentAndName(segments, create) {
955
+ let cur = this.root;
956
+ for (let i = 0; i < segments.length - 1; i++) {
957
+ cur = await cur.getDirectoryHandle(segments[i], { create });
958
+ }
959
+ return { dir: cur, name: segments[segments.length - 1] };
960
+ }
961
+ /**
962
+ * 処理名: ファイル存在確認
963
+ * 処理概要: 指定論理パスのファイルが存在するか判定する。
964
+ * 実装理由: ステージングおよび公開ファイルの有無を調べるため。
965
+ * @param logicalPath - 論理パス。
966
+ * @returns 存在時 true、不存在時 false。
967
+ */
968
+ async exists(logicalPath) {
969
+ try {
970
+ const segments = this.parseSegments(logicalPath);
971
+ const { dir, name } = await this.resolveParentAndName(segments, false);
972
+ await dir.getFileHandle(name);
973
+ return true;
974
+ } catch {
975
+ return false;
976
+ }
977
+ }
978
+ /**
979
+ * 処理名: ファイル読み出し
980
+ * 処理概要: ファイルから全バイトを読み取り Uint8Array で返す。
981
+ * 実装理由: キャッシュ資材の読み込みのため。
982
+ * @param logicalPath - 論理パス。
983
+ * @returns 読み取られたバイト配列、または不存在時 undefined。
984
+ */
985
+ async read(logicalPath) {
986
+ const segments = this.parseSegments(logicalPath);
987
+ try {
988
+ const { dir, name } = await this.resolveParentAndName(segments, false);
989
+ const fileHandle = await dir.getFileHandle(name);
990
+ const snapshot = await fileHandle.getFile();
991
+ const ab = await snapshot.arrayBuffer();
992
+ return new Uint8Array(ab);
993
+ } catch (err) {
994
+ if (err?.name === "NotFoundError") {
995
+ return void 0;
996
+ }
997
+ return void 0;
998
+ }
999
+ }
1000
+ /**
1001
+ * 処理名: ファイルダイジェスト計算
1002
+ * 処理概要: ファイルのサイズおよび SHA-256 ダイジェストを計算して返す。
1003
+ * 実装理由: 資材の完全性を照合するため。
1004
+ * @param logicalPath - 論理パス。
1005
+ * @returns 完全性情報、または不存在時 undefined。
1006
+ */
1007
+ async digest(logicalPath) {
1008
+ const segments = this.parseSegments(logicalPath);
1009
+ try {
1010
+ const { dir, name } = await this.resolveParentAndName(segments, false);
1011
+ const fileHandle = await dir.getFileHandle(name);
1012
+ const snapshot = await fileHandle.getFile();
1013
+ const ab = await snapshot.arrayBuffer();
1014
+ const sha = await sha256Hex3(ab);
1015
+ return { bytes: snapshot.size, sha256: sha };
1016
+ } catch {
1017
+ return void 0;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * 処理名: ライター生成
1022
+ * 処理概要: OPFS ファイルへのチャンク書き込みライターを作成する。
1023
+ * 実装理由: 容量制限チェックとアトミックコミットを支援するため。
1024
+ * @param logicalPath - 出力先論理パス。
1025
+ * @returns ArtifactWriter インスタンス。
1026
+ */
1027
+ async createWriter(logicalPath) {
1028
+ const segments = this.parseSegments(logicalPath);
1029
+ const { dir, name } = await this.resolveParentAndName(segments, true);
1030
+ const fileHandle = await dir.getFileHandle(name, { create: true });
1031
+ const writable = await fileHandle.createWritable();
1032
+ const maxBytes = this.maxWriteBytes;
1033
+ return {
1034
+ write: async (chunk) => {
1035
+ if (chunk.byteLength > maxBytes) {
1036
+ throw new VectorError("E_ASSET_INTEGRITY");
1037
+ }
1038
+ await writable.write(chunk);
1039
+ },
1040
+ close: async () => {
1041
+ await writable.close();
1042
+ },
1043
+ abort: async () => {
1044
+ await writable.abort();
1045
+ }
1046
+ };
1047
+ }
1048
+ /**
1049
+ * 処理名: アトミックコミット
1050
+ * 処理概要: ソースファイルを読み取り、ターゲットへチャンク書き込みしてソースを削除する。
1051
+ * 実装理由: OPFS において標準 rename が未提供な環境でも安全にファイルを移動するため。
1052
+ * @param sourcePath - 移動元論理パス。
1053
+ * @param targetPath - 移動先論理パス。
1054
+ */
1055
+ async commit(sourcePath, targetPath) {
1056
+ const srcSegments = this.parseSegments(sourcePath);
1057
+ const dstSegments = this.parseSegments(targetPath);
1058
+ const { dir: srcDir, name: srcName } = await this.resolveParentAndName(srcSegments, false);
1059
+ const srcFile = await srcDir.getFileHandle(srcName);
1060
+ const snapshot = await srcFile.getFile();
1061
+ const data = new Uint8Array(await snapshot.arrayBuffer());
1062
+ const { dir: dstDir, name: dstName } = await this.resolveParentAndName(dstSegments, true);
1063
+ const dstFile = await dstDir.getFileHandle(dstName, { create: true });
1064
+ const writable = await dstFile.createWritable();
1065
+ let offset = 0;
1066
+ while (offset < data.length) {
1067
+ const sliceLen = Math.min(this.maxWriteBytes, data.length - offset);
1068
+ await writable.write(data.subarray(offset, offset + sliceLen));
1069
+ offset += sliceLen;
1070
+ }
1071
+ await writable.close();
1072
+ await srcDir.removeEntry(srcName);
1073
+ }
1074
+ /**
1075
+ * 処理名: ツリー削除
1076
+ * 処理概要: 指定論理パスのエントリを再帰的に削除する。
1077
+ * 実装理由: ステージング領域などの一括クリーンアップのため。
1078
+ * @param prefix - 削除対象プレフィックス。
1079
+ */
1080
+ async removeTree(prefix) {
1081
+ const segments = this.parseSegments(prefix);
1082
+ try {
1083
+ const { dir, name } = await this.resolveParentAndName(segments, false);
1084
+ await dir.removeEntry(name, { recursive: true });
1085
+ } catch {
1086
+ }
1087
+ }
1088
+ /**
1089
+ * 処理名: Web Locks 排他実行
1090
+ * 処理概要: svw-model-cache プレフィックスを付けた Web Lock を取得して処理を実行する。
1091
+ * 実装理由: ブラウザタブ間およびワーカー間でのアーティファクトセット並行ダウンロード排他を行うため。
1092
+ * @param key - 排他キー。
1093
+ * @param action - 実行処理関数。
1094
+ * @returns 処理結果の Promise。
1095
+ */
1096
+ async runExclusive(key, action) {
1097
+ const lockName = `svw-model-cache:${key}`;
1098
+ return this.locks.request(lockName, action);
1099
+ }
1100
+ };
1101
+ async function createBrowserOpfsPersistentCacheStorage(options) {
1102
+ const root = await navigator.storage.getDirectory();
1103
+ const locks = navigator.locks;
1104
+ return new BrowserOpfsPersistentCacheStorage(root, locks, options);
1105
+ }
1106
+
1107
+ // src/runtime-assets/persistent-model-cache.ts
1108
+ var HASH_REGEX = /^[0-9a-f]{64}$/;
1109
+ async function writeInChunks(writer, data, chunkSize) {
1110
+ let offset = 0;
1111
+ while (offset < data.length) {
1112
+ const sliceLen = Math.min(chunkSize, data.length - offset);
1113
+ await writer.write(data.subarray(offset, offset + sliceLen));
1114
+ offset += sliceLen;
1115
+ }
1116
+ }
1117
+ var PersistentModelCache = class {
1118
+ assets;
1119
+ assetMap = /* @__PURE__ */ new Map();
1120
+ artifactSetHash;
1121
+ manifestHash;
1122
+ storage;
1123
+ fetcher;
1124
+ chunkSize;
1125
+ isReady = false;
1126
+ /**
1127
+ * 処理名: PersistentModelCache コンストラクタ
1128
+ * 処理概要: マニフェスト資材ホワイトリスト、ハッシュ値、チャンクサイズを検証して初期化する。
1129
+ * 実装理由: 不正なハッシュや欠損資材によるキャッシュ初期化を遮断するため。
1130
+ * @param options - キャッシュオプション。
1131
+ */
1132
+ constructor(options) {
1133
+ validateModelAssets(options.assets);
1134
+ if (!HASH_REGEX.test(options.artifactSetHash) || !HASH_REGEX.test(options.manifestHash)) {
1135
+ throw new VectorError("E_ASSET_INTEGRITY");
1136
+ }
1137
+ const chunk = options.chunkSize ?? 1024 * 1024;
1138
+ if (!Number.isSafeInteger(chunk) || chunk <= 0) {
1139
+ throw new VectorError("E_ASSET_INTEGRITY");
1140
+ }
1141
+ this.assets = [...options.assets];
1142
+ for (const a of this.assets) {
1143
+ this.assetMap.set(a.path, a);
1144
+ }
1145
+ this.artifactSetHash = options.artifactSetHash;
1146
+ this.manifestHash = options.manifestHash;
1147
+ this.storage = options.storage;
1148
+ this.fetcher = options.fetcher;
1149
+ this.chunkSize = chunk;
1150
+ }
1151
+ /**
1152
+ * 処理名: 既存資材完全性検証
1153
+ * 処理概要: 公開ディレクトリ配下の全 11 資材のサイズと SHA-256 ダイジェストを照合する。
1154
+ * 実装理由: 破損資材の早期検知およびオフラインモードでの整合性保証のため。
1155
+ * @returns 全資材が完全であれば true。
1156
+ */
1157
+ async checkAllAssetsValid() {
1158
+ for (const asset of this.assets) {
1159
+ const filePath = `sets/${this.artifactSetHash}/files/${asset.path}`;
1160
+ const d = await this.storage.digest(filePath);
1161
+ if (!d || d.bytes !== asset.bytes || d.sha256.toLowerCase() !== asset.sha256.toLowerCase()) {
1162
+ return false;
1163
+ }
1164
+ }
1165
+ return true;
1166
+ }
1167
+ /**
1168
+ * 処理名: 単一資材ストリーム取得
1169
+ * 処理概要: fetcher からレスポンスをストリーム取得し、チャンクサイズ以下でライターへ書き込む。
1170
+ * 実装理由: 大容量ファイルの一括メモリ展開を回避し、書き込みバッファ上限を遵守するため。
1171
+ * @param asset - 取得対象資材。
1172
+ */
1173
+ async fetchAndStageAsset(asset) {
1174
+ if (!this.fetcher) {
1175
+ throw new VectorError("E_MODEL_CACHE_MISS");
1176
+ }
1177
+ const res = await this.fetcher(asset);
1178
+ const stageFilePath = `sets/${this.artifactSetHash}/stage/files/${asset.path}`;
1179
+ const writer = await this.storage.createWriter(stageFilePath);
1180
+ try {
1181
+ const reader = res.body?.getReader();
1182
+ if (reader) {
1183
+ while (true) {
1184
+ const { done, value } = await reader.read();
1185
+ if (done) break;
1186
+ if (value) {
1187
+ let offset = 0;
1188
+ while (offset < value.length) {
1189
+ const sliceLen = Math.min(this.chunkSize, value.length - offset);
1190
+ await writer.write(value.subarray(offset, offset + sliceLen));
1191
+ offset += sliceLen;
1192
+ }
1193
+ }
1194
+ }
1195
+ } else {
1196
+ const buf = new Uint8Array(await res.arrayBuffer());
1197
+ let offset = 0;
1198
+ while (offset < buf.length) {
1199
+ const sliceLen = Math.min(this.chunkSize, buf.length - offset);
1200
+ await writer.write(buf.subarray(offset, offset + sliceLen));
1201
+ offset += sliceLen;
1202
+ }
1203
+ }
1204
+ await writer.close();
1205
+ } catch (err) {
1206
+ await writer.abort();
1207
+ throw err;
1208
+ }
1209
+ const d = await this.storage.digest(stageFilePath);
1210
+ if (!d || d.bytes !== asset.bytes || d.sha256.toLowerCase() !== asset.sha256.toLowerCase()) {
1211
+ throw new VectorError("E_ASSET_INTEGRITY");
1212
+ }
1213
+ }
1214
+ /**
1215
+ * 処理名: キャッシュ初期化実行
1216
+ * 処理概要: 指定モード(online, cold, offline)に従い、排他制御下で資材の検証またはダウンロード・コミットを行う。
1217
+ * 実装理由: 並行呼び出しでの二重ダウンロードを防ぎ、アトミックにキャッシュを READY 化するため。
1218
+ * @param mode - 動作モード ("online", "cold", "offline")。
1219
+ */
1220
+ async initialize(mode) {
1221
+ await this.storage.runExclusive(this.artifactSetHash, async () => {
1222
+ const readyPath = `sets/${this.artifactSetHash}/ready.json`;
1223
+ const readyExists = await this.storage.exists(readyPath);
1224
+ if (readyExists) {
1225
+ const allValid = await this.checkAllAssetsValid();
1226
+ if (allValid) {
1227
+ this.isReady = true;
1228
+ return;
1229
+ }
1230
+ if (mode === "offline" || mode === "cold") {
1231
+ throw new VectorError("E_ASSET_INTEGRITY");
1232
+ }
1233
+ } else {
1234
+ if (mode === "offline") {
1235
+ throw new VectorError("E_MODEL_CACHE_MISS");
1236
+ }
1237
+ }
1238
+ if (!this.fetcher) {
1239
+ throw new VectorError("E_MODEL_CACHE_MISS");
1240
+ }
1241
+ const stageStatePath = `sets/${this.artifactSetHash}/stage/state.json`;
1242
+ if (await this.storage.exists(stageStatePath)) {
1243
+ throw new VectorError("E_ASSET_INTEGRITY");
1244
+ }
1245
+ try {
1246
+ const stateWriter = await this.storage.createWriter(stageStatePath);
1247
+ await writeInChunks(
1248
+ stateWriter,
1249
+ new TextEncoder().encode(JSON.stringify({ status: "staging" })),
1250
+ this.chunkSize
1251
+ );
1252
+ await stateWriter.close();
1253
+ for (const asset of this.assets) {
1254
+ await this.fetchAndStageAsset(asset);
1255
+ }
1256
+ const readyWriter = await this.storage.createWriter(`sets/${this.artifactSetHash}/stage/ready.json`);
1257
+ await writeInChunks(
1258
+ readyWriter,
1259
+ new TextEncoder().encode(
1260
+ JSON.stringify({
1261
+ schemaVersion: 1,
1262
+ artifactSetHash: this.artifactSetHash,
1263
+ manifestHash: this.manifestHash
1264
+ })
1265
+ ),
1266
+ this.chunkSize
1267
+ );
1268
+ await readyWriter.close();
1269
+ if (await this.storage.exists(readyPath)) {
1270
+ await this.storage.removeTree(readyPath);
1271
+ }
1272
+ for (const asset of this.assets) {
1273
+ await this.storage.commit(
1274
+ `sets/${this.artifactSetHash}/stage/files/${asset.path}`,
1275
+ `sets/${this.artifactSetHash}/files/${asset.path}`
1276
+ );
1277
+ }
1278
+ await this.storage.commit(
1279
+ `sets/${this.artifactSetHash}/stage/ready.json`,
1280
+ readyPath
1281
+ );
1282
+ await this.storage.removeTree(`sets/${this.artifactSetHash}/stage`);
1283
+ this.isReady = true;
1284
+ } catch (err) {
1285
+ throw new VectorError("E_ASSET_INTEGRITY");
1286
+ }
1287
+ });
1288
+ }
1289
+ /**
1290
+ * 処理名: 明示的キャッシュ復旧
1291
+ * 処理概要: 中断されたステージング領域を排他的に削除し、未 READY 状態へ戻す。他リビジョンや DB は保持する。
1292
+ * 実装理由: 破損または中断されたダウンロード作業の安全な回復のため。
1293
+ */
1294
+ async recover() {
1295
+ await this.storage.runExclusive(this.artifactSetHash, async () => {
1296
+ await this.storage.removeTree(`sets/${this.artifactSetHash}/stage`);
1297
+ this.isReady = false;
1298
+ });
1299
+ }
1300
+ /**
1301
+ * 処理名: キャッシュファイル読み込み
1302
+ * 処理概要: READY 状態を確認後、公開資材ファイルを読み取って返す。
1303
+ * 実装理由: 未検証状態での推論モデル読み込みを防止するため。
1304
+ * @param path - マニフェスト論理パス。
1305
+ * @returns 資材バイナリ、または未知パスの場合 undefined。
1306
+ */
1307
+ async read(path) {
1308
+ if (path.includes("..") || !this.assetMap.has(path)) {
1309
+ return void 0;
1310
+ }
1311
+ if (!this.isReady) {
1312
+ throw new VectorError("E_MODEL_CACHE_MISS");
1313
+ }
1314
+ return this.storage.read(`sets/${this.artifactSetHash}/files/${path}`);
1315
+ }
1316
+ };
1317
+
1318
+ // src/workers/inference-browser.ts
1319
+ var WORKER_NAME = "inference-browser";
1320
+ async function createBrowserEngine(init) {
1321
+ const workerUrl = typeof location !== "undefined" ? location.href : "https://localhost/dist/workers/inference-browser.mjs";
1322
+ const opfsStorage = await createBrowserOpfsPersistentCacheStorage();
1323
+ const reader = createBrowserModelReader(
1324
+ init.manifest.assets,
1325
+ init.modelBaseUrl
1326
+ );
1327
+ const persistentCache = new PersistentModelCache({
1328
+ storage: opfsStorage,
1329
+ fetcher: async (asset) => {
1330
+ const bytes = await reader(asset.path);
1331
+ if (!bytes) {
1332
+ throw new VectorError("E_MODEL_CACHE_MISS");
1333
+ }
1334
+ return new Response(bytes, { status: 200 });
1335
+ },
1336
+ assets: init.manifest.assets,
1337
+ artifactSetHash: init.manifest.artifactSetHash,
1338
+ manifestHash: init.manifest.fingerprint
1339
+ });
1340
+ const prepared = await prepareBrowserInference({
1341
+ workerUrl,
1342
+ modelBaseUrl: init.modelBaseUrl,
1343
+ backend: init.backend,
1344
+ network: init.network,
1345
+ artifactSetHash: init.manifest.artifactSetHash,
1346
+ manifestHash: init.manifest.fingerprint,
1347
+ assets: init.manifest.assets,
1348
+ persistentCache
1349
+ });
1350
+ const runtimeUrl = new URL("../vendor/transformers-portable.mjs", workerUrl).href;
1351
+ const runtime = await import(
1352
+ /* @vite-ignore */
1353
+ runtimeUrl
1354
+ );
1355
+ await configureBrowserGpu(runtime, init.backend);
1356
+ return initializeInferenceEngine(runtime, {
1357
+ backend: init.backend,
1358
+ cache: prepared.cache,
1359
+ wasmUrl: prepared.wasmUrl,
1360
+ factoryUrl: prepared.factoryUrl,
1361
+ codecs: prepared.codecs,
1362
+ warmupImage: warmupImageBytes()
1363
+ });
1364
+ }
1365
+ if (typeof self !== "undefined" && typeof self.addEventListener === "function") {
1366
+ const host = {
1367
+ postMessage: (msg) => self.postMessage(msg),
1368
+ close: () => self.close()
1369
+ };
1370
+ const controller = new BrowserInferenceController(host, createBrowserEngine);
1371
+ self.addEventListener("message", (event) => {
1372
+ const data = event.data;
1373
+ controller.receiveControl(data);
1374
+ });
1375
+ }
1376
+ export {
1377
+ WORKER_NAME,
1378
+ createBrowserEngine
1379
+ };