@p2arthur/webinference-sdk 0.1.0 → 0.1.1

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/dist/index.js CHANGED
@@ -12,8 +12,8 @@ async function e() {
12
12
  }
13
13
  // src/errors.js
14
14
  var t = class extends Error {
15
- constructor(e, t, { operation: n, repo: r, cause: i } = {}) {
16
- super(t, { cause: i }), this.name = "ModelError", this.code = e, this.operation = n, this.repo = r;
15
+ constructor(e, t, { operation: n, repo: r, cause: i, details: a } = {}) {
16
+ super(t, { cause: i }), this.name = "ModelError", this.code = e, this.operation = n, this.repo = r, a && (this.details = a);
17
17
  }
18
18
  };
19
19
  function n(e, n, r) {
@@ -55,11 +55,11 @@ var i = "https://huggingface.co", a = /^[\w.-]+\/[\w.-]+$/, o = /^[a-f0-9]{40}$/
55
55
  "text_encoder/model.onnx",
56
56
  "unet/model.onnx",
57
57
  "vae_decoder/model.onnx"
58
- ], p = [
58
+ ], p = ["tokenizer/tokenizer.json", "tokenizer/tokenizer_config.json"], m = "local/model", h = [
59
59
  "config.json",
60
60
  "tokenizer.json",
61
61
  "tokenizer_config.json"
62
- ], m = /* @__PURE__ */ new Set([
62
+ ], g = /* @__PURE__ */ new Set([
63
63
  "bloom",
64
64
  "falcon",
65
65
  "gemma",
@@ -83,65 +83,70 @@ var i = "https://huggingface.co", a = /^[\w.-]+\/[\w.-]+$/, o = /^[a-f0-9]{40}$/
83
83
  "stablelm",
84
84
  "starcoder2"
85
85
  ]);
86
- function h(e) {
87
- return m.has(e?.model_type) && !e.is_encoder_decoder && (!Array.isArray(e.architectures) || e.architectures.some((e) => /(?:CausalLM|LMHeadModel)$/.test(e)));
86
+ function _(e) {
87
+ return g.has(e?.model_type) && !e.is_encoder_decoder && (!Array.isArray(e.architectures) || e.architectures.some((e) => /(?:CausalLM|LMHeadModel)$/.test(e)));
88
88
  }
89
- function g(e) {
89
+ function v(e) {
90
90
  let t = /^onnx\/(model|decoder_model_merged)(?:_(q4f16|q4|quantized|fp16))?\.onnx$/.exec(e);
91
91
  if (t) return {
92
92
  modelFile: t[1],
93
93
  dtype: t[2] === "quantized" ? "q8" : t[2] ?? "fp32"
94
94
  };
95
95
  }
96
- function _(e, t) {
96
+ function y(e, t) {
97
97
  let n = `${e}_data`, r = t.filter((e) => e === n || e.startsWith(`${n}_`) && /^[1-9]\d*$/.test(e.slice(n.length + 1)));
98
98
  if (!r.length) return [];
99
99
  let i = r.map((e, t) => t === 0 ? n : `${n}_${t}`);
100
100
  return i.every((e) => r.includes(e)) ? i : void 0;
101
101
  }
102
- function v(e) {
102
+ function b(e, t) {
103
+ let n = e["transformers.js_config"]?.use_external_data_format, r = typeof n == "object" && n ? n[t.split("/").at(-1)] ?? n[v(t).modelFile] : n;
104
+ return r === !0 ? 1 : Number(r) || 0;
105
+ }
106
+ function x(e) {
103
107
  return typeof e == "string" && a.test(e) && e.split("/").every((e) => c.test(e));
104
108
  }
105
- function y(e) {
109
+ function S(e) {
106
110
  return typeof e == "string" && c.test(e);
107
111
  }
108
- function b(e, t, n) {
112
+ function C(e, t, n) {
109
113
  return `${i}/${e}/resolve/${t}/${n.split("/").map(encodeURIComponent).join("/")}`;
110
114
  }
111
- function x(e) {
112
- if (!e || e.version !== 1 || !Object.hasOwn(l, e.adapter) || !v(e.repo) || typeof e.revision != "string" || !o.test(e.revision) || !Array.isArray(e.files) || e.files.length === 0 || e.files.length > 24 || !e.files.every((e) => e && y(e.path) && Number.isSafeInteger(e.size) && e.size > 0 && (e.sha256 === void 0 || typeof e.sha256 == "string" && s.test(e.sha256)))) return !1;
113
- let t = new Set(e.files.map(({ path: e }) => e));
114
- if (t.size !== e.files.length) return !1;
115
+ function w(e) {
116
+ let t = e?.source === "local";
117
+ if (!e || e.version !== 1 || !Object.hasOwn(l, e.adapter) || (t ? e.repo !== "local/model" || e.revision !== void 0 : !x(e.repo) || typeof e.revision != "string" || !o.test(e.revision)) || !Array.isArray(e.files) || e.files.length === 0 || e.files.length > 24 || !e.files.every((e) => e && S(e.path) && Number.isSafeInteger(e.size) && e.size > 0 && (e.sha256 === void 0 || typeof e.sha256 == "string" && s.test(e.sha256)))) return !1;
118
+ let n = new Set(e.files.map(({ path: e }) => e));
119
+ if (n.size !== e.files.length) return !1;
115
120
  switch (e.adapter) {
116
- case "litert-chat": return e.files.length === 1 && /\.litertlm$/i.test(e.files[0].path) && s.test(e.files[0].sha256);
121
+ case "litert-chat": return e.files.length === 1 && /\.litertlm$/i.test(e.files[0].path) && (t || s.test(e.files[0].sha256));
117
122
  case "onnx-chat": {
118
- let n = e.files[0].path;
119
- return !!(g(n) && p.every((e) => t.has(e)) && _(n, [...t]));
123
+ let t = e.files[0].path;
124
+ return !!(v(t) && h.every((e) => n.has(e)) && y(t, [...n]));
120
125
  }
121
- case "laya-choice": return u.every((e) => t.has(e));
122
- case "janus-image": return d.every((e) => t.has(e));
123
- case "sd-turbo": return e.repo.toLowerCase() === "schmuell/sd-turbo-ort-web" && f.every((e) => t.has(e));
126
+ case "laya-choice": return u.every((e) => n.has(e));
127
+ case "janus-image": return d.every((e) => n.has(e));
128
+ case "sd-turbo": return f.every((e) => n.has(e)) && (t ? p.every((e) => n.has(e)) : e.repo.toLowerCase() === "schmuell/sd-turbo-ort-web");
124
129
  }
125
130
  }
126
- function S(e) {
131
+ function T(e) {
127
132
  let t = ["litert-chat", "onnx-chat"].includes(e.adapter) ? `/${e.files[0].path}` : "";
128
133
  return `hub:${e.adapter}:${e.repo}@${e.revision}${t}`;
129
134
  }
130
- function C(e) {
131
- return e.adapter === "onnx-chat" ? `${e.repo.split("/").at(-1)} · ${g(e.files[0].path)?.dtype.toUpperCase()}` : e.adapter === "litert-chat" ? e.files[0].path.split("/").at(-1).replace(/\.litertlm$/i, "") : e.repo;
135
+ function E(e) {
136
+ return e.adapter === "onnx-chat" ? `${e.repo.split("/").at(-1)} · ${v(e.files[0].path)?.dtype.toUpperCase()}` : e.adapter === "litert-chat" ? e.files[0].path.split("/").at(-1).replace(/\.litertlm$/i, "") : e.repo;
132
137
  }
133
- function w(e) {
138
+ function D(e) {
134
139
  return e.files.reduce((e, t) => e + t.size, 0);
135
140
  }
136
- function T(e) {
141
+ function O(e) {
137
142
  let t = e?.laya;
138
143
  return !!(t && e.model_type === "modernbert" && t.split_words === !1 && t.qtypes?.choice === 0 && Number.isInteger(t.max_len) && t.max_len >= 128 && Number.isInteger(t.max_option_tokens) && t.max_option_tokens > 0 && Number.isFinite(t.temperature_by_options?.["choice:3-5"]) && t.temperature_by_options["choice:3-5"] > 0);
139
144
  }
140
- function E(e) {
145
+ function k(e) {
141
146
  return e?.model_type === "multi_modality" && Array.isArray(e.architectures) && e.architectures.includes("MultiModalityCausalLM");
142
147
  }
143
148
  // src/hub-inspector.js
144
- function D(e) {
149
+ function A(e) {
145
150
  let t;
146
151
  try {
147
152
  t = new URL(e.trim());
@@ -150,7 +155,7 @@ function D(e) {
150
155
  }
151
156
  if (t.origin !== "https://huggingface.co" || t.username || t.password) throw Error("Use a public model URL on huggingface.co.");
152
157
  let n = t.pathname.replace(/^\/|\/$/g, "").split("/").map(decodeURIComponent), r = n.slice(0, 2).join("/");
153
- if (!v(r) || [
158
+ if (!x(r) || [
154
159
  "datasets",
155
160
  "spaces",
156
161
  "collections",
@@ -164,7 +169,7 @@ function D(e) {
164
169
  "resolve"
165
170
  ].includes(i) || !a || a.length > 200 || /[?#\\]/.test(a)) throw Error("Use a repository, revision, or model file link from Hugging Face.");
166
171
  let s = o.join("/");
167
- if (s && !y(s) || i !== "tree" && !s) throw Error("This model file link is incomplete.");
172
+ if (s && !S(s) || i !== "tree" && !s) throw Error("This model file link is incomplete.");
168
173
  return i === "tree" ? {
169
174
  repo: r,
170
175
  revision: a,
@@ -175,15 +180,15 @@ function D(e) {
175
180
  path: s
176
181
  };
177
182
  }
178
- function O(e, t) {
183
+ function j(e, t) {
179
184
  return fetch(e, {
180
185
  signal: t,
181
186
  credentials: "omit",
182
187
  headers: { Accept: "application/json" }
183
188
  });
184
189
  }
185
- async function k(e, t) {
186
- let n = `https://huggingface.co/api/models/${e.repo}`, r = await O(`${e.revision ? `${n}/revision/${encodeURIComponent(e.revision)}` : n}?blobs=true`, t);
190
+ async function M(e, t) {
191
+ let n = `https://huggingface.co/api/models/${e.repo}`, r = await j(`${e.revision ? `${n}/revision/${encodeURIComponent(e.revision)}` : n}?blobs=true`, t);
187
192
  if ([
188
193
  401,
189
194
  403,
@@ -191,7 +196,7 @@ async function k(e, t) {
191
196
  ].includes(r.status)) throw Error("Hugging Face could not open this public repository or revision. Check the link and its access settings.");
192
197
  if (r.status === 429) throw Error("Hugging Face rate-limited the request. Try again in a moment.");
193
198
  if (!r.ok) throw Error(`Hugging Face returned HTTP ${r.status}. Try again.`);
194
- let i = await r.json(), a = v(i.id) ? i.id : e.repo, o = i.sha;
199
+ let i = await r.json(), a = x(i.id) ? i.id : e.repo, o = i.sha;
195
200
  if (!/^[a-f0-9]{40}$/.test(o)) throw Error("The Hub did not return a commit for this model.");
196
201
  let s = Array.isArray(i.tags) ? i.tags : [], c = s.find((e) => typeof e == "string" && e.startsWith("base_model:quantized:"))?.slice(21), l = {
197
202
  repo: a,
@@ -203,16 +208,16 @@ async function k(e, t) {
203
208
  upstream: c
204
209
  };
205
210
  if (i.gated || i.private) return l.verdict = "Access required", l.canFindRelated = !0, l.issues.push("This repository requires Hugging Face access. Use a public browser export. This demo imports without account credentials."), l;
206
- let m = new Map((i.siblings ?? []).map((e) => [e.rfilename, e]));
207
- if (l.files = m.size, e.path && !m.has(e.path)) return l.verdict = "File missing", l.issues.push(`This revision does not contain ${e.path}. Check the file path or use the repository URL.`), l;
208
- function y(e, t) {
211
+ let p = new Map((i.siblings ?? []).map((e) => [e.rfilename, e]));
212
+ if (l.files = p.size, e.path && !p.has(e.path)) return l.verdict = "File missing", l.issues.push(`This revision does not contain ${e.path}. Check the file path or use the repository URL.`), l;
213
+ function m(e, t) {
209
214
  let n = {
210
215
  version: 1,
211
216
  adapter: e,
212
217
  repo: a,
213
218
  revision: o,
214
219
  files: t.map((e) => {
215
- let t = m.get(e);
220
+ let t = p.get(e);
216
221
  return {
217
222
  path: e,
218
223
  size: t?.size,
@@ -220,117 +225,116 @@ async function k(e, t) {
220
225
  };
221
226
  })
222
227
  };
223
- x(n) ? l.candidates.push(n) : l.issues.push(`Hugging Face did not provide the required size or checksum metadata for ${t[0]}.`);
228
+ w(n) ? l.candidates.push(n) : l.issues.push(`Hugging Face did not provide the required size or checksum metadata for ${t[0]}.`);
224
229
  }
225
- function S(e) {
226
- let t = e.filter((e) => !m.has(e));
230
+ function g(e) {
231
+ let t = e.filter((e) => !p.has(e));
227
232
  return t.length && (l.verdict = "Files missing"), t;
228
233
  }
229
- let C = [...m.keys()], w = (t) => (!e.path || t === e.path) && (!e.folder || t.startsWith(`${e.folder}/`)), D = C.filter(w);
230
- if (e.folder && !D.length) return l.issues.push("This folder has no files at the selected revision. Try the repository URL."), l;
231
- let k = C.filter((e) => /-(web|gpu)\.litertlm$/i.test(e));
232
- if (k.length === 0 && D.some((e) => /\.litertlm$/i.test(e))) {
234
+ let S = [...p.keys()], T = (t) => (!e.path || t === e.path) && (!e.folder || t.startsWith(`${e.folder}/`)), E = S.filter(T);
235
+ if (e.folder && !E.length) return l.issues.push("This folder has no files at the selected revision. Try the repository URL."), l;
236
+ let D = S.filter((e) => /-(web|gpu)\.litertlm$/i.test(e));
237
+ if (D.length === 0 && E.some((e) => /\.litertlm$/i.test(e))) {
233
238
  let e = s.includes("webgpu") || s.includes("browser");
234
239
  if (!e && a.startsWith("litert-community/")) {
235
- let n = await O("https://huggingface.co/api/collections/litert-community/web-llm-models", t);
240
+ let n = await j("https://huggingface.co/api/collections/litert-community/web-llm-models", t);
236
241
  n.ok && (e = (await n.json()).items?.some((e) => e.repoType === "model" && e.id === a));
237
242
  }
238
- e && k.push(...D.filter((e) => /\.litertlm$/i.test(e) && !/(?:^|[-_])npu(?:[-_.]|$)/i.test(e)).sort((e, t) => m.get(e).size - m.get(t).size));
243
+ e && D.push(...E.filter((e) => /\.litertlm$/i.test(e) && !/(?:^|[-_])npu(?:[-_.]|$)/i.test(e)).sort((e, t) => p.get(e).size - p.get(t).size));
239
244
  }
240
- for (let e of k.filter(w).sort((e, t) => Number(!/-web\.litertlm$/i.test(e)) - Number(!/-web\.litertlm$/i.test(t)))) y("litert-chat", [e]);
245
+ for (let e of D.filter(T).sort((e, t) => Number(!/-web\.litertlm$/i.test(e)) - Number(!/-web\.litertlm$/i.test(t)))) m("litert-chat", [e]);
241
246
  let A = [
242
247
  "q4",
243
248
  "q4f16",
244
249
  "q8",
245
250
  "fp16",
246
251
  "fp32"
247
- ], j = C.filter((t) => g(t) && (w(t) || e.path?.startsWith(`${t}_data`))).sort((e, t) => A.indexOf(g(e).dtype) - A.indexOf(g(t).dtype)), M = /laya/i.test(a) || s.includes("laya") || m.has("onnx/model_fp16.onnx_data"), N = /janus/i.test(a) || s.includes("multi_modality") || m.has("onnx/prepare_inputs_embeds_q4.onnx"), P = !e.path || e.path.endsWith(".onnx") || e.path.endsWith(".onnx_data"), F = (t) => !e.folder || t.some(w);
248
- if (P && !m.has("config.json") && (M || N || j.length) && l.issues.push("The ONNX adapter needs a root config.json describing the model architecture."), P && (M || N || j.length) && m.has("config.json")) {
249
- let n = m.get("config.json").size;
252
+ ], M = S.filter((t) => v(t) && (T(t) || e.path?.startsWith(`${t}_data`))).sort((e, t) => A.indexOf(v(e).dtype) - A.indexOf(v(t).dtype)), N = /laya/i.test(a) || s.includes("laya") || p.has("onnx/model_fp16.onnx_data"), P = /janus/i.test(a) || s.includes("multi_modality") || p.has("onnx/prepare_inputs_embeds_q4.onnx"), F = !e.path || e.path.endsWith(".onnx") || e.path.endsWith(".onnx_data"), I = (t) => !e.folder || t.some(T);
253
+ if (F && !p.has("config.json") && (N || P || M.length) && l.issues.push("The ONNX adapter needs a root config.json describing the model architecture."), F && (N || P || M.length) && p.has("config.json")) {
254
+ let n = p.get("config.json").size;
250
255
  if (!Number.isSafeInteger(n) || n > 256e3) l.issues.push("The Hub config is missing size metadata or exceeds the inspection limit.");
251
256
  else {
252
- let n = await O(b(a, o, "config.json"), t), r = n.ok ? await n.json().catch(() => null) : null;
253
- if (T(r)) {
254
- let t = S(u);
255
- t.length ? l.issues.push(`The Laya adapter needs these files: ${t.join(", ")}.`) : (!e.path || u.includes(e.path)) && F(u) && y("laya-choice", u);
256
- } else if (E(r)) {
257
- let t = S(d);
258
- t.length ? l.issues.push(`The Janus adapter needs these files: ${t.join(", ")}.`) : (!e.path || d.includes(e.path)) && F(d) && y("janus-image", d);
259
- } else if (j.length && h(r)) {
260
- let e = S(p);
257
+ let n = await j(C(a, o, "config.json"), t), r = n.ok ? await n.json().catch(() => null) : null;
258
+ if (O(r)) {
259
+ let t = g(u);
260
+ t.length ? l.issues.push(`The Laya adapter needs these files: ${t.join(", ")}.`) : (!e.path || u.includes(e.path)) && I(u) && m("laya-choice", u);
261
+ } else if (k(r)) {
262
+ let t = g(d);
263
+ t.length ? l.issues.push(`The Janus adapter needs these files: ${t.join(", ")}.`) : (!e.path || d.includes(e.path)) && I(d) && m("janus-image", d);
264
+ } else if (M.length && _(r)) {
265
+ let e = g(h);
261
266
  if (e.length) l.issues.push(`The ONNX chat adapter needs these files: ${e.join(", ")}.`);
262
- else for (let e of j) {
263
- let t = _(e, C);
267
+ else for (let e of M) {
268
+ let t = y(e, S);
264
269
  if (!t) {
265
270
  l.verdict = "Files missing", l.issues.push(`The external weight files for ${e} are incomplete.`);
266
271
  continue;
267
272
  }
268
- let n = r["transformers.js_config"]?.use_external_data_format, i = e.split("/").at(-1), a = typeof n == "object" && n ? n[i] ?? n[g(e).modelFile] : n, o = a === !0 ? 1 : Number(a) || 0;
269
- if (t.length < o) {
270
- l.verdict = "Files missing", l.issues.push(`${e} expects ${o} external weight files. The repository lists ${t.length}.`);
273
+ let n = b(r, e);
274
+ if (t.length < n) {
275
+ l.verdict = "Files missing", l.issues.push(`${e} expects ${n} external weight files. The repository lists ${t.length}.`);
271
276
  continue;
272
277
  }
273
- let s = ["generation_config.json", "chat_template.jinja"].filter((e) => m.has(e));
274
- y("onnx-chat", [
278
+ let i = ["generation_config.json", "chat_template.jinja"].filter((e) => p.has(e));
279
+ m("onnx-chat", [
275
280
  e,
276
- ...p,
281
+ ...h,
277
282
  ...t,
278
- ...s
283
+ ...i
279
284
  ]);
280
285
  }
281
- } else M && (/laya/i.test(a) || s.includes("laya")) ? l.issues.push("The Laya adapter needs the English ModernBERT choice configuration and the matching FP16 ONNX export.") : N && l.issues.push("The Janus adapter needs a MultiModalityCausalLM configuration and its matching ONNX pipeline.");
286
+ } else N && (/laya/i.test(a) || s.includes("laya")) ? l.issues.push("The Laya adapter needs the English ModernBERT choice configuration and the matching FP16 ONNX export.") : P && l.issues.push("The Janus adapter needs a MultiModalityCausalLM configuration and its matching ONNX pipeline.");
282
287
  }
283
288
  }
284
- if (P && a.toLowerCase() === "schmuell/sd-turbo-ort-web" && (!e.path || f.includes(e.path)) && F(f)) {
285
- let e = S(f);
286
- e.length ? l.issues.push(`The SD-Turbo adapter needs these files: ${e.join(", ")}.`) : y("sd-turbo", f);
289
+ if (F && a.toLowerCase() === "schmuell/sd-turbo-ort-web" && (!e.path || f.includes(e.path)) && I(f)) {
290
+ let e = g(f);
291
+ e.length ? l.issues.push(`The SD-Turbo adapter needs these files: ${e.join(", ")}.`) : m("sd-turbo", f);
287
292
  }
288
293
  if (!l.candidates.length && !l.issues.length) {
289
- if (D.some((e) => /\.litertlm$/i.test(e))) l.issues.push("A LiteRT-LM file was found. Link to a browser export, or tag the repository webgpu if its checkpoint was built for the browser.");
290
- else if (D.some((e) => /\.onnx$/i.test(e))) l.issues.push("ONNX files were found, but the architecture or graph layout does not match a supported adapter.");
291
- else if (D.some((e) => /\.(safetensors|gguf|bin)$/i.test(e))) {
294
+ if (E.some((e) => /\.litertlm$/i.test(e))) l.issues.push("A LiteRT-LM file was found. Link to a browser export, or tag the repository webgpu if its checkpoint was built for the browser.");
295
+ else if (E.some((e) => /\.onnx$/i.test(e))) l.issues.push("ONNX files were found, but the architecture or graph layout does not match a supported adapter.");
296
+ else if (E.some((e) => /\.(safetensors|gguf|bin)$/i.test(e))) {
292
297
  let e = [
293
298
  "SafeTensors",
294
299
  "GGUF",
295
300
  "BIN"
296
- ].filter((e) => D.some((t) => t.toLowerCase().endsWith(`.${e.toLowerCase()}`)));
301
+ ].filter((e) => E.some((t) => t.toLowerCase().endsWith(`.${e.toLowerCase()}`)));
297
302
  l.issues.push(`Found ${e.join(" and ")} weights. This runtime needs a browser-compatible ONNX or LiteRT-LM export.`);
298
303
  } else l.issues.push("No supported model files were found at this link. Try the model repository URL or a browser export.");
299
304
  }
300
- return l.canFindRelated = D.some((e) => /\.(onnx|litertlm|safetensors|gguf|bin)$/i.test(e)), l;
305
+ return l.canFindRelated = E.some((e) => /\.(onnx|litertlm|safetensors|gguf|bin)$/i.test(e)), l;
301
306
  }
302
- async function A(e, t, n) {
303
- let r = t.path || t.folder ? await k({
307
+ async function N(e, t, n) {
308
+ let r = t.path || t.folder ? await M({
304
309
  repo: t.repo,
305
310
  revision: t.revision
306
311
  }, n) : null;
307
312
  if (r?.candidates.length) return [r];
308
- let i = v(e.upstream) ? e.upstream : e.repo, a = await Promise.allSettled(["transformers.js", "litert-lm"].map(async (t) => {
313
+ let i = x(e.upstream) ? e.upstream : e.repo, a = await Promise.allSettled(["transformers.js", "litert-lm"].map(async (t) => {
309
314
  let r = new URLSearchParams({
310
315
  limit: "4",
311
316
  sort: "downloads",
312
317
  direction: "-1"
313
318
  });
314
319
  r.append("filter", `base_model:quantized:${i}`), r.append("filter", t);
315
- let a = await O(`https://huggingface.co/api/models?${r}`, n);
320
+ let a = await j(`https://huggingface.co/api/models?${r}`, n);
316
321
  if (!a.ok) return [];
317
322
  let o = await a.json();
318
- return Array.isArray(o) ? o.filter((t) => v(t.id) && !t.gated && !t.private && t.id.toLowerCase() !== e.repo.toLowerCase() && t.tags?.includes(`base_model:quantized:${i}`)) : [];
323
+ return Array.isArray(o) ? o.filter((t) => x(t.id) && !t.gated && !t.private && t.id.toLowerCase() !== e.repo.toLowerCase() && t.tags?.includes(`base_model:quantized:${i}`)) : [];
319
324
  })), o = [...new Set(a.flatMap((e) => e.status === "fulfilled" ? e.value.map((e) => e.id) : []))];
320
- return (await Promise.allSettled(o.map((e) => k({ repo: e }, n)))).flatMap((e) => e.status === "fulfilled" && e.value.candidates.length ? [e.value] : []).slice(0, 3);
325
+ return (await Promise.allSettled(o.map((e) => M({ repo: e }, n)))).flatMap((e) => e.status === "fulfilled" && e.value.candidates.length ? [e.value] : []).slice(0, 3);
321
326
  }
322
- async function j(e, { signal: t, findRelated: n = !0 } = {}) {
323
- let r = await k(e, t);
324
- return n && !r.candidates.length && r.canFindRelated && (r.alternatives = await A(r, e, t).catch((e) => {
327
+ async function P(e, { signal: t, findRelated: n = !0 } = {}) {
328
+ let r = await M(e, t);
329
+ return n && !r.candidates.length && r.canFindRelated && (r.alternatives = await N(r, e, t).catch((e) => {
325
330
  if (t?.aborted) throw e;
326
331
  return [];
327
332
  })), r;
328
333
  }
329
334
  // src/model-discovery.js
330
- var M = "https://huggingface.co/models?library=transformers.js&pipeline_tag=text-generation&other=onnx&num_parameters=min:0,max:3B&sort=downloads";
331
- function N({ version: e, adapter: t, repo: n, revision: r, files: i }) {
332
- let a = {
333
- version: e,
335
+ var F = "https://huggingface.co/models?library=transformers.js&pipeline_tag=text-generation&other=onnx&num_parameters=min:0,max:3B&sort=downloads";
336
+ function I({ version: e, adapter: t, repo: n, revision: r, files: i }, a) {
337
+ let o = {
334
338
  adapter: t,
335
339
  repo: n,
336
340
  revision: r,
@@ -339,38 +343,47 @@ function N({ version: e, adapter: t, repo: n, revision: r, files: i }) {
339
343
  size: t,
340
344
  ...n ? { sha256: n } : {}
341
345
  }))
342
- }, o = t === "onnx-chat" ? g(i[0].path).dtype : void 0, s = l[t].task;
343
- return Object.freeze({
346
+ }, s = t === "onnx-chat" ? v(i[0].path).dtype : void 0, c = l[t].task, u = a ? {
344
347
  ...a,
345
- files: Object.freeze(a.files),
346
- id: S(a),
347
- name: C(a),
348
- bytes: w(a),
349
- task: s,
350
- variant: o,
351
- requiresFp16: o === "q4f16" || o === "fp16" || s !== "chat"
348
+ source: "local",
349
+ name: s ? `${a.name} · ${s.toUpperCase()}` : a.name
350
+ } : {
351
+ repo: n,
352
+ revision: r,
353
+ id: T(o),
354
+ name: E(o)
355
+ };
356
+ return Object.freeze({
357
+ version: e,
358
+ adapter: t,
359
+ ...u,
360
+ files: Object.freeze(o.files),
361
+ bytes: D(o),
362
+ task: c,
363
+ variant: s,
364
+ requiresFp16: s === "q4f16" || s === "fp16" || c !== "chat"
352
365
  });
353
366
  }
354
- async function P({ task: e, search: t, maxDownloadBytes: n = 1e400 } = {}) {
367
+ async function L({ task: e, search: t, maxDownloadBytes: n = 1e400 } = {}) {
355
368
  let { default: r } = await import("./model-catalog-D6UCYXpI.js"), i = t?.toLowerCase().trim();
356
- return r.filter((t) => (!e || l[t.adapter].task === e) && (!i || t.repo.toLowerCase().includes(i)) && w(t) <= n).map(N);
369
+ return r.filter((t) => (!e || l[t.adapter].task === e) && (!i || t.repo.toLowerCase().includes(i)) && D(t) <= n).map((e) => I(e));
357
370
  }
358
- function F(e) {
371
+ function R(e) {
359
372
  return {
360
373
  repo: e.repo,
361
374
  revision: e.revision,
362
375
  status: e.candidates.length ? "ready" : e.verdict === "Access required" ? "access-required" : "unsupported",
363
- models: e.candidates.map(N),
376
+ models: e.candidates.map((e) => I(e)),
364
377
  issues: e.issues.slice(),
365
- alternatives: (e.alternatives ?? []).map(F)
378
+ alternatives: (e.alternatives ?? []).map(R)
366
379
  };
367
380
  }
368
- async function I(e, { signal: n, findRelated: i = !0 } = {}) {
381
+ async function z(e, { signal: n, findRelated: i = !0 } = {}) {
369
382
  let a = "inspectModel";
370
383
  r(n, a);
371
384
  let o;
372
385
  try {
373
- if (o = typeof e == "string" ? D(e) : void 0, !o) throw Error("Use a public Hugging Face model URL.");
386
+ if (o = typeof e == "string" ? A(e) : void 0, !o) throw Error("Use a public Hugging Face model URL.");
374
387
  } catch (e) {
375
388
  throw new t("INVALID_MODEL", e.message, {
376
389
  operation: a,
@@ -378,7 +391,7 @@ async function I(e, { signal: n, findRelated: i = !0 } = {}) {
378
391
  });
379
392
  }
380
393
  try {
381
- return F(await j(o, {
394
+ return R(await P(o, {
382
395
  signal: n,
383
396
  findRelated: i
384
397
  }));
@@ -392,51 +405,210 @@ async function I(e, { signal: n, findRelated: i = !0 } = {}) {
392
405
  });
393
406
  }
394
407
  }
408
+ // src/local-models.js
409
+ var B = "scanLocalModels", V = /* @__PURE__ */ new WeakMap(), H = /(?:\.(?:json|jinja|litertlm|onnx|gguf|safetensors|bin)|\.onnx_data(?:_\d+)?|^sha256-[a-f0-9]{64})$/i, ee = /(?:^|\/)((?:onnx|text_encoder|unet|vae_decoder|tokenizer)\/[^/]+)$/, U = ["generation_config.json", "chat_template.jinja"];
410
+ function W(e) {
411
+ return V.get(e);
412
+ }
413
+ async function* te(e, t, n) {
414
+ let i = [{
415
+ directory: e,
416
+ prefix: e.name
417
+ }];
418
+ for (; i.length;) {
419
+ let { directory: e, prefix: a } = i.pop();
420
+ for await (let o of e.values()) {
421
+ r(t, B);
422
+ let e = `${a}/${o.name}`;
423
+ if (o.kind === "directory") i.push({
424
+ directory: o,
425
+ prefix: e
426
+ });
427
+ else if (H.test(o.name)) {
428
+ let t = await o.getFile().catch(() => {
429
+ n.push(`Could not read ${e}.`);
430
+ });
431
+ t && (yield [e, t]);
432
+ }
433
+ }
434
+ }
435
+ }
436
+ function* ne(e) {
437
+ for (let n of e) {
438
+ if (!(n instanceof Blob) || typeof n.name != "string") throw new t("INVALID_ARGUMENT", "Pass a folder handle or an iterable of selected File objects.", { operation: B });
439
+ H.test(n.name) && (yield [n.webkitRelativePath || n.name, n]);
440
+ }
441
+ }
442
+ async function re(e, { signal: n, task: i } = {}) {
443
+ r(n, B);
444
+ let a = e?.kind === "directory" && typeof e.values == "function";
445
+ if (!a && typeof e?.[Symbol.iterator] != "function") throw new t("INVALID_ARGUMENT", "Pass a folder handle or an iterable of selected File objects.", { operation: B });
446
+ let o = /* @__PURE__ */ new Map(), s = [], c = [], l = /* @__PURE__ */ new Set();
447
+ function g(e, t, n, r, a) {
448
+ let o = new Map(r.map((e) => [e, n.get(e)])), l = {
449
+ version: 1,
450
+ source: "local",
451
+ adapter: e,
452
+ repo: m,
453
+ files: [...o].map(([e, t]) => ({
454
+ path: e,
455
+ size: t?.size
456
+ }))
457
+ };
458
+ if (!w(l)) {
459
+ c.push(`${t || a || "Selected files"} contains an empty or invalid ${e} model file.`);
460
+ return;
461
+ }
462
+ let u = I(l, {
463
+ id: `local:${e}:${t}/${a ?? r[0]}`,
464
+ name: a ?? (t.split("/").at(-1) || e),
465
+ folder: t
466
+ });
467
+ i && u.task !== i || (V.set(u, {
468
+ registration: l,
469
+ files: o
470
+ }), s.push(u));
471
+ }
472
+ function x(e, t, n) {
473
+ let r = n.filter((e) => !t.has(e));
474
+ return r.length && c.push(`${e || "Selected files"} is missing ${r.join(", ")}.`), !r.length;
475
+ }
476
+ try {
477
+ let t = a ? te(e, n, c) : ne(e);
478
+ for await (let [e, a] of t) {
479
+ r(n, B);
480
+ let t = a.name;
481
+ if (/\.litertlm$/i.test(t)) {
482
+ if (i && i !== "chat") continue;
483
+ let o = await a.slice(0, 8).text().catch(() => "");
484
+ r(n, B), o !== "LITERTLM" || /(?:^|[-_])npu(?:[-_.]|$)/i.test(t) ? c.push(`${e} does not look like a WebGPU-compatible LiteRT-LM checkpoint.`) : g("litert-chat", e.slice(0, e.length - t.length).replace(/\/$/, ""), /* @__PURE__ */ new Map([["model.litertlm", a]]), ["model.litertlm"], t);
485
+ continue;
486
+ }
487
+ let s = /\.(gguf|safetensors|bin)$/i.exec(t)?.[1]?.toLowerCase();
488
+ if (s || /^sha256-[a-f0-9]{64}$/i.test(t)) {
489
+ l.add(s ?? "Ollama-style blobs");
490
+ continue;
491
+ }
492
+ let u = ee.exec(e)?.[1] ?? t, d = e.slice(0, e.length - u.length).replace(/\/$/, "");
493
+ o.has(d) || o.set(d, /* @__PURE__ */ new Map()), o.get(d).set(u, a);
494
+ }
495
+ for (let [e, t] of o) {
496
+ r(n, B);
497
+ let a = f.some((e) => t.has(e));
498
+ if (a && (!i || i === "image")) {
499
+ let n = [...f, ...p];
500
+ x(e, t, n) && g("sd-turbo", e, t, n);
501
+ }
502
+ let o = [...t.keys()];
503
+ if (!o.some((e) => /^onnx\/.*\.onnx$/.test(e))) {
504
+ o.some((e) => e.endsWith(".onnx")) && !a && c.push(`${e || "Selected files"} has ONNX weights in an unsupported layout. Keep the export’s config, tokenizer, and graph folders together.`);
505
+ continue;
506
+ }
507
+ let s = t.get("config.json");
508
+ if (!s || s.size > 256e3) {
509
+ c.push(`${e || "Selected files"} needs a readable config.json alongside its onnx folder.`);
510
+ continue;
511
+ }
512
+ let l = await s.text().then(JSON.parse).catch(() => null);
513
+ r(n, B);
514
+ let m = U.filter((e) => t.has(e));
515
+ if (O(l)) (!i || i === "classification") && x(e, t, u) && g("laya-choice", e, t, u);
516
+ else if (k(l)) (!i || i === "image") && x(e, t, d) && g("janus-image", e, t, [...d, ...m]);
517
+ else if (_(l) && o.some(v)) {
518
+ if (i && i !== "chat" || !x(e, t, h)) continue;
519
+ for (let n of o.filter(v)) {
520
+ let r = y(n, o);
521
+ !r || r.length < b(l, n) ? c.push(`${e}/${n} is missing external ONNX weights.`) : g("onnx-chat", e, t, [
522
+ n,
523
+ ...h,
524
+ ...r,
525
+ ...m
526
+ ]);
527
+ }
528
+ } else c.push(`${e || "Selected files"} does not match a supported ONNX adapter.`);
529
+ }
530
+ } catch (e) {
531
+ throw r(n, B), e instanceof t ? e : new t("LOCAL_READ_FAILED", "Could not read the selected files. Check folder permissions and select the folder again.", {
532
+ operation: B,
533
+ cause: e
534
+ });
535
+ }
536
+ return l.size && c.push(`Found ${[...l].join(", ")} files. Choose an ONNX or LiteRT-LM browser export.`), !s.length && !c.length && c.push(`The selection contains no supported ${i ? `${i} ` : ""}model exports.`), {
537
+ models: s,
538
+ issues: c
539
+ };
540
+ }
395
541
  // src/model-session.js
396
- function L(e, n, r, i) {
542
+ function G(e, n, r, i) {
397
543
  if (typeof e != "string" || !e.trim()) throw new t("INVALID_ARGUMENT", `${n} must be a non-empty string.`, {
398
544
  operation: r,
399
545
  repo: i
400
546
  });
401
547
  return e.trim();
402
548
  }
403
- function R(e, n) {
404
- let { task: r, repo: i, adapter: a } = e, o = {
405
- task: r,
549
+ function K(e, n, { cache: r, chatSettings: i } = {}) {
550
+ let { task: a, repo: o, adapter: s } = e, c = {
551
+ task: a,
406
552
  model: e,
553
+ cache: r,
407
554
  dispose: n.dispose
408
555
  };
409
- return r === "chat" ? {
410
- ...o,
411
- async chat(e, { signal: t, onToken: r } = {}) {
412
- let a = L(e, "Prompt", "chat", i), o = "";
556
+ return a === "chat" ? {
557
+ ...c,
558
+ chatSettings: i,
559
+ async chat(e, { signal: t, onToken: r, onFinish: a } = {}) {
560
+ let s = G(e, "Prompt", "chat", o), c = "";
413
561
  return n.run("chat", {
414
562
  type: "generate",
415
- prompt: a
563
+ prompt: s
416
564
  }, t, (e, t) => {
417
- e.type === "delta" && (o += e.text, r?.(e.text)), e.type === "done" && t(o);
565
+ e.type === "delta" && (c += e.text, r?.(e.text)), e.type === "done" && (a?.({
566
+ finishReason: e.finishReason ?? "unknown",
567
+ ...i,
568
+ ...e.settings
569
+ }), t(c));
418
570
  });
419
571
  },
420
- reset({ signal: e } = {}) {
421
- return n.run("reset", { type: "reset" }, e, (e, t) => {
572
+ async reset({ signal: e, instructions: r, history: i = [] } = {}) {
573
+ let a = "reset", s = r === void 0 ? void 0 : G(r, "Instructions", a, o);
574
+ if (!Array.isArray(i) || i.length % 2 != 0) throw new t("INVALID_ARGUMENT", "History must contain complete user and assistant turns.", {
575
+ operation: a,
576
+ repo: o
577
+ });
578
+ let c = Array.from(i, (e, n) => {
579
+ let r = n % 2 ? "assistant" : "user";
580
+ if (e?.role !== r) throw new t("INVALID_ARGUMENT", "History must alternate user and assistant messages.", {
581
+ operation: a,
582
+ repo: o
583
+ });
584
+ return {
585
+ role: r,
586
+ content: G(e.content, "Message content", a, o)
587
+ };
588
+ });
589
+ return n.run(a, {
590
+ type: "reset",
591
+ instructions: s,
592
+ history: c
593
+ }, e, (e, t) => {
422
594
  e.type === "reset" && t();
423
595
  });
424
596
  }
425
- } : r === "image" ? {
426
- ...o,
427
- async generateImage(e, { signal: r, seed: o, onProgress: s } = {}) {
428
- let c = L(e, "Prompt", "generateImage", i);
429
- if (o !== void 0 && (a !== "sd-turbo" || !Number.isInteger(o) || o < 0 || o > 0xffffffff)) throw new t("INVALID_ARGUMENT", "SD-Turbo accepts integer seeds from 0 to 4294967295. Janus chooses its own seed.", {
597
+ } : a === "image" ? {
598
+ ...c,
599
+ async generateImage(e, { signal: r, seed: i, onProgress: a } = {}) {
600
+ let c = G(e, "Prompt", "generateImage", o);
601
+ if (i !== void 0 && (s !== "sd-turbo" || !Number.isInteger(i) || i < 0 || i > 0xffffffff)) throw new t("INVALID_ARGUMENT", "SD-Turbo accepts integer seeds from 0 to 4294967295. Janus chooses its own seed.", {
430
602
  operation: "generateImage",
431
- repo: i
603
+ repo: o
432
604
  });
433
- let l = a === "sd-turbo" ? o ?? crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] : void 0;
605
+ let l = s === "sd-turbo" ? i ?? crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] : void 0;
434
606
  return n.run("generateImage", {
435
607
  type: "generate",
436
608
  prompt: c,
437
609
  seed: l
438
610
  }, r, (e, t) => {
439
- if (e.type === "generate-progress" && s?.({
611
+ if (e.type === "generate-progress" && a?.({
440
612
  fraction: e.fraction,
441
613
  label: e.label
442
614
  }), e.type === "result") {
@@ -451,32 +623,32 @@ function R(e, n) {
451
623
  });
452
624
  }
453
625
  } : {
454
- ...o,
455
- async classify(e, r, { signal: a, question: o = "Which category best matches this text?", onProgress: s } = {}) {
626
+ ...c,
627
+ async classify(e, r, { signal: i, question: a = "Which category best matches this text?", onProgress: s } = {}) {
456
628
  let c = "classify", l = Array.isArray(e) && Array.from(e);
457
629
  if (!l || !l.every((e) => typeof e == "string" && e.trim())) throw new t("INVALID_ARGUMENT", "Texts must be an array of non-empty strings.", {
458
630
  operation: c,
459
- repo: i
631
+ repo: o
460
632
  });
461
633
  if (!Array.isArray(r) || r.length < 3 || r.length > 5) throw new t("INVALID_ARGUMENT", "Provide three to five classification choices.", {
462
634
  operation: c,
463
- repo: i
635
+ repo: o
464
636
  });
465
- let u = Array.from(r, (e) => typeof e == "string" ? { label: L(e, "Choice", c, i) } : {
466
- label: L(e?.label, "Choice label", c, i),
467
- description: e.description === void 0 ? void 0 : L(e.description, "Choice description", c, i)
637
+ let u = Array.from(r, (e) => typeof e == "string" ? { label: G(e, "Choice", c, o) } : {
638
+ label: G(e?.label, "Choice label", c, o),
639
+ description: e.description === void 0 ? void 0 : G(e.description, "Choice description", c, o)
468
640
  }), d = u.map(({ label: e }) => e);
469
641
  if (new Set(d).size !== d.length) throw new t("INVALID_ARGUMENT", "Give each classification choice a distinct label.", {
470
642
  operation: c,
471
- repo: i
643
+ repo: o
472
644
  });
473
- let f = L(o, "Question", c, i), p = [], m = {
645
+ let f = G(a, "Question", c, o), p = [], m = {
474
646
  type: "run",
475
647
  messages: l,
476
648
  choices: u.map(({ label: e, description: t }) => t ? `${e}: ${t}` : e),
477
649
  question: f
478
650
  };
479
- return n.run(c, m, a, (e, t) => {
651
+ return n.run(c, m, i, (e, t) => {
480
652
  if (e.type === "batch") {
481
653
  for (let t of e.records) p.push({
482
654
  index: t.route,
@@ -494,16 +666,114 @@ function R(e, n) {
494
666
  }
495
667
  };
496
668
  }
669
+ // src/cache-store.js
670
+ var q = "browser-model-sdk-weights-v1", J = "transformers-cache", Y = {
671
+ repo: "Xenova/clip-vit-base-patch32",
672
+ revision: "6b7c523703ae26e39be4b03774966f8571c7f523",
673
+ files: [{
674
+ path: "tokenizer.json",
675
+ size: 2224119
676
+ }, {
677
+ path: "tokenizer_config.json",
678
+ size: 775
679
+ }]
680
+ };
681
+ function ie(e) {
682
+ return `browser-model-sdk-${e}.litertlm`;
683
+ }
684
+ function ae(e) {
685
+ if (e.source === "local") return e.files;
686
+ let t = e.files.map((t) => {
687
+ let n = e.adapter === "litert-chat" ? "opfs" : e.adapter === "sd-turbo" || e.adapter === "laya-choice" && t.path.startsWith("onnx/") ? q : J;
688
+ return {
689
+ ...t,
690
+ store: n,
691
+ url: C(e.repo, e.revision, t.path)
692
+ };
693
+ });
694
+ if (e.adapter === "sd-turbo") for (let e of Y.files) t.push({
695
+ ...e,
696
+ path: `tokenizer/${e.path}`,
697
+ store: J,
698
+ url: C(Y.repo, Y.revision, e.path)
699
+ });
700
+ return t;
701
+ }
702
+ // src/preflight.js
703
+ function X(e, n) {
704
+ if (![
705
+ "prefer",
706
+ "require",
707
+ "memory-only"
708
+ ].includes(e)) throw new t("INVALID_ARGUMENT", "Cache must be prefer, require, or memory-only.", { operation: n });
709
+ }
710
+ async function Z(t, n) {
711
+ let r = globalThis.navigator, i = await e(), a = {
712
+ secureContext: !0,
713
+ webgpu: !0,
714
+ webassembly: !0,
715
+ worker: !0,
716
+ shaderFp16: t.requiresFp16,
717
+ offscreenCanvas: t.task === "image",
718
+ persistentCache: t.source !== "local" && n === "require"
719
+ }, o = [];
720
+ function s(e, t, n) {
721
+ e || o.push({
722
+ code: t,
723
+ message: n
724
+ });
725
+ }
726
+ return s(globalThis.isSecureContext, "SECURE_CONTEXT", "Use HTTPS or localhost."), s(typeof Worker == "function", "WORKERS", "This browser does not support dedicated workers."), s(typeof WebAssembly < "u", "WASM", "This browser does not support WebAssembly."), s(i.webgpu, "WEBGPU", "This browser does not have an available WebGPU adapter."), a.shaderFp16 && s(i.shaderFp16, "FP16", "This export requires WebGPU FP16 shaders."), a.offscreenCanvas && s(typeof OffscreenCanvas < "u", "OFFSCREEN_CANVAS", "Image generation needs OffscreenCanvas."), a.persistentCache && s(t.adapter === "litert-chat" ? r?.storage?.getDirectory && r?.locks : globalThis.caches !== void 0, "CACHE_UNAVAILABLE", "Required model cache storage is unavailable. Try cache: prefer or memory-only."), {
727
+ device: i,
728
+ requirements: a,
729
+ blockers: o
730
+ };
731
+ }
732
+ async function Q(e) {
733
+ try {
734
+ if (e.store === "opfs") return (await (await (await navigator.storage.getDirectory()).getFileHandle(ie(e.sha256))).getFile()).size === e.size ? "cached" : "missing";
735
+ if (!await caches.has(e.store)) return "missing";
736
+ let t = await caches.match(e.url, { cacheName: e.store });
737
+ if (!t) return "missing";
738
+ let n = t.headers.get("Content-Length");
739
+ return n === null ? "unknown" : Number(n) === e.size ? "cached" : "missing";
740
+ } catch (e) {
741
+ return e.name === "NotFoundError" ? "missing" : "unknown";
742
+ }
743
+ }
744
+ async function oe(e, { cache: n = "prefer", signal: i } = {}) {
745
+ let a = "preflightModel";
746
+ X(n, a), r(i, a);
747
+ let o = W(e);
748
+ if (!o && (e?.source === "local" || !w(e))) throw new t("INVALID_MODEL", "Pass a descriptor from listModels, inspectModel, or scanLocalModels.", { operation: a });
749
+ let s = o ? e : I(e), [c, l] = await Promise.all([Z(s, n), Promise.all(ae(s).map(async ({ path: e, size: t, ...r }) => ({
750
+ path: e,
751
+ size: t,
752
+ state: o ? "local" : n === "memory-only" ? "bypassed" : await Q({
753
+ ...r,
754
+ size: t
755
+ })
756
+ })))]);
757
+ r(i, a, s.repo);
758
+ let u = l.reduce((e, t) => e + (t.state === "missing" || t.state === "bypassed" ? t.size : 0), 0);
759
+ return {
760
+ ...c,
761
+ files: l,
762
+ totalBytes: l.reduce((e, t) => e + t.size, 0),
763
+ downloadBytes: l.some(({ state: e }) => e === "unknown") ? null : u,
764
+ knownDownloadBytes: u
765
+ };
766
+ }
497
767
  // src/worker-factories.js
498
- var z = () => import("./image.worker-DCCSYqzK.js"), B = {
499
- "litert-chat": () => import("./inference.worker-CuwWqHQs.js"),
500
- "onnx-chat": () => import("./onnx-chat.worker-BkdwoJoF.js"),
501
- "laya-choice": () => import("./laya.worker-Dku9wD9_.js"),
502
- "janus-image": z,
503
- "sd-turbo": z
768
+ var $ = () => import("./image.worker-Bw4MnkKd.js"), se = {
769
+ "litert-chat": () => import("./inference.worker-ObNSBgG3.js"),
770
+ "onnx-chat": () => import("./onnx-chat.worker-BbP3C_6v.js"),
771
+ "laya-choice": () => import("./laya.worker-DgRSLTIF.js"),
772
+ "janus-image": $,
773
+ "sd-turbo": $
504
774
  };
505
775
  // src/worker-transport.js
506
- function V(e, r) {
776
+ function ce(e, r) {
507
777
  let i, a;
508
778
  function o(t) {
509
779
  a || (a = t, e.terminate(), i?.reject(t));
@@ -524,7 +794,9 @@ function V(e, r) {
524
794
  if (e.type === "error" || e.type === "generation-error") {
525
795
  let i = new t(n.operation === "openModel" ? "LOAD_FAILED" : "INFERENCE_FAILED", e.message, {
526
796
  operation: n.operation,
527
- repo: r
797
+ repo: r,
798
+ details: e.details,
799
+ cause: e.cause
528
800
  });
529
801
  n.operation === "openModel" || e.fatal ? o(i) : n.reject(i);
530
802
  } else try {
@@ -578,10 +850,10 @@ function V(e, r) {
578
850
  };
579
851
  }
580
852
  // src/index.js
581
- async function H(e, n, r) {
853
+ async function le(e, n, r) {
582
854
  let i = "openModel";
583
855
  if (typeof e == "string") {
584
- let a = await I(e, {
856
+ let a = await z(e, {
585
857
  signal: r,
586
858
  findRelated: !1
587
859
  }), o = a.models.find((e) => !n || e.task === n);
@@ -592,62 +864,75 @@ async function H(e, n, r) {
592
864
  repo: a.repo
593
865
  });
594
866
  }
595
- if (!x(e)) throw new t("INVALID_MODEL", "Pass a model descriptor from listModels or inspectModel, or a Hugging Face URL.", { operation: i });
596
- let a = N(e);
597
- if (n && a.task !== n) throw new t("UNSUPPORTED_MODEL", `This export supports ${a.task}. Choose a ${n} export.`, {
598
- operation: i,
599
- repo: a.repo
600
- });
601
- return a;
867
+ if (e?.source === "local") throw new t("INVALID_MODEL", "Pass the local model descriptor returned by scanLocalModels. Scan the folder again if the descriptor was copied or saved separately.", { operation: i });
868
+ if (!w(e)) throw new t("INVALID_MODEL", "Pass a model descriptor from listModels, inspectModel, or scanLocalModels, or a Hugging Face URL.", { operation: i });
869
+ return I(e);
602
870
  }
603
- async function U(n) {
604
- let r = globalThis.navigator, i = await e(), a = {
605
- operation: "openModel",
606
- repo: n.repo
607
- };
608
- if (!i.webgpu || typeof Worker != "function" || typeof WebAssembly > "u" || !globalThis.isSecureContext) throw new t("DEVICE_UNSUPPORTED", "Use a browser with WebGPU, WebAssembly, and workers over HTTPS or localhost.", a);
609
- if (n.requiresFp16 && !i.shaderFp16) throw new t("DEVICE_UNSUPPORTED", "This export requires WebGPU FP16 shaders. Try a device with shader-f16 support.", a);
610
- if (n.adapter === "litert-chat" && (!r.storage?.getDirectory || !r.locks)) throw new t("DEVICE_UNSUPPORTED", "LiteRT-LM needs the browser’s private file system and Web Locks APIs.", a);
611
- if (n.task === "image" && typeof OffscreenCanvas > "u") throw new t("DEVICE_UNSUPPORTED", "Image generation needs OffscreenCanvas.", a);
612
- }
613
- async function W(e, { task: n, signal: i, onProgress: a } = {}) {
614
- let o = "openModel";
615
- r(i, o);
616
- let s = await H(e, n, i);
617
- await U(s), r(i, o, s.repo);
618
- let c;
871
+ async function ue(e, { task: n, signal: i, onProgress: a, cache: o = "prefer", maxOutputTokens: s } = {}) {
872
+ let c = "openModel";
873
+ X(o, c), r(i, c);
874
+ let l = W(e), u = l ? e : await le(e, n, i);
875
+ if (n && u.task !== n) throw new t("UNSUPPORTED_MODEL", `This export supports ${u.task}. Choose a ${n} export.`, {
876
+ operation: c,
877
+ repo: u.repo
878
+ });
879
+ if (s !== void 0 && (u.task !== "chat" || !Number.isSafeInteger(s) || s <= 0)) throw new t("INVALID_ARGUMENT", "maxOutputTokens must be a positive integer for a chat model.", {
880
+ operation: c,
881
+ repo: u.repo
882
+ });
883
+ let { blockers: d } = await Z(u, o);
884
+ if (r(i, c, u.repo), d.length) {
885
+ let { code: e, message: n } = d[0];
886
+ throw new t("DEVICE_UNSUPPORTED", n, {
887
+ operation: c,
888
+ repo: u.repo,
889
+ details: {
890
+ kind: e === "CACHE_UNAVAILABLE" ? "cache" : "device",
891
+ stage: "preflight",
892
+ retryable: !1
893
+ }
894
+ });
895
+ }
896
+ let f;
619
897
  try {
620
- let { default: e } = await B[s.adapter]();
621
- r(i, o, s.repo), c = new e({ name: s.adapter });
898
+ let { default: e } = await se[u.adapter]();
899
+ r(i, c, u.repo), f = new e({ name: u.adapter });
622
900
  } catch (e) {
623
- throw r(i, o, s.repo), new t("WORKER_FAILED", "Could not start the model worker. Check that this site allows blob workers.", {
624
- operation: o,
625
- repo: s.repo,
901
+ throw r(i, c, u.repo), new t("WORKER_FAILED", "Could not start the model worker. Check that this site allows blob workers.", {
902
+ operation: c,
903
+ repo: u.repo,
626
904
  cause: e
627
905
  });
628
906
  }
629
- let l = V(c, s.repo), u = 0;
907
+ let p = ce(f, u.repo), m = 0;
630
908
  try {
631
- return await l.run(o, {
909
+ let e = {
632
910
  type: "load",
633
- registration: s
634
- }, i, (e, t) => {
635
- (e.type === "load-progress" || e.type === "progress") && (Number.isFinite(e.loaded) && (u = Math.max(u, Math.min(e.loaded, s.bytes))), a?.({
636
- stage: "download",
637
- loadedBytes: u,
638
- totalBytes: s.bytes
911
+ registration: l?.registration ?? u,
912
+ localFiles: l?.files,
913
+ cache: o,
914
+ maxOutputTokens: s
915
+ };
916
+ return K(u, p, await p.run(c, e, i, (e, t) => {
917
+ (e.type === "load-progress" || e.type === "progress") && (Number.isFinite(e.loaded) && (m = Math.max(m, Math.min(e.loaded, u.bytes))), a?.({
918
+ stage: l ? "read" : "download",
919
+ loadedBytes: m,
920
+ totalBytes: u.bytes
639
921
  })), (e.type === "initializing" || e.type === "preparing") && a?.({
640
922
  stage: "initialize",
641
- loadedBytes: s.bytes,
642
- totalBytes: s.bytes
923
+ loadedBytes: u.bytes,
924
+ totalBytes: u.bytes
643
925
  }), e.type === "ready" && (a?.({
644
926
  stage: "ready",
645
- loadedBytes: s.bytes,
646
- totalBytes: s.bytes
647
- }), t());
648
- }), R(s, l);
927
+ loadedBytes: u.bytes,
928
+ totalBytes: u.bytes
929
+ }), t({
930
+ cache: e.cache,
931
+ chatSettings: e.chatSettings
932
+ }));
933
+ }));
649
934
  } catch (e) {
650
- throw l.dispose(), e;
935
+ throw p.dispose(), e;
651
936
  }
652
937
  }
653
- export { M as HUGGING_FACE_BROWSE_URL, t as ModelError, e as getDeviceInfo, I as inspectModel, P as listModels, W as openModel };
938
+ export { F as HUGGING_FACE_BROWSE_URL, t as ModelError, e as getDeviceInfo, z as inspectModel, L as listModels, ue as openModel, oe as preflightModel, re as scanLocalModels };