@flaxia/node 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/assets/ai-inference.js +288 -86
  2. package/dist/assets/transformers.web.js +2 -2
  3. package/dist/assets/vector-embed.js +1 -1
  4. package/dist/assets/webgpuProbe.js +365 -0
  5. package/dist/client/SignalingClient.d.ts.map +1 -1
  6. package/dist/client/__tests__/light-preloader.test.d.ts +2 -0
  7. package/dist/client/__tests__/light-preloader.test.d.ts.map +1 -0
  8. package/dist/client/__tests__/mobile-lifecycle.test.d.ts +2 -0
  9. package/dist/client/__tests__/mobile-lifecycle.test.d.ts.map +1 -0
  10. package/dist/client/light-preloader.d.ts +47 -0
  11. package/dist/client/light-preloader.d.ts.map +1 -0
  12. package/dist/client/mobile-lifecycle.d.ts +20 -0
  13. package/dist/client/mobile-lifecycle.d.ts.map +1 -0
  14. package/dist/executor/WorkerPool.d.ts +7 -1
  15. package/dist/executor/WorkerPool.d.ts.map +1 -1
  16. package/dist/executor/__tests__/resourceReporter.test.d.ts +2 -0
  17. package/dist/executor/__tests__/resourceReporter.test.d.ts.map +1 -0
  18. package/dist/executor/memoryProbe.d.ts +5 -0
  19. package/dist/executor/memoryProbe.d.ts.map +1 -1
  20. package/dist/executor/resourceReporter.d.ts +15 -0
  21. package/dist/executor/resourceReporter.d.ts.map +1 -0
  22. package/dist/executor/webgpuProbe.d.ts +16 -5
  23. package/dist/executor/webgpuProbe.d.ts.map +1 -1
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +1093 -354
  27. package/dist/swarm/__tests__/peer-quality.test.d.ts +2 -0
  28. package/dist/swarm/__tests__/peer-quality.test.d.ts.map +1 -0
  29. package/dist/swarm/__tests__/peer-transport.test.d.ts +2 -0
  30. package/dist/swarm/__tests__/peer-transport.test.d.ts.map +1 -0
  31. package/dist/swarm/adapter.d.ts +1 -1
  32. package/dist/swarm/adapter.d.ts.map +1 -1
  33. package/dist/swarm/controller.d.ts +4 -0
  34. package/dist/swarm/controller.d.ts.map +1 -1
  35. package/dist/swarm/messages.d.ts +2 -2
  36. package/dist/swarm/messages.d.ts.map +1 -1
  37. package/dist/swarm/peer-quality.d.ts +14 -0
  38. package/dist/swarm/peer-quality.d.ts.map +1 -0
  39. package/dist/swarm/peer-transport.d.ts +81 -0
  40. package/dist/swarm/peer-transport.d.ts.map +1 -0
  41. package/dist/swarm/runtime.d.ts +5 -1
  42. package/dist/swarm/runtime.d.ts.map +1 -1
  43. package/dist/swarm-engine.js +39 -20
  44. package/dist/worker.js +317 -185
  45. package/dist/workloads/__tests__/model-pipeline-cache.test.d.ts +2 -0
  46. package/dist/workloads/__tests__/model-pipeline-cache.test.d.ts.map +1 -0
  47. package/dist/workloads/ai-inference.d.ts +27 -0
  48. package/dist/workloads/ai-inference.d.ts.map +1 -1
  49. package/dist/workloads/ai-model-registry.d.ts +6 -0
  50. package/dist/workloads/ai-model-registry.d.ts.map +1 -1
  51. package/dist/workloads/model-pipeline-cache.d.ts +48 -0
  52. package/dist/workloads/model-pipeline-cache.d.ts.map +1 -0
  53. package/package.json +2 -2
  54. package/dist/assets/dist.js +0 -209
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
- import { d as e, f as t, m as n, p as r, r as i, u as a, v as o, x as s, y as c } from "./assets/dist.js";
2
- import { t as l } from "./assets/egress-guard.js";
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, n as te, o as b, r as ne, t as re } from "./assets/ai-inference.js";
3
4
  //#region src/consent/notice.ts
4
- var u = {
5
+ var x = {
5
6
  summary: "同意すると、このブラウザは第三者から依頼された処理をバックグラウンドで実行します。",
6
7
  items: [
7
8
  "実行する処理: 顧客(第三者)が依頼したワークロード。任意の WebAssembly コンテナの実行や、画像の NSFW(成人向け)判定などを含みます。",
@@ -12,34 +13,34 @@ var u = {
12
13
  acceptGateHint: "開示内容を確認できるよう、「同意して開始」はしばらくの間押せません。",
13
14
  acceptLabel: "同意して開始",
14
15
  rejectLabel: "拒否"
15
- }, d = 4320 * 60 * 60 * 1e3, f = "flaxia_consent_record", p = "flaxia_consent_granted", m = "flaxia_consent_expiry", h = "flaxia_consent_denied", g = 1, _ = 1e4, v = 2e3, ee = "flaxia-consent-integrity", te = 1, y = "keys", b = "consent-hmac-sha256-v1", x = (...e) => console.warn("[flaxia-node]", ...e), S = /* @__PURE__ */ new Map();
16
- function C(e) {
16
+ }, ie = 4320 * 60 * 60 * 1e3, S = "flaxia_consent_record", ae = "flaxia_consent_granted", oe = "flaxia_consent_expiry", C = "flaxia_consent_denied", se = 1, ce = 1e4, le = 2e3, ue = "flaxia-consent-integrity", de = 1, w = "keys", fe = "consent-hmac-sha256-v1", pe = (...e) => console.warn("[flaxia-node]", ...e), me = /* @__PURE__ */ new Map();
17
+ function he(e) {
17
18
  try {
18
19
  return localStorage.getItem(e);
19
20
  } catch {
20
- return S.get(e) ?? null;
21
+ return me.get(e) ?? null;
21
22
  }
22
23
  }
23
- function ne(e, t) {
24
+ function ge(e, t) {
24
25
  try {
25
26
  localStorage.setItem(e, t);
26
27
  } catch {
27
- S.set(e, t);
28
+ me.set(e, t);
28
29
  }
29
30
  }
30
- function w(e) {
31
+ function T(e) {
31
32
  try {
32
33
  localStorage.removeItem(e);
33
34
  } catch {
34
- S.delete(e);
35
+ me.delete(e);
35
36
  }
36
37
  }
37
- function re(e) {
38
+ function _e(e) {
38
39
  return new Promise((t, n) => {
39
40
  e.onsuccess = () => t(e.result), e.onerror = () => n(e.error ?? /* @__PURE__ */ Error("IndexedDB request failed"));
40
41
  });
41
42
  }
42
- function T() {
43
+ function E() {
43
44
  return new Promise((e, t) => {
44
45
  let n;
45
46
  try {
@@ -53,37 +54,37 @@ function T() {
53
54
  }
54
55
  let r;
55
56
  try {
56
- r = n.open(ee, te);
57
+ r = n.open(ue, de);
57
58
  } catch (e) {
58
59
  t(e);
59
60
  return;
60
61
  }
61
62
  r.onupgradeneeded = () => {
62
63
  let e = r.result;
63
- e.objectStoreNames.contains(y) || e.createObjectStore(y);
64
+ e.objectStoreNames.contains(w) || e.createObjectStore(w);
64
65
  }, r.onsuccess = () => e(r.result), r.onerror = () => t(r.error ?? /* @__PURE__ */ Error("IndexedDB open failed")), r.onblocked = () => t(/* @__PURE__ */ Error("IndexedDB open blocked"));
65
66
  });
66
67
  }
67
- function ie(e) {
68
+ function ve(e) {
68
69
  if (!e || typeof e != "object") return !1;
69
70
  let t = e;
70
71
  return t.type === "secret" && t.algorithm?.name === "HMAC";
71
72
  }
72
- var ae = {
73
+ var ye = {
73
74
  async load() {
74
- let e = await T();
75
+ let e = await E();
75
76
  try {
76
- let t = await re(e.transaction(y, "readonly").objectStore(y).get(b));
77
- return ie(t) ? t : null;
77
+ let t = await _e(e.transaction(w, "readonly").objectStore(w).get(fe));
78
+ return ve(t) ? t : null;
78
79
  } finally {
79
80
  e.close();
80
81
  }
81
82
  },
82
83
  async save(e) {
83
- let t = await T();
84
+ let t = await E();
84
85
  try {
85
- let n = t.transaction(y, "readwrite");
86
- n.objectStore(y).put(e, b), await new Promise((e, t) => {
86
+ let n = t.transaction(w, "readwrite");
87
+ n.objectStore(w).put(e, fe), await new Promise((e, t) => {
87
88
  n.oncomplete = () => e(), n.onerror = () => t(n.error ?? /* @__PURE__ */ Error("IndexedDB write failed")), n.onabort = () => t(n.error ?? /* @__PURE__ */ Error("IndexedDB write aborted"));
88
89
  });
89
90
  } finally {
@@ -91,10 +92,10 @@ var ae = {
91
92
  }
92
93
  },
93
94
  async clear() {
94
- let e = await T();
95
+ let e = await E();
95
96
  try {
96
- let t = e.transaction(y, "readwrite");
97
- t.objectStore(y).delete(b), await new Promise((e, n) => {
97
+ let t = e.transaction(w, "readwrite");
98
+ t.objectStore(w).delete(fe), await new Promise((e, n) => {
98
99
  t.oncomplete = () => e(), t.onerror = () => n(t.error ?? /* @__PURE__ */ Error("IndexedDB delete failed")), t.onabort = () => n(t.error ?? /* @__PURE__ */ Error("IndexedDB delete aborted"));
99
100
  });
100
101
  } finally {
@@ -102,7 +103,7 @@ var ae = {
102
103
  }
103
104
  }
104
105
  };
105
- function E(e, t, n) {
106
+ function be(e, t, n) {
106
107
  return new Promise((r) => {
107
108
  let i = !1, a, o = (e) => {
108
109
  i || (i = !0, a !== void 0 && clearTimeout(a), r(e));
@@ -110,26 +111,26 @@ function E(e, t, n) {
110
111
  a = setTimeout(() => o(t), n), e.then((e) => o(e), () => o(t));
111
112
  });
112
113
  }
113
- var D = ae, O = null, k = null, A = !1, j = !1, M = null, N = 0, P = 0, F = null, oe = !1;
114
- function se() {
114
+ var xe = ye, D = null, O = null, k = !1, A = !1, j = null, M = 0, N = 0, P = null, Se = !1;
115
+ function Ce() {
115
116
  try {
116
117
  let e = globalThis.location?.origin;
117
118
  if (typeof e == "string" && e.length > 0) return e;
118
119
  } catch {}
119
120
  return "unknown";
120
121
  }
121
- var ce = se, le = () => ce(), ue = {
122
+ var we = Ce, Te = () => we(), Ee = {
122
123
  name: "HMAC",
123
124
  hash: "SHA-256"
124
125
  };
125
- function I() {
126
+ function F() {
126
127
  try {
127
128
  let e = globalThis.crypto?.subtle;
128
129
  if (e && typeof e.generateKey == "function" && typeof e.sign == "function" && typeof e.verify == "function") return e;
129
130
  } catch {}
130
131
  return null;
131
132
  }
132
- function de(e) {
133
+ function De(e) {
133
134
  let t = new TextEncoder().encode(JSON.stringify([
134
135
  e.v,
135
136
  e.noticeVersion,
@@ -139,12 +140,12 @@ function de(e) {
139
140
  ])), n = new Uint8Array(t.byteLength);
140
141
  return n.set(t), n;
141
142
  }
142
- function fe(e) {
143
+ function Oe(e) {
143
144
  let t = "";
144
145
  for (let n of e) t += String.fromCharCode(n);
145
146
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
146
147
  }
147
- function pe(e) {
148
+ function ke(e) {
148
149
  try {
149
150
  let t = e.replace(/-/g, "+").replace(/_/g, "/"), n = t + "=".repeat((4 - t.length % 4) % 4), r = atob(n), i = new Uint8Array(r.length);
150
151
  for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
@@ -153,40 +154,40 @@ function pe(e) {
153
154
  return null;
154
155
  }
155
156
  }
156
- async function me() {
157
- let e = await E(D.load(), null, v);
157
+ async function Ae() {
158
+ let e = await be(xe.load(), null, le);
158
159
  if (e) return e;
159
- let t = I();
160
+ let t = F();
160
161
  if (!t) return null;
161
162
  try {
162
- let e = await t.generateKey(ue, !1, ["sign", "verify"]);
163
- return await E(D.save(e), void 0, v), e;
163
+ let e = await t.generateKey(Ee, !1, ["sign", "verify"]);
164
+ return await be(xe.save(e), void 0, le), e;
164
165
  } catch {
165
166
  return null;
166
167
  }
167
168
  }
168
- async function he(e) {
169
- let t = I();
170
- if (!t || !O) return null;
169
+ async function je(e) {
170
+ let t = F();
171
+ if (!t || !D) return null;
171
172
  try {
172
- let n = await t.sign("HMAC", O, de(e));
173
- return fe(new Uint8Array(n));
173
+ let n = await t.sign("HMAC", D, De(e));
174
+ return Oe(new Uint8Array(n));
174
175
  } catch {
175
176
  return null;
176
177
  }
177
178
  }
178
- async function ge(e) {
179
- let t = I();
180
- if (!t || !O || !e.mac) return !1;
181
- let n = pe(e.mac);
179
+ async function Me(e) {
180
+ let t = F();
181
+ if (!t || !D || !e.mac) return !1;
182
+ let n = ke(e.mac);
182
183
  if (!n) return !1;
183
184
  try {
184
- return await t.verify("HMAC", O, n, de(e));
185
+ return await t.verify("HMAC", D, n, De(e));
185
186
  } catch {
186
187
  return !1;
187
188
  }
188
189
  }
189
- function _e(e) {
190
+ function Ne(e) {
190
191
  if (!e) return null;
191
192
  try {
192
193
  let t = JSON.parse(e);
@@ -204,128 +205,128 @@ function _e(e) {
204
205
  return null;
205
206
  }
206
207
  }
207
- function L(e, t) {
208
+ function Pe(e, t) {
208
209
  return !(!Number.isFinite(e.grantedAt) || !Number.isFinite(e.expiry) || e.expiry <= t || e.grantedAt > e.expiry || e.expiry - e.grantedAt > 15552e6);
209
210
  }
210
- function R(e) {
211
- return e.v === g && e.noticeVersion === 2 && e.origin === le();
211
+ function I(e) {
212
+ return e.v === se && e.noticeVersion === 2 && e.origin === Te();
212
213
  }
213
- function z() {
214
- return _e(C(f));
214
+ function Fe() {
215
+ return Ne(he(S));
215
216
  }
216
- function ve(e) {
217
- ne(f, JSON.stringify(e));
217
+ function Ie(e) {
218
+ ge(S, JSON.stringify(e));
218
219
  }
219
- function B() {
220
- w(f);
220
+ function L() {
221
+ T(S);
221
222
  }
222
- function V() {
223
- w(p), w(m);
223
+ function R() {
224
+ T(ae), T(oe);
224
225
  }
225
- var ye = () => {
226
- let e = k;
227
- return !e || !A ? !1 : L(e, Date.now()) && R(e);
228
- }, be = () => C(h) === "true", H = () => ye() ? "granted" : be() ? "denied" : "unset", U = () => (M ||= xe(), M);
229
- async function xe() {
230
- let e = ++N, t = P, n = null;
226
+ var Le = () => {
227
+ let e = O;
228
+ return !e || !k ? !1 : Pe(e, Date.now()) && I(e);
229
+ }, Re = () => he(C) === "true", z = () => Le() ? "granted" : Re() ? "denied" : "unset", B = () => (j ||= ze(), j);
230
+ async function ze() {
231
+ let e = ++M, t = N, n = null;
231
232
  try {
232
- n = await me();
233
+ n = await Ae();
233
234
  } catch {
234
235
  n = null;
235
236
  }
236
- if (e !== N) return H();
237
- O = n, V();
238
- let r = z();
239
- return r !== null && await ge(r) && L(r, Date.now()) && R(r) && r ? t === P && e === N && (k = r, A = !0) : r && !j && (B(), t === P && e === N && (k = null, A = !1)), H();
237
+ if (e !== M) return z();
238
+ D = n, R();
239
+ let r = Fe();
240
+ return r !== null && await Me(r) && Pe(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();
240
241
  }
241
- function Se() {
242
- let e = F;
243
- return F = null, e && Date.now() - e.at <= _ ? {
242
+ function Be() {
243
+ let e = P;
244
+ return P = null, e && Date.now() - e.at <= ce ? {
244
245
  noticeVersion: e.noticeVersion,
245
246
  source: "user-gesture"
246
- } : oe ? {
247
+ } : Se ? {
247
248
  noticeVersion: 2,
248
249
  source: "host-managed"
249
250
  } : null;
250
251
  }
251
- function Ce(e) {
252
- return typeof e != "number" || !Number.isFinite(e) || e <= 0 ? d : Math.min(Math.floor(e), d);
252
+ function Ve(e) {
253
+ return typeof e != "number" || !Number.isFinite(e) || e <= 0 ? ie : Math.min(Math.floor(e), ie);
253
254
  }
254
- function we(e, t) {
255
+ function He(e, t) {
255
256
  let n = Date.now();
256
257
  return {
257
- v: g,
258
+ v: se,
258
259
  noticeVersion: e,
259
- origin: le(),
260
+ origin: Te(),
260
261
  grantedAt: n,
261
- expiry: n + Ce(t),
262
+ expiry: n + Ve(t),
262
263
  mac: ""
263
264
  };
264
265
  }
265
- function Te(e, t) {
266
- w(h), V();
267
- let n = we(e.noticeVersion, t);
268
- return k = n, A = !0, j = !0, P += 1, ve(n), n;
266
+ function Ue(e, t) {
267
+ T(C), R();
268
+ let n = He(e.noticeVersion, t);
269
+ return O = n, k = !0, A = !0, N += 1, Ie(n), n;
269
270
  }
270
- async function Ee(e) {
271
+ async function We(e) {
271
272
  try {
272
- if (await U(), k !== e) return;
273
- let t = await he(e);
274
- if (k !== e) return;
273
+ if (await B(), O !== e) return;
274
+ let t = await je(e);
275
+ if (O !== e) return;
275
276
  if (!t) {
276
- B(), j = !1;
277
+ L(), A = !1;
277
278
  return;
278
279
  }
279
280
  let n = {
280
281
  ...e,
281
282
  mac: t
282
283
  };
283
- k = n, A = !0, ve(n), j = !1;
284
+ O = n, k = !0, Ie(n), A = !1;
284
285
  } catch {
285
- k === e && (B(), j = !1);
286
+ O === e && (L(), A = !1);
286
287
  }
287
288
  }
288
- var W = () => {
289
- let e = Se();
289
+ var Ge = () => {
290
+ let e = Be();
290
291
  if (!e) {
291
- x("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
+ pe("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
293
  return;
293
294
  }
294
- Ee(Te(e));
295
- }, De = (e = 2) => {
296
- F = {
295
+ We(Ue(e));
296
+ }, Ke = (e = 2) => {
297
+ P = {
297
298
  noticeVersion: e,
298
299
  at: Date.now()
299
300
  };
300
- }, Oe = (e) => {
301
- oe = e === !0;
302
- }, G = () => {
303
- B(), V(), k = null, A = !1, j = !1, P += 1, ne(h, "true");
304
- }, ke = () => {
305
- B(), V(), w(h), k = null, A = !1, j = !1, F = null, O = null, N += 1, P += 1, M = null, E(D.clear(), void 0, v);
306
- }, Ae = C, je = ne, K = w;
307
- async function Me() {
308
- let e = P, t = z();
301
+ }, qe = (e) => {
302
+ Se = e === !0;
303
+ }, Je = () => {
304
+ L(), R(), O = null, k = !1, A = !1, N += 1, ge(C, "true");
305
+ }, Ye = () => {
306
+ L(), R(), T(C), O = null, k = !1, A = !1, P = null, D = null, M += 1, N += 1, j = null, be(xe.clear(), void 0, le);
307
+ }, Xe = he, Ze = ge, V = T;
308
+ async function Qe() {
309
+ let e = N, t = Fe();
309
310
  if (!t) {
310
- k = null, A = !1;
311
+ O = null, k = !1;
311
312
  return;
312
313
  }
313
- if (!I()) return;
314
- if (!O) {
315
- M = null, await U();
314
+ if (!F()) return;
315
+ if (!D) {
316
+ j = null, await B();
316
317
  return;
317
318
  }
318
- let n = await ge(t), r = z();
319
- if (e !== P || !r || JSON.stringify(r) !== JSON.stringify(t)) return;
320
- let i = n && L(t, Date.now()) && R(t);
321
- k = i ? t : null, A = i;
319
+ let n = await Me(t), r = Fe();
320
+ if (e !== N || !r || JSON.stringify(r) !== JSON.stringify(t)) return;
321
+ let i = n && Pe(t, Date.now()) && I(t);
322
+ O = i ? t : null, k = i;
322
323
  }
323
324
  try {
324
325
  typeof globalThis.addEventListener == "function" && globalThis.addEventListener("storage", (e) => {
325
- e.key !== null && e.key !== f && e.key !== h || (P += 1, Me());
326
+ e.key !== null && e.key !== S && e.key !== C || (N += 1, Qe());
326
327
  });
327
328
  } catch {}
328
- var Ne = () => {
329
+ var $e = () => {
329
330
  try {
330
331
  if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
331
332
  } catch {}
@@ -334,38 +335,38 @@ var Ne = () => {
334
335
  return (e === "x" ? t : t & 3 | 8).toString(16);
335
336
  });
336
337
  };
337
- U();
338
+ B();
338
339
  //#endregion
339
340
  //#region src/consent/ConsentUI.ts
340
- var q = "#6366f1", Pe = 1500, Fe = 1500, Ie = 6e4, Le = 80, Re = 40, ze = [
341
+ var H = "#6366f1", et = 1500, tt = 1500, nt = 6e4, rt = 80, it = 40, at = [
341
342
  "bottom-right",
342
343
  "bottom-left",
343
344
  "top-right",
344
345
  "top-left"
345
- ], Be = /^#[0-9a-f]{3}$/i, Ve = /^#[0-9a-f]{6}$/i, He = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i, Ue = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i, We = 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]));
346
- function Ge(e) {
347
- if (typeof e != "string") return q;
346
+ ], ot = /^#[0-9a-f]{3}$/i, st = /^#[0-9a-f]{6}$/i, ct = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i, lt = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i, ut = 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 dt(e) {
348
+ if (typeof e != "string") return H;
348
349
  let t = e.trim();
349
- if (t.length === 0 || t.length > 64) return q;
350
- if (Be.test(t) || Ve.test(t)) return t.toLowerCase();
351
- let n = He.exec(t);
350
+ if (t.length === 0 || t.length > 64) return H;
351
+ if (ot.test(t) || st.test(t)) return t.toLowerCase();
352
+ let n = ct.exec(t);
352
353
  if (n) {
353
354
  let [e, t, r] = n.slice(1).map(Number);
354
- return e <= 255 && t <= 255 && r <= 255 ? `rgb(${e}, ${t}, ${r})` : q;
355
+ return e <= 255 && t <= 255 && r <= 255 ? `rgb(${e}, ${t}, ${r})` : H;
355
356
  }
356
- let r = Ue.exec(t);
357
+ let r = lt.exec(t);
357
358
  if (r) {
358
359
  let [e, t, n] = r.slice(1, 4).map(Number), i = Number(r[4]);
359
- return e <= 255 && t <= 255 && n <= 255 && i >= 0 && i <= 1 ? `rgba(${e}, ${t}, ${n}, ${i})` : q;
360
+ return e <= 255 && t <= 255 && n <= 255 && i >= 0 && i <= 1 ? `rgba(${e}, ${t}, ${n}, ${i})` : H;
360
361
  }
361
- return We.get(t.toLowerCase()) ?? q;
362
+ return ut.get(t.toLowerCase()) ?? H;
362
363
  }
363
- function Ke(e, t, n) {
364
+ function ft(e, t, n) {
364
365
  if (typeof e != "string") return t;
365
366
  let r = e.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(/\s+/g, " ").trim();
366
367
  return r.length === 0 ? t : r.length > n ? `${r.slice(0, n)}…` : r;
367
368
  }
368
- function qe(e) {
369
+ function pt(e) {
369
370
  if (typeof e != "string" || e.trim().length === 0) return null;
370
371
  try {
371
372
  let t = new URL(e.trim());
@@ -374,75 +375,75 @@ function qe(e) {
374
375
  return null;
375
376
  }
376
377
  }
377
- function Je(e) {
378
+ function mt(e) {
378
379
  return {
379
- brandName: Ke(e?.brandName, "Flaxia Crowd", Le),
380
- position: ze.includes(e?.position) ? e.position : "bottom-right",
381
- accentColor: Ge(e?.accentColor),
382
- acceptLabel: Ke(e?.acceptLabel, u.acceptLabel, Re),
383
- rejectLabel: Ke(e?.rejectLabel, u.rejectLabel, Re),
384
- privacyPolicyUrl: qe(e?.privacyPolicyUrl),
385
- minVisibleMs: Ye(e?.minVisibleMs)
380
+ brandName: ft(e?.brandName, "Flaxia Crowd", rt),
381
+ position: at.includes(e?.position) ? e.position : "bottom-right",
382
+ accentColor: dt(e?.accentColor),
383
+ acceptLabel: ft(e?.acceptLabel, x.acceptLabel, it),
384
+ rejectLabel: ft(e?.rejectLabel, x.rejectLabel, it),
385
+ privacyPolicyUrl: pt(e?.privacyPolicyUrl),
386
+ minVisibleMs: ht(e?.minVisibleMs)
386
387
  };
387
388
  }
388
- function Ye(e) {
389
- return typeof e != "number" || !Number.isFinite(e) ? Pe : Math.min(Math.max(Math.floor(e), Fe), Ie);
389
+ function ht(e) {
390
+ return typeof e != "number" || !Number.isFinite(e) ? et : Math.min(Math.max(Math.floor(e), tt), nt);
390
391
  }
391
- function Xe(e, t) {
392
- return typeof t.minVisibleMs == "number" && Number.isFinite(t.minVisibleMs) ? Math.min(Math.max(Math.floor(t.minVisibleMs), 0), Ie) : e;
392
+ function gt(e, t) {
393
+ return typeof t.minVisibleMs == "number" && Number.isFinite(t.minVisibleMs) ? Math.min(Math.max(Math.floor(t.minVisibleMs), 0), nt) : e;
393
394
  }
394
- var Ze = "\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", Qe = class {
395
+ var _t = "\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", vt = class {
395
396
  constructor(e, t, n, r, i) {
396
- this.config = Je(t), this.options = i ?? {}, this.root = e.attachShadow({ mode: "closed" }), this.render(n, r);
397
+ this.config = mt(t), this.options = i ?? {}, this.root = e.attachShadow({ mode: "closed" }), this.render(n, r);
397
398
  }
398
399
  shadowRootForTesting() {
399
400
  return this.root;
400
401
  }
401
402
  render(e, t) {
402
- let { brandName: n, position: r, accentColor: i, acceptLabel: a, rejectLabel: o, privacyPolicyUrl: s } = this.config, [c, l] = r.split("-"), d = document.createElement("style");
403
- d.textContent = Ze.replace(/__flaxia_accent__/g, i).replace("__flaxia_position__", `${c}: 20px; ${l}: 20px`);
404
- let f = document.createElement("div");
405
- f.className = "overlay", f.setAttribute("role", "dialog"), f.setAttribute("aria-labelledby", "flaxia-consent-title");
406
- let p = document.createElement("h3");
407
- p.id = "flaxia-consent-title", p.textContent = n;
408
- let m = document.createElement("p");
409
- m.textContent = u.summary;
410
- let h = document.createElement("ul");
411
- for (let e of u.items) {
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 = _t.replace(/__flaxia_accent__/g, i).replace("__flaxia_position__", `${c}: 20px; ${l}: 20px`);
405
+ let d = document.createElement("div");
406
+ d.className = "overlay", d.setAttribute("role", "dialog"), d.setAttribute("aria-labelledby", "flaxia-consent-title");
407
+ let f = document.createElement("h3");
408
+ f.id = "flaxia-consent-title", f.textContent = n;
409
+ let p = document.createElement("p");
410
+ p.textContent = x.summary;
411
+ let m = document.createElement("ul");
412
+ for (let e of x.items) {
412
413
  let t = document.createElement("li");
413
- t.textContent = e, h.appendChild(t);
414
+ t.textContent = e, m.appendChild(t);
414
415
  }
415
- if (f.append(p, m, h), s) {
416
+ if (d.append(f, p, m), s) {
416
417
  let e = document.createElement("p");
417
418
  e.className = "privacy";
418
419
  let t = document.createElement("a");
419
- t.href = s, t.target = "_blank", t.rel = "noopener noreferrer", t.textContent = "プライバシーポリシー", e.appendChild(t), f.appendChild(e);
420
+ t.href = s, t.target = "_blank", t.rel = "noopener noreferrer", t.textContent = "プライバシーポリシー", e.appendChild(t), d.appendChild(e);
420
421
  }
421
- let g = document.createElement("p");
422
- g.className = "hint", g.textContent = u.acceptGateHint;
422
+ let h = document.createElement("p");
423
+ h.className = "hint", h.textContent = x.acceptGateHint;
424
+ let g = document.createElement("button");
425
+ g.id = "consent-btn", g.type = "button", g.textContent = a;
423
426
  let _ = document.createElement("button");
424
- _.id = "consent-btn", _.type = "button", _.textContent = a;
425
- let v = document.createElement("button");
426
- v.id = "reject-btn", v.type = "button", v.className = "reject", v.textContent = o;
427
- let ee = this.options.now ?? (() => Date.now()), te = this.options.schedule ?? ((e, t) => void setTimeout(e, t)), y = Xe(this.config.minVisibleMs, this.options), b = ee() + y, x = y <= 0, S = !1;
428
- x || (_.disabled = !0, _.setAttribute("aria-disabled", "true"), te(() => {
429
- x = !0, _.disabled = !1, _.removeAttribute("aria-disabled"), g.remove();
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 = gt(this.config.minVisibleMs, this.options), te = v() + y, b = y <= 0, ne = !1;
429
+ b || (g.disabled = !0, g.setAttribute("aria-disabled", "true"), ee(() => {
430
+ b = !0, g.disabled = !1, g.removeAttribute("aria-disabled"), h.remove();
430
431
  }, y));
431
- let C = (e) => {
432
- S || (S = !0, f.remove(), e?.());
432
+ let re = (e) => {
433
+ ne || (ne = !0, d.remove(), e?.());
433
434
  };
434
- _.addEventListener("click", () => {
435
- !x || ee() < b || (De(2), C(e));
436
- }), v.addEventListener("click", () => {
437
- C(t);
438
- }), x || f.appendChild(g), f.append(_, v), this.root.append(d, f);
435
+ g.addEventListener("click", () => {
436
+ !b || v() < te || (Ke(2), re(e));
437
+ }), _.addEventListener("click", () => {
438
+ re(t);
439
+ }), b || d.appendChild(h), d.append(g, _), this.root.append(u, d);
439
440
  }
440
- }, J = (...e) => console.log("[flaxia-node]", ...e), $e = class e {
441
+ }, U = (...e) => console.log("[flaxia-node]", ...e), yt = class e {
441
442
  static {
442
443
  this.MAX_PENDING_CONTROLS = 64;
443
444
  }
444
445
  constructor(e, t = 3e5) {
445
- this.worker = null, this.queue = [], this.active = null, this.pendingControls = [], this._lastCpuLoad = 0, this.workerUrl = e || "/worker.js", this.defaultTimeoutMs = t, this.initWorker();
446
+ 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();
446
447
  }
447
448
  initWorker() {
448
449
  if (typeof Worker > "u") return;
@@ -460,68 +461,73 @@ var Ze = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
460
461
  return;
461
462
  }
462
463
  let l = () => this.execute(e, t, n, r, i, a, s, c, o);
463
- this.active ? (J(`task queued id=${e} workload=${t} (active task running)`), this.queue.push({
464
+ this.active ? (U(`task queued id=${e} workload=${t} (active task running)`), this.queue.push({
464
465
  id: e,
465
466
  job: l,
466
467
  reject: c
467
468
  })) : l();
468
469
  });
469
470
  }
470
- execute(e, t, n, r, i, a, o, s, c) {
471
- let l = this.worker;
472
- if (!l) {
473
- s(/* @__PURE__ */ Error("Worker not available")), this.dequeue();
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();
474
475
  return;
475
476
  }
476
- let u = r ?? this.defaultTimeoutMs, d = !1, f = performance.now();
477
- J(`task start id=${e} workload=${t} timeoutMs=${u}`);
478
- let p = (t) => {
479
- if (d) return;
480
- d = !0;
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;
481
482
  let n = this.active;
482
483
  n && (clearTimeout(n.timer), n.removeListener()), this.active = null, this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), t(), this.dequeue();
483
- }, m = (n) => {
484
- let { id: r, type: a, result: l, error: u, token: d, cpuLoad: m } = n.data;
484
+ }, g = (n) => {
485
+ let { id: r, type: s, result: d, error: f, token: p, cpuLoad: g } = n.data;
485
486
  if (r === e) {
486
- if (a === "token") {
487
- i?.(d);
487
+ if (i(n.data.modelCache) && (this._modelCacheSnapshot = n.data.modelCache), s === "token") {
488
+ a?.(p);
488
489
  return;
489
490
  }
490
- if (a === "heartbeat") {
491
- typeof m == "number" && Number.isFinite(m) && (this._lastCpuLoad = Math.min(1, Math.max(0, m)));
491
+ if (s === "heartbeat") {
492
+ typeof g == "number" && Number.isFinite(g) && (this._lastCpuLoad = Math.min(1, Math.max(0, g)), this._hasCpuLoadSample = !0);
492
493
  return;
493
494
  }
494
- if (a === "swarm-frame") {
495
- c?.onFrame?.(n.data.frame);
495
+ if (s === "swarm-frame") {
496
+ u?.onFrame?.(n.data.frame);
496
497
  return;
497
498
  }
498
- if (a === "swarm-message") {
499
- c?.onMessage?.(n.data.message);
499
+ if (s === "swarm-message") {
500
+ u?.onMessage?.(n.data.message);
500
501
  return;
501
502
  }
502
- a === "done" ? (J(`task done id=${e} workload=${t} durationMs=${Math.round(performance.now() - f)}`), p(() => o(l))) : a === "error" ? (J(`task failed id=${e} workload=${t} error=${u}`), p(() => s(Error(u)))) : (J(`task unknown-message id=${e} type=${String(a)}`), p(() => s(/* @__PURE__ */ Error(`Unknown message type: ${String(a)}`))));
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)}`)));
503
509
  }
504
- }, h = () => l.removeEventListener("message", m), g = setTimeout(() => {
505
- J(`task timeout id=${e} workload=${t} (worker terminated after ${u}ms)`), this.cleanupWorker(), p(() => s(/* @__PURE__ */ Error("TIMEOUT")));
506
- }, u);
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);
507
513
  this.active = {
508
514
  id: e,
509
- resolve: o,
510
- reject: s,
511
- timer: g,
512
- worker: l,
513
- removeListener: h
514
- }, l.addEventListener("message", m);
515
+ resolve: c,
516
+ reject: l,
517
+ timer: v,
518
+ worker: d,
519
+ removeListener: _
520
+ }, d.addEventListener("message", g);
515
521
  try {
516
- l.postMessage({
522
+ d.postMessage({
517
523
  id: e,
518
524
  workload: t,
519
525
  payload: n,
520
- timeoutMs: u,
521
- config: a
526
+ timeoutMs: f,
527
+ config: s
522
528
  }), this.flushControls();
523
529
  } catch (e) {
524
- p(() => s(e instanceof Error ? e : Error(String(e))));
530
+ h(() => l(e instanceof Error ? e : Error(String(e))));
525
531
  }
526
532
  }
527
533
  flushControls() {
@@ -560,11 +566,17 @@ var Ze = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
560
566
  frame: e
561
567
  }, [e]);
562
568
  }
569
+ setTokenFlow(e, t) {
570
+ return this.active?.id === e ? this.postToActive({
571
+ type: "token-flow",
572
+ paused: t
573
+ }) : !1;
574
+ }
563
575
  abort(e, t) {
564
576
  let n = this.queue.findIndex((t) => t.id === e);
565
577
  if (n >= 0) {
566
578
  let [r] = this.queue.splice(n, 1);
567
- return this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), J(`task aborted before start id=${e} reason=${t}`), r.reject(Error(t)), !0;
579
+ return this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), U(`task aborted before start id=${e} reason=${t}`), r.reject(Error(t)), !0;
568
580
  }
569
581
  if (this.active?.id !== e || !this.worker) return !1;
570
582
  try {
@@ -572,13 +584,13 @@ var Ze = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
572
584
  id: e,
573
585
  type: "abort",
574
586
  reason: t
575
- }), J(`task abort sent id=${e} reason=${t}`), !0;
587
+ }), U(`task abort sent id=${e} reason=${t}`), !0;
576
588
  } catch {
577
589
  return !1;
578
590
  }
579
591
  }
580
592
  handleWorkerError(e) {
581
- J(`worker error error=${e.message}`);
593
+ U(`worker error error=${e.message}`);
582
594
  let t = this.active;
583
595
  this.cleanupWorker(), t && (clearTimeout(t.timer), this.active = null, t.reject(e), this.dequeue());
584
596
  }
@@ -587,13 +599,13 @@ var Ze = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
587
599
  e && e.job();
588
600
  }
589
601
  cleanupWorker() {
590
- this.worker &&= (this.worker.terminate(), null), this.initWorker();
602
+ this.worker &&= (this.worker.terminate(), null), this._modelCacheSnapshot = null, this.initWorker();
591
603
  }
592
604
  terminate() {
593
605
  let e = this.queue;
594
606
  this.queue = [], this.pendingControls = [];
595
607
  for (let t of e) t.reject(/* @__PURE__ */ Error("TERMINATED"));
596
- this.active &&= (clearTimeout(this.active.timer), this.active.reject(/* @__PURE__ */ Error("TERMINATED")), null), this.worker &&= (this.worker.terminate(), null);
608
+ this.active &&= (clearTimeout(this.active.timer), this.active.reject(/* @__PURE__ */ Error("TERMINATED")), null), this.worker &&= (this.worker.terminate(), null), this._modelCacheSnapshot = null;
597
609
  }
598
610
  resume() {
599
611
  this.worker || this.initWorker();
@@ -601,30 +613,623 @@ var Ze = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
601
613
  get lastCpuLoad() {
602
614
  return this._lastCpuLoad;
603
615
  }
604
- }, Y = (...e) => console.log("[flaxia-node]", ...e), X = (...e) => console.error("[flaxia-node]", ...e);
605
- function Z(e) {
616
+ get hasCpuLoadSample() {
617
+ return this._hasCpuLoadSample;
618
+ }
619
+ get modelCacheSnapshot() {
620
+ let e = this._modelCacheSnapshot;
621
+ return !e || e.expiresAt <= Date.now() ? null : e;
622
+ }
623
+ }, W = null, bt = null;
624
+ function G(e, t, n, r, i, a) {
625
+ return {
626
+ value: e,
627
+ unit: t,
628
+ source: n,
629
+ sampledAt: r,
630
+ expiresAt: i,
631
+ sampleCount: a
632
+ };
633
+ }
634
+ function K(e, t, n) {
635
+ return G(null, e, "unknown", t, t + n, 0);
636
+ }
637
+ async function xt(e, t) {
638
+ return e ? ((!W || W.expiresAt <= t) && (bt ||= p().then((e) => (W = e, e)).finally(() => {
639
+ bt = null;
640
+ }), W = await bt), W) : null;
641
+ }
642
+ async function St(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 xt(e.probeGpu === !0, t), s = o?.sampledAt ?? t, c = o?.expiresAt ?? t + 6e5;
644
+ return {
645
+ 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),
651
+ 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)
659
+ }
660
+ };
661
+ }
662
+ //#endregion
663
+ //#region src/swarm/peer-quality.ts
664
+ var Ct = 15e3;
665
+ function wt(e) {
666
+ let t = e.filter((e) => Number.isFinite(e) && e >= 0).slice(-5);
667
+ if (!t.length) return [];
668
+ let n = [...t].sort((e, t) => e - t), r = n[Math.floor(n.length / 2)], i = r + Math.max(20, r * 4);
669
+ return t.filter((e) => e <= i);
670
+ }
671
+ function q(e, t) {
672
+ return !Number.isFinite(e) || e < 0 || !Number.isFinite(t) || t <= 0 ? null : e * 8 / t / 1e3;
673
+ }
674
+ function Tt(e, t) {
675
+ let n = wt(e);
676
+ if (!n.length) return {
677
+ value: null,
678
+ sampledAt: t,
679
+ sampleCount: 0
680
+ };
681
+ let r = [...n].sort((e, t) => e - t);
682
+ return {
683
+ value: r[Math.floor(r.length / 2)],
684
+ sampledAt: t,
685
+ sampleCount: n.length
686
+ };
687
+ }
688
+ function Et(e, t, n, r, i) {
689
+ let o = (e, n) => {
690
+ let r = (r) => {
691
+ let i = n?.[r] ?? t;
692
+ return t - i >= 6e4 ? Tt([], t) : Tt(e[r] ?? [], i);
693
+ };
694
+ return {
695
+ rttMs: r("rttMs"),
696
+ jitterMs: r("jitterMs"),
697
+ sendMbps: r("sendMbps"),
698
+ receiveMbps: r("receiveMbps")
699
+ };
700
+ };
701
+ return {
702
+ version: 1,
703
+ peerNodeId: e,
704
+ sampledAt: t,
705
+ expiresAt: t + a,
706
+ webRtc: o(n, i?.webRtc),
707
+ application: o(r, i?.application)
708
+ };
709
+ }
710
+ //#endregion
711
+ //#region src/swarm/peer-transport.ts
712
+ var Dt = 5e3, J = 16 * 1024, Ot = g, kt = 256 * 1024, At = 1129860166, Y = 16, jt = 2, Mt = 64, Nt = "flaxia-swarm-v1", Pt = "flaxia-peer-quality-v1", Ft = 128, It = [{ urls: "stun:stun.cloudflare.com:3478" }];
713
+ function Lt() {
714
+ return {
715
+ rttMs: [],
716
+ jitterMs: [],
717
+ sendMbps: [],
718
+ receiveMbps: []
719
+ };
720
+ }
721
+ function Rt(e) {
722
+ if (e.byteLength < Y || e.byteLength > 16400) return null;
723
+ let t = new DataView(e);
724
+ if (t.getUint32(0, !0) !== At) return null;
725
+ 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 > Ot || i < 1 || i !== Math.ceil(a / 16384) || r >= i) return null;
727
+ let o = Math.min(J, a - r * J);
728
+ return e.byteLength - Y === o ? {
729
+ messageId: n,
730
+ index: r,
731
+ count: i,
732
+ totalBytes: a,
733
+ payload: new Uint8Array(e, Y)
734
+ } : null;
735
+ }
736
+ function zt(e, t) {
737
+ if (e.byteLength < 1 || e.byteLength > Ot) throw Error(`swarm peer frame size is outside 1..${Ot} bytes`);
738
+ let n = Math.ceil(e.byteLength / J), r = [];
739
+ for (let i = 0; i < n; i++) {
740
+ 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, At, !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
+ }
743
+ return r;
744
+ }
745
+ var Bt = class {
746
+ constructor() {
747
+ this.assemblies = /* @__PURE__ */ new Map();
748
+ }
749
+ accept(e, t = Date.now()) {
750
+ this.expire(t);
751
+ let n = Rt(e);
752
+ if (!n) return null;
753
+ let r = this.assemblies.get(n.messageId);
754
+ if (!r) {
755
+ if (this.assemblies.size >= jt) return null;
756
+ r = {
757
+ count: n.count,
758
+ totalBytes: n.totalBytes,
759
+ parts: Array(n.count),
760
+ received: 0,
761
+ receivedBytes: 0,
762
+ createdAt: t
763
+ }, this.assemblies.set(n.messageId, r);
764
+ }
765
+ if (r.count !== n.count || r.totalBytes !== n.totalBytes) return this.assemblies.delete(n.messageId), null;
766
+ let i = r.parts[n.index];
767
+ if (i) return i.byteLength === n.payload.byteLength && i.every((e, t) => e === n.payload[t]) || this.assemblies.delete(n.messageId), null;
768
+ let a = n.payload.slice();
769
+ if (r.parts[n.index] = a, r.received++, r.receivedBytes += a.byteLength, r.receivedBytes > r.totalBytes) return this.assemblies.delete(n.messageId), null;
770
+ if (r.received !== r.count) return null;
771
+ if (r.receivedBytes !== r.totalBytes) return this.assemblies.delete(n.messageId), null;
772
+ let o = new Uint8Array(r.totalBytes), s = 0;
773
+ for (let e of r.parts) {
774
+ if (!e) return this.assemblies.delete(n.messageId), null;
775
+ o.set(e, s), s += e.byteLength;
776
+ }
777
+ return this.assemblies.delete(n.messageId), o.buffer;
778
+ }
779
+ clear() {
780
+ this.assemblies.clear();
781
+ }
782
+ expire(e) {
783
+ for (let [t, n] of this.assemblies) e - n.createdAt > 5e3 * 2 && this.assemblies.delete(t);
784
+ }
785
+ }, Vt = class {
786
+ constructor(e) {
787
+ this.options = e, this.peers = /* @__PURE__ */ new Map(), this.reassembler = new Bt(), 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
+ }
789
+ get selectedMode() {
790
+ return this.mode;
791
+ }
792
+ async start() {
793
+ if (this.closed || this.peers.size) return;
794
+ if (typeof RTCPeerConnection > "u" && !this.options.createPeerConnection) {
795
+ this.unavailable();
796
+ return;
797
+ }
798
+ let e = [...new Set([this.options.previousNodeId, this.options.nextNodeId])].filter((e) => !!e && e !== this.options.nodeId);
799
+ try {
800
+ for (let t of e) {
801
+ let e = (this.options.createPeerConnection ?? ((e) => new RTCPeerConnection(e)))({ iceServers: It }), n = {
802
+ nodeId: t,
803
+ connection: e,
804
+ channel: null,
805
+ remoteDescriptionSet: !1,
806
+ pendingCandidates: [],
807
+ quality: {
808
+ webRtc: Lt(),
809
+ application: Lt()
810
+ },
811
+ qualitySampledAt: {
812
+ webRtc: {},
813
+ application: {}
814
+ },
815
+ applicationBytesSent: 0,
816
+ applicationBytesReceived: 0,
817
+ lastApplicationBytesSent: 0,
818
+ lastApplicationBytesReceived: 0,
819
+ nextProbeId: 1
820
+ };
821
+ this.peers.set(t, n), e.onicecandidate = (e) => {
822
+ let n = e.candidate;
823
+ this.options.onSignal(t, {
824
+ kind: "candidate",
825
+ candidate: n?.candidate ? {
826
+ candidate: n.candidate,
827
+ sdpMid: n.sdpMid,
828
+ sdpMLineIndex: n.sdpMLineIndex,
829
+ usernameFragment: n.usernameFragment
830
+ } : null
831
+ });
832
+ }, e.ondatachannel = (e) => this.bindChannel(n, e.channel), e.onconnectionstatechange = () => {
833
+ (e.connectionState === "failed" || e.connectionState === "closed") && this.unavailable();
834
+ };
835
+ }
836
+ for (let e of this.peers.values()) {
837
+ let { nodeId: t, connection: n } = e;
838
+ if (this.options.nodeId.localeCompare(t) < 0) {
839
+ this.bindChannel(e, n.createDataChannel(Nt, { ordered: !0 }));
840
+ let r = await n.createOffer();
841
+ if (this.closed || this.failed) return;
842
+ await n.setLocalDescription(r);
843
+ let i = n.localDescription;
844
+ if (!i?.sdp || i.type !== "offer" && i.type !== "answer") throw Error("empty local SDP offer");
845
+ this.options.onSignal(t, {
846
+ kind: "description",
847
+ description: {
848
+ type: i.type,
849
+ sdp: i.sdp
850
+ }
851
+ });
852
+ }
853
+ }
854
+ this.resolveReadyIfOpen();
855
+ } catch (e) {
856
+ this.unavailable(e instanceof Error ? e : Error(String(e)));
857
+ }
858
+ }
859
+ async handleSignal(e, t) {
860
+ if (this.closed || this.failed) return;
861
+ let n = this.peers.get(e);
862
+ if (n) try {
863
+ if (t.kind === "description") {
864
+ await n.connection.setRemoteDescription(t.description), n.remoteDescriptionSet = !0;
865
+ for (let e of n.pendingCandidates.splice(0)) await n.connection.addIceCandidate(e);
866
+ if (t.description.type === "offer") {
867
+ let t = await n.connection.createAnswer();
868
+ await n.connection.setLocalDescription(t);
869
+ let r = n.connection.localDescription;
870
+ if (!r?.sdp || r.type !== "offer" && r.type !== "answer") throw Error("empty local SDP answer");
871
+ this.options.onSignal(e, {
872
+ kind: "description",
873
+ description: {
874
+ type: r.type,
875
+ sdp: r.sdp
876
+ }
877
+ });
878
+ }
879
+ } else if (t.candidate !== null) if (n.remoteDescriptionSet) await n.connection.addIceCandidate(t.candidate);
880
+ else {
881
+ if (n.pendingCandidates.length >= Mt) throw Error("too many ICE candidates before remote description");
882
+ n.pendingCandidates.push(t.candidate);
883
+ }
884
+ } catch (e) {
885
+ this.unavailable(e instanceof Error ? e : Error(String(e)));
886
+ }
887
+ }
888
+ waitUntilReady(e = this.options.connectTimeoutMs ?? 5e3) {
889
+ return this.mode === "undecided" ? this.readyPromise ? this.readyPromise : this.failed || this.closed || !this.peers.size ? Promise.resolve(!1) : this.allPeersOpen() ? Promise.resolve(!0) : (this.readyPromise = new Promise((t) => {
890
+ this.readyResolve = t, this.readyTimer = setTimeout(() => this.resolveReady(this.allPeersOpen()), e);
891
+ }), this.readyPromise) : Promise.resolve(this.mode === "peer");
892
+ }
893
+ selectMode(e) {
894
+ if (!(this.closed || this.mode !== "undecided")) {
895
+ if (this.mode = e, e === "relay") {
896
+ this.stopQualitySampling(), this.closePeerConnections();
897
+ return;
898
+ }
899
+ this.allPeersOpen() ? this.startQualitySampling() : this.unavailable(/* @__PURE__ */ Error("peer mode selected without every data channel open"));
900
+ }
901
+ }
902
+ async sendFrame(e) {
903
+ if (this.mode !== "peer") return !1;
904
+ let t = this.options.nextNodeId, n = t ? this.peers.get(t)?.channel : void 0;
905
+ if (!n || n.readyState !== "open") {
906
+ let e = /* @__PURE__ */ Error("swarm peer data channel closed during the session");
907
+ throw this.unavailable(e), e;
908
+ }
909
+ let r = this.nextMessageId++ >>> 0;
910
+ try {
911
+ for (let t of zt(e, r)) {
912
+ if (await this.waitForBuffer(n), n.readyState !== "open") throw Error("swarm peer data channel closed while sending");
913
+ n.send(t);
914
+ }
915
+ let i = t ? this.peers.get(t) : void 0;
916
+ return i && (i.applicationBytesSent += e.byteLength), !0;
917
+ } catch (e) {
918
+ let t = e instanceof Error ? e : Error(String(e));
919
+ throw this.unavailable(t), t;
920
+ }
921
+ }
922
+ close() {
923
+ this.closed || (this.closed = !0, this.stopQualitySampling(), this.resolveReady(!1), this.closePeerConnections(), this.reassembler.clear());
924
+ }
925
+ bindChannel(e, t) {
926
+ if (e.channel && e.channel !== t) {
927
+ try {
928
+ t.close();
929
+ } catch {}
930
+ return;
931
+ }
932
+ e.channel = t, t.binaryType = "arraybuffer", t.bufferedAmountLowThreshold = kt / 2, t.onopen = () => this.resolveReadyIfOpen(), t.onmessage = (t) => {
933
+ if (typeof t.data == "string") {
934
+ this.handleQualityProbe(e, t.data);
935
+ return;
936
+ }
937
+ if (e.nodeId !== this.options.previousNodeId || !(t.data instanceof ArrayBuffer)) return;
938
+ let n = this.reassembler.accept(t.data, this.options.now?.());
939
+ n && (e.applicationBytesReceived += n.byteLength, this.options.onFrame(n));
940
+ }, t.onclose = () => this.unavailable(/* @__PURE__ */ Error("swarm peer data channel closed")), t.onerror = () => this.unavailable(/* @__PURE__ */ Error("swarm peer data channel failed")), this.resolveReadyIfOpen();
941
+ }
942
+ allPeersOpen() {
943
+ return this.peers.size ? [...this.peers.values()].every((e) => e.channel?.readyState === "open") : !1;
944
+ }
945
+ resolveReadyIfOpen() {
946
+ this.allPeersOpen() && this.resolveReady(!0);
947
+ }
948
+ resolveReady(e) {
949
+ this.readyTimer && clearTimeout(this.readyTimer), this.readyTimer = null;
950
+ let t = this.readyResolve;
951
+ this.readyResolve = null, t?.(e && !this.failed && !this.closed);
952
+ }
953
+ unavailable(e = /* @__PURE__ */ Error("swarm peer link unavailable")) {
954
+ this.closed || this.failed || (this.failed = !0, this.stopQualitySampling(), this.resolveReady(!1), this.mode === "peer" && this.options.onFailure(e));
955
+ }
956
+ async waitForBuffer(e) {
957
+ e.bufferedAmount <= 262144 || await new Promise((t, n) => {
958
+ let r = setTimeout(() => i(/* @__PURE__ */ Error("swarm peer send buffer stalled")), Dt), i = (i) => {
959
+ clearTimeout(r), e.removeEventListener("bufferedamountlow", a), e.removeEventListener("close", o), i ? n(i) : t();
960
+ }, a = () => i(), o = () => i(/* @__PURE__ */ Error("swarm peer data channel closed while backpressured"));
961
+ e.addEventListener("bufferedamountlow", a, { once: !0 }), e.addEventListener("close", o, { once: !0 });
962
+ });
963
+ }
964
+ closePeerConnections() {
965
+ this.stopQualitySampling();
966
+ for (let e of this.peers.values()) e.channel?.close(), e.connection.close();
967
+ this.peers.clear();
968
+ }
969
+ startQualitySampling() {
970
+ this.qualityTimer || !this.options.onQuality || (this.samplePeerQuality(), this.qualityTimer = setInterval(() => void this.samplePeerQuality(), Ct));
971
+ }
972
+ stopQualitySampling() {
973
+ this.qualityTimer && clearInterval(this.qualityTimer), this.qualityTimer = null;
974
+ for (let e of this.peers.values()) e.pendingProbe = void 0;
975
+ }
976
+ wallNow() {
977
+ return this.options.now?.() ?? Date.now();
978
+ }
979
+ monotonicNow() {
980
+ return this.options.monotonicNow?.() ?? (typeof performance < "u" ? performance.now() : Date.now());
981
+ }
982
+ recordQuality(e, t, n, r) {
983
+ if (!Number.isFinite(r) || r < 0) return;
984
+ let i = e.quality[t][n], a = this.wallNow(), o = e.qualitySampledAt[t][n];
985
+ o !== void 0 && a - o >= 6e4 && (i.length = 0), i.push(r), e.qualitySampledAt[t][n] = a, i.length > 5 && i.splice(0, i.length - 5);
986
+ }
987
+ sendQualityProbe(e) {
988
+ let t = e.channel;
989
+ if (e.pendingProbe && this.monotonicNow() - e.pendingProbe.sentAt > 15e3 * 2 && (e.pendingProbe = void 0), !t || t.readyState !== "open" || t.bufferedAmount > 262144 || e.pendingProbe) return;
990
+ let n = e.nextProbeId++;
991
+ e.pendingProbe = {
992
+ id: n,
993
+ sentAt: this.monotonicNow()
994
+ };
995
+ try {
996
+ t.send(JSON.stringify({
997
+ type: Pt,
998
+ kind: "ping",
999
+ id: n
1000
+ }));
1001
+ } catch {
1002
+ e.pendingProbe = void 0;
1003
+ }
1004
+ }
1005
+ handleQualityProbe(e, t) {
1006
+ if (t.length > Ft) return;
1007
+ let n;
1008
+ try {
1009
+ let e = JSON.parse(t);
1010
+ if (!e || typeof e != "object" || Array.isArray(e)) return;
1011
+ n = e;
1012
+ } catch {
1013
+ return;
1014
+ }
1015
+ if (n.type !== Pt || !Number.isSafeInteger(n.id) || n.id < 1) return;
1016
+ if (n.kind === "ping") {
1017
+ if (e.channel?.readyState !== "open" || e.channel.bufferedAmount > 262144) return;
1018
+ try {
1019
+ e.channel.send(JSON.stringify({
1020
+ type: Pt,
1021
+ kind: "pong",
1022
+ id: n.id
1023
+ }));
1024
+ } catch {}
1025
+ return;
1026
+ }
1027
+ let r = e.pendingProbe;
1028
+ if (n.kind !== "pong" || !r || r.id !== n.id) return;
1029
+ e.pendingProbe = void 0;
1030
+ let i = Math.max(0, this.monotonicNow() - r.sentAt);
1031
+ this.recordQuality(e, "application", "rttMs", i), e.lastApplicationRttMs !== void 0 && this.recordQuality(e, "application", "jitterMs", Math.abs(i - e.lastApplicationRttMs)), e.lastApplicationRttMs = i;
1032
+ }
1033
+ async samplePeerQuality() {
1034
+ if (!(this.closed || this.failed || this.mode !== "peer" || !this.options.onQuality || this.samplingQuality)) {
1035
+ this.samplingQuality = !0;
1036
+ try {
1037
+ let e = this.wallNow(), t = [];
1038
+ for (let n of this.peers.values()) {
1039
+ if (n.channel?.readyState !== "open") continue;
1040
+ this.sendQualityProbe(n);
1041
+ let r = this.monotonicNow();
1042
+ if (await this.sampleWebRtc(n, r), n.lastApplicationSampleAt !== void 0) {
1043
+ let e = r - n.lastApplicationSampleAt, t = q(n.applicationBytesSent - n.lastApplicationBytesSent, e), i = q(n.applicationBytesReceived - n.lastApplicationBytesReceived, e);
1044
+ t !== null && this.recordQuality(n, "application", "sendMbps", t), i !== null && this.recordQuality(n, "application", "receiveMbps", i);
1045
+ }
1046
+ n.lastApplicationSampleAt = r, n.lastApplicationBytesSent = n.applicationBytesSent, n.lastApplicationBytesReceived = n.applicationBytesReceived, t.push(Et(n.nodeId, e, n.quality.webRtc, n.quality.application, n.qualitySampledAt));
1047
+ }
1048
+ t.length && this.options.onQuality(t.slice(0, 2));
1049
+ } finally {
1050
+ this.samplingQuality = !1;
1051
+ }
1052
+ }
1053
+ }
1054
+ async sampleWebRtc(e, t) {
1055
+ try {
1056
+ let n = await e.connection.getStats(), r = [];
1057
+ n.forEach((e) => r.push(e));
1058
+ let i = r.filter((e) => e.type === "candidate-pair" && e.state === "succeeded"), a = i.find((e) => e.selected === !0) ?? i.find((e) => e.nominated === !0) ?? i[0], o = a?.currentRoundTripTime;
1059
+ typeof o == "number" && Number.isFinite(o) && o >= 0 && this.recordQuality(e, "webRtc", "rttMs", o * 1e3);
1060
+ let s = a?.availableOutgoingBitrate;
1061
+ typeof s == "number" && Number.isFinite(s) && s >= 0 && this.recordQuality(e, "webRtc", "sendMbps", s / 1e6);
1062
+ let c = a?.availableIncomingBitrate;
1063
+ typeof c == "number" && Number.isFinite(c) && c >= 0 && this.recordQuality(e, "webRtc", "receiveMbps", c / 1e6);
1064
+ let l = r.filter((e) => e.type === "data-channel"), u = (e) => {
1065
+ let t = l.map((t) => t[e]).filter((e) => typeof e == "number" && Number.isFinite(e) && e >= 0);
1066
+ return t.length ? t.reduce((e, t) => e + t, 0) : void 0;
1067
+ }, d = u("bytesSent"), f = u("bytesReceived");
1068
+ if (e.lastRtcSampleAt !== void 0) {
1069
+ let n = t - e.lastRtcSampleAt;
1070
+ if (d !== void 0 && e.lastRtcBytesSent !== void 0 && s === void 0) {
1071
+ let t = q(d - e.lastRtcBytesSent, n);
1072
+ t !== null && this.recordQuality(e, "webRtc", "sendMbps", t);
1073
+ }
1074
+ if (f !== void 0 && e.lastRtcBytesReceived !== void 0 && c === void 0) {
1075
+ let t = q(f - e.lastRtcBytesReceived, n);
1076
+ t !== null && this.recordQuality(e, "webRtc", "receiveMbps", t);
1077
+ }
1078
+ }
1079
+ d !== void 0 && (e.lastRtcBytesSent = d), f !== void 0 && (e.lastRtcBytesReceived = f), e.lastRtcSampleAt = t;
1080
+ } catch {}
1081
+ }
1082
+ };
1083
+ function Ht(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;
1087
+ }
1088
+ //#endregion
1089
+ //#region src/client/mobile-lifecycle.ts
1090
+ var Ut = .25, Wt = .08, Gt = .45;
1091
+ function Kt(e, t) {
1092
+ let n = e.batteryCharging === !1, r = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Ut, i = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Wt, a = e.effectiveType === "slow-2g" || e.effectiveType === "2g", o = r || a || e.saveData === !0;
1093
+ return {
1094
+ suspend: e.hidden || e.pageHidden || !e.online || i,
1095
+ constrained: o,
1096
+ maxCpuLoad: o ? Math.min(t ?? Gt, Gt) : t
1097
+ };
1098
+ }
1099
+ //#endregion
1100
+ //#region src/client/light-preloader.ts
1101
+ var qt = "Xenova/m2m100_418M", Jt = class {
1102
+ constructor(e, t = {}, n = () => !1, r = async () => {}) {
1103
+ 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.model = t.model ?? "Xenova/m2m100_418M", this.task = t.task ?? "translation", this.dtype = t.dtype ?? "q4f16";
1104
+ }
1105
+ start() {
1106
+ if (this.stopped || this.getConsentState() !== "granted" || this.isUnconstrained() === !1 || this.isPreloaded(this.model) || this.preloading) return;
1107
+ let e = () => {
1108
+ this.idleHandle = null, this.preloadNow();
1109
+ };
1110
+ typeof requestIdleCallback == "function" ? this.idleHandle = requestIdleCallback(e, { timeout: 2e3 }) : this.timer = setTimeout(e, 1e3);
1111
+ }
1112
+ stop() {
1113
+ this.stopped = !0, this.idleHandle !== null && typeof cancelIdleCallback == "function" && cancelIdleCallback(this.idleHandle), this.timer && clearTimeout(this.timer), this.idleHandle = null, this.timer = null;
1114
+ }
1115
+ isUnconstrained() {
1116
+ try {
1117
+ let e = navigator, t = Kt({
1118
+ hidden: document.hidden,
1119
+ pageHidden: document.hidden,
1120
+ online: navigator.onLine !== !1,
1121
+ effectiveType: e.connection?.effectiveType,
1122
+ saveData: e.connection?.saveData
1123
+ }, void 0);
1124
+ return !t.constrained && !t.suspend;
1125
+ } catch {
1126
+ return !0;
1127
+ }
1128
+ }
1129
+ async preloadNow() {
1130
+ if (!(this.stopped || this.preloading) && this.getConsentState() === "granted" && this.isUnconstrained() !== !1 && !this.isPreloaded(this.model)) {
1131
+ this.preloading = !0;
1132
+ try {
1133
+ await this.preload({
1134
+ task: this.task,
1135
+ model: this.model,
1136
+ dtype: this.dtype
1137
+ }), this.options.onPreloaded?.();
1138
+ } catch {} finally {
1139
+ this.preloading = !1;
1140
+ }
1141
+ }
1142
+ }
1143
+ }, X = (...e) => console.log("[flaxia-node]", ...e), Z = (...e) => console.error("[flaxia-node]", ...e);
1144
+ function Q(e) {
606
1145
  let t = /* @__PURE__ */ new Set();
607
1146
  if (!Array.isArray(e)) return [];
608
1147
  for (let n of e.slice(0, 32)) try {
609
- let e = l(n);
1148
+ let e = ee(n);
610
1149
  e.origin === n && t.add(e.origin);
611
1150
  } catch {}
612
1151
  return [...t];
613
1152
  }
614
- var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
1153
+ var Yt = "flaxia_node_id", Xt = "flaxia_node_token", Zt = class {
1154
+ receiveSwarmEnvelope(e) {
1155
+ let t = f(e);
1156
+ !t || ![...this.swarmSessions.values()].includes(t.sessionId) || (this.swarmInboundChain = this.swarmInboundChain.then(async () => {
1157
+ let e = this.swarmHopKeys.get(t.sessionId);
1158
+ if (e && e.chainLength > 1) {
1159
+ if (!t.mac || !e.inboundKey) return;
1160
+ if (!await v(e.inboundKey, t.sessionId, t.frame, t.mac)) {
1161
+ Z(`swarm frame rejected: bad hop MAC sessionId=${t.sessionId}`);
1162
+ return;
1163
+ }
1164
+ }
1165
+ this.workerPool.sendFrame(t.frame);
1166
+ }).catch(() => {}));
1167
+ }
1168
+ ensureSwarmPeerTransport(e) {
1169
+ let t = typeof e.sessionId == "string" ? e.sessionId : "", n = typeof e.taskId == "string" ? e.taskId : "", r = typeof e.attemptId == "string" ? e.attemptId : "";
1170
+ if (!t || !n || !r || this.swarmPeerTransports.has(t)) return;
1171
+ let i = typeof e.previousNodeId == "string" ? e.previousNodeId : void 0, a = typeof e.nextNodeId == "string" ? e.nextNodeId : void 0, o = [...new Set([i, a].filter((e) => !!e))];
1172
+ this.swarmPeerMetadata.set(t, {
1173
+ taskId: n,
1174
+ attemptId: r,
1175
+ peers: o
1176
+ });
1177
+ let s = new Vt({
1178
+ sessionId: t,
1179
+ taskId: n,
1180
+ attemptId: r,
1181
+ nodeId: this.nodeId,
1182
+ previousNodeId: i,
1183
+ nextNodeId: a,
1184
+ onSignal: (e, i) => this.send({
1185
+ type: "swarm-peer-signal",
1186
+ taskId: n,
1187
+ sessionId: t,
1188
+ attemptId: r,
1189
+ toNodeId: e,
1190
+ signal: i
1191
+ }),
1192
+ onFrame: (e) => this.receiveSwarmEnvelope(e),
1193
+ onQuality: (e) => this.send({
1194
+ type: "swarm-peer-quality",
1195
+ taskId: n,
1196
+ sessionId: t,
1197
+ attemptId: r,
1198
+ reports: e
1199
+ }),
1200
+ onFailure: (e) => {
1201
+ this.swarmFailureReported.add(t), this.send({
1202
+ type: "swarm-error",
1203
+ taskId: n,
1204
+ sessionId: t,
1205
+ attemptId: r,
1206
+ error: e.message
1207
+ });
1208
+ }
1209
+ });
1210
+ this.swarmPeerTransports.set(t, s), s.start();
1211
+ }
1212
+ handleSwarmPeerSignal(e) {
1213
+ let t = typeof e.sessionId == "string" ? e.sessionId : "", n = this.swarmPeerMetadata.get(t), r = this.swarmPeerTransports.get(t);
1214
+ !n || !r || !Ht(e, {
1215
+ ...n,
1216
+ sessionId: t,
1217
+ nodeId: this.nodeId
1218
+ }) || r.handleSignal(e.fromNodeId, e.signal);
1219
+ }
615
1220
  retireSwarmSession(e) {
616
- this.swarmHopKeys.delete(e), this.retiredSwarmSessions.add(e), this.retiredSwarmSessions.size > 64 && this.retiredSwarmSessions.delete(this.retiredSwarmSessions.values().next().value);
1221
+ this.swarmHopKeys.delete(e), this.swarmPeerTransports.get(e)?.close(), this.swarmPeerTransports.delete(e), this.swarmPeerMetadata.delete(e), this.swarmFailureReported.delete(e), this.retiredSwarmSessions.add(e), this.retiredSwarmSessions.size > 64 && this.retiredSwarmSessions.delete(this.retiredSwarmSessions.values().next().value);
617
1222
  }
618
1223
  constructor(e, t, n) {
619
- this.config = e, this.workerPool = t, this.nodeId = n, this.ws = null, this.reconnectAttempts = 0, this.MAX_RECONNECT_DELAY = 3e4, this.destroyed = !1, this.suspended = !1, this.visibilityHandler = null, this.inflightTasks = /* @__PURE__ */ new Set(), this.abortedTasks = /* @__PURE__ */ new Set(), this.swarmSessions = /* @__PURE__ */ new Map(), this.retiredSwarmSessions = /* @__PURE__ */ new Set(), this.swarmHopKeys = /* @__PURE__ */ new Map(), this.swarmInboundChain = Promise.resolve(), this.swarmOutboundChain = Promise.resolve(), this.attempts = /* @__PURE__ */ new Map(), this.cachedToken = null;
1224
+ this.config = e, this.workerPool = t, this.nodeId = n, this.ws = null, this.reconnectAttempts = 0, this.MAX_RECONNECT_DELAY = 3e4, this.destroyed = !1, this.suspended = !1, this.lifecycleCleanup = [], this.lifecyclePageHidden = !1, this.lifecycleOffline = !1, this.lifecycleEpoch = 0, this.batteryState = null, this.networkState = null, this.inflightTasks = /* @__PURE__ */ new Set(), this.abortedTasks = /* @__PURE__ */ new Set(), this.lightPreloader = null, this.preloaderTask = null, this.swarmSessions = /* @__PURE__ */ new Map(), this.retiredSwarmSessions = /* @__PURE__ */ new Set(), this.swarmHopKeys = /* @__PURE__ */ new Map(), this.swarmPeerTransports = /* @__PURE__ */ new Map(), this.swarmPeerMetadata = /* @__PURE__ */ new Map(), this.swarmFailureReported = /* @__PURE__ */ new Set(), this.swarmInboundChain = Promise.resolve(), this.swarmOutboundChain = Promise.resolve(), this.attempts = /* @__PURE__ */ new Map(), this.cachedToken = null;
620
1225
  }
621
1226
  async connect() {
622
1227
  if (this.destroyed) return;
623
- if (H() !== "granted") {
1228
+ if (z() !== "granted") {
624
1229
  this.disconnect();
625
1230
  return;
626
1231
  }
627
- if (Y(`connect nodeId=${this.nodeId}`), this.ws) {
1232
+ if (X(`connect nodeId=${this.nodeId}`), this.ws) {
628
1233
  let e = this.ws;
629
1234
  e.onclose = null;
630
1235
  try {
@@ -632,102 +1237,110 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
632
1237
  } catch {}
633
1238
  this.ws = null;
634
1239
  }
635
- this.setupVisibilityHandler();
636
- let r = await this.obtainToken();
637
- if (H() !== "granted") {
638
- Y("connect cancelled because consent was revoked while obtaining a token");
1240
+ if (this.setupMobileLifecycleHandlers(), this.suspended) return;
1241
+ let n = await this.obtainToken();
1242
+ if (this.destroyed || this.suspended) return;
1243
+ if (z() !== "granted") {
1244
+ X("connect cancelled because consent was revoked while obtaining a token");
639
1245
  return;
640
1246
  }
641
- if (!r) {
642
- X("token acquisition failed; scheduling reconnect"), this.scheduleReconnect();
1247
+ if (!n) {
1248
+ Z("token acquisition failed; scheduling reconnect"), this.scheduleReconnect();
643
1249
  return;
644
1250
  }
645
- let i = e(this.config.orchestratorUrl, "/crowd/signal"), o = new WebSocket(i, a(r.token));
646
- o.binaryType = "arraybuffer", this.ws = o;
647
- let s = !1;
648
- o.onopen = () => {
649
- s = !0, this.reconnectAttempts = 0, Y(`signal connected ${i}`);
650
- }, o.onmessage = async (e) => {
651
- if (this.ws !== o) return;
1251
+ this.startLightPreloader();
1252
+ let r = t(this.config.orchestratorUrl, "/crowd/signal"), i = new WebSocket(r, e(n.token));
1253
+ i.binaryType = "arraybuffer", this.ws = i;
1254
+ let a = !1;
1255
+ i.onopen = () => {
1256
+ a = !0, this.reconnectAttempts = 0, X(`signal connected ${r}`), this.sendHeartbeat(i);
1257
+ }, i.onmessage = async (e) => {
1258
+ if (this.ws !== i) return;
652
1259
  if (typeof e.data != "string") {
653
- let r = n(e.data);
654
- if (!r || ![...this.swarmSessions.values()].includes(r.sessionId)) return;
655
- this.swarmInboundChain = this.swarmInboundChain.then(async () => {
656
- let e = this.swarmHopKeys.get(r.sessionId);
657
- if (e && e.chainLength > 1) {
658
- if (!r.mac || !e.inboundKey) return;
659
- if (!await t(e.inboundKey, r.sessionId, r.frame, r.mac)) {
660
- X(`swarm frame rejected: bad hop MAC sessionId=${r.sessionId}`);
661
- return;
662
- }
663
- }
664
- this.workerPool.sendFrame(r.frame);
665
- }).catch(() => {});
1260
+ this.receiveSwarmEnvelope(e.data);
666
1261
  return;
667
1262
  }
668
- let r;
1263
+ let t;
669
1264
  try {
670
- r = JSON.parse(e.data);
1265
+ t = JSON.parse(e.data);
671
1266
  } catch {
672
1267
  return;
673
1268
  }
674
- if (r.type === "ping") {
675
- this.send({
676
- type: "pong",
677
- cpuLoad: this.workerPool.lastCpuLoad
678
- });
1269
+ if (t.type === "ping") {
1270
+ this.sendHeartbeat(i);
679
1271
  return;
680
1272
  }
681
- if (r.type === "task") {
682
- let e = r;
683
- Y(`task received taskId=${e.taskId} workload=${e.workload} timeoutMs=${e.timeoutMs ?? "default"}`), typeof e.attemptId == "string" && this.attempts.set(e.taskId, e.attemptId);
684
- let t = e.attemptId ?? this.attempts.get(e.taskId);
1273
+ if (t.type === "task") {
1274
+ let e = t;
1275
+ X(`task received taskId=${e.taskId} workload=${e.workload} timeoutMs=${e.timeoutMs ?? "default"}`), typeof e.attemptId == "string" && this.attempts.set(e.taskId, e.attemptId);
1276
+ let n = e.attemptId ?? this.attempts.get(e.taskId);
685
1277
  try {
686
1278
  await this.handleTask(e);
687
- } catch (n) {
688
- let i = n instanceof Error ? n.message : String(n);
1279
+ } catch (r) {
1280
+ let i = r instanceof Error ? r.message : String(r);
689
1281
  if (this.abortedTasks.delete(e.taskId)) {
690
- Y(`task stopped on coordinator abort taskId=${e.taskId} error=${i}`);
1282
+ X(`task stopped on coordinator abort taskId=${e.taskId} error=${i}`);
691
1283
  return;
692
1284
  }
693
- X(`task failed taskId=${e.taskId} workload=${e.workload} error=${i}`), this.send({
1285
+ Z(`task failed taskId=${e.taskId} workload=${e.workload} error=${i}`), this.send({
694
1286
  type: "error",
695
- taskId: String(r.taskId ?? ""),
1287
+ taskId: String(t.taskId ?? ""),
696
1288
  error: i,
697
- attemptId: t
1289
+ attemptId: n
698
1290
  });
699
1291
  }
700
1292
  return;
701
1293
  }
702
- if (r.type === "swarm-init" || r.type === "swarm-slice") {
703
- let e = String(r.taskId ?? "");
704
- if (!e || typeof r.sessionId != "string" || this.retiredSwarmSessions.has(r.sessionId)) return;
705
- if (r.type === "swarm-slice" && this.swarmHopKeys.set(r.sessionId, {
706
- inboundKey: typeof r.inboundKey == "string" ? r.inboundKey : void 0,
707
- outboundKey: typeof r.outboundKey == "string" ? r.outboundKey : void 0,
708
- chainLength: typeof r.chainLength == "number" ? r.chainLength : 1
709
- }), typeof r.attemptId == "string" && this.attempts.set(e, r.attemptId), this.swarmSessions.get(e) === r.sessionId) {
710
- this.workerPool.sendControl(r, r.sessionId);
1294
+ if (t.type === "swarm-init" || t.type === "swarm-slice") {
1295
+ let e = String(t.taskId ?? "");
1296
+ if (!e || typeof t.sessionId != "string" || this.retiredSwarmSessions.has(t.sessionId)) return;
1297
+ if (t.type === "swarm-slice" && (this.ensureSwarmPeerTransport(t), this.swarmHopKeys.set(t.sessionId, {
1298
+ inboundKey: typeof t.inboundKey == "string" ? t.inboundKey : void 0,
1299
+ outboundKey: typeof t.outboundKey == "string" ? t.outboundKey : void 0,
1300
+ chainLength: typeof t.chainLength == "number" ? t.chainLength : 1
1301
+ })), typeof t.attemptId == "string" && this.attempts.set(e, t.attemptId), this.swarmSessions.get(e) === t.sessionId) {
1302
+ this.workerPool.sendControl(t, t.sessionId);
711
1303
  return;
712
1304
  }
713
- this.startSwarm(e, r);
1305
+ this.startSwarm(e, t);
1306
+ return;
1307
+ }
1308
+ if (t.type === "swarm-peer-signal") {
1309
+ this.handleSwarmPeerSignal(t);
1310
+ return;
1311
+ }
1312
+ if (t.type === "swarm-transport") {
1313
+ let e = typeof t.sessionId == "string" ? t.sessionId : "", n = this.swarmPeerMetadata.get(e), r = this.swarmPeerTransports.get(e);
1314
+ n && r && t.taskId === n.taskId && t.attemptId === n.attemptId && (t.mode === "peer" || t.mode === "relay") && r.selectMode(t.mode);
1315
+ return;
1316
+ }
1317
+ if (t.type === "swarm-flow") {
1318
+ let e = typeof t.taskId == "string" ? t.taskId : "", n = typeof t.sessionId == "string" ? t.sessionId : "", r = typeof t.attemptId == "string" ? t.attemptId : "";
1319
+ e && n && this.swarmSessions.get(e) === n && this.attempts.get(e) === r && typeof t.paused == "boolean" && this.workerPool.sendControl(t, n);
714
1320
  return;
715
1321
  }
716
- if (r.type === "swarm-start") {
717
- this.swarmSessions.get(String(r.taskId)) === r.sessionId && this.workerPool.sendControl(r, r.sessionId);
1322
+ if (t.type === "task-flow") {
1323
+ let e = typeof t.taskId == "string" ? t.taskId : "", n = typeof t.attemptId == "string" ? t.attemptId : "";
1324
+ e && this.attempts.get(e) === n && typeof t.paused == "boolean" && this.workerPool.setTokenFlow(e, t.paused);
718
1325
  return;
719
1326
  }
720
- if (r.type === "swarm-error") {
721
- let e = String(r.taskId ?? "");
722
- e && this.swarmSessions.get(e) === r.sessionId && this.workerPool.sendControl(r, r.sessionId);
1327
+ if (t.type === "swarm-start") {
1328
+ this.swarmSessions.get(String(t.taskId)) === t.sessionId && this.workerPool.sendControl(t, t.sessionId);
723
1329
  return;
724
1330
  }
725
- if (r.type === "abort") {
726
- this.handleAbort(r);
1331
+ if (t.type === "swarm-error") {
1332
+ let e = String(t.taskId ?? "");
1333
+ e && this.swarmSessions.get(e) === t.sessionId && this.workerPool.sendControl(t, t.sessionId);
727
1334
  return;
728
1335
  }
729
- }, o.onclose = () => {
730
- o.onclose = null, this.ws === o && (this.ws = null, s || (this.cachedToken = null), !this.destroyed && (Y(`signal disconnected; scheduling reconnect attempt=${this.reconnectAttempts + 1}`), this.scheduleReconnect()));
1336
+ if (t.type === "abort") {
1337
+ this.handleAbort(t);
1338
+ return;
1339
+ }
1340
+ }, i.onerror = () => {
1341
+ this.ws === i && Z("signal websocket error");
1342
+ }, i.onclose = (e) => {
1343
+ 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()));
731
1344
  };
732
1345
  }
733
1346
  handleAbort(e) {
@@ -736,7 +1349,21 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
736
1349
  let n = typeof e.error == "string" && e.error ? e.error : "aborted by the coordinator", r = this.swarmSessions.get(t);
737
1350
  if (r && r !== e.sessionId) return;
738
1351
  let i = r ?? t;
739
- r && this.retireSwarmSession(r), this.workerPool.abort(i, n) && this.abortedTasks.add(i), Y(`task abort received taskId=${t} error=${n}`);
1352
+ r && this.retireSwarmSession(r), this.workerPool.abort(i, n) && this.abortedTasks.add(i), X(`task abort received taskId=${t} error=${n}`);
1353
+ }
1354
+ async sendHeartbeat(e) {
1355
+ if (this.ws !== e || e.readyState !== WebSocket.OPEN || z() !== "granted") return;
1356
+ let t = (this.config.capabilities ?? ["ai-inference", "image-process"]).includes("swarm-inference") && this.config.allowModelDownload === !0, n = navigator.deviceMemory, r = await St({
1357
+ cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1358
+ deviceMemory: n,
1359
+ probeGpu: t
1360
+ });
1361
+ this.ws !== e || e.readyState !== WebSocket.OPEN || z() !== "granted" || this.send({
1362
+ type: "pong",
1363
+ cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1364
+ resources: r,
1365
+ modelCache: this.workerPool.modelCacheSnapshot
1366
+ });
740
1367
  }
741
1368
  scheduleReconnect() {
742
1369
  let e = Math.min(1e3 * 2 ** this.reconnectAttempts, this.MAX_RECONNECT_DELAY);
@@ -745,13 +1372,15 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
745
1372
  }, e);
746
1373
  }
747
1374
  disconnect() {
748
- Y(`disconnect nodeId=${this.nodeId}`), this.destroyed = !0, this.suspended = !1, this.removeVisibilityHandler();
1375
+ X(`disconnect nodeId=${this.nodeId}`), this.destroyed = !0, this.suspended = !1, this.stopLightPreloader(), this.removeMobileLifecycleHandlers();
749
1376
  try {
750
1377
  this.ws?.close();
751
1378
  } catch {}
752
1379
  this.ws = null;
1380
+ for (let e of this.swarmPeerTransports.values()) e.close();
1381
+ this.swarmPeerTransports.clear(), this.swarmPeerMetadata.clear();
753
1382
  try {
754
- delete window[$];
1383
+ delete window[Qt];
755
1384
  } catch {}
756
1385
  try {
757
1386
  this.workerPool.terminate();
@@ -759,7 +1388,7 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
759
1388
  }
760
1389
  suspend() {
761
1390
  if (!(this.suspended || this.destroyed)) {
762
- if (Y("suspended (visibility or manual)"), this.suspended = !0, this.ws) {
1391
+ if (X("suspended (visibility or manual)"), this.suspended = !0, this.stopLightPreloader(), this.ws) {
763
1392
  let e = this.ws;
764
1393
  e.onclose = null;
765
1394
  try {
@@ -771,41 +1400,46 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
771
1400
  }
772
1401
  }
773
1402
  resume() {
774
- !this.suspended || this.destroyed || (Y("resumed"), this.suspended = !1, this.workerPool.resume(), this.connect());
1403
+ !this.suspended || this.destroyed || (X("resumed"), this.suspended = !1, this.workerPool.resume(), this.connect());
775
1404
  }
776
1405
  async obtainToken() {
777
- let e = () => H() === "granted";
1406
+ let e = () => z() === "granted";
778
1407
  if (!e()) return null;
779
1408
  try {
780
- if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 6e4) return Y(`token cached nodeId=${this.cachedToken.nodeId} expiresIn=${Math.round((this.cachedToken.expiresAt - Date.now()) / 1e3)}s`), this.cachedToken;
781
- let t = s(), n = t >= c, r = this.config.capabilities ?? ["ai-inference", "image-process"], i = n ? [...r] : [];
782
- Z(this.config.containerImageOrigins).length === 0 && (i = i.filter((e) => e !== "container"));
1409
+ 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;
1410
+ let t = m(), n = t >= h, r = this.config.capabilities ?? ["ai-inference", "image-process"], i = n ? [...r] : [];
1411
+ Q(this.config.containerImageOrigins).length === 0 && (i = i.filter((e) => e !== "container"));
783
1412
  let a;
784
1413
  if (n && r.includes("swarm-inference") && this.config.allowModelDownload === !0) {
785
- if (a = await o(), !e()) return null;
786
- a.webgpu || (i = i.filter((e) => e !== "swarm-inference"), a = void 0);
1414
+ let t = await St({
1415
+ cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1416
+ deviceMemory: navigator.deviceMemory,
1417
+ probeGpu: !0
1418
+ });
1419
+ if (!e()) return null;
1420
+ t.gpu.status === "available" ? (a = { webgpu: !0 }, t.gpu.architecture.value && (a.gpuArchitecture = t.gpu.architecture.value), t.gpu.maxStorageBufferBindingSize.value !== null && (a.maxStorageBufferBindingSize = t.gpu.maxStorageBufferBindingSize.value)) : i = i.filter((e) => e !== "swarm-inference");
787
1421
  } else i = i.filter((e) => e !== "swarm-inference");
788
- Y(`register capability probe capable=${n} wasmMemoryBytes=${t} capabilities=${JSON.stringify(i)} webgpu=${a?.webgpu ?? !1}`);
789
- let l = this.config.orchestratorUrl.replace(/\/+$/, "");
1422
+ X(`register capability probe capable=${n} wasmMemoryBytes=${t} capabilities=${JSON.stringify(i)} webgpu=${a?.webgpu ?? !1}`);
1423
+ let o = this.config.orchestratorUrl.replace(/\/+$/, "");
790
1424
  if (!e()) return null;
791
- let u = await fetch(`${l}/crowd/nodes/register`, {
1425
+ let s = await fetch(`${o}/crowd/nodes/register`, {
792
1426
  method: "POST",
793
1427
  headers: { "Content-Type": "application/json" },
794
1428
  body: JSON.stringify({
795
1429
  siteId: this.config.siteId,
796
1430
  capabilities: i,
797
- fileSources: Z(this.config.fileSourceOrigins).length > 0,
798
- wasmMemoryBytes: s(),
1431
+ fileSources: Q(this.config.fileSourceOrigins).length > 0,
1432
+ wasmMemoryBytes: m(),
799
1433
  deviceMemory: typeof navigator.deviceMemory == "number" ? navigator.deviceMemory : null,
800
1434
  swarm: a
801
1435
  })
802
1436
  });
803
1437
  if (!e()) return null;
804
- if (!u.ok) return X(`node register failed HTTP ${u.status} (${l}/crowd/nodes/register)`), null;
805
- let d = await u.json();
806
- return e() ? d.token ? (typeof d.nodeId == "string" && d.nodeId && (this.nodeId = d.nodeId), this.cachedToken = d, Y(`node registered nodeId=${this.nodeId} expiresIn=${Math.round((d.expiresAt - Date.now()) / 1e3)}s`), d) : (X("node register returned no token"), null) : null;
1438
+ if (!s.ok) return Z(`node register failed HTTP ${s.status} (${o}/crowd/nodes/register)`), null;
1439
+ let c = await s.json();
1440
+ return e() ? c.token ? (typeof c.nodeId == "string" && c.nodeId && (this.nodeId = c.nodeId), this.cachedToken = c, X(`node registered nodeId=${this.nodeId} expiresIn=${Math.round((c.expiresAt - Date.now()) / 1e3)}s`), c) : (Z("node register returned no token"), null) : null;
807
1441
  } catch (e) {
808
- return X("node register threw", e instanceof Error ? e.message : e), null;
1442
+ return Z("node register threw", e instanceof Error ? e.message : e), null;
809
1443
  }
810
1444
  }
811
1445
  send(e) {
@@ -819,14 +1453,25 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
819
1453
  let n = this.swarmHopKeys.get(e);
820
1454
  if (n && n.chainLength > 1) {
821
1455
  if (!n.outboundKey) {
822
- X(`swarm frame not sent: no hop key sessionId=${e}`);
1456
+ Z(`swarm frame not sent: no hop key sessionId=${e}`);
823
1457
  return;
824
1458
  }
825
- this.sendBinary(await r(n.outboundKey, e, t));
1459
+ let r = await s(n.outboundKey, e, t), i = this.swarmPeerTransports.get(e);
1460
+ (!i || !await i.sendFrame(r)) && this.sendBinary(r);
826
1461
  return;
827
1462
  }
828
- this.sendBinary(i(e, t));
829
- }).catch(() => {});
1463
+ let r = c(e, t), i = this.swarmPeerTransports.get(e);
1464
+ (!i || !await i.sendFrame(r)) && this.sendBinary(r);
1465
+ }).catch((t) => {
1466
+ let n = this.swarmPeerMetadata.get(e);
1467
+ !n || this.swarmFailureReported.has(e) || (this.swarmFailureReported.add(e), this.send({
1468
+ type: "swarm-error",
1469
+ taskId: n.taskId,
1470
+ sessionId: e,
1471
+ attemptId: n.attemptId,
1472
+ error: t instanceof Error ? t.message : String(t)
1473
+ }));
1474
+ });
830
1475
  }
831
1476
  async startSwarm(e, t) {
832
1477
  let n = t.sessionId;
@@ -842,12 +1487,26 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
842
1487
  token: t,
843
1488
  attemptId: a
844
1489
  });
845
- }, { maxCpuLoad: this.config.maxCpuLoad }, {
1490
+ }, { maxCpuLoad: this.effectiveMaxCpuLoad() }, {
846
1491
  onFrame: (e) => this.queueSwarmFrame(n, e),
847
- onMessage: (e) => this.send(e && typeof e == "object" && !("attemptId" in e) ? {
848
- ...e,
849
- attemptId: a
850
- } : e)
1492
+ onMessage: (e) => {
1493
+ let t = e && typeof e == "object" && !("attemptId" in e) ? {
1494
+ ...e,
1495
+ attemptId: a
1496
+ } : e;
1497
+ if (t?.type === "swarm-ready") {
1498
+ let e = this.swarmPeerTransports.get(n);
1499
+ (async () => {
1500
+ let n = e ? await e.waitUntilReady() : !1;
1501
+ this.send({
1502
+ ...t,
1503
+ peerReady: n
1504
+ });
1505
+ })();
1506
+ return;
1507
+ }
1508
+ this.send(t);
1509
+ }
851
1510
  });
852
1511
  this.abortedTasks.delete(n) || this.send({
853
1512
  type: "result",
@@ -855,10 +1514,10 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
855
1514
  sessionId: n,
856
1515
  payload: o,
857
1516
  attemptId: a
858
- }), Y(`swarm result sent taskId=${e} durationMs=${Math.round(performance.now() - r)}`);
1517
+ }), X(`swarm result sent taskId=${e} durationMs=${Math.round(performance.now() - r)}`);
859
1518
  } catch (t) {
860
1519
  let r = t instanceof Error ? t.message : String(t);
861
- this.abortedTasks.delete(n) ? Y(`swarm stopped on coordinator abort taskId=${e} error=${r}`) : (X(`swarm failed taskId=${e} error=${r}`), this.send({
1520
+ this.abortedTasks.delete(n) ? X(`swarm stopped on coordinator abort taskId=${e} error=${r}`) : (Z(`swarm failed taskId=${e} error=${r}`), this.send({
862
1521
  type: "error",
863
1522
  taskId: e,
864
1523
  sessionId: n,
@@ -882,88 +1541,168 @@ var et = "flaxia_node_id", tt = "flaxia_node_token", nt = class {
882
1541
  attemptId: n
883
1542
  });
884
1543
  }, {
885
- maxCpuLoad: this.config.maxCpuLoad,
886
- fileSourceOrigins: Z(this.config.fileSourceOrigins),
887
- containerImageOrigins: Z(this.config.containerImageOrigins)
1544
+ maxCpuLoad: this.effectiveMaxCpuLoad(),
1545
+ fileSourceOrigins: Q(this.config.fileSourceOrigins),
1546
+ containerImageOrigins: Q(this.config.containerImageOrigins)
888
1547
  });
889
1548
  this.send({
890
1549
  type: "result",
891
1550
  taskId: e.taskId,
892
1551
  payload: i,
893
1552
  attemptId: n
894
- }), Y(`task result sent taskId=${e.taskId} workload=${e.workload} durationMs=${Math.round(performance.now() - t)}`);
1553
+ }), X(`task result sent taskId=${e.taskId} workload=${e.workload} durationMs=${Math.round(performance.now() - t)}`);
895
1554
  } finally {
896
1555
  this.inflightTasks.delete(e.taskId), this.attempts.delete(e.taskId);
897
1556
  }
898
1557
  }
899
- setupVisibilityHandler() {
900
- this.removeVisibilityHandler(), this.visibilityHandler = () => {
901
- document.hidden ? this.suspend() : this.suspended && this.resume();
902
- }, document.addEventListener("visibilitychange", this.visibilityHandler);
1558
+ async runLocalAiInference(e, t) {
1559
+ if (!this.workerPool) throw new r("No running Crowd node on this device", "node_not_running");
1560
+ if (z() !== "granted") throw new r("Crowd consent is not granted", "consent_not_granted");
1561
+ let n = `local-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1562
+ return await this.workerPool.run(n, "ai-inference", e, 3e5, t, {
1563
+ maxCpuLoad: this.effectiveMaxCpuLoad(),
1564
+ fileSourceOrigins: Q(this.config.fileSourceOrigins),
1565
+ containerImageOrigins: Q(this.config.containerImageOrigins)
1566
+ });
1567
+ }
1568
+ isAiModelPreloaded(e) {
1569
+ let t = this.workerPool.modelCacheSnapshot;
1570
+ return t ? t.entries.some((t) => t.modelId === e && t.state === "ready") : !1;
1571
+ }
1572
+ async preloadAiModel(e) {
1573
+ let t = `preload-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1574
+ await this.workerPool.run(t, "ai-preload", e, 3e5, void 0, { maxCpuLoad: this.effectiveMaxCpuLoad() });
903
1575
  }
904
- removeVisibilityHandler() {
905
- this.visibilityHandler &&= (document.removeEventListener("visibilitychange", this.visibilityHandler), null);
1576
+ startLightPreloader() {
1577
+ this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = new Jt(() => z(), { onPreloaded: () => {} }, (e) => this.isAiModelPreloaded(e), (e) => this.preloadAiModel(e)), this.lightPreloader.start();
906
1578
  }
907
- }, Q = "__flaxia_node_signal_client", $ = "__flaxia_node_init_started", rt = "__flaxia_node_controller", it = (e) => {
908
- if (H() !== "granted") {
909
- X("refusing to start the node without a granted consent record");
1579
+ stopLightPreloader() {
1580
+ this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = null;
1581
+ }
1582
+ listenForLifecycle(e, t, n) {
1583
+ e.addEventListener(t, n), this.lifecycleCleanup.push(() => e.removeEventListener(t, n));
1584
+ }
1585
+ setupMobileLifecycleHandlers() {
1586
+ this.removeMobileLifecycleHandlers();
1587
+ let e = this.lifecycleEpoch;
1588
+ this.lifecyclePageHidden = document.hidden, this.lifecycleOffline = navigator.onLine === !1;
1589
+ let t = navigator;
1590
+ if (this.networkState = t.connection ?? null, this.listenForLifecycle(document, "visibilitychange", () => {
1591
+ this.lifecyclePageHidden = document.hidden, this.refreshMobileLifecycle();
1592
+ }), this.listenForLifecycle(window, "offline", () => {
1593
+ this.lifecycleOffline = !0, this.refreshMobileLifecycle();
1594
+ }), this.listenForLifecycle(window, "online", () => {
1595
+ this.lifecycleOffline = !1, this.refreshMobileLifecycle();
1596
+ }), this.listenForLifecycle(window, "pagehide", () => {
1597
+ this.lifecyclePageHidden = !0, this.refreshMobileLifecycle();
1598
+ }), this.listenForLifecycle(window, "pageshow", () => {
1599
+ this.lifecyclePageHidden = !1, this.refreshMobileLifecycle();
1600
+ }), this.networkState && this.listenForLifecycle(this.networkState, "change", () => this.refreshMobileLifecycle()), typeof t.getBattery == "function") try {
1601
+ t.getBattery.call(navigator).then((t) => {
1602
+ if (this.destroyed || e !== this.lifecycleEpoch) return;
1603
+ this.batteryState = t;
1604
+ let n = () => this.refreshMobileLifecycle();
1605
+ this.listenForLifecycle(t, "levelchange", n), this.listenForLifecycle(t, "chargingchange", n), this.refreshMobileLifecycle();
1606
+ }).catch(() => {});
1607
+ } catch {}
1608
+ this.refreshMobileLifecycle();
1609
+ }
1610
+ removeMobileLifecycleHandlers() {
1611
+ this.lifecycleEpoch++;
1612
+ for (let e of this.lifecycleCleanup.splice(0)) e();
1613
+ this.batteryState = null, this.networkState = null;
1614
+ }
1615
+ mobileLifecycleDecision() {
1616
+ return Kt({
1617
+ hidden: document.hidden,
1618
+ pageHidden: this.lifecyclePageHidden,
1619
+ online: !this.lifecycleOffline && navigator.onLine !== !1,
1620
+ batteryLevel: this.batteryState?.level,
1621
+ batteryCharging: this.batteryState?.charging,
1622
+ effectiveType: this.networkState?.effectiveType,
1623
+ saveData: this.networkState?.saveData
1624
+ }, this.config.maxCpuLoad);
1625
+ }
1626
+ effectiveMaxCpuLoad() {
1627
+ return this.mobileLifecycleDecision().maxCpuLoad;
1628
+ }
1629
+ refreshMobileLifecycle() {
1630
+ this.mobileLifecycleDecision().suspend ? this.suspend() : this.suspended && this.resume();
1631
+ }
1632
+ }, $ = "__flaxia_node_signal_client", Qt = "__flaxia_node_init_started", $t = "__flaxia_node_controller", en = (e) => {
1633
+ if (z() !== "granted") {
1634
+ Z("refusing to start the node without a granted consent record");
910
1635
  return;
911
1636
  }
912
- let t = window[Q];
913
- t && t.disconnect(), K(tt);
914
- let n = new URL("./worker.js", "" + import.meta.url).href, r = new $e(n), i = Ae(et);
915
- i || (i = Ne(), je(et, i));
916
- let a = new nt(e, r, i);
917
- window[Q] = a, a.connect();
918
- }, at = class {
1637
+ let t = window[$];
1638
+ t && t.disconnect(), V(Xt);
1639
+ let n = new URL("./worker.js", "" + import.meta.url).href, r = new yt(n), i = Xe(Yt);
1640
+ i || (i = $e(), Ze(Yt, i));
1641
+ let a = new Zt(e, r, i);
1642
+ window[$] = a, a.connect();
1643
+ }, tn = class {
919
1644
  constructor(e) {
920
1645
  this.config = e;
921
1646
  }
922
1647
  start() {
923
- this.isRunning() || !ye() || it(this.config);
1648
+ this.isRunning() || !Le() || en(this.config);
924
1649
  }
925
1650
  stop() {
926
- let e = window[Q];
927
- e && e.disconnect(), delete window[Q], delete window[$];
1651
+ let e = window[$];
1652
+ e && e.disconnect(), delete window[$], delete window[Qt];
928
1653
  }
929
1654
  isRunning() {
930
- return !!window[Q];
1655
+ return !!window[$];
931
1656
  }
932
1657
  getConsentState() {
933
- return H();
1658
+ return z();
934
1659
  }
935
1660
  grant() {
936
- W();
1661
+ Ge();
937
1662
  }
938
1663
  deny() {
939
- G(), this.stop(), K(tt);
1664
+ Je(), this.stop(), V(Xt);
940
1665
  }
941
1666
  clearConsent() {
942
- ke(), this.stop(), K(tt);
1667
+ Ye(), this.stop(), V(Xt);
1668
+ }
1669
+ async runLocalAiInference(e, t) {
1670
+ let n = window[$];
1671
+ if (!n || !this.isRunning()) throw new r("No running Crowd node on this device", "node_not_running");
1672
+ return n.runLocalAiInference(e, t);
943
1673
  }
944
- }, ot = (e) => {
945
- let t = window[rt];
1674
+ isAiModelPreloaded(e) {
1675
+ let t = window[$];
1676
+ return t ? t.isAiModelPreloaded(e) : !1;
1677
+ }
1678
+ async preloadAiModel(e) {
1679
+ let t = window[$];
1680
+ if (!t) throw new r("No running Crowd node on this device", "node_not_running");
1681
+ await t.preloadAiModel(e);
1682
+ }
1683
+ }, nn = (e) => {
1684
+ let t = window[$t];
946
1685
  if (t) return t;
947
- let n = new at(e);
948
- window[rt] = n, window[$] = !0;
949
- let r = H();
1686
+ let n = new tn(e);
1687
+ window[$t] = n, window[Qt] = !0;
1688
+ let r = z();
950
1689
  if (r === "granted") return n.start(), n;
951
1690
  if (r === "denied") return n;
952
1691
  if (e.consent.onConsentRequired) return e.consent.onConsentRequired({
953
1692
  state: r,
954
1693
  accept: () => {
955
- W(), n.start();
1694
+ Ge(), n.start();
956
1695
  },
957
1696
  reject: () => {
958
- G();
1697
+ Je();
959
1698
  }
960
1699
  }), n;
961
1700
  let i = document.createElement("div");
962
- return i.id = "flaxia-consent-container", document.body.appendChild(i), new Qe(i, e.consent, () => {
963
- W(), i.remove(), n.start();
1701
+ return i.id = "flaxia-consent-container", document.body.appendChild(i), new vt(i, e.consent, () => {
1702
+ Ge(), i.remove(), n.start();
964
1703
  }, () => {
965
- G(), i.remove();
1704
+ Je(), i.remove();
966
1705
  }), n;
967
1706
  };
968
1707
  //#endregion
969
- export { H as getFlaxiaNodeConsentState, ot as initFlaxiaNode, U as initFlaxiaNodeConsent, Oe as setFlaxiaNodeHostManagedConsent };
1708
+ export { re as LIGHT_INFERENCE_TRANSLATE_DTYPE, qt as LIGHT_INFERENCE_TRANSLATE_MODEL, te as LIGHT_INFERENCE_TRANSLATE_MODEL_ID, ne as LIGHT_INFERENCE_TRANSLATE_TASK, z as getFlaxiaNodeConsentState, nn as initFlaxiaNode, B as initFlaxiaNodeConsent, y as isAiModelPreloaded, b as preloadAiModel, qe as setFlaxiaNodeHostManagedConsent };