@flaxia/node 0.6.1 → 0.7.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.
Files changed (66) hide show
  1. package/README.md +2 -0
  2. package/dist/assets/ai-inference.js +83 -183
  3. package/dist/assets/ai-model-registry.js +127 -0
  4. package/dist/assets/cc-extract.js +5166 -0
  5. package/dist/assets/container.js +59 -43
  6. package/dist/assets/decision.js +149 -0
  7. package/dist/assets/embed-gemma.js +105 -0
  8. package/dist/assets/image-process.js +78 -70
  9. package/dist/assets/nudenet.js +2 -2
  10. package/dist/assets/{VectorStoreEngine.js → sharedEngine.js} +67 -41
  11. package/dist/assets/transformers.web.js +2 -2
  12. package/dist/assets/vector-embed.js +148 -25
  13. package/dist/assets/vector-query.js +4 -4
  14. package/dist/assets/vector-store.js +4 -4
  15. package/dist/assets/webgpuProbe.js +127 -70
  16. package/dist/client/SignalingClient.d.ts.map +1 -1
  17. package/dist/client/light-preloader.d.ts +14 -1
  18. package/dist/client/light-preloader.d.ts.map +1 -1
  19. package/dist/consent/notice.d.ts +3 -1
  20. package/dist/consent/notice.d.ts.map +1 -1
  21. package/dist/executor/WorkerPool.d.ts +7 -0
  22. package/dist/executor/WorkerPool.d.ts.map +1 -1
  23. package/dist/executor/__tests__/resultLimits.test.d.ts +2 -0
  24. package/dist/executor/__tests__/resultLimits.test.d.ts.map +1 -0
  25. package/dist/executor/container-executor.d.ts +15 -0
  26. package/dist/executor/container-executor.d.ts.map +1 -1
  27. package/dist/executor/memoryProbe.d.ts +25 -1
  28. package/dist/executor/memoryProbe.d.ts.map +1 -1
  29. package/dist/executor/resultLimits.d.ts +19 -0
  30. package/dist/executor/resultLimits.d.ts.map +1 -0
  31. package/dist/index.js +357 -326
  32. package/dist/vector-store/HNSWIndex.d.ts +4 -1
  33. package/dist/vector-store/HNSWIndex.d.ts.map +1 -1
  34. package/dist/vector-store/VectorStoreEngine.d.ts +7 -1
  35. package/dist/vector-store/VectorStoreEngine.d.ts.map +1 -1
  36. package/dist/vector-store/__tests__/sharedEngine.test.d.ts +2 -0
  37. package/dist/vector-store/__tests__/sharedEngine.test.d.ts.map +1 -0
  38. package/dist/vector-store/sharedEngine.d.ts +13 -0
  39. package/dist/vector-store/sharedEngine.d.ts.map +1 -0
  40. package/dist/worker.js +187 -175
  41. package/dist/workloads/__tests__/cc-extract.test.d.ts +2 -0
  42. package/dist/workloads/__tests__/cc-extract.test.d.ts.map +1 -0
  43. package/dist/workloads/__tests__/decision.test.d.ts +2 -0
  44. package/dist/workloads/__tests__/decision.test.d.ts.map +1 -0
  45. package/dist/workloads/__tests__/embed-gemma.test.d.ts +2 -0
  46. package/dist/workloads/__tests__/embed-gemma.test.d.ts.map +1 -0
  47. package/dist/workloads/__tests__/nudenet-session-cache.test.d.ts +2 -0
  48. package/dist/workloads/__tests__/nudenet-session-cache.test.d.ts.map +1 -0
  49. package/dist/workloads/__tests__/wasm-threads.test.d.ts.map +1 -1
  50. package/dist/workloads/ai-inference.d.ts +21 -2
  51. package/dist/workloads/ai-inference.d.ts.map +1 -1
  52. package/dist/workloads/ai-model-registry.d.ts.map +1 -1
  53. package/dist/workloads/cc-extract.d.ts +11 -0
  54. package/dist/workloads/cc-extract.d.ts.map +1 -0
  55. package/dist/workloads/decision.d.ts +23 -0
  56. package/dist/workloads/decision.d.ts.map +1 -0
  57. package/dist/workloads/embed-gemma.d.ts +8 -0
  58. package/dist/workloads/embed-gemma.d.ts.map +1 -0
  59. package/dist/workloads/image-process.d.ts +8 -0
  60. package/dist/workloads/image-process.d.ts.map +1 -1
  61. package/dist/workloads/nudenet.d.ts.map +1 -1
  62. package/dist/workloads/vector-embed.d.ts +16 -0
  63. package/dist/workloads/vector-embed.d.ts.map +1 -1
  64. package/dist/workloads/vector-query.d.ts.map +1 -1
  65. package/dist/workloads/vector-store.d.ts.map +1 -1
  66. package/package.json +4 -3
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { A as e, C as t, D as n, E as r, M as i, N as a, S as o, T as s, c, f as l, g as u, i as d, j as f, n as p, o as m, r as h, u as g, v as _, w as v } from "./assets/webgpuProbe.js";
2
- import { t as ee } from "./assets/egress-guard.js";
3
- import { a as y, c as te, i as b, l as ne, n as re, o as ie, r as ae, t as oe } from "./assets/ai-inference.js";
1
+ import { B as e, D as t, E as n, F as r, L as i, M as a, R as o, U as s, Y as c, _ as l, a as u, c as d, h as f, i as p, k as m, l as h, m as g, n as _, o as v, p as ee, r as y, v as te, z as b } from "./assets/webgpuProbe.js";
2
+ import { t as ne } from "./assets/egress-guard.js";
3
+ import { a as re, c as ie, i as ae, l as oe, n as se, o as ce, r as le, t as ue } from "./assets/ai-inference.js";
4
4
  //#region src/consent/notice.ts
5
5
  var x = {
6
6
  summary: "同意すると、このブラウザは第三者から依頼された処理をバックグラウンドで実行します。",
@@ -13,34 +13,34 @@ var x = {
13
13
  acceptGateHint: "開示内容を確認できるよう、「同意して開始」はしばらくの間押せません。",
14
14
  acceptLabel: "同意して開始",
15
15
  rejectLabel: "拒否"
16
- }, se = 4320 * 60 * 60 * 1e3, S = "flaxia_consent_record", ce = "flaxia_consent_granted", le = "flaxia_consent_expiry", C = "flaxia_consent_denied", ue = 1, de = 1e4, fe = 2e3, pe = "flaxia-consent-integrity", me = 1, w = "keys", he = "consent-hmac-sha256-v1", ge = (...e) => console.warn("[flaxia-node]", ...e), _e = /* @__PURE__ */ new Map();
17
- function ve(e) {
16
+ }, de = 4320 * 60 * 60 * 1e3, S = "flaxia_consent_record", fe = "flaxia_consent_granted", pe = "flaxia_consent_expiry", C = "flaxia_consent_denied", me = 1, he = 1e4, w = 2e3, ge = "flaxia-consent-integrity", _e = 1, T = "keys", ve = "consent-hmac-sha256-v1", ye = (...e) => console.warn("[flaxia-node]", ...e), be = /* @__PURE__ */ new Map();
17
+ function xe(e) {
18
18
  try {
19
19
  return localStorage.getItem(e);
20
20
  } catch {
21
- return _e.get(e) ?? null;
21
+ return be.get(e) ?? null;
22
22
  }
23
23
  }
24
- function ye(e, t) {
24
+ function Se(e, t) {
25
25
  try {
26
26
  localStorage.setItem(e, t);
27
27
  } catch {
28
- _e.set(e, t);
28
+ be.set(e, t);
29
29
  }
30
30
  }
31
- function T(e) {
31
+ function E(e) {
32
32
  try {
33
33
  localStorage.removeItem(e);
34
34
  } catch {
35
- _e.delete(e);
35
+ be.delete(e);
36
36
  }
37
37
  }
38
- function be(e) {
38
+ function Ce(e) {
39
39
  return new Promise((t, n) => {
40
40
  e.onsuccess = () => t(e.result), e.onerror = () => n(e.error ?? /* @__PURE__ */ Error("IndexedDB request failed"));
41
41
  });
42
42
  }
43
- function E() {
43
+ function we() {
44
44
  return new Promise((e, t) => {
45
45
  let n;
46
46
  try {
@@ -54,37 +54,37 @@ function E() {
54
54
  }
55
55
  let r;
56
56
  try {
57
- r = n.open(pe, me);
57
+ r = n.open(ge, _e);
58
58
  } catch (e) {
59
59
  t(e);
60
60
  return;
61
61
  }
62
62
  r.onupgradeneeded = () => {
63
63
  let e = r.result;
64
- e.objectStoreNames.contains(w) || e.createObjectStore(w);
64
+ e.objectStoreNames.contains(T) || e.createObjectStore(T);
65
65
  }, r.onsuccess = () => e(r.result), r.onerror = () => t(r.error ?? /* @__PURE__ */ Error("IndexedDB open failed")), r.onblocked = () => t(/* @__PURE__ */ Error("IndexedDB open blocked"));
66
66
  });
67
67
  }
68
- function xe(e) {
68
+ function Te(e) {
69
69
  if (!e || typeof e != "object") return !1;
70
70
  let t = e;
71
71
  return t.type === "secret" && t.algorithm?.name === "HMAC";
72
72
  }
73
- var Se = {
73
+ var Ee = {
74
74
  async load() {
75
- let e = await E();
75
+ let e = await we();
76
76
  try {
77
- let t = await be(e.transaction(w, "readonly").objectStore(w).get(he));
78
- return xe(t) ? t : null;
77
+ let t = await Ce(e.transaction(T, "readonly").objectStore(T).get(ve));
78
+ return Te(t) ? t : null;
79
79
  } finally {
80
80
  e.close();
81
81
  }
82
82
  },
83
83
  async save(e) {
84
- let t = await E();
84
+ let t = await we();
85
85
  try {
86
- let n = t.transaction(w, "readwrite");
87
- n.objectStore(w).put(e, he), await new Promise((e, t) => {
86
+ let n = t.transaction(T, "readwrite");
87
+ n.objectStore(T).put(e, ve), await new Promise((e, t) => {
88
88
  n.oncomplete = () => e(), n.onerror = () => t(n.error ?? /* @__PURE__ */ Error("IndexedDB write failed")), n.onabort = () => t(n.error ?? /* @__PURE__ */ Error("IndexedDB write aborted"));
89
89
  });
90
90
  } finally {
@@ -92,10 +92,10 @@ var Se = {
92
92
  }
93
93
  },
94
94
  async clear() {
95
- let e = await E();
95
+ let e = await we();
96
96
  try {
97
- let t = e.transaction(w, "readwrite");
98
- t.objectStore(w).delete(he), await new Promise((e, n) => {
97
+ let t = e.transaction(T, "readwrite");
98
+ t.objectStore(T).delete(ve), await new Promise((e, n) => {
99
99
  t.oncomplete = () => e(), t.onerror = () => n(t.error ?? /* @__PURE__ */ Error("IndexedDB delete failed")), t.onabort = () => n(t.error ?? /* @__PURE__ */ Error("IndexedDB delete aborted"));
100
100
  });
101
101
  } finally {
@@ -103,7 +103,7 @@ var Se = {
103
103
  }
104
104
  }
105
105
  };
106
- function Ce(e, t, n) {
106
+ function De(e, t, n) {
107
107
  return new Promise((r) => {
108
108
  let i = !1, a, o = (e) => {
109
109
  i || (i = !0, a !== void 0 && clearTimeout(a), r(e));
@@ -111,15 +111,15 @@ function Ce(e, t, n) {
111
111
  a = setTimeout(() => o(t), n), e.then((e) => o(e), () => o(t));
112
112
  });
113
113
  }
114
- var we = Se, D = null, O = null, k = !1, A = !1, j = null, M = 0, N = 0, P = null, Te = !1;
115
- function Ee() {
114
+ var Oe = Ee, D = null, O = null, k = !1, A = !1, j = null, M = 0, N = 0, P = null, ke = !1;
115
+ function Ae() {
116
116
  try {
117
117
  let e = globalThis.location?.origin;
118
118
  if (typeof e == "string" && e.length > 0) return e;
119
119
  } catch {}
120
120
  return "unknown";
121
121
  }
122
- var De = Ee, Oe = () => De(), ke = {
122
+ var je = Ae, Me = () => je(), Ne = {
123
123
  name: "HMAC",
124
124
  hash: "SHA-256"
125
125
  };
@@ -130,7 +130,7 @@ function F() {
130
130
  } catch {}
131
131
  return null;
132
132
  }
133
- function Ae(e) {
133
+ function Pe(e) {
134
134
  let t = new TextEncoder().encode(JSON.stringify([
135
135
  e.v,
136
136
  e.noticeVersion,
@@ -140,12 +140,12 @@ function Ae(e) {
140
140
  ])), n = new Uint8Array(t.byteLength);
141
141
  return n.set(t), n;
142
142
  }
143
- function je(e) {
143
+ function Fe(e) {
144
144
  let t = "";
145
145
  for (let n of e) t += String.fromCharCode(n);
146
146
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
147
147
  }
148
- function Me(e) {
148
+ function Ie(e) {
149
149
  try {
150
150
  let t = e.replace(/-/g, "+").replace(/_/g, "/"), n = t + "=".repeat((4 - t.length % 4) % 4), r = atob(n), i = new Uint8Array(r.length);
151
151
  for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
@@ -154,40 +154,40 @@ function Me(e) {
154
154
  return null;
155
155
  }
156
156
  }
157
- async function Ne() {
158
- let e = await Ce(we.load(), null, fe);
157
+ async function Le() {
158
+ let e = await De(Oe.load(), null, w);
159
159
  if (e) return e;
160
160
  let t = F();
161
161
  if (!t) return null;
162
162
  try {
163
- let e = await t.generateKey(ke, !1, ["sign", "verify"]);
164
- return await Ce(we.save(e), void 0, fe), e;
163
+ let e = await t.generateKey(Ne, !1, ["sign", "verify"]);
164
+ return await De(Oe.save(e), void 0, w), e;
165
165
  } catch {
166
166
  return null;
167
167
  }
168
168
  }
169
- async function Pe(e) {
169
+ async function Re(e) {
170
170
  let t = F();
171
171
  if (!t || !D) return null;
172
172
  try {
173
- let n = await t.sign("HMAC", D, Ae(e));
174
- return je(new Uint8Array(n));
173
+ let n = await t.sign("HMAC", D, Pe(e));
174
+ return Fe(new Uint8Array(n));
175
175
  } catch {
176
176
  return null;
177
177
  }
178
178
  }
179
- async function Fe(e) {
179
+ async function ze(e) {
180
180
  let t = F();
181
181
  if (!t || !D || !e.mac) return !1;
182
- let n = Me(e.mac);
182
+ let n = Ie(e.mac);
183
183
  if (!n) return !1;
184
184
  try {
185
- return await t.verify("HMAC", D, n, Ae(e));
185
+ return await t.verify("HMAC", D, n, Pe(e));
186
186
  } catch {
187
187
  return !1;
188
188
  }
189
189
  }
190
- function Ie(e) {
190
+ function Be(e) {
191
191
  if (!e) return null;
192
192
  try {
193
193
  let t = JSON.parse(e);
@@ -205,128 +205,128 @@ function Ie(e) {
205
205
  return null;
206
206
  }
207
207
  }
208
- function Le(e, t) {
208
+ function Ve(e, t) {
209
209
  return !(!Number.isFinite(e.grantedAt) || !Number.isFinite(e.expiry) || e.expiry <= t || e.grantedAt > e.expiry || e.expiry - e.grantedAt > 15552e6);
210
210
  }
211
211
  function I(e) {
212
- return e.v === ue && e.noticeVersion === 2 && e.origin === Oe();
213
- }
214
- function Re() {
215
- return Ie(ve(S));
216
- }
217
- function ze(e) {
218
- ye(S, JSON.stringify(e));
212
+ return e.v === me && e.noticeVersion === 3 && e.origin === Me();
219
213
  }
220
214
  function L() {
221
- T(S);
215
+ return Be(xe(S));
216
+ }
217
+ function He(e) {
218
+ Se(S, JSON.stringify(e));
222
219
  }
223
220
  function R() {
224
- T(ce), T(le);
221
+ E(S);
222
+ }
223
+ function z() {
224
+ E(fe), E(pe);
225
225
  }
226
- var Be = () => {
226
+ var Ue = () => {
227
227
  let e = O;
228
- return !e || !k ? !1 : Le(e, Date.now()) && I(e);
229
- }, Ve = () => ve(C) === "true", z = () => Be() ? "granted" : Ve() ? "denied" : "unset", B = () => (j ||= He(), j);
230
- async function He() {
228
+ return !e || !k ? !1 : Ve(e, Date.now()) && I(e);
229
+ }, We = () => xe(C) === "true", B = () => Ue() ? "granted" : We() ? "denied" : "unset", V = () => (j ||= Ge(), j);
230
+ async function Ge() {
231
231
  let e = ++M, t = N, n = null;
232
232
  try {
233
- n = await Ne();
233
+ n = await Le();
234
234
  } catch {
235
235
  n = null;
236
236
  }
237
- if (e !== M) return z();
238
- D = n, R();
239
- let r = Re();
240
- return r !== null && await Fe(r) && Le(r, Date.now()) && I(r) && r ? t === N && e === M && (O = r, k = !0) : r && !A && (L(), t === N && e === M && (O = null, k = !1)), z();
237
+ if (e !== M) return B();
238
+ D = n, z();
239
+ let r = L();
240
+ return r !== null && await ze(r) && Ve(r, Date.now()) && I(r) && r ? t === N && e === M && (O = r, k = !0) : r && !A && (R(), t === N && e === M && (O = null, k = !1)), B();
241
241
  }
242
- function Ue() {
242
+ function Ke() {
243
243
  let e = P;
244
- return P = null, e && Date.now() - e.at <= de ? {
244
+ return P = null, e && Date.now() - e.at <= he ? {
245
245
  noticeVersion: e.noticeVersion,
246
246
  source: "user-gesture"
247
- } : Te ? {
248
- noticeVersion: 2,
247
+ } : ke ? {
248
+ noticeVersion: 3,
249
249
  source: "host-managed"
250
250
  } : null;
251
251
  }
252
- function We(e) {
253
- return typeof e != "number" || !Number.isFinite(e) || e <= 0 ? se : Math.min(Math.floor(e), se);
252
+ function qe(e) {
253
+ return typeof e != "number" || !Number.isFinite(e) || e <= 0 ? de : Math.min(Math.floor(e), de);
254
254
  }
255
- function Ge(e, t) {
255
+ function Je(e, t) {
256
256
  let n = Date.now();
257
257
  return {
258
- v: ue,
258
+ v: me,
259
259
  noticeVersion: e,
260
- origin: Oe(),
260
+ origin: Me(),
261
261
  grantedAt: n,
262
- expiry: n + We(t),
262
+ expiry: n + qe(t),
263
263
  mac: ""
264
264
  };
265
265
  }
266
- function Ke(e, t) {
267
- T(C), R();
268
- let n = Ge(e.noticeVersion, t);
269
- return O = n, k = !0, A = !0, N += 1, ze(n), n;
266
+ function Ye(e, t) {
267
+ E(C), z();
268
+ let n = Je(e.noticeVersion, t);
269
+ return O = n, k = !0, A = !0, N += 1, He(n), n;
270
270
  }
271
- async function qe(e) {
271
+ async function Xe(e) {
272
272
  try {
273
- if (await B(), O !== e) return;
274
- let t = await Pe(e);
273
+ if (await V(), O !== e) return;
274
+ let t = await Re(e);
275
275
  if (O !== e) return;
276
276
  if (!t) {
277
- L(), A = !1;
277
+ R(), A = !1;
278
278
  return;
279
279
  }
280
280
  let n = {
281
281
  ...e,
282
282
  mac: t
283
283
  };
284
- O = n, k = !0, ze(n), A = !1;
284
+ O = n, k = !0, He(n), A = !1;
285
285
  } catch {
286
- O === e && (L(), A = !1);
286
+ O === e && (R(), A = !1);
287
287
  }
288
288
  }
289
- var Je = () => {
290
- let e = Ue();
289
+ var Ze = () => {
290
+ let e = Ke();
291
291
  if (!e) {
292
- ge("refusing programmatic consent grant: consent requires the built-in banner to be rendered and accepted by the visitor (see setHostManagedConsentAllowed for host-managed UIs)");
292
+ ye("refusing programmatic consent grant: consent requires the built-in banner to be rendered and accepted by the visitor (see setHostManagedConsentAllowed for host-managed UIs)");
293
293
  return;
294
294
  }
295
- qe(Ke(e));
296
- }, Ye = (e = 2) => {
295
+ Xe(Ye(e));
296
+ }, Qe = (e = 3) => {
297
297
  P = {
298
298
  noticeVersion: e,
299
299
  at: Date.now()
300
300
  };
301
- }, Xe = (e) => {
302
- Te = e === !0;
303
- }, Ze = () => {
304
- L(), R(), O = null, k = !1, A = !1, N += 1, ye(C, "true");
305
- }, Qe = () => {
306
- L(), R(), T(C), O = null, k = !1, A = !1, P = null, D = null, M += 1, N += 1, j = null, Ce(we.clear(), void 0, fe);
307
- }, $e = ve, et = ye, V = T;
308
- async function tt() {
309
- let e = N, t = Re();
301
+ }, $e = (e) => {
302
+ ke = e === !0;
303
+ }, et = () => {
304
+ R(), z(), O = null, k = !1, A = !1, N += 1, Se(C, "true");
305
+ }, tt = () => {
306
+ R(), z(), E(C), O = null, k = !1, A = !1, P = null, D = null, M += 1, N += 1, j = null, De(Oe.clear(), void 0, w);
307
+ }, nt = xe, rt = Se, it = E;
308
+ async function at() {
309
+ let e = N, t = L();
310
310
  if (!t) {
311
311
  O = null, k = !1;
312
312
  return;
313
313
  }
314
314
  if (!F()) return;
315
315
  if (!D) {
316
- j = null, await B();
316
+ j = null, await V();
317
317
  return;
318
318
  }
319
- let n = await Fe(t), r = Re();
319
+ let n = await ze(t), r = L();
320
320
  if (e !== N || !r || JSON.stringify(r) !== JSON.stringify(t)) return;
321
- let i = n && Le(t, Date.now()) && I(t);
321
+ let i = n && Ve(t, Date.now()) && I(t);
322
322
  O = i ? t : null, k = i;
323
323
  }
324
324
  try {
325
325
  typeof globalThis.addEventListener == "function" && globalThis.addEventListener("storage", (e) => {
326
- e.key !== null && e.key !== S && e.key !== C || (N += 1, tt());
326
+ e.key !== null && e.key !== S && e.key !== C || (N += 1, at());
327
327
  });
328
328
  } catch {}
329
- var nt = () => {
329
+ var ot = () => {
330
330
  try {
331
331
  if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
332
332
  } catch {}
@@ -335,38 +335,38 @@ var nt = () => {
335
335
  return (e === "x" ? t : t & 3 | 8).toString(16);
336
336
  });
337
337
  };
338
- B();
338
+ V();
339
339
  //#endregion
340
340
  //#region src/consent/ConsentUI.ts
341
- var H = "#6366f1", rt = 1500, it = 1500, at = 6e4, ot = 80, st = 40, ct = [
341
+ var H = "#6366f1", st = 1500, ct = 1500, lt = 6e4, ut = 80, dt = 40, ft = [
342
342
  "bottom-right",
343
343
  "bottom-left",
344
344
  "top-right",
345
345
  "top-left"
346
- ], lt = /^#[0-9a-f]{3}$/i, ut = /^#[0-9a-f]{6}$/i, dt = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i, ft = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i, pt = new Map((/* @__PURE__ */ "black.white.red.green.blue.indigo.violet.purple.teal.cyan.orange.pink.brown.gray.grey.slate.navy.maroon.olive.gold.crimson.tomato.salmon.coral.seagreen.steelblue.royalblue.dodgerblue.mediumseagreen.mediumpurple.rebeccapurple".split(".")).map((e) => [e, e]));
347
- function mt(e) {
346
+ ], pt = /^#[0-9a-f]{3}$/i, mt = /^#[0-9a-f]{6}$/i, ht = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i, gt = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i, _t = new Map((/* @__PURE__ */ "black.white.red.green.blue.indigo.violet.purple.teal.cyan.orange.pink.brown.gray.grey.slate.navy.maroon.olive.gold.crimson.tomato.salmon.coral.seagreen.steelblue.royalblue.dodgerblue.mediumseagreen.mediumpurple.rebeccapurple".split(".")).map((e) => [e, e]));
347
+ function vt(e) {
348
348
  if (typeof e != "string") return H;
349
349
  let t = e.trim();
350
350
  if (t.length === 0 || t.length > 64) return H;
351
- if (lt.test(t) || ut.test(t)) return t.toLowerCase();
352
- let n = dt.exec(t);
351
+ if (pt.test(t) || mt.test(t)) return t.toLowerCase();
352
+ let n = ht.exec(t);
353
353
  if (n) {
354
354
  let [e, t, r] = n.slice(1).map(Number);
355
355
  return e <= 255 && t <= 255 && r <= 255 ? `rgb(${e}, ${t}, ${r})` : H;
356
356
  }
357
- let r = ft.exec(t);
357
+ let r = gt.exec(t);
358
358
  if (r) {
359
359
  let [e, t, n] = r.slice(1, 4).map(Number), i = Number(r[4]);
360
360
  return e <= 255 && t <= 255 && n <= 255 && i >= 0 && i <= 1 ? `rgba(${e}, ${t}, ${n}, ${i})` : H;
361
361
  }
362
- return pt.get(t.toLowerCase()) ?? H;
362
+ return _t.get(t.toLowerCase()) ?? H;
363
363
  }
364
- function ht(e, t, n) {
364
+ function yt(e, t, n) {
365
365
  if (typeof e != "string") return t;
366
366
  let r = e.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(/\s+/g, " ").trim();
367
367
  return r.length === 0 ? t : r.length > n ? `${r.slice(0, n)}…` : r;
368
368
  }
369
- function gt(e) {
369
+ function bt(e) {
370
370
  if (typeof e != "string" || e.trim().length === 0) return null;
371
371
  try {
372
372
  let t = new URL(e.trim());
@@ -375,33 +375,33 @@ function gt(e) {
375
375
  return null;
376
376
  }
377
377
  }
378
- function _t(e) {
378
+ function xt(e) {
379
379
  return {
380
- brandName: ht(e?.brandName, "Flaxia Crowd", ot),
381
- position: ct.includes(e?.position) ? e.position : "bottom-right",
382
- accentColor: mt(e?.accentColor),
383
- acceptLabel: ht(e?.acceptLabel, x.acceptLabel, st),
384
- rejectLabel: ht(e?.rejectLabel, x.rejectLabel, st),
385
- privacyPolicyUrl: gt(e?.privacyPolicyUrl),
386
- minVisibleMs: vt(e?.minVisibleMs)
380
+ brandName: yt(e?.brandName, "Flaxia Crowd", ut),
381
+ position: ft.includes(e?.position) ? e.position : "bottom-right",
382
+ accentColor: vt(e?.accentColor),
383
+ acceptLabel: yt(e?.acceptLabel, x.acceptLabel, dt),
384
+ rejectLabel: yt(e?.rejectLabel, x.rejectLabel, dt),
385
+ privacyPolicyUrl: bt(e?.privacyPolicyUrl),
386
+ minVisibleMs: St(e?.minVisibleMs)
387
387
  };
388
388
  }
389
- function vt(e) {
390
- return typeof e != "number" || !Number.isFinite(e) ? rt : Math.min(Math.max(Math.floor(e), it), at);
389
+ function St(e) {
390
+ return typeof e != "number" || !Number.isFinite(e) ? st : Math.min(Math.max(Math.floor(e), ct), lt);
391
391
  }
392
- function yt(e, t) {
393
- return typeof t.minVisibleMs == "number" && Number.isFinite(t.minVisibleMs) ? Math.min(Math.max(Math.floor(t.minVisibleMs), 0), at) : e;
392
+ function Ct(e, t) {
393
+ return typeof t.minVisibleMs == "number" && Number.isFinite(t.minVisibleMs) ? Math.min(Math.max(Math.floor(t.minVisibleMs), 0), lt) : e;
394
394
  }
395
- var bt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n padding: 20px;\n background: #fff;\n color: #1f2937;\n border: 1px solid #ccc;\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n z-index: 9999;\n border-radius: 8px;\n max-width: 300px;\n font-family: sans-serif;\n }\n .overlay h3 {\n margin: 0 0 8px;\n color: #111827;\n font-size: 16px;\n }\n .overlay p {\n margin: 0 0 12px;\n color: #4b5563;\n font-size: 14px;\n line-height: 1.4;\n }\n .overlay ul {\n margin: 0 0 12px;\n padding-left: 18px;\n color: #4b5563;\n font-size: 13px;\n line-height: 1.45;\n }\n .overlay li {\n margin-bottom: 6px;\n }\n .overlay .hint {\n margin: 0 0 8px;\n color: #6b7280;\n font-size: 12px;\n }\n .overlay .privacy {\n margin: 0 0 8px;\n font-size: 12px;\n }\n .overlay .privacy a {\n color: __flaxia_accent__;\n }\n button {\n background: __flaxia_accent__;\n color: white;\n border: none;\n padding: 10px 15px;\n border-radius: 4px;\n cursor: pointer;\n margin-top: 10px;\n width: 100%;\n font-size: 14px;\n }\n button:disabled {\n opacity: 0.6;\n cursor: default;\n }\n button.reject {\n background: transparent;\n color: #4b5563;\n border: 1px solid #ccc;\n }\n @media (prefers-color-scheme: dark) {\n .overlay {\n background: #1f2937;\n color: #f9fafb;\n border-color: #374151;\n box-shadow: 0 4px 6px rgba(0,0,0,0.4);\n }\n .overlay h3 {\n color: #f9fafb;\n }\n .overlay p,\n .overlay ul {\n color: #d1d5db;\n }\n .overlay .hint {\n color: #9ca3af;\n }\n button.reject {\n color: #d1d5db;\n border-color: #4b5563;\n }\n }\n", xt = class {
395
+ var wt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n padding: 20px;\n background: #fff;\n color: #1f2937;\n border: 1px solid #ccc;\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n z-index: 9999;\n border-radius: 8px;\n max-width: 300px;\n font-family: sans-serif;\n }\n .overlay h3 {\n margin: 0 0 8px;\n color: #111827;\n font-size: 16px;\n }\n .overlay p {\n margin: 0 0 12px;\n color: #4b5563;\n font-size: 14px;\n line-height: 1.4;\n }\n .overlay ul {\n margin: 0 0 12px;\n padding-left: 18px;\n color: #4b5563;\n font-size: 13px;\n line-height: 1.45;\n }\n .overlay li {\n margin-bottom: 6px;\n }\n .overlay .hint {\n margin: 0 0 8px;\n color: #6b7280;\n font-size: 12px;\n }\n .overlay .privacy {\n margin: 0 0 8px;\n font-size: 12px;\n }\n .overlay .privacy a {\n color: __flaxia_accent__;\n }\n button {\n background: __flaxia_accent__;\n color: white;\n border: none;\n padding: 10px 15px;\n border-radius: 4px;\n cursor: pointer;\n margin-top: 10px;\n width: 100%;\n font-size: 14px;\n }\n button:disabled {\n opacity: 0.6;\n cursor: default;\n }\n button.reject {\n background: transparent;\n color: #4b5563;\n border: 1px solid #ccc;\n }\n @media (prefers-color-scheme: dark) {\n .overlay {\n background: #1f2937;\n color: #f9fafb;\n border-color: #374151;\n box-shadow: 0 4px 6px rgba(0,0,0,0.4);\n }\n .overlay h3 {\n color: #f9fafb;\n }\n .overlay p,\n .overlay ul {\n color: #d1d5db;\n }\n .overlay .hint {\n color: #9ca3af;\n }\n button.reject {\n color: #d1d5db;\n border-color: #4b5563;\n }\n }\n", Tt = class {
396
396
  constructor(e, t, n, r, i) {
397
- this.config = _t(t), this.options = i ?? {}, this.root = e.attachShadow({ mode: "closed" }), this.render(n, r);
397
+ this.config = xt(t), this.options = i ?? {}, this.root = e.attachShadow({ mode: "closed" }), this.render(n, r);
398
398
  }
399
399
  shadowRootForTesting() {
400
400
  return this.root;
401
401
  }
402
402
  render(e, t) {
403
403
  let { brandName: n, position: r, accentColor: i, acceptLabel: a, rejectLabel: o, privacyPolicyUrl: s } = this.config, [c, l] = r.split("-"), u = document.createElement("style");
404
- u.textContent = bt.replace(/__flaxia_accent__/g, i).replace("__flaxia_position__", `${c}: 20px; ${l}: 20px`);
404
+ u.textContent = wt.replace(/__flaxia_accent__/g, i).replace("__flaxia_position__", `${c}: 20px; ${l}: 20px`);
405
405
  let d = document.createElement("div");
406
406
  d.className = "overlay", d.setAttribute("role", "dialog"), d.setAttribute("aria-labelledby", "flaxia-consent-title");
407
407
  let f = document.createElement("h3");
@@ -425,7 +425,7 @@ var bt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
425
425
  g.id = "consent-btn", g.type = "button", g.textContent = a;
426
426
  let _ = document.createElement("button");
427
427
  _.id = "reject-btn", _.type = "button", _.className = "reject", _.textContent = o;
428
- let v = this.options.now ?? (() => Date.now()), ee = this.options.schedule ?? ((e, t) => void setTimeout(e, t)), y = yt(this.config.minVisibleMs, this.options), te = v() + y, b = y <= 0, ne = !1;
428
+ let v = this.options.now ?? (() => Date.now()), ee = this.options.schedule ?? ((e, t) => void setTimeout(e, t)), y = Ct(this.config.minVisibleMs, this.options), te = v() + y, b = y <= 0, ne = !1;
429
429
  b || (g.disabled = !0, g.setAttribute("aria-disabled", "true"), ee(() => {
430
430
  b = !0, g.disabled = !1, g.removeAttribute("aria-disabled"), h.remove();
431
431
  }, y));
@@ -433,15 +433,18 @@ var bt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
433
433
  ne || (ne = !0, d.remove(), e?.());
434
434
  };
435
435
  g.addEventListener("click", () => {
436
- !b || v() < te || (Ye(2), re(e));
436
+ !b || v() < te || (Qe(3), re(e));
437
437
  }), _.addEventListener("click", () => {
438
438
  re(t);
439
439
  }), b || d.appendChild(h), d.append(g, _), this.root.append(u, d);
440
440
  }
441
- }, U = (...e) => console.log("[flaxia-node]", ...e), St = class e {
441
+ }, U = (...e) => console.log("[flaxia-node]", ...e), Et = class e {
442
442
  static {
443
443
  this.MAX_PENDING_CONTROLS = 64;
444
444
  }
445
+ static {
446
+ this.MAX_QUEUE_LENGTH = 16;
447
+ }
445
448
  constructor(e, t = 3e5) {
446
449
  this.worker = null, this.queue = [], this.active = null, this.pendingControls = [], this._lastCpuLoad = 0, this._hasCpuLoadSample = !1, this._modelCacheSnapshot = null, this.workerUrl = e || "/worker.js", this.defaultTimeoutMs = t, this.initWorker();
447
450
  }
@@ -454,80 +457,93 @@ var bt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
454
457
  this.handleWorkerError(/* @__PURE__ */ Error("Worker message error"));
455
458
  }, this.worker = e;
456
459
  }
457
- run(e, t, n, r, i, a, o) {
458
- return new Promise((s, c) => {
460
+ run(t, n, r, i, a, o, s) {
461
+ return new Promise((c, l) => {
459
462
  if (!this.worker) {
460
- c(/* @__PURE__ */ Error("Worker not available"));
463
+ l(/* @__PURE__ */ Error("Worker not available"));
461
464
  return;
462
465
  }
463
- let l = () => this.execute(e, t, n, r, i, a, s, c, o);
464
- this.active ? (U(`task queued id=${e} workload=${t} (active task running)`), this.queue.push({
465
- id: e,
466
- job: l,
467
- reject: c
468
- })) : l();
466
+ if (this.active?.id === t || this.queue.some((e) => e.id === t)) {
467
+ l(/* @__PURE__ */ Error(`WorkerPool already has task ${t} in flight`));
468
+ return;
469
+ }
470
+ if (this.queue.length >= e.MAX_QUEUE_LENGTH) {
471
+ l(/* @__PURE__ */ Error("WorkerPool queue is full; task rejected (retryable)"));
472
+ return;
473
+ }
474
+ let u = () => this.execute(t, n, r, i, a, o, c, l, s);
475
+ this.active ? (U(`task queued id=${t} workload=${n} (active task running)`), this.queue.push({
476
+ id: t,
477
+ job: u,
478
+ reject: l
479
+ })) : u();
469
480
  });
470
481
  }
471
- execute(e, t, n, r, a, s, c, l, u) {
472
- let d = this.worker;
473
- if (!d) {
474
- l(/* @__PURE__ */ Error("Worker not available")), this.dequeue();
482
+ execute(e, t, n, i, a, o, s, c, u) {
483
+ let f = this.worker;
484
+ if (!f) {
485
+ c(/* @__PURE__ */ Error("Worker not available")), this.dequeue();
475
486
  return;
476
487
  }
477
- let f = r ?? this.defaultTimeoutMs, p = !1, m = performance.now();
478
- U(`task start id=${e} workload=${t} timeoutMs=${f}`);
479
- let h = (t) => {
480
- if (p) return;
481
- p = !0;
488
+ let p = i ?? this.defaultTimeoutMs, m = !1, g = performance.now();
489
+ U(`task start id=${e} workload=${t} timeoutMs=${p}`);
490
+ let _ = (t) => {
491
+ if (m) return;
492
+ m = !0;
482
493
  let n = this.active;
483
494
  n && (clearTimeout(n.timer), n.removeListener()), this.active = null, this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), t(), this.dequeue();
484
- }, g = (n) => {
485
- let { id: r, type: s, result: d, error: f, token: p, cpuLoad: g } = n.data;
486
- if (r === e) {
487
- if (i(n.data.modelCache) && (this._modelCacheSnapshot = n.data.modelCache), s === "token") {
488
- a?.(p);
495
+ }, v = (n) => {
496
+ let { id: i, type: o, result: f, error: p, token: m, cpuLoad: v } = n.data;
497
+ if (i === e) {
498
+ if (l(n.data.modelCache) && (this._modelCacheSnapshot = n.data.modelCache), o === "token") {
499
+ a?.(m);
489
500
  return;
490
501
  }
491
- if (s === "heartbeat") {
492
- typeof g == "number" && Number.isFinite(g) && (this._lastCpuLoad = Math.min(1, Math.max(0, g)), this._hasCpuLoadSample = !0);
502
+ if (o === "heartbeat") {
503
+ typeof v == "number" && Number.isFinite(v) && (this._lastCpuLoad = Math.min(1, Math.max(0, v)), this._hasCpuLoadSample = !0);
493
504
  return;
494
505
  }
495
- if (s === "swarm-frame") {
506
+ if (o === "swarm-frame") {
496
507
  u?.onFrame?.(n.data.frame);
497
508
  return;
498
509
  }
499
- if (s === "swarm-message") {
510
+ if (o === "swarm-message") {
500
511
  u?.onMessage?.(n.data.message);
501
512
  return;
502
513
  }
503
- if (s === "done") U(`task done id=${e} workload=${t} durationMs=${Math.round(performance.now() - m)}`), h(() => c(d));
504
- else if (s === "error") {
505
- U(`task failed id=${e} workload=${t} error=${f}`);
506
- let r = typeof n.data.errorCode == "string" ? n.data.errorCode : "TASK_FAILED", i = typeof n.data.errorStatus == "number" ? n.data.errorStatus : 500, a = new o(String(f), r, i);
507
- typeof n.data.detail == "string" && (a.detail = n.data.detail), h(() => l(a));
508
- } else U(`task unknown-message id=${e} type=${String(s)}`), h(() => l(/* @__PURE__ */ Error(`Unknown message type: ${String(s)}`)));
514
+ if (o === "done") {
515
+ if (U(`task done id=${e} workload=${t} durationMs=${Math.round(performance.now() - g)}`), !h(f)) {
516
+ _(() => c(/* @__PURE__ */ Error(`task result exceeds the ${d} byte limit; refused on the main thread`)));
517
+ return;
518
+ }
519
+ _(() => s(f));
520
+ } else if (o === "error") {
521
+ U(`task failed id=${e} workload=${t} error=${p}`);
522
+ let i = typeof n.data.errorCode == "string" ? n.data.errorCode : "TASK_FAILED", a = typeof n.data.errorStatus == "number" ? n.data.errorStatus : 500, o = new r(String(p), i, a);
523
+ typeof n.data.detail == "string" && (o.detail = n.data.detail), _(() => c(o));
524
+ } else U(`task unknown-message id=${e} type=${String(o)}`), _(() => c(/* @__PURE__ */ Error(`Unknown message type: ${String(o)}`)));
509
525
  }
510
- }, _ = () => d.removeEventListener("message", g), v = setTimeout(() => {
511
- U(`task timeout id=${e} workload=${t} (worker terminated after ${f}ms)`), this.cleanupWorker(), h(() => l(/* @__PURE__ */ Error("TIMEOUT")));
512
- }, f);
526
+ }, ee = () => f.removeEventListener("message", v), y = setTimeout(() => {
527
+ U(`task timeout id=${e} workload=${t} (worker terminated after ${p}ms)`), this.cleanupWorker(), _(() => c(/* @__PURE__ */ Error("TIMEOUT")));
528
+ }, p);
513
529
  this.active = {
514
530
  id: e,
515
- resolve: c,
516
- reject: l,
517
- timer: v,
518
- worker: d,
519
- removeListener: _
520
- }, d.addEventListener("message", g);
531
+ resolve: s,
532
+ reject: c,
533
+ timer: y,
534
+ worker: f,
535
+ removeListener: ee
536
+ }, f.addEventListener("message", v);
521
537
  try {
522
- d.postMessage({
538
+ f.postMessage({
523
539
  id: e,
524
540
  workload: t,
525
541
  payload: n,
526
- timeoutMs: f,
527
- config: s
542
+ timeoutMs: p,
543
+ config: o
528
544
  }), this.flushControls();
529
545
  } catch (e) {
530
- h(() => l(e instanceof Error ? e : Error(String(e))));
546
+ _(() => c(e instanceof Error ? e : Error(String(e))));
531
547
  }
532
548
  }
533
549
  flushControls() {
@@ -620,7 +636,7 @@ var bt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
620
636
  let e = this._modelCacheSnapshot;
621
637
  return !e || e.expiresAt <= Date.now() ? null : e;
622
638
  }
623
- }, W = null, Ct = null;
639
+ }, W = null, Dt = null;
624
640
  function G(e, t, n, r, i, a) {
625
641
  return {
626
642
  value: e,
@@ -634,35 +650,35 @@ function G(e, t, n, r, i, a) {
634
650
  function K(e, t, n) {
635
651
  return G(null, e, "unknown", t, t + n, 0);
636
652
  }
637
- async function wt(e, t) {
638
- return e ? ((!W || W.expiresAt <= t) && (Ct ||= p().then((e) => (W = e, e)).finally(() => {
639
- Ct = null;
640
- }), W = await Ct), W) : null;
653
+ async function Ot(e, t) {
654
+ return e ? ((!W || W.expiresAt <= t) && (Dt ||= _().then((e) => (W = e, e)).finally(() => {
655
+ Dt = null;
656
+ }), W = await Dt), W) : null;
641
657
  }
642
- async function Tt(e) {
643
- let t = e.now ?? Date.now(), n = t + _, r = d(), i = r.bytes !== null && r.sampledAt !== null && t - r.sampledAt <= 864e5, a = Number.isFinite(e.deviceMemory) && e.deviceMemory > 0 && e.deviceMemory <= 1024, o = await wt(e.probeGpu === !0, t), s = o?.sampledAt ?? t, c = o?.expiresAt ?? t + 6e5;
658
+ async function kt(e) {
659
+ let n = e.now ?? Date.now(), r = n + f, i = u(), a = i.bytes !== null && i.sampledAt !== null && n - i.sampledAt <= 864e5, o = Number.isFinite(e.deviceMemory) && e.deviceMemory > 0 && e.deviceMemory <= 1024, s = await Ot(e.probeGpu === !0, n), c = s?.sampledAt ?? n, l = s?.expiresAt ?? n + 6e5;
644
660
  return {
645
661
  version: 1,
646
- sampledAt: t,
647
- expiresAt: n,
648
- cpuLoad: typeof e.cpuLoad == "number" && Number.isFinite(e.cpuLoad) && e.cpuLoad >= 0 && e.cpuLoad <= 1 ? G(e.cpuLoad, "ratio", "estimated", t, n, 1) : K("ratio", t, _),
649
- wasmMemoryLowerBound: i ? G(r.bytes, "bytes", "measured", r.sampledAt, r.sampledAt + u, 1) : K("bytes", t, u),
650
- deviceMemory: a ? G(e.deviceMemory, "GiB", "estimated", t, t + u, 1) : K("GiB", t, u),
662
+ sampledAt: n,
663
+ expiresAt: r,
664
+ cpuLoad: typeof e.cpuLoad == "number" && Number.isFinite(e.cpuLoad) && e.cpuLoad >= 0 && e.cpuLoad <= 1 ? G(e.cpuLoad, "ratio", "estimated", n, r, 1) : K("ratio", n, f),
665
+ wasmMemoryLowerBound: a ? G(i.bytes, "bytes", "measured", i.sampledAt, i.sampledAt + t, 1) : K("bytes", n, t),
666
+ deviceMemory: o ? G(e.deviceMemory, "GiB", "estimated", n, n + t, 1) : K("GiB", n, t),
651
667
  gpu: {
652
- status: o?.status ?? "unknown",
653
- sampledAt: s,
654
- expiresAt: c,
655
- architecture: o?.architecture ? G(o.architecture, "text", "measured", s, c, 1) : K("text", s, l),
656
- maxStorageBufferBindingSize: o?.maxStorageBufferBindingSize !== null && o?.maxStorageBufferBindingSize !== void 0 ? G(o.maxStorageBufferBindingSize, "bytes", "measured", s, c, 1) : K("bytes", s, l),
657
- computeCompletionMs: o?.computeCompletionMs !== null && o?.computeCompletionMs !== void 0 ? G(o.computeCompletionMs, "ms", "measured", s, c, o.sampleCount) : K("ms", s, l),
658
- memoryBytes: K("bytes", s, l)
668
+ status: s?.status ?? "unknown",
669
+ sampledAt: c,
670
+ expiresAt: l,
671
+ architecture: s?.architecture ? G(s.architecture, "text", "measured", c, l, 1) : K("text", c, m),
672
+ maxStorageBufferBindingSize: s?.maxStorageBufferBindingSize !== null && s?.maxStorageBufferBindingSize !== void 0 ? G(s.maxStorageBufferBindingSize, "bytes", "measured", c, l, 1) : K("bytes", c, m),
673
+ computeCompletionMs: s?.computeCompletionMs !== null && s?.computeCompletionMs !== void 0 ? G(s.computeCompletionMs, "ms", "measured", c, l, s.sampleCount) : K("ms", c, m),
674
+ memoryBytes: K("bytes", c, m)
659
675
  }
660
676
  };
661
677
  }
662
678
  //#endregion
663
679
  //#region src/swarm/peer-quality.ts
664
- var Et = 15e3;
665
- function Dt(e) {
680
+ var At = 15e3;
681
+ function jt(e) {
666
682
  let t = e.filter((e) => Number.isFinite(e) && e >= 0).slice(-5);
667
683
  if (!t.length) return [];
668
684
  let n = [...t].sort((e, t) => e - t), r = n[Math.floor(n.length / 2)], i = r + Math.max(20, r * 4);
@@ -671,8 +687,8 @@ function Dt(e) {
671
687
  function q(e, t) {
672
688
  return !Number.isFinite(e) || e < 0 || !Number.isFinite(t) || t <= 0 ? null : e * 8 / t / 1e3;
673
689
  }
674
- function Ot(e, t) {
675
- let n = Dt(e);
690
+ function Mt(e, t) {
691
+ let n = jt(e);
676
692
  if (!n.length) return {
677
693
  value: null,
678
694
  sampledAt: t,
@@ -685,11 +701,11 @@ function Ot(e, t) {
685
701
  sampleCount: n.length
686
702
  };
687
703
  }
688
- function kt(e, t, n, r, i) {
689
- let o = (e, n) => {
704
+ function Nt(e, t, n, r, i) {
705
+ let a = (e, n) => {
690
706
  let r = (r) => {
691
707
  let i = n?.[r] ?? t;
692
- return t - i >= 6e4 ? Ot([], t) : Ot(e[r] ?? [], i);
708
+ return t - i >= 6e4 ? Mt([], t) : Mt(e[r] ?? [], i);
693
709
  };
694
710
  return {
695
711
  rttMs: r("rttMs"),
@@ -702,15 +718,15 @@ function kt(e, t, n, r, i) {
702
718
  version: 1,
703
719
  peerNodeId: e,
704
720
  sampledAt: t,
705
- expiresAt: t + a,
706
- webRtc: o(n, i?.webRtc),
707
- application: o(r, i?.application)
721
+ expiresAt: t + c,
722
+ webRtc: a(n, i?.webRtc),
723
+ application: a(r, i?.application)
708
724
  };
709
725
  }
710
726
  //#endregion
711
727
  //#region src/swarm/peer-transport.ts
712
- var At = 5e3, J = 16 * 1024, jt = g, Mt = 256 * 1024, Nt = 1129860166, Y = 16, Pt = 2, Ft = 64, It = "flaxia-swarm-v1", Lt = "flaxia-peer-quality-v1", Rt = 128, zt = [{ urls: "stun:stun.cloudflare.com:3478" }];
713
- function Bt() {
728
+ var Pt = 5e3, J = 16 * 1024, Ft = n, It = 256 * 1024, Lt = 1129860166, Y = 16, Rt = 2, zt = 64, Bt = "flaxia-swarm-v1", Vt = "flaxia-peer-quality-v1", Ht = 128, Ut = [{ urls: "stun:stun.cloudflare.com:3478" }];
729
+ function Wt() {
714
730
  return {
715
731
  rttMs: [],
716
732
  jitterMs: [],
@@ -718,12 +734,12 @@ function Bt() {
718
734
  receiveMbps: []
719
735
  };
720
736
  }
721
- function Vt(e) {
737
+ function Gt(e) {
722
738
  if (e.byteLength < Y || e.byteLength > 16400) return null;
723
739
  let t = new DataView(e);
724
- if (t.getUint32(0, !0) !== Nt) return null;
740
+ if (t.getUint32(0, !0) !== Lt) return null;
725
741
  let n = t.getUint32(4, !0), r = t.getUint16(8, !0), i = t.getUint16(10, !0), a = t.getUint32(12, !0);
726
- if (a < 1 || a > jt || i < 1 || i !== Math.ceil(a / 16384) || r >= i) return null;
742
+ if (a < 1 || a > Ft || i < 1 || i !== Math.ceil(a / 16384) || r >= i) return null;
727
743
  let o = Math.min(J, a - r * J);
728
744
  return e.byteLength - Y === o ? {
729
745
  messageId: n,
@@ -733,26 +749,26 @@ function Vt(e) {
733
749
  payload: new Uint8Array(e, Y)
734
750
  } : null;
735
751
  }
736
- function Ht(e, t) {
737
- if (e.byteLength < 1 || e.byteLength > jt) throw Error(`swarm peer frame size is outside 1..${jt} bytes`);
752
+ function Kt(e, t) {
753
+ if (e.byteLength < 1 || e.byteLength > Ft) throw Error(`swarm peer frame size is outside 1..${Ft} bytes`);
738
754
  let n = Math.ceil(e.byteLength / J), r = [];
739
755
  for (let i = 0; i < n; i++) {
740
756
  let a = i * J, o = Math.min(a + J, e.byteLength), s = new Uint8Array(e, a, o - a), c = new ArrayBuffer(Y + s.byteLength), l = new DataView(c);
741
- l.setUint32(0, Nt, !0), l.setUint32(4, t >>> 0, !0), l.setUint16(8, i, !0), l.setUint16(10, n, !0), l.setUint32(12, e.byteLength, !0), new Uint8Array(c, Y).set(s), r.push(c);
757
+ l.setUint32(0, Lt, !0), l.setUint32(4, t >>> 0, !0), l.setUint16(8, i, !0), l.setUint16(10, n, !0), l.setUint32(12, e.byteLength, !0), new Uint8Array(c, Y).set(s), r.push(c);
742
758
  }
743
759
  return r;
744
760
  }
745
- var Ut = class {
761
+ var qt = class {
746
762
  constructor() {
747
763
  this.assemblies = /* @__PURE__ */ new Map();
748
764
  }
749
765
  accept(e, t = Date.now()) {
750
766
  this.expire(t);
751
- let n = Vt(e);
767
+ let n = Gt(e);
752
768
  if (!n) return null;
753
769
  let r = this.assemblies.get(n.messageId);
754
770
  if (!r) {
755
- if (this.assemblies.size >= Pt) return null;
771
+ if (this.assemblies.size >= Rt) return null;
756
772
  r = {
757
773
  count: n.count,
758
774
  totalBytes: n.totalBytes,
@@ -782,9 +798,9 @@ var Ut = class {
782
798
  expire(e) {
783
799
  for (let [t, n] of this.assemblies) e - n.createdAt > 5e3 * 2 && this.assemblies.delete(t);
784
800
  }
785
- }, Wt = class {
801
+ }, Jt = class {
786
802
  constructor(e) {
787
- this.options = e, this.peers = /* @__PURE__ */ new Map(), this.reassembler = new Ut(), this.nextMessageId = 1, this.mode = "undecided", this.closed = !1, this.failed = !1, this.readyPromise = null, this.readyResolve = null, this.readyTimer = null, this.qualityTimer = null, this.samplingQuality = !1;
803
+ this.options = e, this.peers = /* @__PURE__ */ new Map(), this.reassembler = new qt(), this.nextMessageId = 1, this.mode = "undecided", this.closed = !1, this.failed = !1, this.readyPromise = null, this.readyResolve = null, this.readyTimer = null, this.qualityTimer = null, this.samplingQuality = !1;
788
804
  }
789
805
  get selectedMode() {
790
806
  return this.mode;
@@ -798,15 +814,15 @@ var Ut = class {
798
814
  let e = [...new Set([this.options.previousNodeId, this.options.nextNodeId])].filter((e) => !!e && e !== this.options.nodeId);
799
815
  try {
800
816
  for (let t of e) {
801
- let e = (this.options.createPeerConnection ?? ((e) => new RTCPeerConnection(e)))({ iceServers: zt }), n = {
817
+ let e = (this.options.createPeerConnection ?? ((e) => new RTCPeerConnection(e)))({ iceServers: Ut }), n = {
802
818
  nodeId: t,
803
819
  connection: e,
804
820
  channel: null,
805
821
  remoteDescriptionSet: !1,
806
822
  pendingCandidates: [],
807
823
  quality: {
808
- webRtc: Bt(),
809
- application: Bt()
824
+ webRtc: Wt(),
825
+ application: Wt()
810
826
  },
811
827
  qualitySampledAt: {
812
828
  webRtc: {},
@@ -836,7 +852,7 @@ var Ut = class {
836
852
  for (let e of this.peers.values()) {
837
853
  let { nodeId: t, connection: n } = e;
838
854
  if (this.options.nodeId.localeCompare(t) < 0) {
839
- this.bindChannel(e, n.createDataChannel(It, { ordered: !0 }));
855
+ this.bindChannel(e, n.createDataChannel(Bt, { ordered: !0 }));
840
856
  let r = await n.createOffer();
841
857
  if (this.closed || this.failed) return;
842
858
  await n.setLocalDescription(r);
@@ -878,7 +894,7 @@ var Ut = class {
878
894
  }
879
895
  } else if (t.candidate !== null) if (n.remoteDescriptionSet) await n.connection.addIceCandidate(t.candidate);
880
896
  else {
881
- if (n.pendingCandidates.length >= Ft) throw Error("too many ICE candidates before remote description");
897
+ if (n.pendingCandidates.length >= zt) throw Error("too many ICE candidates before remote description");
882
898
  n.pendingCandidates.push(t.candidate);
883
899
  }
884
900
  } catch (e) {
@@ -908,7 +924,7 @@ var Ut = class {
908
924
  }
909
925
  let r = this.nextMessageId++ >>> 0;
910
926
  try {
911
- for (let t of Ht(e, r)) {
927
+ for (let t of Kt(e, r)) {
912
928
  if (await this.waitForBuffer(n), n.readyState !== "open") throw Error("swarm peer data channel closed while sending");
913
929
  n.send(t);
914
930
  }
@@ -929,7 +945,7 @@ var Ut = class {
929
945
  } catch {}
930
946
  return;
931
947
  }
932
- e.channel = t, t.binaryType = "arraybuffer", t.bufferedAmountLowThreshold = Mt / 2, t.onopen = () => this.resolveReadyIfOpen(), t.onmessage = (t) => {
948
+ e.channel = t, t.binaryType = "arraybuffer", t.bufferedAmountLowThreshold = It / 2, t.onopen = () => this.resolveReadyIfOpen(), t.onmessage = (t) => {
933
949
  if (typeof t.data == "string") {
934
950
  this.handleQualityProbe(e, t.data);
935
951
  return;
@@ -955,7 +971,7 @@ var Ut = class {
955
971
  }
956
972
  async waitForBuffer(e) {
957
973
  e.bufferedAmount <= 262144 || await new Promise((t, n) => {
958
- let r = setTimeout(() => i(/* @__PURE__ */ Error("swarm peer send buffer stalled")), At), i = (i) => {
974
+ let r = setTimeout(() => i(/* @__PURE__ */ Error("swarm peer send buffer stalled")), Pt), i = (i) => {
959
975
  clearTimeout(r), e.removeEventListener("bufferedamountlow", a), e.removeEventListener("close", o), i ? n(i) : t();
960
976
  }, a = () => i(), o = () => i(/* @__PURE__ */ Error("swarm peer data channel closed while backpressured"));
961
977
  e.addEventListener("bufferedamountlow", a, { once: !0 }), e.addEventListener("close", o, { once: !0 });
@@ -967,7 +983,7 @@ var Ut = class {
967
983
  this.peers.clear();
968
984
  }
969
985
  startQualitySampling() {
970
- this.qualityTimer || !this.options.onQuality || (this.samplePeerQuality(), this.qualityTimer = setInterval(() => void this.samplePeerQuality(), Et));
986
+ this.qualityTimer || !this.options.onQuality || (this.samplePeerQuality(), this.qualityTimer = setInterval(() => void this.samplePeerQuality(), At));
971
987
  }
972
988
  stopQualitySampling() {
973
989
  this.qualityTimer && clearInterval(this.qualityTimer), this.qualityTimer = null;
@@ -994,7 +1010,7 @@ var Ut = class {
994
1010
  };
995
1011
  try {
996
1012
  t.send(JSON.stringify({
997
- type: Lt,
1013
+ type: Vt,
998
1014
  kind: "ping",
999
1015
  id: n
1000
1016
  }));
@@ -1003,7 +1019,7 @@ var Ut = class {
1003
1019
  }
1004
1020
  }
1005
1021
  handleQualityProbe(e, t) {
1006
- if (t.length > Rt) return;
1022
+ if (t.length > Ht) return;
1007
1023
  let n;
1008
1024
  try {
1009
1025
  let e = JSON.parse(t);
@@ -1012,12 +1028,12 @@ var Ut = class {
1012
1028
  } catch {
1013
1029
  return;
1014
1030
  }
1015
- if (n.type !== Lt || !Number.isSafeInteger(n.id) || n.id < 1) return;
1031
+ if (n.type !== Vt || !Number.isSafeInteger(n.id) || n.id < 1) return;
1016
1032
  if (n.kind === "ping") {
1017
1033
  if (e.channel?.readyState !== "open" || e.channel.bufferedAmount > 262144) return;
1018
1034
  try {
1019
1035
  e.channel.send(JSON.stringify({
1020
- type: Lt,
1036
+ type: Vt,
1021
1037
  kind: "pong",
1022
1038
  id: n.id
1023
1039
  }));
@@ -1043,7 +1059,7 @@ var Ut = class {
1043
1059
  let e = r - n.lastApplicationSampleAt, t = q(n.applicationBytesSent - n.lastApplicationBytesSent, e), i = q(n.applicationBytesReceived - n.lastApplicationBytesReceived, e);
1044
1060
  t !== null && this.recordQuality(n, "application", "sendMbps", t), i !== null && this.recordQuality(n, "application", "receiveMbps", i);
1045
1061
  }
1046
- n.lastApplicationSampleAt = r, n.lastApplicationBytesSent = n.applicationBytesSent, n.lastApplicationBytesReceived = n.applicationBytesReceived, t.push(kt(n.nodeId, e, n.quality.webRtc, n.quality.application, n.qualitySampledAt));
1062
+ n.lastApplicationSampleAt = r, n.lastApplicationBytesSent = n.applicationBytesSent, n.lastApplicationBytesReceived = n.applicationBytesReceived, t.push(Nt(n.nodeId, e, n.quality.webRtc, n.quality.application, n.qualitySampledAt));
1047
1063
  }
1048
1064
  t.length && this.options.onQuality(t.slice(0, 2));
1049
1065
  } finally {
@@ -1080,25 +1096,25 @@ var Ut = class {
1080
1096
  } catch {}
1081
1097
  }
1082
1098
  };
1083
- function Gt(e, t) {
1084
- if (!n(e)) return !1;
1085
- let r = e;
1086
- return r.type === "swarm-peer-signal" && r.taskId === t.taskId && r.sessionId === t.sessionId && r.attemptId === t.attemptId && r.toNodeId === t.nodeId && typeof r.fromNodeId == "string" && t.peers.includes(r.fromNodeId) && typeof r.signal == "object" && r.signal !== null;
1099
+ function Yt(e, t) {
1100
+ if (!ee(e)) return !1;
1101
+ let n = e;
1102
+ return n.type === "swarm-peer-signal" && n.taskId === t.taskId && n.sessionId === t.sessionId && n.attemptId === t.attemptId && n.toNodeId === t.nodeId && typeof n.fromNodeId == "string" && t.peers.includes(n.fromNodeId) && typeof n.signal == "object" && n.signal !== null;
1087
1103
  }
1088
1104
  //#endregion
1089
1105
  //#region src/client/mobile-lifecycle.ts
1090
- var Kt = .25, qt = .08, Jt = .45;
1091
- function Yt(e, t) {
1092
- let n = e.batteryCharging === !1, r = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Kt, i = n && typeof e.batteryLevel == "number" && e.batteryLevel <= qt, a = e.effectiveType === "slow-2g" || e.effectiveType === "2g", o = r || a || e.saveData === !0;
1106
+ var Xt = .25, Zt = .08, Qt = .45;
1107
+ function $t(e, t) {
1108
+ let n = e.batteryCharging === !1, r = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Xt, i = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Zt, a = e.effectiveType === "slow-2g" || e.effectiveType === "2g", o = r || a || e.saveData === !0;
1093
1109
  return {
1094
1110
  suspend: e.hidden || e.pageHidden || !e.online || i,
1095
1111
  constrained: o,
1096
- maxCpuLoad: o ? Math.min(t ?? Jt, Jt) : t
1112
+ maxCpuLoad: o ? Math.min(t ?? Qt, Qt) : t
1097
1113
  };
1098
1114
  }
1099
1115
  //#endregion
1100
1116
  //#region src/client/light-preloader.ts
1101
- var Xt = "Xenova/m2m100_418M", Zt = "translation", Qt = "q4f16", $t = "TeamFlaxia/plamo-3-translate-0.8b-onnx", en = "text-generation", tn = "q4f16", nn = class {
1117
+ var en = "Xenova/m2m100_418M", tn = "translation", nn = "q4f16", rn = "TeamFlaxia/plamo-3-translate-0.8b-onnx", an = "text-generation", on = "q4f16", sn = class {
1102
1118
  constructor(e, t = {}, n = () => !1, r = async () => {}) {
1103
1119
  this.getConsentState = e, this.options = t, this.isPreloaded = n, this.preload = r, this.timer = null, this.idleHandle = null, this.preloading = !1, this.stopped = !1, this.targets = t.targets ?? [{
1104
1120
  model: t.model ?? "Xenova/m2m100_418M",
@@ -1107,7 +1123,7 @@ var Xt = "Xenova/m2m100_418M", Zt = "translation", Qt = "q4f16", $t = "TeamFlaxi
1107
1123
  }];
1108
1124
  }
1109
1125
  start() {
1110
- if (this.stopped || this.getConsentState() !== "granted" || this.isUnconstrained() === !1 || !this.targets.some((e) => !this.isPreloaded(e.model)) || this.preloading) return;
1126
+ if (this.stopped || this.getConsentState() !== "granted" || this.isUnconstrained() === !1 || !this.hasMemoryHeadroom() || !this.targets.some((e) => !this.isPreloaded(e)) || this.preloading) return;
1111
1127
  let e = () => {
1112
1128
  this.idleHandle = null, this.preloadNow();
1113
1129
  };
@@ -1118,7 +1134,7 @@ var Xt = "Xenova/m2m100_418M", Zt = "translation", Qt = "q4f16", $t = "TeamFlaxi
1118
1134
  }
1119
1135
  isUnconstrained() {
1120
1136
  try {
1121
- let e = navigator, t = Yt({
1137
+ let e = navigator, t = $t({
1122
1138
  hidden: document.hidden,
1123
1139
  pageHidden: document.hidden,
1124
1140
  online: navigator.onLine !== !1,
@@ -1130,13 +1146,20 @@ var Xt = "Xenova/m2m100_418M", Zt = "translation", Qt = "q4f16", $t = "TeamFlaxi
1130
1146
  return !0;
1131
1147
  }
1132
1148
  }
1149
+ hasMemoryHeadroom() {
1150
+ try {
1151
+ return this.options.hasMemoryHeadroom?.() !== !1;
1152
+ } catch {
1153
+ return !1;
1154
+ }
1155
+ }
1133
1156
  async preloadNow() {
1134
- if (!(this.stopped || this.preloading) && this.getConsentState() === "granted" && this.isUnconstrained() !== !1) {
1157
+ if (!(this.stopped || this.preloading) && this.getConsentState() === "granted" && this.isUnconstrained() !== !1 && this.hasMemoryHeadroom()) {
1135
1158
  this.preloading = !0;
1136
1159
  try {
1137
1160
  for (let e of this.targets) {
1138
1161
  if (this.stopped || this.getConsentState() !== "granted") return;
1139
- if (!this.isPreloaded(e.model)) try {
1162
+ if (!this.isPreloaded(e)) try {
1140
1163
  await this.preload({
1141
1164
  task: e.task,
1142
1165
  model: e.model,
@@ -1154,19 +1177,19 @@ function Q(e) {
1154
1177
  let t = /* @__PURE__ */ new Set();
1155
1178
  if (!Array.isArray(e)) return [];
1156
1179
  for (let n of e.slice(0, 32)) try {
1157
- let e = ee(n);
1180
+ let e = ne(n);
1158
1181
  e.origin === n && t.add(e.origin);
1159
1182
  } catch {}
1160
1183
  return [...t];
1161
1184
  }
1162
- var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1185
+ var cn = "flaxia_node_id", ln = "flaxia_node_token", un = class {
1163
1186
  receiveSwarmEnvelope(e) {
1164
- let t = f(e);
1187
+ let t = b(e);
1165
1188
  !t || ![...this.swarmSessions.values()].includes(t.sessionId) || (this.swarmInboundChain = this.swarmInboundChain.then(async () => {
1166
1189
  let e = this.swarmHopKeys.get(t.sessionId);
1167
1190
  if (e && e.chainLength > 1) {
1168
1191
  if (!t.mac || !e.inboundKey) return;
1169
- if (!await v(e.inboundKey, t.sessionId, t.frame, t.mac)) {
1192
+ if (!await a(e.inboundKey, t.sessionId, t.frame, t.mac)) {
1170
1193
  Z(`swarm frame rejected: bad hop MAC sessionId=${t.sessionId}`);
1171
1194
  return;
1172
1195
  }
@@ -1183,7 +1206,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1183
1206
  attemptId: r,
1184
1207
  peers: o
1185
1208
  });
1186
- let s = new Wt({
1209
+ let s = new Jt({
1187
1210
  sessionId: t,
1188
1211
  taskId: n,
1189
1212
  attemptId: r,
@@ -1220,7 +1243,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1220
1243
  }
1221
1244
  handleSwarmPeerSignal(e) {
1222
1245
  let t = typeof e.sessionId == "string" ? e.sessionId : "", n = this.swarmPeerMetadata.get(t), r = this.swarmPeerTransports.get(t);
1223
- !n || !r || !Gt(e, {
1246
+ !n || !r || !Yt(e, {
1224
1247
  ...n,
1225
1248
  sessionId: t,
1226
1249
  nodeId: this.nodeId
@@ -1234,7 +1257,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1234
1257
  }
1235
1258
  async connect() {
1236
1259
  if (this.destroyed) return;
1237
- if (z() !== "granted") {
1260
+ if (B() !== "granted") {
1238
1261
  this.disconnect();
1239
1262
  return;
1240
1263
  }
@@ -1247,24 +1270,24 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1247
1270
  this.ws = null;
1248
1271
  }
1249
1272
  if (this.setupMobileLifecycleHandlers(), this.suspended) return;
1250
- let n = await this.obtainToken();
1273
+ let e = await this.obtainToken();
1251
1274
  if (this.destroyed || this.suspended) return;
1252
- if (z() !== "granted") {
1275
+ if (B() !== "granted") {
1253
1276
  X("connect cancelled because consent was revoked while obtaining a token");
1254
1277
  return;
1255
1278
  }
1256
- if (!n) {
1279
+ if (!e) {
1257
1280
  Z("token acquisition failed; scheduling reconnect"), this.scheduleReconnect();
1258
1281
  return;
1259
1282
  }
1260
1283
  this.startLightPreloader();
1261
- let r = t(this.config.orchestratorUrl, "/crowd/signal"), i = new WebSocket(r, e(n.token));
1262
- i.binaryType = "arraybuffer", this.ws = i;
1263
- let a = !1;
1264
- i.onopen = () => {
1265
- a = !0, this.reconnectAttempts = 0, X(`signal connected ${r}`), this.sendHeartbeat(i);
1266
- }, i.onmessage = async (e) => {
1267
- if (this.ws !== i) return;
1284
+ let t = i(this.config.orchestratorUrl, "/crowd/signal"), n = new WebSocket(t, s(e.token));
1285
+ n.binaryType = "arraybuffer", this.ws = n;
1286
+ let r = !1;
1287
+ n.onopen = () => {
1288
+ r = !0, this.reconnectAttempts = 0, X(`signal connected ${t}`), this.sendHeartbeat(n);
1289
+ }, n.onmessage = async (e) => {
1290
+ if (this.ws !== n) return;
1268
1291
  if (typeof e.data != "string") {
1269
1292
  this.receiveSwarmEnvelope(e.data);
1270
1293
  return;
@@ -1276,7 +1299,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1276
1299
  return;
1277
1300
  }
1278
1301
  if (t.type === "ping") {
1279
- this.sendHeartbeat(i);
1302
+ this.sendHeartbeat(n);
1280
1303
  return;
1281
1304
  }
1282
1305
  if (t.type === "task") {
@@ -1346,10 +1369,10 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1346
1369
  this.handleAbort(t);
1347
1370
  return;
1348
1371
  }
1349
- }, i.onerror = () => {
1350
- this.ws === i && Z("signal websocket error");
1351
- }, i.onclose = (e) => {
1352
- i.onclose = null, this.ws === i && (this.ws = null, a || (this.cachedToken = null), !this.destroyed && (X(`signal disconnected code=${e.code} reason=${JSON.stringify(e.reason)} clean=${e.wasClean}; scheduling reconnect attempt=${this.reconnectAttempts + 1}`), this.scheduleReconnect()));
1372
+ }, n.onerror = () => {
1373
+ this.ws === n && Z("signal websocket error");
1374
+ }, n.onclose = (e) => {
1375
+ n.onclose = null, this.ws === n && (this.ws = null, r || (this.cachedToken = null), !this.destroyed && (X(`signal disconnected code=${e.code} reason=${JSON.stringify(e.reason)} clean=${e.wasClean}; scheduling reconnect attempt=${this.reconnectAttempts + 1}`), this.scheduleReconnect()));
1353
1376
  };
1354
1377
  }
1355
1378
  handleAbort(e) {
@@ -1361,13 +1384,13 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1361
1384
  r && this.retireSwarmSession(r), this.workerPool.abort(i, n) && this.abortedTasks.add(i), X(`task abort received taskId=${t} error=${n}`);
1362
1385
  }
1363
1386
  async sendHeartbeat(e) {
1364
- if (this.ws !== e || e.readyState !== WebSocket.OPEN || z() !== "granted") return;
1365
- let t = (this.config.capabilities ?? ["ai-inference", "image-process"]).includes("swarm-inference") && this.config.allowModelDownload === !0, n = navigator.deviceMemory, r = await Tt({
1387
+ if (this.ws !== e || e.readyState !== WebSocket.OPEN || B() !== "granted") return;
1388
+ let t = (this.config.capabilities ?? ["ai-inference", "image-process"]).includes("swarm-inference") && this.config.allowModelDownload === !0, n = navigator.deviceMemory, r = await kt({
1366
1389
  cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1367
1390
  deviceMemory: n,
1368
1391
  probeGpu: t
1369
1392
  });
1370
- this.ws !== e || e.readyState !== WebSocket.OPEN || z() !== "granted" || this.send({
1393
+ this.ws !== e || e.readyState !== WebSocket.OPEN || B() !== "granted" || this.send({
1371
1394
  type: "pong",
1372
1395
  cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1373
1396
  resources: r,
@@ -1389,7 +1412,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1389
1412
  for (let e of this.swarmPeerTransports.values()) e.close();
1390
1413
  this.swarmPeerTransports.clear(), this.swarmPeerMetadata.clear();
1391
1414
  try {
1392
- delete window[sn];
1415
+ delete window[dn];
1393
1416
  } catch {}
1394
1417
  try {
1395
1418
  this.workerPool.terminate();
@@ -1412,15 +1435,15 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1412
1435
  !this.suspended || this.destroyed || (X("resumed"), this.suspended = !1, this.workerPool.resume(), this.connect());
1413
1436
  }
1414
1437
  async obtainToken() {
1415
- let e = () => z() === "granted";
1438
+ let e = () => B() === "granted";
1416
1439
  if (!e()) return null;
1417
1440
  try {
1418
1441
  if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 6e4) return X(`token cached nodeId=${this.cachedToken.nodeId} expiresIn=${Math.round((this.cachedToken.expiresAt - Date.now()) / 1e3)}s`), this.cachedToken;
1419
- let t = m(), n = t >= h, r = this.config.capabilities ?? ["ai-inference", "image-process"], i = n ? [...r] : [];
1420
- Q(this.config.containerImageOrigins).length === 0 && (i = i.filter((e) => e !== "container"));
1442
+ let t = p(), n = t >= y, r = this.config.capabilities ?? ["ai-inference", "image-process"], i = [...r];
1443
+ n || (i = i.filter((e) => !te.has(e))), Q(this.config.containerImageOrigins).length === 0 && (i = i.filter((e) => e !== "container")), Q(this.config.ccRangeOrigins).length === 0 && (i = i.filter((e) => e !== "cc-extract"));
1421
1444
  let a;
1422
1445
  if (n && r.includes("swarm-inference") && this.config.allowModelDownload === !0) {
1423
- let t = await Tt({
1446
+ let t = await kt({
1424
1447
  cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1425
1448
  deviceMemory: navigator.deviceMemory,
1426
1449
  probeGpu: !0
@@ -1438,7 +1461,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1438
1461
  siteId: this.config.siteId,
1439
1462
  capabilities: i,
1440
1463
  fileSources: Q(this.config.fileSourceOrigins).length > 0,
1441
- wasmMemoryBytes: m(),
1464
+ wasmMemoryBytes: p(),
1442
1465
  deviceMemory: typeof navigator.deviceMemory == "number" ? navigator.deviceMemory : null,
1443
1466
  swarm: a
1444
1467
  })
@@ -1465,11 +1488,11 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1465
1488
  Z(`swarm frame not sent: no hop key sessionId=${e}`);
1466
1489
  return;
1467
1490
  }
1468
- let r = await s(n.outboundKey, e, t), i = this.swarmPeerTransports.get(e);
1491
+ let r = await o(n.outboundKey, e, t), i = this.swarmPeerTransports.get(e);
1469
1492
  (!i || !await i.sendFrame(r)) && this.sendBinary(r);
1470
1493
  return;
1471
1494
  }
1472
- let r = c(e, t), i = this.swarmPeerTransports.get(e);
1495
+ let r = g(e, t), i = this.swarmPeerTransports.get(e);
1473
1496
  (!i || !await i.sendFrame(r)) && this.sendBinary(r);
1474
1497
  }).catch((t) => {
1475
1498
  let n = this.swarmPeerMetadata.get(e);
@@ -1552,7 +1575,8 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1552
1575
  }, {
1553
1576
  maxCpuLoad: this.effectiveMaxCpuLoad(),
1554
1577
  fileSourceOrigins: Q(this.config.fileSourceOrigins),
1555
- containerImageOrigins: Q(this.config.containerImageOrigins)
1578
+ containerImageOrigins: Q(this.config.containerImageOrigins),
1579
+ ccRangeOrigins: Q(this.config.ccRangeOrigins)
1556
1580
  });
1557
1581
  this.send({
1558
1582
  type: "result",
@@ -1564,11 +1588,11 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1564
1588
  this.inflightTasks.delete(e.taskId), this.attempts.delete(e.taskId);
1565
1589
  }
1566
1590
  }
1567
- async runLocalAiInference(e, t) {
1568
- if (!this.workerPool) throw new r("No running Crowd node on this device", "node_not_running");
1569
- if (z() !== "granted") throw new r("Crowd consent is not granted", "consent_not_granted");
1570
- let n = `local-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1571
- return await this.workerPool.run(n, "ai-inference", e, 3e5, t, {
1591
+ async runLocalAiInference(t, n) {
1592
+ if (!this.workerPool) throw new e("No running Crowd node on this device", "node_not_running");
1593
+ if (B() !== "granted") throw new e("Crowd consent is not granted", "consent_not_granted");
1594
+ let r = `local-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1595
+ return await this.workerPool.run(r, "ai-inference", t, 3e5, n, {
1572
1596
  maxCpuLoad: this.effectiveMaxCpuLoad(),
1573
1597
  fileSourceOrigins: Q(this.config.fileSourceOrigins),
1574
1598
  containerImageOrigins: Q(this.config.containerImageOrigins)
@@ -1576,25 +1600,32 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1576
1600
  }
1577
1601
  isAiModelPreloaded(e) {
1578
1602
  let t = this.workerPool.modelCacheSnapshot;
1579
- return t ? t.entries.some((t) => t.modelId === e && t.state === "ready") : !1;
1603
+ if (!t) return !1;
1604
+ if (typeof e == "string") return t.entries.some((t) => t.modelId === e && t.state === "ready");
1605
+ let n = e.dtype ?? "q4f16", r = e.device ?? "wasm";
1606
+ return t.entries.some((t) => t.modelId === e.model && t.dtype === n && t.backend === r && t.state === "ready");
1580
1607
  }
1581
1608
  async preloadAiModel(e) {
1582
1609
  let t = `preload-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1583
1610
  await this.workerPool.run(t, "ai-preload", e, 3e5, void 0, { maxCpuLoad: this.effectiveMaxCpuLoad() });
1584
1611
  }
1585
1612
  startLightPreloader() {
1586
- this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = new nn(() => z(), {
1613
+ this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = new sn(() => B(), {
1587
1614
  targets: [{
1588
- model: Xt,
1589
- task: Zt,
1590
- dtype: Qt
1615
+ model: en,
1616
+ task: tn,
1617
+ dtype: nn
1591
1618
  }, {
1592
- model: $t,
1593
- task: en,
1594
- dtype: tn
1619
+ model: rn,
1620
+ task: an,
1621
+ dtype: on
1595
1622
  }],
1596
- onPreloaded: () => {}
1597
- }, (e) => this.isAiModelPreloaded(e), (e) => this.preloadAiModel(e)), this.lightPreloader.start();
1623
+ onPreloaded: () => {},
1624
+ hasMemoryHeadroom: () => v()
1625
+ }, (e) => this.isAiModelPreloaded({
1626
+ model: e.model,
1627
+ dtype: e.dtype
1628
+ }), (e) => this.preloadAiModel(e)), this.lightPreloader.start();
1598
1629
  }
1599
1630
  stopLightPreloader() {
1600
1631
  this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = null;
@@ -1633,7 +1664,7 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1633
1664
  this.batteryState = null, this.networkState = null;
1634
1665
  }
1635
1666
  mobileLifecycleDecision() {
1636
- return Yt({
1667
+ return $t({
1637
1668
  hidden: document.hidden,
1638
1669
  pageHidden: this.lifecyclePageHidden,
1639
1670
  online: !this.lifecycleOffline && navigator.onLine !== !1,
@@ -1649,80 +1680,80 @@ var rn = "flaxia_node_id", an = "flaxia_node_token", on = class {
1649
1680
  refreshMobileLifecycle() {
1650
1681
  this.mobileLifecycleDecision().suspend ? this.suspend() : this.suspended && this.resume();
1651
1682
  }
1652
- }, $ = "__flaxia_node_signal_client", sn = "__flaxia_node_init_started", cn = "__flaxia_node_controller", ln = (e) => {
1653
- if (z() !== "granted") {
1683
+ }, $ = "__flaxia_node_signal_client", dn = "__flaxia_node_init_started", fn = "__flaxia_node_controller", pn = (e) => {
1684
+ if (B() !== "granted") {
1654
1685
  Z("refusing to start the node without a granted consent record");
1655
1686
  return;
1656
1687
  }
1657
1688
  let t = window[$];
1658
- t && t.disconnect(), V(an);
1659
- let n = new URL("./worker.js", "" + import.meta.url).href, r = new St(n), i = $e(rn);
1660
- i || (i = nt(), et(rn, i));
1661
- let a = new on(e, r, i);
1689
+ t && t.disconnect(), it(ln);
1690
+ let n = new URL("./worker.js", "" + import.meta.url).href, r = new Et(n), i = nt(cn);
1691
+ i || (i = ot(), rt(cn, i));
1692
+ let a = new un(e, r, i);
1662
1693
  window[$] = a, a.connect();
1663
- }, un = class {
1694
+ }, mn = class {
1664
1695
  constructor(e) {
1665
1696
  this.config = e;
1666
1697
  }
1667
1698
  start() {
1668
- this.isRunning() || !Be() || ln(this.config);
1699
+ this.isRunning() || !Ue() || pn(this.config);
1669
1700
  }
1670
1701
  stop() {
1671
1702
  let e = window[$];
1672
- e && e.disconnect(), delete window[$], delete window[sn];
1703
+ e && e.disconnect(), delete window[$], delete window[dn];
1673
1704
  }
1674
1705
  isRunning() {
1675
1706
  return !!window[$];
1676
1707
  }
1677
1708
  getConsentState() {
1678
- return z();
1709
+ return B();
1679
1710
  }
1680
1711
  grant() {
1681
- Je();
1712
+ Ze();
1682
1713
  }
1683
1714
  deny() {
1684
- Ze(), this.stop(), V(an);
1715
+ et(), this.stop(), it(ln);
1685
1716
  }
1686
1717
  clearConsent() {
1687
- Qe(), this.stop(), V(an);
1718
+ tt(), this.stop(), it(ln);
1688
1719
  }
1689
- async runLocalAiInference(e, t) {
1690
- let n = window[$];
1691
- if (!n || !this.isRunning()) throw new r("No running Crowd node on this device", "node_not_running");
1692
- return n.runLocalAiInference(e, t);
1720
+ async runLocalAiInference(t, n) {
1721
+ let r = window[$];
1722
+ if (!r || !this.isRunning()) throw new e("No running Crowd node on this device", "node_not_running");
1723
+ return r.runLocalAiInference(t, n);
1693
1724
  }
1694
1725
  isAiModelPreloaded(e) {
1695
1726
  let t = window[$];
1696
1727
  return t ? t.isAiModelPreloaded(e) : !1;
1697
1728
  }
1698
- async preloadAiModel(e) {
1699
- let t = window[$];
1700
- if (!t) throw new r("No running Crowd node on this device", "node_not_running");
1701
- await t.preloadAiModel(e);
1729
+ async preloadAiModel(t) {
1730
+ let n = window[$];
1731
+ if (!n) throw new e("No running Crowd node on this device", "node_not_running");
1732
+ await n.preloadAiModel(t);
1702
1733
  }
1703
- }, dn = (e) => {
1704
- let t = window[cn];
1734
+ }, hn = (e) => {
1735
+ let t = window[fn];
1705
1736
  if (t) return t;
1706
- let n = new un(e);
1707
- window[cn] = n, window[sn] = !0;
1708
- let r = z();
1737
+ let n = new mn(e);
1738
+ window[fn] = n, window[dn] = !0;
1739
+ let r = B();
1709
1740
  if (r === "granted") return n.start(), n;
1710
1741
  if (r === "denied") return n;
1711
1742
  if (e.consent.onConsentRequired) return e.consent.onConsentRequired({
1712
1743
  state: r,
1713
1744
  accept: () => {
1714
- Je(), n.start();
1745
+ Ze(), n.start();
1715
1746
  },
1716
1747
  reject: () => {
1717
- Ze();
1748
+ et();
1718
1749
  }
1719
1750
  }), n;
1720
1751
  let i = document.createElement("div");
1721
- return i.id = "flaxia-consent-container", document.body.appendChild(i), new xt(i, e.consent, () => {
1722
- Je(), i.remove(), n.start();
1752
+ return i.id = "flaxia-consent-container", document.body.appendChild(i), new Tt(i, e.consent, () => {
1753
+ Ze(), i.remove(), n.start();
1723
1754
  }, () => {
1724
- Ze(), i.remove();
1755
+ et(), i.remove();
1725
1756
  }), n;
1726
1757
  };
1727
1758
  //#endregion
1728
- export { tn as LIGHT_INFERENCE_PLAMO_TRANSLATE_DTYPE, oe as LIGHT_INFERENCE_PLAMO_TRANSLATE_DTYPE_ID, $t as LIGHT_INFERENCE_PLAMO_TRANSLATE_MODEL, re as LIGHT_INFERENCE_PLAMO_TRANSLATE_MODEL_ID, en as LIGHT_INFERENCE_PLAMO_TRANSLATE_TASK, ae as LIGHT_INFERENCE_PLAMO_TRANSLATE_TASK_ID, b as LIGHT_INFERENCE_TRANSLATE_DTYPE, Xt as LIGHT_INFERENCE_TRANSLATE_MODEL, y as LIGHT_INFERENCE_TRANSLATE_MODEL_ID, ie as LIGHT_INFERENCE_TRANSLATE_TASK, z as getFlaxiaNodeConsentState, dn as initFlaxiaNode, B as initFlaxiaNodeConsent, te as isAiModelPreloaded, ne as preloadAiModel, Xe as setFlaxiaNodeHostManagedConsent };
1759
+ export { on as LIGHT_INFERENCE_PLAMO_TRANSLATE_DTYPE, ue as LIGHT_INFERENCE_PLAMO_TRANSLATE_DTYPE_ID, rn as LIGHT_INFERENCE_PLAMO_TRANSLATE_MODEL, se as LIGHT_INFERENCE_PLAMO_TRANSLATE_MODEL_ID, an as LIGHT_INFERENCE_PLAMO_TRANSLATE_TASK, le as LIGHT_INFERENCE_PLAMO_TRANSLATE_TASK_ID, ae as LIGHT_INFERENCE_TRANSLATE_DTYPE, en as LIGHT_INFERENCE_TRANSLATE_MODEL, re as LIGHT_INFERENCE_TRANSLATE_MODEL_ID, ce as LIGHT_INFERENCE_TRANSLATE_TASK, B as getFlaxiaNodeConsentState, hn as initFlaxiaNode, V as initFlaxiaNodeConsent, ie as isAiModelPreloaded, oe as preloadAiModel, $e as setFlaxiaNodeHostManagedConsent };