@fest-lib/fl-ui 0.1.6 → 0.1.8

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.
@@ -1,2985 +0,0 @@
1
- (function() {
2
- var ee = Object.defineProperty, De = (e, t, n) => () => {
3
- if (n) throw n[0];
4
- try {
5
- return e && (t = e(e = 0)), t;
6
- } catch (s) {
7
- throw n = [s], s;
8
- }
9
- }, Ne = (e, t) => {
10
- let n = {};
11
- for (var s in e) ee(n, s, {
12
- get: e[s],
13
- enumerable: !0
14
- });
15
- return t || ee(n, Symbol.toStringTag, { value: "Module" }), n;
16
- };
17
- let h = (function(e) {
18
- return e.GET = "get", e.SET = "set", e.CALL = "call", e.APPLY = "apply", e.CONSTRUCT = "construct", e.DELETE = "delete", e.DELETE_PROPERTY = "deleteProperty", e.HAS = "has", e.OWN_KEYS = "ownKeys", e.GET_OWN_PROPERTY_DESCRIPTOR = "getOwnPropertyDescriptor", e.GET_PROPERTY_DESCRIPTOR = "getPropertyDescriptor", e.GET_PROTOTYPE_OF = "getPrototypeOf", e.SET_PROTOTYPE_OF = "setPrototypeOf", e.IS_EXTENSIBLE = "isExtensible", e.PREVENT_EXTENSIONS = "preventExtensions", e.TRANSFER = "transfer", e.IMPORT = "import", e.DISPOSE = "dispose", e;
19
- })({});
20
- const Le = {
21
- ws: "websocket",
22
- socket: "websocket",
23
- socketio: "socket-io",
24
- service: "service-worker",
25
- sw: "service-worker",
26
- "service-worker-client": "service-worker",
27
- "service-worker-host": "service-worker",
28
- "ring-buffer": "atomics"
29
- };
30
- function Be(e) {
31
- const t = String(e ?? "").trim().toLowerCase();
32
- return t ? Le[t] ?? t : "internal";
33
- }
34
- function qe(e) {
35
- return typeof e == "string" ? Be(e) : typeof Worker < "u" && e instanceof Worker ? "worker" : typeof SharedWorker < "u" && e instanceof SharedWorker ? "shared-worker" : typeof MessagePort < "u" && e instanceof MessagePort ? "message-port" : typeof BroadcastChannel < "u" && e instanceof BroadcastChannel ? "broadcast" : typeof WebSocket < "u" && e instanceof WebSocket ? "websocket" : typeof RTCDataChannel < "u" && e instanceof RTCDataChannel ? "rtc-data" : typeof chrome < "u" && e && typeof e == "object" && typeof e.postMessage == "function" && e.onMessage?.addListener ? "chrome-port" : "internal";
36
- }
37
- const te = Symbol.for("@fix"), C = (e) => typeof e == "string" || typeof e == "number" || typeof e == "boolean" || typeof e == "bigint" || typeof e > "u" || e == null, Fe = (e, t) => C(e) ? t == "number" ? Number(e) || 0 : t == "string" ? String(e) || "" : t == "boolean" ? !!e : e : null, p = (e, t) => e?.[te] ?? e ?? t ?? t, He = (e) => {
38
- if (typeof e == "function" || e == null) return e;
39
- const t = function() {};
40
- return t[te] = e, t;
41
- }, Ge = (e) => crypto?.getRandomValues ? crypto?.getRandomValues?.(e) : (() => {
42
- const t = new Uint8Array(e.length);
43
- for (let n = 0; n < e.length; n++) t[n] = Math.floor(Math.random() * 256);
44
- return t;
45
- })(), d = () => crypto?.randomUUID ? crypto?.randomUUID?.() : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (e) => (+e ^ Ge?.(/* @__PURE__ */ new Uint8Array(1))?.[0] & 15 >> +e / 4).toString(16)), ne = (e) => Array.isArray(e) ? e?.flatMap?.((t) => Array.isArray(t) ? ne(t) : t) : e, $ = (e) => ne(e)?.every?.(x), x = (e) => C(e) || typeof SharedArrayBuffer == "function" && e instanceof SharedArrayBuffer || Ue(e) || Array.isArray(e) && $(e), Ue = (e) => ArrayBuffer.isView(e) && !(e instanceof DataView), z = (e) => C(e) || typeof ArrayBuffer == "function" && e instanceof ArrayBuffer || typeof MessagePort == "function" && e instanceof MessagePort || typeof ReadableStream == "function" && e instanceof ReadableStream || typeof WritableStream == "function" && e instanceof WritableStream || typeof TransformStream == "function" && e instanceof TransformStream || typeof ImageBitmap == "function" && e instanceof ImageBitmap || typeof VideoFrame == "function" && e instanceof VideoFrame || typeof OffscreenCanvas == "function" && e instanceof OffscreenCanvas || typeof RTCDataChannel == "function" && e instanceof RTCDataChannel || typeof AudioData == "function" && e instanceof AudioData || typeof WebTransportReceiveStream == "function" && e instanceof WebTransportReceiveStream || typeof WebTransportSendStream == "function" && e instanceof WebTransportSendStream || typeof WebTransportReceiveStream == "function" && e instanceof WebTransportReceiveStream, se = Symbol.for("object.boundCtx");
46
- globalThis[se] ??= /* @__PURE__ */ new WeakMap();
47
- globalThis[se];
48
- const k = (e, t, n) => {
49
- if (Array.isArray(e)) return e.every(x) ? e.map(t) : e.map((s, r) => k(s, t, [e, r]));
50
- if (e instanceof Map) {
51
- const s = Array.from(e.entries());
52
- return s.map(([r, i]) => i).every(x) ? new Map(s.map(([r, i]) => [r, t(i, r, e)])) : new Map(s.map(([r, i]) => [r, k(i, t, [e, r])]));
53
- }
54
- if (e instanceof Set) {
55
- const s = Array.from(e.entries()), r = s.map(([i, o]) => o);
56
- return s.every(x) ? new Set(r.map(t)) : new Set(r.map((i) => k(i, t, [e, i])));
57
- }
58
- if (typeof e == "object" && e?.constructor == Object && Object.prototype.toString.call(e) == "[object Object]") {
59
- const s = Array.from(Object.entries(e));
60
- return s.map(([r, i]) => i).every(x) ? Object.fromEntries(s.map(([r, i]) => [r, t(i, r, e)])) : Object.fromEntries(s.map(([r, i]) => [r, k(i, t, [e, r])]));
61
- }
62
- return t(e, n?.[1] ?? "", n?.[0] ?? null);
63
- }, S = /* @__PURE__ */ new WeakMap(), re = /* @__PURE__ */ new WeakMap(), g = (e, t) => e instanceof Promise || typeof e?.then == "function" ? S?.has?.(e) ? t(S?.get?.(e)) : Promise.try?.(async () => {
64
- const n = await e;
65
- return S?.set?.(e, n), n;
66
- })?.then?.(t) : t(e);
67
- var We = class {
68
- #e;
69
- #t;
70
- constructor(e, t) {
71
- this.#e = e, this.#t = t;
72
- }
73
- defineProperty(e, t, n) {
74
- return p(e) instanceof Promise ? Reflect.defineProperty(e, t, n) : g(p(e), (s) => Reflect.defineProperty(s, t, n));
75
- }
76
- deleteProperty(e, t) {
77
- return p(e) instanceof Promise ? Reflect.deleteProperty(e, t) : g(p(e), (n) => Reflect.deleteProperty(n, t));
78
- }
79
- getPrototypeOf(e) {
80
- return p(e) instanceof Promise ? Reflect.getPrototypeOf(e) : g(p(e), (t) => Reflect.getPrototypeOf(t));
81
- }
82
- setPrototypeOf(e, t) {
83
- return p(e) instanceof Promise ? Reflect.setPrototypeOf(e, t) : g(p(e), (n) => Reflect.setPrototypeOf(n, t));
84
- }
85
- isExtensible(e) {
86
- return p(e) instanceof Promise ? Reflect.isExtensible(e) : g(p(e), (t) => Reflect.isExtensible(t));
87
- }
88
- preventExtensions(e) {
89
- return p(e) instanceof Promise ? Reflect.ownKeys(e) : g(p(e), (t) => Reflect.preventExtensions(t));
90
- }
91
- ownKeys(e) {
92
- const t = p(e);
93
- return t instanceof Promise ? Object.keys(t) : g(t, (n) => (typeof n == "object" || typeof n == "function") && n != null ? Object.keys(n) : []) ?? [];
94
- }
95
- getOwnPropertyDescriptor(e, t) {
96
- return p(e) instanceof Promise ? Reflect.getOwnPropertyDescriptor(e, t) : g(p(e), (n) => Reflect.getOwnPropertyDescriptor(n, t));
97
- }
98
- construct(e, t, n) {
99
- return g(p(e), (s) => Reflect.construct(s, t, n));
100
- }
101
- has(e, t) {
102
- return p(e) instanceof Promise ? Reflect.has(e, t) : g(p(e), (n) => Reflect.has(n, t));
103
- }
104
- get(e, t, n) {
105
- if (e = p(e), t == "promise") return e;
106
- if (t == "resolve" && this.#e) return (...r) => {
107
- const i = this.#e?.(...r);
108
- return this.#e = null, i;
109
- };
110
- if (t == "reject" && this.#t) return (...r) => {
111
- const i = this.#t?.(...r);
112
- return this.#t = null, i;
113
- };
114
- if (t == "then" || t == "catch" || t == "finally") {
115
- if (e instanceof Promise) return e?.[t]?.bind?.(e);
116
- {
117
- const r = Promise.try(() => e);
118
- return r?.[t]?.bind?.(r);
119
- }
120
- }
121
- let s;
122
- return S?.has?.(e) && (s = S?.get?.(e))?.[t] != null ? s = S?.get?.(e)?.[t] : s = oe(g(e, async (r) => {
123
- if (p(r) instanceof Promise) return Reflect.get(r, t, n);
124
- if (C(r)) return t == Symbol.toPrimitive || t == Symbol.toStringTag ? r : void 0;
125
- let i;
126
- try {
127
- i = Reflect.get(r, t, n);
128
- } catch {
129
- i = e?.[t];
130
- }
131
- return typeof i == "function" ? i?.bind?.(r) : i;
132
- })), t == Symbol.toStringTag ? C(s) ? String(s ?? "") || "" : s?.[Symbol.toStringTag]?.() || String(s ?? "") || "" : t == Symbol.toPrimitive ? (r) => {
133
- if (C(s)) return Fe(s, r);
134
- } : s;
135
- }
136
- set(e, t, n) {
137
- return g(p(e), (s) => Reflect.set(s, t, n));
138
- }
139
- apply(e, t, n) {
140
- if (this.#e) {
141
- const s = this.#e?.(...n);
142
- return this.#e = null, s;
143
- }
144
- return g(p(e, this.#e), (s) => {
145
- if (typeof s == "function") return p(s) instanceof Promise, Reflect.apply(s, t, n);
146
- });
147
- }
148
- };
149
- function oe(e, t, n) {
150
- return e instanceof Promise || typeof e?.then == "function" ? S?.has?.(e) ? S?.get?.(e) : (re?.has?.(e) || e?.then?.((s) => S?.set?.(e, s)), re?.getOrInsertComputed?.(e, () => new Proxy(He(e), new We(t, n)))) : e;
151
- }
152
- var ie = class {
153
- _unsubscribe;
154
- _closed = !1;
155
- constructor(e) {
156
- this._unsubscribe = e;
157
- }
158
- get closed() {
159
- return this._closed;
160
- }
161
- unsubscribe() {
162
- this._closed || (this._closed = !0, this._unsubscribe());
163
- }
164
- }, $e = class {
165
- _producer;
166
- constructor(e) {
167
- this._producer = e;
168
- }
169
- subscribe(e, t) {
170
- const n = typeof e == "function" ? { next: e } : e ?? {}, s = new AbortController();
171
- t?.signal?.addEventListener("abort", () => s.abort());
172
- let r = !0, i;
173
- const o = () => {
174
- r = !1, s.abort(), i?.();
175
- }, a = {
176
- next: (c) => r && n.next?.(c),
177
- error: (c) => {
178
- r && (n.error?.(c), o());
179
- },
180
- complete: () => {
181
- r && (n.complete?.(), o());
182
- },
183
- signal: s.signal,
184
- get active() {
185
- return r && !s.signal.aborted;
186
- }
187
- };
188
- try {
189
- i = this._producer(a);
190
- } catch (c) {
191
- a.error(c);
192
- }
193
- return new ie(o);
194
- }
195
- pipe(...e) {
196
- return e.reduce((t, n) => n(t), this);
197
- }
198
- }, y = class {
199
- _subs = /* @__PURE__ */ new Set();
200
- _buffer = [];
201
- _maxBuffer;
202
- _replay;
203
- constructor(e = {}) {
204
- this._maxBuffer = e.bufferSize ?? 0, this._replay = e.replayOnSubscribe ?? !1;
205
- }
206
- next(e) {
207
- this._maxBuffer > 0 && (this._buffer.push(e), this._buffer.length > this._maxBuffer && this._buffer.shift());
208
- for (const t of this._subs) try {
209
- t.next?.(e);
210
- } catch (n) {
211
- t.error?.(n);
212
- }
213
- }
214
- error(e) {
215
- for (const t of this._subs) t.error?.(e);
216
- }
217
- complete() {
218
- for (const e of this._subs) e.complete?.();
219
- this._subs.clear();
220
- }
221
- subscribe(e) {
222
- const t = typeof e == "function" ? { next: e } : e;
223
- if (this._subs.add(t), this._replay) for (const n of this._buffer) try {
224
- t.next?.(n);
225
- } catch (s) {
226
- t.error?.(s);
227
- }
228
- return new ie(() => {
229
- this._subs.delete(t);
230
- });
231
- }
232
- getValue() {
233
- return this._buffer.at(-1);
234
- }
235
- getBuffer() {
236
- return [...this._buffer];
237
- }
238
- get subscriberCount() {
239
- return this._subs.size;
240
- }
241
- };
242
- const ze = (e) => (t) => new $e((n) => {
243
- const s = t.subscribe({
244
- next: (r) => e(r) && n.next(r),
245
- error: (r) => n.error(r),
246
- complete: () => n.complete()
247
- });
248
- return () => s.unsubscribe();
249
- });
250
- function ae() {
251
- if (typeof globalThis.Deno < "u") return "deno";
252
- if (typeof globalThis.process < "u" && globalThis.process?.versions?.node) return "node";
253
- const e = globalThis.ServiceWorkerGlobalScope, t = globalThis.SharedWorkerGlobalScope, n = globalThis.DedicatedWorkerGlobalScope;
254
- if (e && self instanceof e) return "service-worker";
255
- if (t && self instanceof t) return "shared-worker";
256
- if (n && self instanceof n) return "worker";
257
- if (typeof chrome < "u" && chrome.runtime?.id) {
258
- if (typeof chrome.runtime.getBackgroundPage == "function" || chrome.runtime.getManifest?.()?.background?.service_worker) return "chrome-background";
259
- if (typeof chrome.devtools < "u") return "chrome-devtools";
260
- if (typeof document < "u" && globalThis?.location?.protocol === "chrome-extension:" && (chrome.extension?.getViews?.({ type: "popup" }) ?? []).includes(globalThis)) return "chrome-popup";
261
- if (typeof document < "u" && globalThis?.location?.protocol !== "chrome-extension:") return "chrome-content";
262
- }
263
- return typeof globalThis < "u" && typeof document < "u" ? "window" : "unknown";
264
- }
265
- function ce(e) {
266
- if (typeof RTCDataChannel < "u" && e instanceof RTCDataChannel) return "rtc-data";
267
- const t = qe(e);
268
- return t && t !== "internal" ? t : e === self || e === globalThis || e === "self" ? "self" : "internal";
269
- }
270
- function Ye(e) {
271
- if (!e) return "unknown";
272
- if (e.contextType) return e.contextType;
273
- const t = e.sender ?? "";
274
- return t.includes("worker") ? "worker" : t.includes("sw") || t.includes("service") ? "service-worker" : t.includes("chrome") || t.includes("crx") ? "chrome-content" : t.includes("background") ? "chrome-background" : "unknown";
275
- }
276
- const Ke = {
277
- get: (e, t) => Reflect.get(e, t),
278
- set: (e, t, n) => Reflect.set(e, t, n),
279
- has: (e, t) => Reflect.has(e, t),
280
- apply: (e, t, n) => Reflect.apply(e, t, n),
281
- construct: (e, t) => Reflect.construct(e, t),
282
- deleteProperty: (e, t) => Reflect.deleteProperty(e, t),
283
- ownKeys: (e) => Reflect.ownKeys(e),
284
- getOwnPropertyDescriptor: (e, t) => Reflect.getOwnPropertyDescriptor(e, t),
285
- getPrototypeOf: (e) => Reflect.getPrototypeOf(e),
286
- setPrototypeOf: (e, t) => Reflect.setPrototypeOf(e, t),
287
- isExtensible: (e) => Reflect.isExtensible(e),
288
- preventExtensions: (e) => Reflect.preventExtensions(e)
289
- }, Ve = Symbol.for("uniform.proxy"), Xe = Symbol.for("uniform.proxy.internals");
290
- var je = class {
291
- _invoker;
292
- _config;
293
- _childCache = /* @__PURE__ */ new Map();
294
- constructor(e, t) {
295
- this._invoker = e, this._config = {
296
- channel: t.channel,
297
- basePath: t.basePath ?? [],
298
- invoker: e,
299
- cache: t.cache ?? !0,
300
- timeout: t.timeout ?? 3e4
301
- };
302
- }
303
- get(e, t, n) {
304
- const s = String(t);
305
- if (t === Ve) return !0;
306
- if (t === Xe) return this._config;
307
- if (t === at) return !0;
308
- if (t === D) return this._getDescriptor();
309
- if (t === "then" || t === "catch" || t === "finally" || typeof t == "symbol") return;
310
- if (t === "$path") return this._config.basePath;
311
- if (t === "$channel") return this._config.channel;
312
- if (t === "$descriptor") return this._getDescriptor();
313
- if (t === "$invoke") return this._invoker;
314
- const r = [...this._config.basePath, s];
315
- if (this._config.cache && this._childCache.has(s)) return this._childCache.get(s);
316
- const i = H(this._invoker, {
317
- ...this._config,
318
- basePath: r
319
- });
320
- return this._config.cache && this._childCache.set(s, i), i;
321
- }
322
- set(e, t, n, s) {
323
- return typeof t == "symbol" || this._invoker(h.SET, [...this._config.basePath, String(t)], [n]), !0;
324
- }
325
- apply(e, t, n) {
326
- return this._invoker(h.APPLY, this._config.basePath, [n]);
327
- }
328
- construct(e, t, n) {
329
- return this._invoker(h.CONSTRUCT, this._config.basePath, [t]);
330
- }
331
- has(e, t) {
332
- return typeof t == "symbol" ? !1 : this._invoker(h.HAS, this._config.basePath, [t]);
333
- }
334
- deleteProperty(e, t) {
335
- return typeof t == "symbol" ? !0 : this._invoker(h.DELETE_PROPERTY, [...this._config.basePath, String(t)], []);
336
- }
337
- ownKeys(e) {
338
- return [];
339
- }
340
- getOwnPropertyDescriptor(e, t) {
341
- return {
342
- configurable: !0,
343
- enumerable: !0,
344
- writable: !0
345
- };
346
- }
347
- getPrototypeOf(e) {
348
- return Function.prototype;
349
- }
350
- setPrototypeOf(e, t) {
351
- return this._invoker(h.SET_PROTOTYPE_OF, this._config.basePath, [t]);
352
- }
353
- isExtensible(e) {
354
- return !0;
355
- }
356
- preventExtensions(e) {
357
- return this._invoker(h.PREVENT_EXTENSIONS, this._config.basePath, []);
358
- }
359
- _getDescriptor() {
360
- return {
361
- path: this._config.basePath,
362
- channel: this._config.channel,
363
- primitive: !1
364
- };
365
- }
366
- };
367
- function H(e, t) {
368
- const n = function() {}, s = new je(e, t);
369
- return new Proxy(n, s);
370
- }
371
- function le(e, t, n) {
372
- if (!e || typeof e != "object" || e.primitive) return e;
373
- const s = ye.get(e);
374
- if (s) return s;
375
- const r = H(t, {
376
- channel: n ?? e.channel ?? "unknown",
377
- basePath: e.path ?? []
378
- });
379
- return ye.set(e, r), V.set(r, e), r;
380
- }
381
- const Ze = le;
382
- function et(e) {
383
- return [
384
- e.localChannel,
385
- e.remoteChannel,
386
- e.sender,
387
- e.transportType,
388
- e.direction
389
- ].join("::");
390
- }
391
- function tt(e, t = {}) {
392
- const n = t.includeClosed ?? !1, s = t.status ?? (n ? void 0 : "active");
393
- return [...e].filter((r) => !(s && r.status !== s || t.channel && r.localChannel !== t.channel && r.remoteChannel !== t.channel || t.localChannel && r.localChannel !== t.localChannel || t.remoteChannel && r.remoteChannel !== t.remoteChannel || t.sender && r.sender !== t.sender || t.transportType && r.transportType !== t.transportType || t.direction && r.direction !== t.direction)).sort((r, i) => i.updatedAt - r.updatedAt);
394
- }
395
- var ue = class {
396
- _createId;
397
- _emitEvent;
398
- _connections = /* @__PURE__ */ new Map();
399
- constructor(e, t) {
400
- this._createId = e, this._emitEvent = t;
401
- }
402
- register(e) {
403
- const t = et(e), n = Date.now(), s = this._connections.get(t);
404
- if (s) return s.updatedAt = n, s.status = "active", s.metadata = {
405
- ...s.metadata,
406
- ...e.metadata
407
- }, s;
408
- const r = {
409
- id: this._createId(),
410
- localChannel: e.localChannel,
411
- remoteChannel: e.remoteChannel,
412
- sender: e.sender,
413
- transportType: e.transportType,
414
- direction: e.direction,
415
- status: "active",
416
- createdAt: n,
417
- updatedAt: n,
418
- metadata: e.metadata
419
- };
420
- return this._connections.set(t, r), this._emitEvent?.({
421
- type: "connected",
422
- connection: r,
423
- timestamp: n
424
- }), r;
425
- }
426
- markNotified(e, t) {
427
- const n = Date.now();
428
- e.lastNotifyAt = n, e.updatedAt = n, this._emitEvent?.({
429
- type: "notified",
430
- connection: e,
431
- timestamp: n,
432
- payload: t
433
- });
434
- }
435
- closeByChannel(e) {
436
- const t = Date.now();
437
- for (const n of this._connections.values()) n.localChannel !== e && n.remoteChannel !== e || n.status !== "closed" && (n.status = "closed", n.updatedAt = t, this._emitEvent?.({
438
- type: "disconnected",
439
- connection: n,
440
- timestamp: t
441
- }));
442
- }
443
- closeAll() {
444
- const e = Date.now();
445
- for (const t of this._connections.values()) t.status !== "closed" && (t.status = "closed", t.updatedAt = e, this._emitEvent?.({
446
- type: "disconnected",
447
- connection: t,
448
- timestamp: e
449
- }));
450
- }
451
- query(e = {}) {
452
- return tt(this._connections.values(), e);
453
- }
454
- values() {
455
- return [...this._connections.values()];
456
- }
457
- clear() {
458
- this._connections.clear();
459
- }
460
- }, he = class {
461
- _name;
462
- _contextType;
463
- _config;
464
- _transports = /* @__PURE__ */ new Map();
465
- _defaultTransport = null;
466
- _connectionEvents = new y({ bufferSize: 200 });
467
- _connectionRegistry = new ue(() => d(), (e) => this._connectionEvents.next(e));
468
- _pending = /* @__PURE__ */ new Map();
469
- _subscriptions = [];
470
- _inbound = new y({ bufferSize: 100 });
471
- _outbound = new y({ bufferSize: 100 });
472
- _invocations = new y({ bufferSize: 100 });
473
- _responses = new y({ bufferSize: 100 });
474
- _exposed = /* @__PURE__ */ new Map();
475
- _proxyCache = /* @__PURE__ */ new WeakMap();
476
- __getPrivate(e) {
477
- return this[e];
478
- }
479
- __setPrivate(e, t) {
480
- this[e] = t;
481
- }
482
- constructor(e) {
483
- const t = typeof e == "string" ? { name: e } : e;
484
- this._name = t.name, this._contextType = t.autoDetect !== !1 ? ae() : "unknown", this._config = {
485
- name: t.name,
486
- autoDetect: t.autoDetect ?? !0,
487
- timeout: t.timeout ?? 3e4,
488
- reflect: t.reflect ?? Ke,
489
- bufferSize: t.bufferSize ?? 100,
490
- autoListen: t.autoListen ?? !0
491
- }, this._config.autoListen && this._isWorkerContext() && this.listen(self);
492
- }
493
- connect(e, t = {}) {
494
- const n = ce(e), s = t.targetChannel ?? this._inferTargetChannel(e, n), r = this._createTransportBinding(e, n, s, t);
495
- this._transports.set(s, r), this._defaultTransport || (this._defaultTransport = r);
496
- const i = this._registerConnection({
497
- localChannel: this._name,
498
- remoteChannel: s,
499
- sender: this._name,
500
- transportType: n,
501
- direction: "outgoing",
502
- metadata: { phase: "connect" }
503
- });
504
- return this._emitConnectionSignal(r, "connect", {
505
- connectionId: i.id,
506
- from: this._name,
507
- to: s
508
- }), this;
509
- }
510
- listen(e, t = {}) {
511
- const n = ce(e), s = t.targetChannel ?? this._inferTargetChannel(e, n), r = (o) => this._handleIncoming(o), i = this._registerConnection({
512
- localChannel: this._name,
513
- remoteChannel: s,
514
- sender: s,
515
- transportType: n,
516
- direction: "incoming",
517
- metadata: { phase: "listen" }
518
- });
519
- switch (n) {
520
- case "worker":
521
- case "message-port":
522
- case "broadcast":
523
- t.autoStart !== !1 && e.start && e.start(), e.addEventListener?.("message", ((o) => r(o.data)));
524
- break;
525
- case "websocket":
526
- e.addEventListener?.("message", ((o) => {
527
- try {
528
- r(JSON.parse(o.data));
529
- } catch {}
530
- }));
531
- break;
532
- case "chrome-runtime":
533
- chrome.runtime.onMessage?.addListener?.((o, a, c) => (r(o), !0));
534
- break;
535
- case "chrome-tabs":
536
- chrome.runtime.onMessage?.addListener?.((o, a) => t.tabId != null && a?.tab?.id !== t.tabId ? !1 : (r(o), !0));
537
- break;
538
- case "chrome-port":
539
- e?.onMessage?.addListener?.((o) => {
540
- r(o);
541
- });
542
- break;
543
- case "chrome-external":
544
- chrome.runtime.onMessageExternal?.addListener?.((o) => (r(o), !0));
545
- break;
546
- case "self":
547
- addEventListener?.("message", ((o) => r(o.data)));
548
- break;
549
- default: t.onMessage && t.onMessage(r);
550
- }
551
- return this._sendSignalToTarget(e, n, {
552
- connectionId: i.id,
553
- from: this._name,
554
- to: s,
555
- tabId: t.tabId,
556
- externalId: t.externalId
557
- }, "notify"), this;
558
- }
559
- attach(e, t = {}) {
560
- return this.connect(e, t);
561
- }
562
- expose(e, t) {
563
- const n = [e];
564
- return U(n, t), this._exposed.set(e, {
565
- name: e,
566
- obj: t,
567
- path: n
568
- }), this;
569
- }
570
- exposeAll(e) {
571
- for (const [t, n] of Object.entries(e)) this.expose(t, n);
572
- return this;
573
- }
574
- async import(e, t) {
575
- return this.invoke(t ?? this._getDefaultTarget(), h.IMPORT, [], [e]);
576
- }
577
- invoke(e, t, n, s = []) {
578
- const r = d(), i = Promise.withResolvers();
579
- this._pending.set(r, i);
580
- const o = setTimeout(() => {
581
- this._pending.has(r) && (this._pending.delete(r), i.reject(/* @__PURE__ */ new Error(`Request timeout: ${t} on ${n.join(".")}`)));
582
- }, this._config.timeout), a = {
583
- id: r,
584
- channel: e,
585
- sender: this._name,
586
- type: "request",
587
- payload: {
588
- channel: e,
589
- sender: this._name,
590
- action: t,
591
- path: n,
592
- args: s
593
- },
594
- timestamp: Date.now()
595
- };
596
- return this._send(e, a), this._outbound.next(a), i.promise.finally(() => clearTimeout(o));
597
- }
598
- get(e, t, n) {
599
- return this.invoke(e, h.GET, t, [n]);
600
- }
601
- set(e, t, n, s) {
602
- return this.invoke(e, h.SET, t, [n, s]);
603
- }
604
- call(e, t, n = []) {
605
- return this.invoke(e, h.APPLY, t, [n]);
606
- }
607
- construct(e, t, n = []) {
608
- return this.invoke(e, h.CONSTRUCT, t, [n]);
609
- }
610
- proxy(e, t = []) {
611
- const n = e ?? this._getDefaultTarget();
612
- return this._createProxy(n, t);
613
- }
614
- remote(e, t) {
615
- return this.proxy(t, [e]);
616
- }
617
- wrapDescriptor(e, t) {
618
- return le(e, (s, r, i) => {
619
- const o = t ?? e?.channel ?? this._getDefaultTarget();
620
- return this.invoke(o, s, r, i);
621
- }, t ?? e?.channel ?? this._getDefaultTarget());
622
- }
623
- subscribe(e) {
624
- return this._inbound.subscribe(e);
625
- }
626
- next(e) {
627
- this._send(e.channel, e), this._outbound.next(e);
628
- }
629
- emit(e, t, n) {
630
- const s = {
631
- id: d(),
632
- channel: e,
633
- sender: this._name,
634
- type: "event",
635
- payload: {
636
- type: t,
637
- data: n
638
- },
639
- timestamp: Date.now()
640
- };
641
- this.next(s);
642
- }
643
- notify(e, t = {}, n = "notify") {
644
- const s = this._transports.get(e);
645
- return s ? (this._emitConnectionSignal(s, n, {
646
- from: this._name,
647
- to: e,
648
- ...t
649
- }), !0) : !1;
650
- }
651
- get onMessage() {
652
- return this._inbound;
653
- }
654
- get onOutbound() {
655
- return this._outbound;
656
- }
657
- get onInvocation() {
658
- return this._invocations;
659
- }
660
- get onResponse() {
661
- return this._responses;
662
- }
663
- get onConnection() {
664
- return this._connectionEvents;
665
- }
666
- subscribeConnections(e) {
667
- return this._connectionEvents.subscribe(e);
668
- }
669
- queryConnections(e = {}) {
670
- return this._connectionRegistry.query(e);
671
- }
672
- notifyConnections(e = {}, t = {}) {
673
- let n = 0;
674
- const s = this.queryConnections({
675
- ...t,
676
- status: "active",
677
- includeClosed: !1
678
- });
679
- for (const r of s) {
680
- const i = this._transports.get(r.remoteChannel);
681
- i && (this._emitConnectionSignal(i, "notify", {
682
- connectionId: r.id,
683
- from: this._name,
684
- to: r.remoteChannel,
685
- ...e
686
- }), n++);
687
- }
688
- return n;
689
- }
690
- get name() {
691
- return this._name;
692
- }
693
- get contextType() {
694
- return this._contextType;
695
- }
696
- get config() {
697
- return this._config;
698
- }
699
- get connectedChannels() {
700
- return [...this._transports.keys()];
701
- }
702
- get exposedModules() {
703
- return [...this._exposed.keys()];
704
- }
705
- close() {
706
- this._subscriptions.forEach((e) => e.unsubscribe()), this._subscriptions = [], this._pending.clear(), this._markAllConnectionsClosed();
707
- for (const e of this._transports.values()) {
708
- try {
709
- e.cleanup?.();
710
- } catch {}
711
- if (e.transportType === "message-port" || e.transportType === "broadcast") try {
712
- e.target?.close?.();
713
- } catch {}
714
- }
715
- this._transports.clear(), this._defaultTransport = null, this._connectionRegistry.clear(), this._inbound.complete(), this._outbound.complete(), this._invocations.complete(), this._responses.complete(), this._connectionEvents.complete();
716
- }
717
- _handleIncoming(e) {
718
- if (!(!e || typeof e != "object")) switch (this._inbound.next(e), e.type) {
719
- case "request":
720
- e.channel === this._name && this._handleRequest(e);
721
- break;
722
- case "response":
723
- this._handleResponse(e);
724
- break;
725
- case "event": break;
726
- case "signal":
727
- this._handleSignal(e);
728
- break;
729
- }
730
- }
731
- _handleResponse(e) {
732
- const t = e.reqId ?? e.id, n = this._pending.get(t);
733
- if (n) {
734
- if (this._pending.delete(t), e.payload?.error) n.reject(new Error(e.payload.error));
735
- else {
736
- const s = e.payload?.result, r = e.payload?.descriptor;
737
- s != null ? n.resolve(s) : r ? n.resolve(this.wrapDescriptor(r, e.sender)) : n.resolve(void 0);
738
- }
739
- this._responses.next({
740
- id: t,
741
- channel: e.channel,
742
- sender: e.sender,
743
- result: e.payload?.result,
744
- descriptor: e.payload?.descriptor,
745
- timestamp: Date.now()
746
- });
747
- }
748
- }
749
- async _handleRequest(e) {
750
- const t = e.payload;
751
- if (!t) return;
752
- const { action: n, path: s, args: r, sender: i } = t, o = e.reqId ?? e.id;
753
- this._invocations.next({
754
- id: o,
755
- channel: this._name,
756
- sender: i,
757
- action: n,
758
- path: s,
759
- args: r ?? [],
760
- timestamp: Date.now(),
761
- contextType: Ye(e)
762
- });
763
- const { result: a, toTransfer: c, newPath: l } = await this._executeAction(n, s, r ?? [], i);
764
- await this._sendResponse(o, n, i, l, a, c);
765
- }
766
- async _executeAction(e, t, n, s) {
767
- const { result: r, toTransfer: i, path: o } = we(e, t, n, {
768
- channel: this._name,
769
- sender: s,
770
- reflect: this._config.reflect
771
- });
772
- return {
773
- result: await r,
774
- toTransfer: i,
775
- newPath: o
776
- };
777
- }
778
- async _sendResponse(e, t, n, s, r, i) {
779
- const { response: o, transfer: a } = await be(e, t, this._name, n, s, r, i), c = {
780
- id: e,
781
- ...o,
782
- timestamp: Date.now(),
783
- transferable: a
784
- };
785
- this._send(n, c, a);
786
- }
787
- _handleSignal(e) {
788
- const t = e?.payload ?? {}, n = t.from ?? e.sender ?? "unknown", s = e.transportType ?? this._transports.get(e.channel)?.transportType ?? "internal", r = this._registerConnection({
789
- localChannel: this._name,
790
- remoteChannel: n,
791
- sender: e.sender ?? n,
792
- transportType: s,
793
- direction: "incoming"
794
- });
795
- this._markConnectionNotified(r, t);
796
- }
797
- _registerConnection(e) {
798
- return this._connectionRegistry.register(e);
799
- }
800
- _markConnectionNotified(e, t) {
801
- this._connectionRegistry.markNotified(e, t);
802
- }
803
- _emitConnectionSignal(e, t, n = {}) {
804
- const s = {
805
- id: d(),
806
- type: "signal",
807
- channel: e.targetChannel,
808
- sender: this._name,
809
- transportType: e.transportType,
810
- payload: {
811
- type: t,
812
- from: this._name,
813
- to: e.targetChannel,
814
- ...n
815
- },
816
- timestamp: Date.now()
817
- };
818
- (e?.sender ?? e?.postMessage)?.call(e, s);
819
- const r = this._registerConnection({
820
- localChannel: this._name,
821
- remoteChannel: e.targetChannel,
822
- sender: this._name,
823
- transportType: e.transportType,
824
- direction: "outgoing"
825
- });
826
- this._markConnectionNotified(r, s.payload);
827
- }
828
- _sendSignalToTarget(e, t, n, s) {
829
- const r = {
830
- id: d(),
831
- type: "signal",
832
- channel: n.to ?? this._name,
833
- sender: this._name,
834
- transportType: t,
835
- payload: {
836
- type: s,
837
- ...n
838
- },
839
- timestamp: Date.now()
840
- };
841
- try {
842
- if (t === "websocket") {
843
- e?.send?.(JSON.stringify(r));
844
- return;
845
- }
846
- if (t === "chrome-runtime") {
847
- chrome.runtime?.sendMessage?.(r);
848
- return;
849
- }
850
- if (t === "chrome-tabs") {
851
- const i = n.tabId;
852
- i != null && chrome.tabs?.sendMessage?.(i, r);
853
- return;
854
- }
855
- if (t === "chrome-port") {
856
- e?.postMessage?.(r);
857
- return;
858
- }
859
- if (t === "chrome-external") {
860
- n.externalId && chrome.runtime?.sendMessage?.(n.externalId, r);
861
- return;
862
- }
863
- e?.postMessage?.(r, { transfer: [] });
864
- } catch {}
865
- }
866
- _markAllConnectionsClosed() {
867
- this._connectionRegistry.closeAll();
868
- }
869
- _createTransportBinding(e, t, n, s) {
870
- let r, i;
871
- switch (t) {
872
- case "worker":
873
- case "message-port":
874
- case "broadcast":
875
- s.autoStart !== !1 && e.start && e.start(), r = (o, a) => e.postMessage(o, { transfer: a });
876
- {
877
- const o = ((a) => this._handleIncoming(a.data));
878
- e.addEventListener?.("message", o), i = () => e.removeEventListener?.("message", o);
879
- }
880
- break;
881
- case "websocket":
882
- r = (o) => e.send(JSON.stringify(o));
883
- {
884
- const o = ((a) => {
885
- try {
886
- this._handleIncoming(JSON.parse(a.data));
887
- } catch {}
888
- });
889
- e.addEventListener?.("message", o), i = () => e.removeEventListener?.("message", o);
890
- }
891
- break;
892
- case "chrome-runtime":
893
- r = (o) => chrome.runtime.sendMessage(o);
894
- {
895
- const o = (a) => this._handleIncoming(a);
896
- chrome.runtime.onMessage?.addListener?.(o), i = () => chrome.runtime.onMessage?.removeListener?.(o);
897
- }
898
- break;
899
- case "chrome-tabs":
900
- r = (o) => {
901
- s.tabId != null && chrome.tabs?.sendMessage?.(s.tabId, o);
902
- };
903
- {
904
- const o = (a, c) => s.tabId != null && c?.tab?.id !== s.tabId ? !1 : (this._handleIncoming(a), !0);
905
- chrome.runtime.onMessage?.addListener?.(o), i = () => chrome.runtime.onMessage?.removeListener?.(o);
906
- }
907
- break;
908
- case "chrome-port":
909
- if (e?.postMessage && e?.onMessage?.addListener) {
910
- r = (a) => e.postMessage(a);
911
- const o = (a) => this._handleIncoming(a);
912
- e.onMessage.addListener(o), i = () => {
913
- try {
914
- e.onMessage.removeListener(o);
915
- } catch {}
916
- try {
917
- e.disconnect?.();
918
- } catch {}
919
- };
920
- } else {
921
- const o = s.portName ?? n, a = s.tabId != null && chrome.tabs?.connect ? chrome.tabs.connect(s.tabId, { name: o }) : chrome.runtime.connect({ name: o });
922
- r = (l) => a.postMessage(l);
923
- const c = (l) => this._handleIncoming(l);
924
- a.onMessage.addListener(c), i = () => {
925
- try {
926
- a.onMessage.removeListener(c);
927
- } catch {}
928
- try {
929
- a.disconnect();
930
- } catch {}
931
- };
932
- }
933
- break;
934
- case "chrome-external":
935
- r = (o) => {
936
- s.externalId && chrome.runtime.sendMessage(s.externalId, o);
937
- };
938
- {
939
- const o = (a) => (this._handleIncoming(a), !0);
940
- chrome.runtime.onMessageExternal?.addListener?.(o), i = () => chrome.runtime.onMessageExternal?.removeListener?.(o);
941
- }
942
- break;
943
- case "self":
944
- r = (o, a) => globalThis.postMessage?.(o, { transfer: a ?? [] });
945
- {
946
- const o = ((a) => this._handleIncoming(a.data));
947
- globalThis.addEventListener?.("message", o), i = () => globalThis.removeEventListener?.("message", o);
948
- }
949
- break;
950
- default: s.onMessage && (i = s.onMessage((o) => this._handleIncoming(o))), r = (o) => e?.postMessage?.(o);
951
- }
952
- return {
953
- target: e,
954
- targetChannel: n,
955
- transportType: t,
956
- sender: r,
957
- cleanup: i,
958
- postMessage: (o, a) => r?.(o, a),
959
- start: () => e?.start?.(),
960
- close: () => e?.close?.()
961
- };
962
- }
963
- _send(e, t, n) {
964
- const s = this._transports.get(e) ?? this._defaultTransport;
965
- (s?.sender ?? s?.postMessage)?.call(s, t, n);
966
- }
967
- _getDefaultTarget() {
968
- return this._defaultTransport ? this._defaultTransport.targetChannel : "worker";
969
- }
970
- _inferTargetChannel(e, t) {
971
- return t === "worker" ? "worker" : t === "broadcast" && e.name ? e.name : t === "self" ? "self" : `${t}-${d().slice(0, 8)}`;
972
- }
973
- _createProxy(e, t) {
974
- return H((s, r, i) => this.invoke(e, s, r, i), {
975
- channel: e,
976
- basePath: t,
977
- cache: !0,
978
- timeout: this._config.timeout
979
- });
980
- }
981
- _isWorkerContext() {
982
- return [
983
- "worker",
984
- "shared-worker",
985
- "service-worker"
986
- ].includes(this._contextType);
987
- }
988
- };
989
- function Y(e) {
990
- return new he(e);
991
- }
992
- let G = null;
993
- function nt() {
994
- if (!G) {
995
- const e = ae();
996
- [
997
- "worker",
998
- "shared-worker",
999
- "service-worker"
1000
- ].includes(e) ? G = Y({
1001
- name: "worker",
1002
- autoListen: !0
1003
- }) : G = Y({
1004
- name: "host",
1005
- autoListen: !1
1006
- });
1007
- }
1008
- return G;
1009
- }
1010
- const m = {
1011
- rjb: "rejectBy",
1012
- rvb: "resolveBy",
1013
- rj: "reject",
1014
- rv: "resolve",
1015
- cr: "create",
1016
- cs: "createSync",
1017
- a: "array",
1018
- ta: "typedarray",
1019
- udf: "undefined"
1020
- };
1021
- [
1022
- typeof ArrayBuffer != m.udf ? ArrayBuffer : null,
1023
- typeof MessagePort != m.udf ? MessagePort : null,
1024
- typeof ReadableStream != m.udf ? ReadableStream : null,
1025
- typeof WritableStream != m.udf ? WritableStream : null,
1026
- typeof TransformStream != m.udf ? TransformStream : null,
1027
- typeof WebTransportReceiveStream != m.udf ? WebTransportReceiveStream : null,
1028
- typeof WebTransportSendStream != m.udf ? WebTransportSendStream : null,
1029
- typeof AudioData != m.udf ? AudioData : null,
1030
- typeof ImageBitmap != m.udf ? ImageBitmap : null,
1031
- typeof VideoFrame != m.udf ? VideoFrame : null,
1032
- typeof OffscreenCanvas != m.udf ? OffscreenCanvas : null,
1033
- typeof RTCDataChannel != m.udf ? RTCDataChannel : null
1034
- ].filter((e) => e != null);
1035
- function de() {
1036
- try {
1037
- const e = globalThis.location?.href;
1038
- if (typeof e == "string" && e.length > 0) return e;
1039
- } catch {}
1040
- try {
1041
- if (typeof document < "u" && typeof document.baseURI == "string" && document.baseURI.length > 0) return document.baseURI;
1042
- } catch {}
1043
- return "";
1044
- }
1045
- function fe(e) {
1046
- const t = de();
1047
- if (!t.length) throw new TypeError("[uniform] No base URL for worker resolution (missing location / document.baseURI)");
1048
- const n = e.startsWith("/") ? e.replace(/^\//, "./") : e;
1049
- return new URL(n, t).href;
1050
- }
1051
- const w = {
1052
- name: "unknown",
1053
- instance: null
1054
- }, K = /* @__PURE__ */ new Map(), pe = (e) => [...Object.values(h)].includes(e);
1055
- var st = class {
1056
- channelName;
1057
- options;
1058
- _channel;
1059
- constructor(e, t = {}) {
1060
- this.channelName = e, this.options = t, this._channel = nt();
1061
- }
1062
- request(e, t, n, s = {}) {
1063
- return typeof e == "string" && (e = [e]), Array.isArray(t) && pe(e) && (s = n, n = t, t = e, e = []), this._channel.invoke(this.channelName, t, e, n);
1064
- }
1065
- doImportModule(e, t) {
1066
- return this._channel.import(e, this.channelName);
1067
- }
1068
- }, rt = class {
1069
- channel;
1070
- options;
1071
- _unified;
1072
- broadcasts = {};
1073
- constructor(e, t = {}) {
1074
- this.channel = e, this.options = t, this._unified = Y({
1075
- name: e,
1076
- autoListen: !1
1077
- }), w.name = e, w.instance = this;
1078
- }
1079
- createRemoteChannel(e, t = {}, n) {
1080
- return n && (this._unified.attach(n, { targetChannel: e }), this.broadcasts[e] = n), Promise.resolve(new st(e, t));
1081
- }
1082
- getChannel() {
1083
- return this.channel;
1084
- }
1085
- request(e, t, n, s = {}, r = "worker") {
1086
- return typeof e == "string" && (e = [e]), Array.isArray(t) && pe(e) && (r = s, s = n, n = t, t = e, e = []), this._unified.invoke(r, t, e, n);
1087
- }
1088
- resolveResponse(e, t) {
1089
- return Promise.resolve(t);
1090
- }
1091
- async handleAndResponse(e, t, n) {
1092
- const s = await ut(e, t, this.channel);
1093
- s && n?.(s.response, s.transfer);
1094
- }
1095
- close() {
1096
- this._unified.close();
1097
- }
1098
- };
1099
- const ot = (e = "$host$") => {
1100
- if (w?.instance && e === "$host$") return w.instance;
1101
- if (K.has(e)) return K.get(e) ?? null;
1102
- const t = new rt(e);
1103
- return e === "$host$" && (w.name = e, w.instance = t), K.set(e, t), t;
1104
- }, _e = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakMap(), ye = /* @__PURE__ */ new WeakMap(), it = (e, t = w?.name, n) => typeof e == "object" && e != null || typeof e == "function" && e != null ? V.has(e) ? V.get(e) : _e.has(e) ? _e.get(e) : $(e) || n?.includes?.(e) || t == w?.name ? e : {
1105
- $isDescriptor: !0,
1106
- path: E.get(e) ?? (() => {
1107
- const s = [d()];
1108
- return U(s, e), s;
1109
- })(),
1110
- owner: w?.name,
1111
- channel: t,
1112
- primitive: C(e),
1113
- writable: !0,
1114
- enumerable: !0,
1115
- configurable: !0,
1116
- argumentCount: e instanceof Function ? e.length : -1
1117
- } : x(e) ? e : null, at = Symbol.for("@requestHandler"), D = Symbol.for("@descriptor"), X = (e) => x(e) || e?.[D] ? e : e?.$isDescriptor ? Ze(e, async () => {}) : $(e) ? e : null, L = /* @__PURE__ */ new Map(), E = /* @__PURE__ */ new WeakMap(), j = (e, t) => {
1118
- if (t != null && !Array.isArray(t) && (t = [t]), t == null || t?.length < 1) return e;
1119
- const n = e?.[D] ?? (e?.$isDescriptor ? e : null);
1120
- if (n && n?.owner == w?.name && (e = R(n?.path) ?? e), C(e)) return e;
1121
- for (const s of t) if (e = e?.[s], e == null) return e;
1122
- return e;
1123
- }, R = (e) => {
1124
- if (e != null && !Array.isArray(e) && (e = [e]), e == null || e?.length < 1) return null;
1125
- const t = L?.get?.(e?.[0]) ?? null;
1126
- return t != null ? j(t, e?.slice?.(1)) : null;
1127
- }, U = (e, t) => {
1128
- const n = t?.[D] ?? (t?.$isDescriptor ? t : null);
1129
- if (n && n?.owner == w?.name && (t = R(n?.path) ?? t), e != null && !Array.isArray(e) && (e = [e]), e == null || e?.length < 1) return null;
1130
- const s = L?.get?.(e?.[0]) ?? null;
1131
- return e?.length > 1 ? j(s, e?.slice?.(1, -1))[e?.[e?.length - 1]] = t : L?.set?.(e?.[0], t), (typeof t == "object" || typeof t == "function") && E?.set?.(t, e), t;
1132
- }, ge = (e) => {
1133
- if (e != null && !Array.isArray(e) && (e = [e]), e == null || e?.length < 1) return !1;
1134
- return !(L?.get?.(e?.[0]) ?? null) && e?.length <= 1 ? (L?.delete?.(e?.[0]), !0) : !1;
1135
- }, ct = (e) => {
1136
- const t = e?.[D] ?? (e?.$isDescriptor ? e : null);
1137
- t && t?.owner == w?.name && (e = R(t?.path) ?? e);
1138
- const n = E?.get?.(e) ?? t?.path;
1139
- return n == null || n?.length < 1 ? !1 : (ge(n), (typeof e == "object" || typeof e == "function") && E?.delete?.(e), !0);
1140
- }, lt = (e) => {
1141
- const t = e?.[D] ?? (e?.$isDescriptor ? e : null);
1142
- return (E?.get?.(e) ?? t?.path) == null;
1143
- }, P = (e) => (typeof e == "object" || typeof e == "function") && e != null, me = {
1144
- get: (e, t) => e?.[t],
1145
- set: (e, t, n) => (e[t] = n, !0),
1146
- has: (e, t) => t in e,
1147
- apply: (e, t, n) => e.apply(t, n),
1148
- construct: (e, t) => new e(...t),
1149
- deleteProperty: (e, t) => delete e[t],
1150
- ownKeys: (e) => Object.keys(e),
1151
- getOwnPropertyDescriptor: (e, t) => Object.getOwnPropertyDescriptor(e, t),
1152
- getPrototypeOf: (e) => Object.getPrototypeOf(e),
1153
- setPrototypeOf: (e, t) => Object.setPrototypeOf(e, t),
1154
- isExtensible: (e) => Object.isExtensible(e),
1155
- preventExtensions: (e) => Object.preventExtensions(e)
1156
- };
1157
- function we(e, t, n, s = {}) {
1158
- const { channel: r = "", sender: i = "", reflect: o = me } = s, a = s.target ?? R(t), c = [];
1159
- let l = null, _ = t;
1160
- switch (String(e).toLowerCase()) {
1161
- case "import":
1162
- case h.IMPORT:
1163
- l = import(n?.[0]);
1164
- break;
1165
- case "transfer":
1166
- case h.TRANSFER:
1167
- z(a) && r !== i && c.push(a), l = a;
1168
- break;
1169
- case "get":
1170
- case h.GET: {
1171
- const f = n?.[0], b = o.get?.(a, f) ?? a?.[f];
1172
- l = typeof b == "function" && a != null ? b.bind(a) : b, _ = [...t, String(f)];
1173
- break;
1174
- }
1175
- case "set":
1176
- case h.SET: {
1177
- const [f, b] = n, N = k(b, X);
1178
- s.target ? l = o.set?.(a, f, N) ?? (a[f] = N, !0) : l = o.set?.(a, f, N) ?? U([...t, String(f)], N);
1179
- break;
1180
- }
1181
- case "apply":
1182
- case "call":
1183
- case h.APPLY:
1184
- case h.CALL:
1185
- if (typeof a == "function") {
1186
- const f = s.context ?? (s.target ? void 0 : R(t.slice(0, -1))), b = k(n?.[0] ?? n ?? [], X);
1187
- l = o.apply?.(a, f, b) ?? a.apply(f, b), z(l) && t?.at(-1) === "transfer" && r !== i && c.push(l);
1188
- }
1189
- break;
1190
- case "construct":
1191
- case h.CONSTRUCT:
1192
- if (typeof a == "function") {
1193
- const f = k(n?.[0] ?? n ?? [], X);
1194
- l = o.construct?.(a, f) ?? new a(...f);
1195
- }
1196
- break;
1197
- case "delete":
1198
- case "deleteproperty":
1199
- case "dispose":
1200
- case h.DELETE:
1201
- case h.DELETE_PROPERTY:
1202
- case h.DISPOSE:
1203
- if (s.target) {
1204
- const f = t[t.length - 1];
1205
- l = o.deleteProperty?.(a, f) ?? delete a[f];
1206
- } else l = t?.length > 0 ? ge(t) : ct(a), l && (_ = E.get(a) ?? []);
1207
- break;
1208
- case "has":
1209
- case h.HAS:
1210
- l = o.has?.(a, n?.[0]) ?? (P(a) ? n?.[0] in a : !1);
1211
- break;
1212
- case "ownkeys":
1213
- case h.OWN_KEYS:
1214
- l = o.ownKeys?.(a) ?? (P(a) ? Object.keys(a) : []);
1215
- break;
1216
- case "getownpropertydescriptor":
1217
- case "getpropertydescriptor":
1218
- case h.GET_OWN_PROPERTY_DESCRIPTOR:
1219
- case h.GET_PROPERTY_DESCRIPTOR:
1220
- l = o.getOwnPropertyDescriptor?.(a, n?.[0] ?? t?.at(-1) ?? "") ?? (P(a) ? Object.getOwnPropertyDescriptor(a, n?.[0] ?? t?.at(-1) ?? "") : void 0);
1221
- break;
1222
- case "getprototypeof":
1223
- case h.GET_PROTOTYPE_OF:
1224
- l = o.getPrototypeOf?.(a) ?? (P(a) ? Object.getPrototypeOf(a) : null);
1225
- break;
1226
- case "setprototypeof":
1227
- case h.SET_PROTOTYPE_OF:
1228
- l = o.setPrototypeOf?.(a, n?.[0]) ?? (P(a) ? Object.setPrototypeOf(a, n?.[0]) : !1);
1229
- break;
1230
- case "isextensible":
1231
- case h.IS_EXTENSIBLE:
1232
- l = o.isExtensible?.(a) ?? (P(a) ? Object.isExtensible(a) : !0);
1233
- break;
1234
- case "preventextensions":
1235
- case h.PREVENT_EXTENSIONS:
1236
- l = o.preventExtensions?.(a) ?? (P(a) ? Object.preventExtensions(a) : !1);
1237
- break;
1238
- }
1239
- return {
1240
- result: l,
1241
- toTransfer: c,
1242
- path: _
1243
- };
1244
- }
1245
- async function be(e, t, n, s, r, i, o) {
1246
- const a = await i, c = z(a) && o.includes(a) || x(a);
1247
- let l = r;
1248
- !c && t !== "get" && t !== h.GET && (typeof a == "object" || typeof a == "function") && (lt(a) ? (l = [d()], U(l, a)) : l = E.get(a) ?? []);
1249
- const _ = R(l), f = t === "get" || t === h.GET ? l?.at(-1) : void 0, b = R(r), N = k(a, (Ot) => it(Ot, n, o)) ?? a;
1250
- return {
1251
- response: {
1252
- channel: s,
1253
- sender: n,
1254
- reqId: e,
1255
- action: t,
1256
- type: "response",
1257
- payload: {
1258
- result: c ? N : null,
1259
- type: typeof a,
1260
- channel: s,
1261
- sender: n,
1262
- descriptor: {
1263
- $isDescriptor: !0,
1264
- path: l,
1265
- owner: n,
1266
- channel: n,
1267
- primitive: C(a),
1268
- writable: !0,
1269
- enumerable: !0,
1270
- configurable: !0,
1271
- argumentCount: b instanceof Function ? b.length : -1,
1272
- ...P(_) && f != null ? Object.getOwnPropertyDescriptor(_, f) : {}
1273
- }
1274
- }
1275
- },
1276
- transfer: o
1277
- };
1278
- }
1279
- async function ut(e, t, n, s) {
1280
- const { channel: r, sender: i, path: o, action: a, args: c } = e;
1281
- if (r !== n) return null;
1282
- const { result: l, toTransfer: _, path: f } = we(a, o, c, {
1283
- channel: r,
1284
- sender: i,
1285
- ...s
1286
- });
1287
- return be(t, a, n, i, f, l, _);
1288
- }
1289
- var dt = class {
1290
- _name;
1291
- _transportType;
1292
- _id = d();
1293
- _state = "disconnected";
1294
- _inbound = new y({ bufferSize: 1e3 });
1295
- _outbound = new y({ bufferSize: 1e3 });
1296
- _stateChanges = new y();
1297
- _connectedPeers = /* @__PURE__ */ new Map();
1298
- _subs = [];
1299
- _stats = {
1300
- messagesSent: 0,
1301
- messagesReceived: 0,
1302
- bytesTransferred: 0,
1303
- latencyMs: 0,
1304
- uptime: 0,
1305
- reconnectCount: 0
1306
- };
1307
- _startTime = 0;
1308
- _pending = /* @__PURE__ */ new Map();
1309
- _buffer = [];
1310
- _opts;
1311
- constructor(e, t = "internal", n = {}) {
1312
- this._name = e, this._transportType = t, this._opts = {
1313
- timeout: 3e4,
1314
- autoReconnect: !0,
1315
- reconnectInterval: 1e3,
1316
- maxReconnectAttempts: 5,
1317
- bufferMessages: !0,
1318
- bufferSize: 1e3,
1319
- metadata: {},
1320
- ...n
1321
- }, this._setupSubscriptions();
1322
- }
1323
- subscribe(e, t) {
1324
- return (t ? ze((n) => n.sender === t)(this._inbound) : this._inbound).subscribe(typeof e == "function" ? { next: e } : e);
1325
- }
1326
- next(e) {
1327
- if (this._state !== "connected") {
1328
- this._opts.bufferMessages && this._buffer.length < this._opts.bufferSize && this._buffer.push(e);
1329
- return;
1330
- }
1331
- this._outbound.next(e), this._stats.messagesSent++;
1332
- }
1333
- async request(e, t, n = {}) {
1334
- const s = d(), r = Promise.withResolvers();
1335
- this._pending.set(s, r);
1336
- const i = setTimeout(() => {
1337
- this._pending.has(s) && (this._pending.delete(s), r.reject(/* @__PURE__ */ new Error("Request timeout")));
1338
- }, n.timeout ?? this._opts.timeout);
1339
- return this.next({
1340
- id: d(),
1341
- channel: e,
1342
- sender: this._name,
1343
- type: "request",
1344
- reqId: s,
1345
- payload: {
1346
- ...t,
1347
- action: n.action,
1348
- path: n.path
1349
- },
1350
- timestamp: Date.now()
1351
- }), r.promise.finally(() => clearTimeout(i));
1352
- }
1353
- respond(e, t) {
1354
- this.next({
1355
- id: d(),
1356
- channel: e.sender,
1357
- sender: this._name,
1358
- type: "response",
1359
- reqId: e.reqId,
1360
- payload: t,
1361
- timestamp: Date.now()
1362
- });
1363
- }
1364
- emit(e, t, n) {
1365
- this.next({
1366
- id: d(),
1367
- channel: e,
1368
- sender: this._name,
1369
- type: "event",
1370
- payload: {
1371
- type: t,
1372
- data: n
1373
- },
1374
- timestamp: Date.now()
1375
- });
1376
- }
1377
- subscribeOutbound(e) {
1378
- return this._outbound.subscribe(typeof e == "function" ? { next: e } : e);
1379
- }
1380
- pushInbound(e) {
1381
- if (this._stats.messagesReceived++, e.type === "response" && e.reqId) {
1382
- const t = this._pending.get(e.reqId);
1383
- if (t) {
1384
- this._pending.delete(e.reqId), t.resolve(e.payload);
1385
- return;
1386
- }
1387
- }
1388
- this._inbound.next(e);
1389
- }
1390
- async connect() {
1391
- this._state !== "connected" && (this._setState("connecting"), this._startTime = Date.now(), this._setState("connected"), this._flushBuffer());
1392
- }
1393
- disconnect() {
1394
- this._state === "disconnected" || this._state === "closed" || (this._setState("disconnected"), this._subs.forEach((e) => e.unsubscribe()), this._subs = []);
1395
- }
1396
- close() {
1397
- this.disconnect(), this._setState("closed"), this._inbound.complete(), this._outbound.complete(), this._stateChanges.complete();
1398
- }
1399
- markConnected() {
1400
- this._setState("connected"), this._flushBuffer();
1401
- }
1402
- markDisconnected() {
1403
- this._setState("disconnected");
1404
- }
1405
- _setState(e) {
1406
- this._state !== e && (this._state = e, this._stateChanges.next(e));
1407
- }
1408
- _flushBuffer() {
1409
- for (const e of this._buffer) this._outbound.next(e);
1410
- this._buffer = [];
1411
- }
1412
- _setupSubscriptions() {
1413
- this._subs.push(this._inbound.subscribe({ next: (e) => {
1414
- e.type === "signal" && e.payload?.type === "connect" && this._connectedPeers.set(e.sender, {
1415
- name: e.sender,
1416
- state: "connected",
1417
- isHost: !1
1418
- });
1419
- } }));
1420
- }
1421
- get id() {
1422
- return this._id;
1423
- }
1424
- get name() {
1425
- return this._name;
1426
- }
1427
- get state() {
1428
- return this._state;
1429
- }
1430
- get transportType() {
1431
- return this._transportType;
1432
- }
1433
- get stats() {
1434
- return {
1435
- ...this._stats,
1436
- uptime: this._startTime ? Date.now() - this._startTime : 0
1437
- };
1438
- }
1439
- get stateChanges() {
1440
- return this._stateChanges;
1441
- }
1442
- get connectedPeers() {
1443
- return [...this._connectedPeers.keys()];
1444
- }
1445
- get meta() {
1446
- return {
1447
- id: this._id,
1448
- name: this._name,
1449
- state: this._state,
1450
- isHost: !1,
1451
- connectedChannels: new Set(this._connectedPeers.keys())
1452
- };
1453
- }
1454
- }, ft = class F {
1455
- _connections = /* @__PURE__ */ new Map();
1456
- static _instance = null;
1457
- static getInstance() {
1458
- return F._instance || (F._instance = new F()), F._instance;
1459
- }
1460
- getOrCreate(t, n = "internal", s = {}) {
1461
- return this._connections.has(t) || this._connections.set(t, new dt(t, n, s)), this._connections.get(t);
1462
- }
1463
- get(t) {
1464
- return this._connections.get(t);
1465
- }
1466
- has(t) {
1467
- return this._connections.has(t);
1468
- }
1469
- delete(t) {
1470
- return this._connections.get(t)?.close(), this._connections.delete(t);
1471
- }
1472
- clear() {
1473
- this._connections.forEach((t) => t.close()), this._connections.clear();
1474
- }
1475
- get size() {
1476
- return this._connections.size;
1477
- }
1478
- get names() {
1479
- return [...this._connections.keys()];
1480
- }
1481
- };
1482
- const Ce = () => ft.getInstance(), pt = (e, t, n) => Ce().getOrCreate(e, t, n), _t = "uniform_channels", yt = 1, u = {
1483
- MESSAGES: "messages",
1484
- MAILBOX: "mailbox",
1485
- PENDING: "pending",
1486
- EXCHANGE: "exchange",
1487
- TRANSACTIONS: "transactions"
1488
- };
1489
- var gt = class {
1490
- _db = null;
1491
- _isOpen = !1;
1492
- _openPromise = null;
1493
- _channelName;
1494
- _messageUpdates = new y();
1495
- _exchangeUpdates = new y();
1496
- constructor(e) {
1497
- this._channelName = e;
1498
- }
1499
- async open() {
1500
- return this._db && this._isOpen ? this._db : this._openPromise ? this._openPromise : (this._openPromise = new Promise((e, t) => {
1501
- const n = indexedDB.open(_t, yt);
1502
- n.onerror = () => {
1503
- this._openPromise = null, t(/* @__PURE__ */ new Error("Failed to open IndexedDB"));
1504
- }, n.onsuccess = () => {
1505
- this._db = n.result, this._isOpen = !0, this._openPromise = null, e(this._db);
1506
- }, n.onupgradeneeded = (s) => {
1507
- const r = s.target.result;
1508
- this._createStores(r);
1509
- };
1510
- }), this._openPromise);
1511
- }
1512
- close() {
1513
- this._db && (this._db.close(), this._db = null, this._isOpen = !1);
1514
- }
1515
- _createStores(e) {
1516
- if (!e.objectStoreNames.contains(u.MESSAGES)) {
1517
- const t = e.createObjectStore(u.MESSAGES, { keyPath: "id" });
1518
- t.createIndex("channel", "channel", { unique: !1 }), t.createIndex("status", "status", { unique: !1 }), t.createIndex("recipient", "recipient", { unique: !1 }), t.createIndex("createdAt", "createdAt", { unique: !1 }), t.createIndex("channel_status", ["channel", "status"], { unique: !1 });
1519
- }
1520
- if (!e.objectStoreNames.contains(u.MAILBOX)) {
1521
- const t = e.createObjectStore(u.MAILBOX, { keyPath: "id" });
1522
- t.createIndex("channel", "channel", { unique: !1 }), t.createIndex("priority", "priority", { unique: !1 }), t.createIndex("expiresAt", "expiresAt", { unique: !1 });
1523
- }
1524
- if (!e.objectStoreNames.contains(u.PENDING)) {
1525
- const t = e.createObjectStore(u.PENDING, { keyPath: "id" });
1526
- t.createIndex("channel", "channel", { unique: !1 }), t.createIndex("createdAt", "createdAt", { unique: !1 });
1527
- }
1528
- if (!e.objectStoreNames.contains(u.EXCHANGE)) {
1529
- const t = e.createObjectStore(u.EXCHANGE, { keyPath: "id" });
1530
- t.createIndex("key", "key", { unique: !0 }), t.createIndex("owner", "owner", { unique: !1 });
1531
- }
1532
- e.objectStoreNames.contains(u.TRANSACTIONS) || e.createObjectStore(u.TRANSACTIONS, { keyPath: "id" }).createIndex("createdAt", "createdAt", { unique: !1 });
1533
- }
1534
- async defer(e, t = {}) {
1535
- const n = await this.open(), s = {
1536
- id: d(),
1537
- channel: e.channel,
1538
- sender: e.sender ?? this._channelName,
1539
- recipient: e.channel,
1540
- type: e.type,
1541
- payload: e.payload,
1542
- status: "pending",
1543
- priority: t.priority ?? 0,
1544
- createdAt: Date.now(),
1545
- updatedAt: Date.now(),
1546
- expiresAt: t.expiresIn ? Date.now() + t.expiresIn : null,
1547
- retryCount: 0,
1548
- maxRetries: t.maxRetries ?? 3,
1549
- metadata: t.metadata
1550
- };
1551
- return new Promise((r, i) => {
1552
- const o = n.transaction([u.MESSAGES, u.MAILBOX], "readwrite"), a = o.objectStore(u.MESSAGES), c = o.objectStore(u.MAILBOX);
1553
- a.add(s), c.add(s), o.oncomplete = () => {
1554
- this._messageUpdates.next(s), r(s.id);
1555
- }, o.onerror = () => i(/* @__PURE__ */ new Error("Failed to defer message"));
1556
- });
1557
- }
1558
- async getDeferredMessages(e, t = {}) {
1559
- const n = await this.open();
1560
- return new Promise((s, r) => {
1561
- const i = n.transaction(u.MESSAGES, "readonly").objectStore(u.MESSAGES), o = t.status ? i.index("channel_status") : i.index("channel"), a = t.status ? IDBKeyRange.only([e, t.status]) : IDBKeyRange.only(e), c = o.getAll(a, t.limit);
1562
- c.onsuccess = () => {
1563
- let l = c.result;
1564
- t.offset && (l = l.slice(t.offset)), s(l);
1565
- }, c.onerror = () => r(/* @__PURE__ */ new Error("Failed to get deferred messages"));
1566
- });
1567
- }
1568
- async processNextPending(e) {
1569
- const t = await this.open();
1570
- return new Promise((n, s) => {
1571
- const r = t.transaction(u.MESSAGES, "readwrite").objectStore(u.MESSAGES).index("channel_status").openCursor(IDBKeyRange.only([e, "pending"]));
1572
- r.onsuccess = () => {
1573
- const i = r.result;
1574
- if (i) {
1575
- const o = i.value;
1576
- o.status = "processing", o.updatedAt = Date.now(), i.update(o), this._messageUpdates.next(o), n(o);
1577
- } else n(null);
1578
- }, r.onerror = () => s(/* @__PURE__ */ new Error("Failed to process pending message"));
1579
- });
1580
- }
1581
- async markDelivered(e) {
1582
- await this._updateMessageStatus(e, "delivered");
1583
- }
1584
- async markFailed(e) {
1585
- const t = await this.open();
1586
- return new Promise((n, s) => {
1587
- const r = t.transaction(u.MESSAGES, "readwrite").objectStore(u.MESSAGES), i = r.get(e);
1588
- i.onsuccess = () => {
1589
- const o = i.result;
1590
- if (!o) {
1591
- n(!1);
1592
- return;
1593
- }
1594
- o.retryCount++, o.updatedAt = Date.now(), o.retryCount < o.maxRetries ? o.status = "pending" : o.status = "failed", r.put(o), this._messageUpdates.next(o), n(o.status === "pending");
1595
- }, i.onerror = () => s(/* @__PURE__ */ new Error("Failed to mark message as failed"));
1596
- });
1597
- }
1598
- async _updateMessageStatus(e, t) {
1599
- const n = await this.open();
1600
- return new Promise((s, r) => {
1601
- const i = n.transaction(u.MESSAGES, "readwrite").objectStore(u.MESSAGES), o = i.get(e);
1602
- o.onsuccess = () => {
1603
- const a = o.result;
1604
- a && (a.status = t, a.updatedAt = Date.now(), i.put(a), this._messageUpdates.next(a)), s();
1605
- }, o.onerror = () => r(/* @__PURE__ */ new Error("Failed to update message status"));
1606
- });
1607
- }
1608
- async getMailbox(e, t = {}) {
1609
- const n = await this.open();
1610
- return new Promise((s, r) => {
1611
- const i = n.transaction(u.MAILBOX, "readonly").objectStore(u.MAILBOX).index("channel").getAll(IDBKeyRange.only(e), t.limit);
1612
- i.onsuccess = () => {
1613
- let o = i.result;
1614
- t.sortBy === "priority" ? o.sort((a, c) => c.priority - a.priority) : o.sort((a, c) => c.createdAt - a.createdAt), s(o);
1615
- }, i.onerror = () => r(/* @__PURE__ */ new Error("Failed to get mailbox"));
1616
- });
1617
- }
1618
- async getMailboxStats(e) {
1619
- const t = await this.getDeferredMessages(e), n = {
1620
- total: t.length,
1621
- pending: 0,
1622
- processing: 0,
1623
- delivered: 0,
1624
- failed: 0,
1625
- expired: 0
1626
- }, s = Date.now();
1627
- for (const r of t) r.expiresAt && r.expiresAt < s ? n.expired++ : n[r.status]++;
1628
- return n;
1629
- }
1630
- async clearMailbox(e) {
1631
- const t = await this.open();
1632
- return new Promise((n, s) => {
1633
- const r = t.transaction(u.MAILBOX, "readwrite"), i = r.objectStore(u.MAILBOX).index("channel");
1634
- let o = 0;
1635
- const a = i.openCursor(IDBKeyRange.only(e));
1636
- a.onsuccess = () => {
1637
- const c = a.result;
1638
- c && (c.delete(), o++, c.continue());
1639
- }, r.oncomplete = () => n(o), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to clear mailbox"));
1640
- });
1641
- }
1642
- async registerPending(e) {
1643
- const t = await this.open(), n = {
1644
- id: d(),
1645
- channel: this._channelName,
1646
- type: e.type,
1647
- data: e.data,
1648
- metadata: e.metadata,
1649
- createdAt: Date.now(),
1650
- status: "pending"
1651
- };
1652
- return new Promise((s, r) => {
1653
- const i = t.transaction(u.PENDING, "readwrite");
1654
- i.objectStore(u.PENDING).add(n), i.oncomplete = () => s(n.id), i.onerror = () => r(/* @__PURE__ */ new Error("Failed to register pending operation"));
1655
- });
1656
- }
1657
- async getPendingOperations() {
1658
- const e = await this.open();
1659
- return new Promise((t, n) => {
1660
- const s = e.transaction(u.PENDING, "readonly").objectStore(u.PENDING).index("channel").getAll(IDBKeyRange.only(this._channelName));
1661
- s.onsuccess = () => t(s.result), s.onerror = () => n(/* @__PURE__ */ new Error("Failed to get pending operations"));
1662
- });
1663
- }
1664
- async completePending(e) {
1665
- const t = await this.open();
1666
- return new Promise((n, s) => {
1667
- const r = t.transaction(u.PENDING, "readwrite");
1668
- r.objectStore(u.PENDING).delete(e), r.oncomplete = () => n(), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to complete pending operation"));
1669
- });
1670
- }
1671
- async awaitPending(e, t = {}) {
1672
- const n = t.timeout ?? 3e4, s = t.pollInterval ?? 100, r = Date.now();
1673
- for (; Date.now() - r < n;) {
1674
- const i = await this._getPendingById(e);
1675
- if (!i) return null;
1676
- if (i.status === "completed") return await this.completePending(e), i.result;
1677
- await new Promise((o) => setTimeout(o, s));
1678
- }
1679
- throw new Error(`Pending operation ${e} timed out`);
1680
- }
1681
- async _getPendingById(e) {
1682
- const t = await this.open();
1683
- return new Promise((n, s) => {
1684
- const r = t.transaction(u.PENDING, "readonly").objectStore(u.PENDING).get(e);
1685
- r.onsuccess = () => n(r.result ?? null), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to get pending operation"));
1686
- });
1687
- }
1688
- async exchangePut(e, t, n = {}) {
1689
- const s = await this.open(), r = {
1690
- id: d(),
1691
- key: e,
1692
- value: t,
1693
- owner: this._channelName,
1694
- sharedWith: n.sharedWith ?? ["*"],
1695
- version: 1,
1696
- createdAt: Date.now(),
1697
- updatedAt: Date.now()
1698
- };
1699
- return new Promise((i, o) => {
1700
- const a = s.transaction(u.EXCHANGE, "readwrite"), c = a.objectStore(u.EXCHANGE), l = c.index("key").get(e);
1701
- l.onsuccess = () => {
1702
- const _ = l.result;
1703
- _ && (r.id = _.id, r.version = _.version + 1, r.createdAt = _.createdAt), c.put(r);
1704
- }, a.oncomplete = () => {
1705
- this._exchangeUpdates.next(r), i(r.id);
1706
- }, a.onerror = () => o(/* @__PURE__ */ new Error("Failed to put exchange data"));
1707
- });
1708
- }
1709
- async exchangeGet(e) {
1710
- const t = await this.open();
1711
- return new Promise((n, s) => {
1712
- const r = t.transaction(u.EXCHANGE, "readonly").objectStore(u.EXCHANGE).index("key").get(e);
1713
- r.onsuccess = () => {
1714
- const i = r.result;
1715
- if (!i) {
1716
- n(null);
1717
- return;
1718
- }
1719
- if (!this._canAccessExchange(i)) {
1720
- n(null);
1721
- return;
1722
- }
1723
- n(i.value);
1724
- }, r.onerror = () => s(/* @__PURE__ */ new Error("Failed to get exchange data"));
1725
- });
1726
- }
1727
- async exchangeDelete(e) {
1728
- const t = await this.open();
1729
- return new Promise((n, s) => {
1730
- const r = t.transaction(u.EXCHANGE, "readwrite"), i = r.objectStore(u.EXCHANGE), o = i.index("key").get(e);
1731
- o.onsuccess = () => {
1732
- const a = o.result;
1733
- if (!a) {
1734
- n(!1);
1735
- return;
1736
- }
1737
- if (a.owner !== this._channelName) {
1738
- n(!1);
1739
- return;
1740
- }
1741
- i.delete(a.id);
1742
- }, r.oncomplete = () => n(!0), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to delete exchange data"));
1743
- });
1744
- }
1745
- async exchangeLock(e, t = {}) {
1746
- const n = await this.open(), s = t.timeout ?? 3e4;
1747
- return new Promise((r, i) => {
1748
- const o = n.transaction(u.EXCHANGE, "readwrite"), a = o.objectStore(u.EXCHANGE), c = a.index("key").get(e);
1749
- c.onsuccess = () => {
1750
- const l = c.result;
1751
- if (!l) {
1752
- r(!1);
1753
- return;
1754
- }
1755
- if (l.lock && l.lock.holder !== this._channelName && l.lock.expiresAt > Date.now()) {
1756
- r(!1);
1757
- return;
1758
- }
1759
- l.lock = {
1760
- holder: this._channelName,
1761
- acquiredAt: Date.now(),
1762
- expiresAt: Date.now() + s
1763
- }, l.updatedAt = Date.now(), a.put(l);
1764
- }, o.oncomplete = () => r(!0), o.onerror = () => i(/* @__PURE__ */ new Error("Failed to acquire lock"));
1765
- });
1766
- }
1767
- async exchangeUnlock(e) {
1768
- const t = await this.open();
1769
- return new Promise((n, s) => {
1770
- const r = t.transaction(u.EXCHANGE, "readwrite"), i = r.objectStore(u.EXCHANGE), o = i.index("key").get(e);
1771
- o.onsuccess = () => {
1772
- const a = o.result;
1773
- a && a.lock?.holder === this._channelName && (delete a.lock, a.updatedAt = Date.now(), i.put(a));
1774
- }, r.oncomplete = () => n(), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to release lock"));
1775
- });
1776
- }
1777
- _canAccessExchange(e) {
1778
- return e.owner === this._channelName || e.sharedWith.includes("*") ? !0 : e.sharedWith.includes(this._channelName);
1779
- }
1780
- async beginTransaction() {
1781
- return new mt(this);
1782
- }
1783
- async executeTransaction(e) {
1784
- const t = await this.open(), n = new Set(e.map((s) => s.store));
1785
- return new Promise((s, r) => {
1786
- const i = t.transaction(Array.from(n), "readwrite");
1787
- for (const o of e) {
1788
- const a = i.objectStore(o.store);
1789
- switch (o.type) {
1790
- case "put":
1791
- o.value !== void 0 && a.put(o.value);
1792
- break;
1793
- case "delete":
1794
- o.key !== void 0 && a.delete(o.key);
1795
- break;
1796
- case "update":
1797
- if (o.key !== void 0) {
1798
- const c = a.get(o.key);
1799
- c.onsuccess = () => {
1800
- c.result && o.value && a.put({
1801
- ...c.result,
1802
- ...o.value
1803
- });
1804
- };
1805
- }
1806
- break;
1807
- }
1808
- }
1809
- i.oncomplete = () => s(), i.onerror = () => r(/* @__PURE__ */ new Error("Transaction failed"));
1810
- });
1811
- }
1812
- onMessageUpdate(e) {
1813
- return this._messageUpdates.subscribe({ next: e });
1814
- }
1815
- onExchangeUpdate(e) {
1816
- return this._exchangeUpdates.subscribe({ next: e });
1817
- }
1818
- async cleanupExpired() {
1819
- const e = await this.open(), t = Date.now();
1820
- return new Promise((n, s) => {
1821
- const r = e.transaction([u.MESSAGES, u.MAILBOX], "readwrite"), i = r.objectStore(u.MESSAGES), o = r.objectStore(u.MAILBOX);
1822
- let a = 0;
1823
- const c = i.openCursor();
1824
- c.onsuccess = () => {
1825
- const _ = c.result;
1826
- if (_) {
1827
- const f = _.value;
1828
- f.expiresAt && f.expiresAt < t && (_.delete(), a++), _.continue();
1829
- }
1830
- };
1831
- const l = o.openCursor();
1832
- l.onsuccess = () => {
1833
- const _ = l.result;
1834
- if (_) {
1835
- const f = _.value;
1836
- f.expiresAt && f.expiresAt < t && (_.delete(), a++), _.continue();
1837
- }
1838
- }, r.oncomplete = () => n(a), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to cleanup expired"));
1839
- });
1840
- }
1841
- }, mt = class {
1842
- _storage;
1843
- _operations = [];
1844
- _isCommitted = !1;
1845
- _isRolledBack = !1;
1846
- constructor(e) {
1847
- this._storage = e;
1848
- }
1849
- put(e, t) {
1850
- return this._checkState(), this._operations.push({
1851
- id: d(),
1852
- type: "put",
1853
- store: e,
1854
- value: t,
1855
- timestamp: Date.now()
1856
- }), this;
1857
- }
1858
- delete(e, t) {
1859
- return this._checkState(), this._operations.push({
1860
- id: d(),
1861
- type: "delete",
1862
- store: e,
1863
- key: t,
1864
- timestamp: Date.now()
1865
- }), this;
1866
- }
1867
- update(e, t, n) {
1868
- return this._checkState(), this._operations.push({
1869
- id: d(),
1870
- type: "update",
1871
- store: e,
1872
- key: t,
1873
- value: n,
1874
- timestamp: Date.now()
1875
- }), this;
1876
- }
1877
- async commit() {
1878
- if (this._checkState(), this._operations.length === 0) {
1879
- this._isCommitted = !0;
1880
- return;
1881
- }
1882
- await this._storage.executeTransaction(this._operations), this._isCommitted = !0;
1883
- }
1884
- rollback() {
1885
- this._operations = [], this._isRolledBack = !0;
1886
- }
1887
- get operationCount() {
1888
- return this._operations.length;
1889
- }
1890
- _checkState() {
1891
- if (this._isCommitted) throw new Error("Transaction already committed");
1892
- if (this._isRolledBack) throw new Error("Transaction already rolled back");
1893
- }
1894
- };
1895
- const J = /* @__PURE__ */ new Map();
1896
- function wt(e) {
1897
- return J.has(e) || J.set(e, new gt(e)), J.get(e);
1898
- }
1899
- const Se = de(), bt = Se.length > 0 ? new URL("../transport/Worker.ts", Se) : "";
1900
- var xe = class {
1901
- _channel;
1902
- _context;
1903
- _options;
1904
- _connection;
1905
- _storage;
1906
- constructor(e, t, n = {}) {
1907
- this._channel = e, this._context = t, this._options = n, this._connection = pt(e), this._storage = wt(e);
1908
- }
1909
- async request(e, t, n, s = {}) {
1910
- let r = typeof e == "string" ? [e] : e, i = t, o = n;
1911
- return Array.isArray(t) && ke(e) && (s = n, o = t, i = e, r = []), this._context.getHost()?.request(r, i, o, s, this._channel);
1912
- }
1913
- async doImportModule(e, t = {}) {
1914
- return this.request([], h.IMPORT, [e], t);
1915
- }
1916
- async deferMessage(e, t = {}) {
1917
- return this._storage.defer({
1918
- channel: this._channel,
1919
- sender: this._context.hostName,
1920
- type: "request",
1921
- payload: e
1922
- }, t);
1923
- }
1924
- async getPendingMessages() {
1925
- return this._storage.getDeferredMessages(this._channel, { status: "pending" });
1926
- }
1927
- get connection() {
1928
- return this._connection;
1929
- }
1930
- get channelName() {
1931
- return this._channel;
1932
- }
1933
- get context() {
1934
- return this._context;
1935
- }
1936
- }, v = class {
1937
- _channel;
1938
- _context;
1939
- _options;
1940
- _connection;
1941
- _unified;
1942
- get _forResolves() {
1943
- return this._unified.__getPrivate("_pending");
1944
- }
1945
- get _subscriptions() {
1946
- return this._unified.__getPrivate("_subscriptions");
1947
- }
1948
- get _broadcasts() {
1949
- return this._unified.__getPrivate("_transports");
1950
- }
1951
- constructor(e, t, n = {}) {
1952
- this._channel = e, this._context = t, this._options = n, this._connection = Ce().getOrCreate(e, "internal", n), this._unified = new he({
1953
- name: e,
1954
- autoListen: !1,
1955
- timeout: n?.timeout
1956
- });
1957
- }
1958
- createRemoteChannel(e, t = {}, n) {
1959
- const s = St(n ?? this._context.$createOrUseExistingRemote(e, t, n ?? null)?.messageChannel?.port1), r = Pe(s?.target ?? s);
1960
- return this._unified.listen(s?.target, { targetChannel: e }), s && (this._broadcasts?.set?.(e, s), r === "self" && typeof postMessage > "u" || this._unified.connect(s, { targetChannel: e }), this._context.$registerConnection({
1961
- localChannel: this._channel,
1962
- remoteChannel: e,
1963
- sender: this._channel,
1964
- direction: "outgoing",
1965
- transportType: r
1966
- }), this.notifyChannel(e, {
1967
- contextId: this._context.id,
1968
- contextName: this._context.hostName
1969
- }, "connect")), new xe(e, this._context, t);
1970
- }
1971
- getChannel() {
1972
- return this._channel;
1973
- }
1974
- get connection() {
1975
- return this._connection;
1976
- }
1977
- request(e, t, n, s = {}, r = "worker") {
1978
- let i = typeof e == "string" ? [e] : e, o = n;
1979
- return Array.isArray(t) && ke(e) && (r = s, s = n, o = t, t = e, i = []), this._unified.invoke(r, t, i ?? [], Array.isArray(o) ? o : [o]);
1980
- }
1981
- resolveResponse(e, t) {
1982
- this._forResolves.get(e)?.resolve?.(t);
1983
- const n = this._forResolves.get(e)?.promise;
1984
- return this._forResolves.delete(e), n;
1985
- }
1986
- async handleAndResponse(e, t, n) {}
1987
- notifyChannel(e, t = {}, n = "notify") {
1988
- return this._unified.notify(e, {
1989
- ...t,
1990
- from: this._channel,
1991
- to: e
1992
- }, n);
1993
- }
1994
- getConnectedChannels() {
1995
- return this._unified.connectedChannels;
1996
- }
1997
- close() {
1998
- this._subscriptions.forEach((e) => e.unsubscribe()), this._forResolves.clear(), this._broadcasts?.values?.()?.forEach((e) => e.close?.()), this._broadcasts?.clear?.(), this._unified.close();
1999
- }
2000
- get unified() {
2001
- return this._unified;
2002
- }
2003
- }, Ct = class {
2004
- _options;
2005
- _id = d();
2006
- _hostName;
2007
- _host = null;
2008
- _endpoints = /* @__PURE__ */ new Map();
2009
- _unifiedByChannel = /* @__PURE__ */ new Map();
2010
- _unifiedConnectionSubs = /* @__PURE__ */ new Map();
2011
- _remoteChannels = /* @__PURE__ */ new Map();
2012
- _deferredChannels = /* @__PURE__ */ new Map();
2013
- _connectionEvents = new y({ bufferSize: 200 });
2014
- _connectionRegistry = new ue(() => d(), (e) => this._emitConnectionEvent(e));
2015
- _closed = !1;
2016
- _globalSelf = null;
2017
- constructor(e = {}) {
2018
- this._options = e, this._hostName = e.name ?? `ctx-${this._id.slice(0, 8)}`, e.useGlobalSelf !== !1 && (this._globalSelf = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : null);
2019
- }
2020
- initHost(e) {
2021
- if (this._host && !e) return this._host;
2022
- const t = e ?? this._hostName;
2023
- if (this._hostName = t, this._endpoints.has(t)) return this._host = this._endpoints.get(t).handler, this._host;
2024
- this._host = new v(t, this, this._options.defaultOptions);
2025
- const n = {
2026
- name: t,
2027
- handler: this._host,
2028
- connection: this._host.connection,
2029
- subscriptions: [],
2030
- ready: Promise.resolve(null),
2031
- unified: this._host.unified
2032
- };
2033
- return this._endpoints.set(t, n), this._registerUnifiedChannel(t, this._host.unified), this._host;
2034
- }
2035
- getHost() {
2036
- return this._host ?? this.initHost();
2037
- }
2038
- get hostName() {
2039
- return this._hostName;
2040
- }
2041
- get id() {
2042
- return this._id;
2043
- }
2044
- get onConnection() {
2045
- return this._connectionEvents;
2046
- }
2047
- subscribeConnections(e) {
2048
- return this._connectionEvents.subscribe(e);
2049
- }
2050
- notifyConnections(e = {}, t = {}) {
2051
- let n = 0;
2052
- for (const s of this._endpoints.values()) {
2053
- const r = s.handler.getConnectedChannels();
2054
- for (const i of r) {
2055
- if (t.localChannel && t.localChannel !== s.name || t.remoteChannel && t.remoteChannel !== i) continue;
2056
- const o = this.queryConnections({
2057
- localChannel: s.name,
2058
- remoteChannel: i,
2059
- status: "active"
2060
- })[0];
2061
- t.sender && o?.sender !== t.sender || t.transportType && o?.transportType !== t.transportType || t.channel && t.channel !== s.name && t.channel !== i || s.handler.notifyChannel(i, e, "notify") && n++;
2062
- }
2063
- }
2064
- return n;
2065
- }
2066
- queryConnections(e = {}) {
2067
- return this._connectionRegistry.query(e).map((t) => ({
2068
- ...t,
2069
- contextId: this._id
2070
- }));
2071
- }
2072
- createChannel(e, t = {}) {
2073
- if (this._endpoints.has(e)) return this._endpoints.get(e);
2074
- const n = new v(e, this, {
2075
- ...this._options.defaultOptions,
2076
- ...t
2077
- }), s = {
2078
- name: e,
2079
- handler: n,
2080
- connection: n.connection,
2081
- subscriptions: [],
2082
- ready: Promise.resolve(null),
2083
- unified: n.unified
2084
- };
2085
- return this._endpoints.set(e, s), this._registerUnifiedChannel(e, n.unified), s;
2086
- }
2087
- createChannels(e, t = {}) {
2088
- const n = /* @__PURE__ */ new Map();
2089
- for (const s of e) n.set(s, this.createChannel(s, t));
2090
- return n;
2091
- }
2092
- getChannel(e) {
2093
- return this._endpoints.get(e);
2094
- }
2095
- getOrCreateChannel(e, t = {}) {
2096
- return this._endpoints.get(e) ?? this.createChannel(e, t);
2097
- }
2098
- hasChannel(e) {
2099
- return this._endpoints.has(e);
2100
- }
2101
- getChannelNames() {
2102
- return [...this._endpoints.keys()];
2103
- }
2104
- get size() {
2105
- return this._endpoints.size;
2106
- }
2107
- defer(e, t) {
2108
- this._deferredChannels.set(e, t);
2109
- }
2110
- async initDeferred(e) {
2111
- const t = this._deferredChannels.get(e);
2112
- if (!t) return null;
2113
- const n = await t();
2114
- return this._endpoints.set(e, n), this._deferredChannels.delete(e), n;
2115
- }
2116
- isDeferred(e) {
2117
- return this._deferredChannels.has(e);
2118
- }
2119
- async getChannelAsync(e) {
2120
- return this._endpoints.has(e) ? this._endpoints.get(e) : this._deferredChannels.has(e) ? this.initDeferred(e) : null;
2121
- }
2122
- async addWorker(e, t, n = {}) {
2123
- const s = ve(t);
2124
- if (!s) throw new Error(`Failed to create worker for channel: ${e}`);
2125
- const r = new v(e, this, {
2126
- ...this._options.defaultOptions,
2127
- ...n
2128
- }), i = r.createRemoteChannel(e, n, s), o = {
2129
- name: e,
2130
- handler: r,
2131
- connection: r.connection,
2132
- subscriptions: [],
2133
- transportType: "worker",
2134
- ready: Promise.resolve(i),
2135
- unified: r.unified
2136
- };
2137
- return this._endpoints.set(e, o), this._registerUnifiedChannel(e, r.unified), this._remoteChannels.set(e, {
2138
- channel: e,
2139
- context: this,
2140
- remote: Promise.resolve(i),
2141
- transport: s,
2142
- transportType: "worker"
2143
- }), o;
2144
- }
2145
- async addPort(e, t, n = {}) {
2146
- const s = new v(e, this, {
2147
- ...this._options.defaultOptions,
2148
- ...n
2149
- });
2150
- t.start?.();
2151
- const r = s.createRemoteChannel(e, n, t), i = {
2152
- name: e,
2153
- handler: s,
2154
- connection: s.connection,
2155
- subscriptions: [],
2156
- transportType: "message-port",
2157
- ready: Promise.resolve(r),
2158
- unified: s.unified
2159
- };
2160
- return this._endpoints.set(e, i), this._registerUnifiedChannel(e, s.unified), this._remoteChannels.set(e, {
2161
- channel: e,
2162
- context: this,
2163
- remote: Promise.resolve(r),
2164
- transport: t,
2165
- transportType: "message-port"
2166
- }), i;
2167
- }
2168
- async addBroadcast(e, t, n = {}) {
2169
- const s = new BroadcastChannel(t ?? e), r = new v(e, this, {
2170
- ...this._options.defaultOptions,
2171
- ...n
2172
- }), i = r.createRemoteChannel(e, n, s), o = {
2173
- name: e,
2174
- handler: r,
2175
- connection: r.connection,
2176
- subscriptions: [],
2177
- transportType: "broadcast",
2178
- ready: Promise.resolve(i),
2179
- unified: r.unified
2180
- };
2181
- return this._endpoints.set(e, o), this._registerUnifiedChannel(e, r.unified), this._remoteChannels.set(e, {
2182
- channel: e,
2183
- context: this,
2184
- remote: Promise.resolve(i),
2185
- transport: s,
2186
- transportType: "broadcast"
2187
- }), o;
2188
- }
2189
- addSelfChannel(e, t = {}) {
2190
- const n = new v(e, this, {
2191
- ...this._options.defaultOptions,
2192
- ...t
2193
- }), s = this._globalSelf ?? (typeof self < "u" ? self : null), r = {
2194
- name: e,
2195
- handler: n,
2196
- connection: n.connection,
2197
- subscriptions: [],
2198
- transportType: "self",
2199
- ready: Promise.resolve(s ? n.createRemoteChannel(e, t, s) : null),
2200
- unified: n.unified
2201
- };
2202
- return this._endpoints.set(e, r), this._registerUnifiedChannel(e, n.unified), r;
2203
- }
2204
- async addTransport(e, t) {
2205
- const n = t.options ?? {};
2206
- switch (t.type) {
2207
- case "worker":
2208
- if (!t.worker) throw new Error("Worker required for worker transport");
2209
- return this.addWorker(e, t.worker, n);
2210
- case "message-port":
2211
- if (!t.port) throw new Error("Port required for message-port transport");
2212
- return this.addPort(e, t.port, n);
2213
- case "broadcast":
2214
- const s = typeof t.broadcast == "string" ? t.broadcast : void 0;
2215
- return this.addBroadcast(e, s, n);
2216
- case "self": return this.addSelfChannel(e, n);
2217
- default: return this.createChannel(e, n);
2218
- }
2219
- }
2220
- createChannelPair(e, t, n = {}) {
2221
- const s = new MessageChannel(), r = new v(e, this, {
2222
- ...this._options.defaultOptions,
2223
- ...n
2224
- }), i = new v(t, this, {
2225
- ...this._options.defaultOptions,
2226
- ...n
2227
- });
2228
- s.port1.start(), s.port2.start();
2229
- const o = Promise.resolve(r.createRemoteChannel(t, n, s.port1)), a = Promise.resolve(i.createRemoteChannel(e, n, s.port2)), c = {
2230
- name: e,
2231
- handler: r,
2232
- connection: r.connection,
2233
- subscriptions: [],
2234
- transportType: "message-port",
2235
- ready: o,
2236
- unified: r.unified
2237
- }, l = {
2238
- name: t,
2239
- handler: i,
2240
- connection: i.connection,
2241
- subscriptions: [],
2242
- transportType: "message-port",
2243
- ready: a,
2244
- unified: i.unified
2245
- };
2246
- return this._endpoints.set(e, c), this._endpoints.set(t, l), this._registerUnifiedChannel(e, r.unified), this._registerUnifiedChannel(t, i.unified), {
2247
- channel1: c,
2248
- channel2: l,
2249
- messageChannel: s
2250
- };
2251
- }
2252
- get globalSelf() {
2253
- return this._globalSelf;
2254
- }
2255
- async connectRemote(e, t = {}, n) {
2256
- return this.initHost(), this._host.createRemoteChannel(e, t, n);
2257
- }
2258
- async importModuleInChannel(e, t, n = {}, s) {
2259
- return (await this.connectRemote(e, n.channelOptions, s))?.doImportModule?.(t, n.importOptions);
2260
- }
2261
- $createOrUseExistingRemote(e, t = {}, n) {
2262
- if (e == null || n) return null;
2263
- if (this._remoteChannels.has(e)) return this._remoteChannels.get(e);
2264
- const s = new MessageChannel(), r = oe(new Promise((o) => {
2265
- const a = ve(bt);
2266
- a?.addEventListener?.("message", (c) => {
2267
- c.data.type === "channelCreated" && (s.port1?.start?.(), o(new xe(c.data.channel, this, t)));
2268
- }), a?.postMessage?.({
2269
- type: "createChannel",
2270
- channel: e,
2271
- sender: this._hostName,
2272
- options: t,
2273
- messagePort: s.port2
2274
- }, { transfer: [s.port2] });
2275
- })), i = {
2276
- channel: e,
2277
- context: this,
2278
- messageChannel: s,
2279
- remote: r
2280
- };
2281
- return this._remoteChannels.set(e, i), i;
2282
- }
2283
- $registerConnection(e) {
2284
- return {
2285
- ...this._connectionRegistry.register(e),
2286
- contextId: this._id
2287
- };
2288
- }
2289
- $markNotified(e) {
2290
- const t = this._connectionRegistry.register({
2291
- localChannel: e.localChannel,
2292
- remoteChannel: e.remoteChannel,
2293
- sender: e.sender,
2294
- direction: e.direction,
2295
- transportType: e.transportType
2296
- });
2297
- this._connectionRegistry.markNotified(t, e.payload);
2298
- }
2299
- $observeSignal(e) {
2300
- const t = (e.payload?.type, "incoming");
2301
- this.$markNotified({
2302
- localChannel: e.localChannel,
2303
- remoteChannel: e.remoteChannel,
2304
- sender: e.sender,
2305
- direction: t,
2306
- transportType: e.transportType,
2307
- payload: e.payload
2308
- });
2309
- }
2310
- $forwardUnifiedConnectionEvent(e, t) {
2311
- const n = t.connection.transportType ?? "internal", s = this._connectionRegistry.register({
2312
- localChannel: t.connection.localChannel || e,
2313
- remoteChannel: t.connection.remoteChannel,
2314
- sender: t.connection.sender,
2315
- direction: t.connection.direction,
2316
- transportType: n,
2317
- metadata: t.connection.metadata
2318
- });
2319
- t.type === "notified" ? this._connectionRegistry.markNotified(s, t.payload) : t.type === "disconnected" && this._connectionRegistry.closeByChannel(t.connection.localChannel);
2320
- }
2321
- closeChannel(e) {
2322
- const t = this._endpoints.get(e);
2323
- return t ? (t.subscriptions.forEach((n) => n.unsubscribe()), t.handler.close(), t.transport?.detach(), this._unifiedConnectionSubs.get(e)?.unsubscribe(), this._unifiedConnectionSubs.delete(e), this._unifiedByChannel.delete(e), this._endpoints.delete(e), e === this._hostName && (this._host = null), this._connectionRegistry.closeByChannel(e), !0) : !1;
2324
- }
2325
- close() {
2326
- if (!this._closed) {
2327
- this._closed = !0;
2328
- for (const [e] of this._endpoints) this.closeChannel(e);
2329
- this._remoteChannels.clear(), this._host = null, this._unifiedConnectionSubs.forEach((e) => e.unsubscribe()), this._unifiedConnectionSubs.clear(), this._unifiedByChannel.clear(), this._connectionRegistry.clear(), this._connectionEvents.complete();
2330
- }
2331
- }
2332
- get closed() {
2333
- return this._closed;
2334
- }
2335
- _registerUnifiedChannel(e, t) {
2336
- this._unifiedByChannel.set(e, t), this._unifiedConnectionSubs.get(e)?.unsubscribe();
2337
- const n = t.subscribeConnections((s) => {
2338
- this.$forwardUnifiedConnectionEvent(e, s);
2339
- });
2340
- this._unifiedConnectionSubs.set(e, n);
2341
- }
2342
- _emitConnectionEvent(e) {
2343
- this._connectionEvents.next({
2344
- ...e,
2345
- connection: {
2346
- ...e.connection,
2347
- contextId: this._id
2348
- }
2349
- });
2350
- }
2351
- };
2352
- function ke(e) {
2353
- return [...Object.values(h)].includes(e);
2354
- }
2355
- function St(e) {
2356
- if (!e) return null;
2357
- if (Ee(e)) return e;
2358
- const t = e, n = Pe(t);
2359
- return {
2360
- target: t,
2361
- targetChannel: "unknown",
2362
- transportType: n === "internal" ? "self" : n,
2363
- sender: (s, r) => {
2364
- if (typeof WebSocket < "u" && t instanceof WebSocket) {
2365
- t.send(JSON.stringify(s));
2366
- return;
2367
- }
2368
- t.postMessage?.(s, r?.length ? { transfer: r } : void 0);
2369
- },
2370
- postMessage: (s, r) => {
2371
- t.postMessage?.(s, r);
2372
- },
2373
- addEventListener: t.addEventListener?.bind(t),
2374
- removeEventListener: t.removeEventListener?.bind(t),
2375
- start: t.start?.bind(t),
2376
- close: t.close?.bind(t)
2377
- };
2378
- }
2379
- function Ee(e) {
2380
- return !!e && typeof e == "object" && "target" in e && typeof e.postMessage == "function";
2381
- }
2382
- function Pe(e) {
2383
- const t = Ee(e) ? e.target : e;
2384
- return t ? t === "chrome-runtime" ? "chrome-runtime" : t === "chrome-tabs" ? "chrome-tabs" : t === "chrome-port" ? "chrome-port" : t === "chrome-external" ? "chrome-external" : typeof MessagePort < "u" && t instanceof MessagePort ? "message-port" : typeof BroadcastChannel < "u" && t instanceof BroadcastChannel ? "broadcast" : typeof Worker < "u" && t instanceof Worker ? "worker" : typeof WebSocket < "u" && t instanceof WebSocket ? "websocket" : typeof chrome < "u" && typeof t == "object" && t && typeof t.postMessage == "function" && t.onMessage?.addListener ? "chrome-port" : typeof self < "u" && t === self ? "self" : "internal" : "internal";
2385
- }
2386
- function ve(e) {
2387
- if (e instanceof Worker) return e;
2388
- if (e instanceof URL) return new Worker(e.href, { type: "module" });
2389
- if (typeof e == "function") try {
2390
- return new e({ type: "module" });
2391
- } catch {
2392
- return e({ type: "module" });
2393
- }
2394
- return typeof e == "string" ? e.startsWith("/") ? new Worker(fe(e.replace(/^\//, "./")), { type: "module" }) : URL.canParse(e) || e.startsWith("./") ? new Worker(fe(e), { type: "module" }) : new Worker(URL.createObjectURL(new Blob([e], { type: "application/javascript" })), { type: "module" }) : e instanceof Blob || e instanceof File ? new Worker(URL.createObjectURL(e), { type: "module" }) : e ?? (typeof self < "u" ? self : null);
2395
- }
2396
- const xt = /* @__PURE__ */ new Map();
2397
- function kt(e = {}) {
2398
- const t = new Ct(e);
2399
- return e.name && xt.set(e.name, t), t;
2400
- }
2401
- var Et = class {
2402
- _context;
2403
- _config;
2404
- _subscriptions = [];
2405
- _incomingConnections = new y({ bufferSize: 100 });
2406
- _channelCreated = new y({ bufferSize: 100 });
2407
- _channelClosed = new y();
2408
- constructor(e = {}) {
2409
- this._config = {
2410
- name: e.name ?? "worker",
2411
- workerName: e.workerName ?? `worker-${d().slice(0, 8)}`,
2412
- autoAcceptChannels: e.autoAcceptChannels ?? !0,
2413
- allowedChannels: e.allowedChannels ?? [],
2414
- maxChannels: e.maxChannels ?? 100,
2415
- autoConnect: e.autoConnect ?? !0,
2416
- useGlobalSelf: !0,
2417
- defaultOptions: e.defaultOptions ?? {},
2418
- isolatedStorage: e.isolatedStorage ?? !1,
2419
- ...e
2420
- }, this._context = kt({
2421
- name: this._config.name,
2422
- useGlobalSelf: !0,
2423
- defaultOptions: e.defaultOptions
2424
- }), this._setupMessageListener();
2425
- }
2426
- get onConnection() {
2427
- return this._incomingConnections;
2428
- }
2429
- get onChannelCreated() {
2430
- return this._channelCreated;
2431
- }
2432
- get onChannelClosed() {
2433
- return this._channelClosed;
2434
- }
2435
- subscribeConnections(e) {
2436
- return this._incomingConnections.subscribe(e);
2437
- }
2438
- subscribeChannelCreated(e) {
2439
- return this._channelCreated.subscribe(e);
2440
- }
2441
- acceptConnection(e) {
2442
- if (!this._canAcceptChannel(e.channel)) return null;
2443
- const t = this._context.createChannel(e.channel, e.options);
2444
- return e.port && (e.port.start?.(), t.handler.createRemoteChannel(e.sender, e.options, e.port)), this._channelCreated.next({
2445
- channel: e.channel,
2446
- endpoint: t,
2447
- sender: e.sender,
2448
- timestamp: Date.now()
2449
- }), this._postChannelCreated(e.channel, e.sender, e.id), t;
2450
- }
2451
- createChannel(e, t) {
2452
- return this._context.createChannel(e, t);
2453
- }
2454
- getChannel(e) {
2455
- return this._context.getChannel(e);
2456
- }
2457
- hasChannel(e) {
2458
- return this._context.hasChannel(e);
2459
- }
2460
- getChannelNames() {
2461
- return this._context.getChannelNames();
2462
- }
2463
- queryConnections(e = {}) {
2464
- return this._context.queryConnections(e);
2465
- }
2466
- notifyConnections(e = {}, t = {}) {
2467
- return this._context.notifyConnections(e, t);
2468
- }
2469
- closeChannel(e) {
2470
- const t = this._context.closeChannel(e);
2471
- return t && this._channelClosed.next({
2472
- channel: e,
2473
- timestamp: Date.now()
2474
- }), t;
2475
- }
2476
- get context() {
2477
- return this._context;
2478
- }
2479
- get config() {
2480
- return this._config;
2481
- }
2482
- _setupMessageListener() {
2483
- addEventListener("message", ((e) => {
2484
- this._handleIncomingMessage(e);
2485
- }));
2486
- }
2487
- _handleIncomingMessage(e) {
2488
- const t = e.data;
2489
- if (!(!t || typeof t != "object")) switch (t.type) {
2490
- case "createChannel":
2491
- this._handleCreateChannel(t);
2492
- break;
2493
- case "connectChannel":
2494
- this._handleConnectChannel(t);
2495
- break;
2496
- case "addPort":
2497
- this._handleAddPort(t);
2498
- break;
2499
- case "listChannels":
2500
- this._handleListChannels(t);
2501
- break;
2502
- case "closeChannel":
2503
- this._handleCloseChannel(t);
2504
- break;
2505
- case "ping":
2506
- postMessage({
2507
- type: "pong",
2508
- id: t.id,
2509
- timestamp: Date.now()
2510
- });
2511
- break;
2512
- default: t.channel && this._context.hasChannel(t.channel) && this._context.getChannel(t.channel)?.handler?.handleAndResponse?.(t.payload, t.reqId);
2513
- }
2514
- }
2515
- _handleCreateChannel(e) {
2516
- const t = {
2517
- id: e.reqId ?? d(),
2518
- channel: e.channel,
2519
- sender: e.sender ?? "unknown",
2520
- type: "channel",
2521
- port: e.messagePort,
2522
- timestamp: Date.now(),
2523
- options: e.options
2524
- };
2525
- this._incomingConnections.next(t), this._config.autoAcceptChannels && this.acceptConnection(t);
2526
- }
2527
- _handleConnectChannel(e) {
2528
- const t = {
2529
- id: e.reqId ?? d(),
2530
- channel: e.channel,
2531
- sender: e.sender ?? "unknown",
2532
- type: e.portType ?? "channel",
2533
- port: e.port,
2534
- timestamp: Date.now(),
2535
- options: e.options
2536
- };
2537
- if (this._incomingConnections.next(t), this._config.autoAcceptChannels && this._canAcceptChannel(e.channel)) {
2538
- const n = this._context.getOrCreateChannel(e.channel, e.options);
2539
- e.port && (e.port.start?.(), n.handler.createRemoteChannel(e.sender, e.options, e.port)), postMessage({
2540
- type: "channelConnected",
2541
- channel: e.channel,
2542
- reqId: e.reqId
2543
- });
2544
- }
2545
- }
2546
- _handleAddPort(e) {
2547
- if (!e.port || !e.channel) return;
2548
- const t = {
2549
- id: e.reqId ?? d(),
2550
- channel: e.channel,
2551
- sender: e.sender ?? "unknown",
2552
- type: "port",
2553
- port: e.port,
2554
- timestamp: Date.now(),
2555
- options: e.options
2556
- };
2557
- this._incomingConnections.next(t), this._config.autoAcceptChannels && this.acceptConnection(t);
2558
- }
2559
- _handleListChannels(e) {
2560
- postMessage({
2561
- type: "channelList",
2562
- channels: this.getChannelNames(),
2563
- reqId: e.reqId
2564
- });
2565
- }
2566
- _handleCloseChannel(e) {
2567
- e.channel && (this.closeChannel(e.channel), postMessage({
2568
- type: "channelClosed",
2569
- channel: e.channel,
2570
- reqId: e.reqId
2571
- }));
2572
- }
2573
- _canAcceptChannel(e) {
2574
- return this._context.size >= this._config.maxChannels ? !1 : this._config.allowedChannels.length > 0 ? this._config.allowedChannels.includes(e) : !0;
2575
- }
2576
- _postChannelCreated(e, t, n) {
2577
- postMessage({
2578
- type: "channelCreated",
2579
- channel: e,
2580
- sender: t,
2581
- reqId: n,
2582
- timestamp: Date.now()
2583
- });
2584
- }
2585
- close() {
2586
- this._subscriptions.forEach((e) => e.unsubscribe()), this._subscriptions = [], this._incomingConnections.complete(), this._channelCreated.complete(), this._channelClosed.complete(), this._context.close();
2587
- }
2588
- };
2589
- let Q = null;
2590
- function Pt(e) {
2591
- return Q || (Q = new Et(e)), Q;
2592
- }
2593
- Pt({ name: "worker" });
2594
- var W = class {
2595
- _channelName;
2596
- _config;
2597
- _port;
2598
- _subs = /* @__PURE__ */ new Set();
2599
- _pending = /* @__PURE__ */ new Map();
2600
- _listening = !1;
2601
- _cleanup = null;
2602
- _portId = d();
2603
- _state = new y();
2604
- _keepAliveTimer = null;
2605
- constructor(e, t, n = {}) {
2606
- this._channelName = t, this._config = n, this._port = e, this._setupPort(), n.autoStart !== !1 && this.start();
2607
- }
2608
- _setupPort() {
2609
- const e = (n) => {
2610
- const s = n.data;
2611
- if (s.type === "response" && s.reqId) {
2612
- const r = this._pending.get(s.reqId);
2613
- if (r) {
2614
- this._pending.delete(s.reqId), s.payload?.error ? r.reject(new Error(s.payload.error)) : r.resolve(s.payload?.result ?? s.payload);
2615
- return;
2616
- }
2617
- }
2618
- if (s.type === "signal" && s.payload?.action === "ping") {
2619
- this.send({
2620
- id: d(),
2621
- channel: this._channelName,
2622
- sender: this._portId,
2623
- type: "signal",
2624
- payload: { action: "pong" }
2625
- });
2626
- return;
2627
- }
2628
- s.portId = s.portId ?? this._portId;
2629
- for (const r of this._subs) try {
2630
- r.next?.(s);
2631
- } catch (i) {
2632
- r.error?.(i);
2633
- }
2634
- }, t = () => {
2635
- this._state.next("error");
2636
- const n = /* @__PURE__ */ new Error("Port error");
2637
- for (const s of this._subs) s.error?.(n);
2638
- };
2639
- this._port.addEventListener("message", e), this._port.addEventListener("messageerror", t), this._cleanup = () => {
2640
- this._port.removeEventListener("message", e), this._port.removeEventListener("messageerror", t);
2641
- };
2642
- }
2643
- start() {
2644
- this._listening || (this._port.start(), this._listening = !0, this._state.next("ready"), this._config.keepAlive && this._startKeepAlive());
2645
- }
2646
- send(e, t) {
2647
- const { transferable: n, ...s } = e;
2648
- this._port.postMessage({
2649
- ...s,
2650
- portId: this._portId
2651
- }, t ?? []);
2652
- }
2653
- request(e) {
2654
- const t = e.reqId ?? d();
2655
- return new Promise((n, s) => {
2656
- const r = setTimeout(() => {
2657
- this._pending.delete(t), s(/* @__PURE__ */ new Error("Request timeout"));
2658
- }, this._config.timeout ?? 3e4);
2659
- this._pending.set(t, {
2660
- resolve: (i) => {
2661
- clearTimeout(r), n(i);
2662
- },
2663
- reject: (i) => {
2664
- clearTimeout(r), s(i);
2665
- },
2666
- timestamp: Date.now()
2667
- }), this.send({
2668
- ...e,
2669
- reqId: t,
2670
- type: "request"
2671
- });
2672
- });
2673
- }
2674
- subscribe(e) {
2675
- const t = typeof e == "function" ? { next: e } : e;
2676
- return this._subs.add(t), {
2677
- closed: !1,
2678
- unsubscribe: () => {
2679
- this._subs.delete(t);
2680
- }
2681
- };
2682
- }
2683
- _startKeepAlive() {
2684
- this._keepAliveTimer = setInterval(() => {
2685
- this.send({
2686
- id: d(),
2687
- channel: this._channelName,
2688
- sender: this._portId,
2689
- type: "signal",
2690
- payload: { action: "ping" }
2691
- });
2692
- }, this._config.keepAliveInterval ?? 3e4);
2693
- }
2694
- close() {
2695
- this._keepAliveTimer && (clearInterval(this._keepAliveTimer), this._keepAliveTimer = null), this._cleanup?.(), this._subs.forEach((e) => e.complete?.()), this._subs.clear(), this._port.close(), this._state.next("closed");
2696
- }
2697
- get port() {
2698
- return this._port;
2699
- }
2700
- get portId() {
2701
- return this._portId;
2702
- }
2703
- get isListening() {
2704
- return this._listening;
2705
- }
2706
- get state() {
2707
- return this._state;
2708
- }
2709
- get channelName() {
2710
- return this._channelName;
2711
- }
2712
- };
2713
- function Z(e, t) {
2714
- const n = new MessageChannel();
2715
- return {
2716
- local: new W(n.port1, e, t),
2717
- remote: n.port2,
2718
- transfer: () => n.port2
2719
- };
2720
- }
2721
- var Te = class {
2722
- _target;
2723
- _channelName;
2724
- _config;
2725
- _transport = null;
2726
- _state = new y();
2727
- _handshakeComplete = !1;
2728
- constructor(e, t, n = {}) {
2729
- this._target = e, this._channelName = t, this._config = n;
2730
- }
2731
- async connect() {
2732
- if (this._transport && this._handshakeComplete) return this._transport;
2733
- this._state.next("connecting");
2734
- const { local: e, remote: t } = Z(this._channelName, this._config);
2735
- return this._target.postMessage({
2736
- type: "port-connect",
2737
- channelName: this._channelName,
2738
- portId: e.portId
2739
- }, this._config.targetOrigin ?? "*", [t]), new Promise((n, s) => {
2740
- const r = setTimeout(() => {
2741
- s(/* @__PURE__ */ new Error("Handshake timeout")), this._state.next("error");
2742
- }, this._config.handshakeTimeout ?? 1e4), i = e.subscribe({ next: (o) => {
2743
- o.type === "signal" && o.payload?.action === "handshake-ack" && (clearTimeout(r), this._handshakeComplete = !0, this._transport = e, this._state.next("connected"), i.unsubscribe(), n(e));
2744
- } });
2745
- });
2746
- }
2747
- static listen(e, t, n) {
2748
- const s = (r) => {
2749
- if (r.data?.type !== "port-connect" || r.data?.channelName !== e || !r.ports[0]) return;
2750
- const i = new W(r.ports[0], e, n);
2751
- i.send({
2752
- id: d(),
2753
- channel: e,
2754
- sender: i.portId,
2755
- type: "signal",
2756
- payload: { action: "handshake-ack" }
2757
- }), t(i);
2758
- };
2759
- return globalThis.addEventListener("message", s), () => globalThis.removeEventListener("message", s);
2760
- }
2761
- disconnect() {
2762
- this._transport?.close(), this._transport = null, this._handshakeComplete = !1, this._state.next("disconnected");
2763
- }
2764
- get isConnected() {
2765
- return this._handshakeComplete;
2766
- }
2767
- get state() {
2768
- return this._state;
2769
- }
2770
- get transport() {
2771
- return this._transport;
2772
- }
2773
- };
2774
- Te.listen;
2775
- const Re = (e, t = "worker") => {
2776
- const n = ot(t ?? "worker");
2777
- return Object.keys(e).forEach((s) => {
2778
- e[s];
2779
- }), n;
2780
- };
2781
- var At = Ne({
2782
- getDirHandle: () => O,
2783
- getFileSystemRoot: () => A,
2784
- handlers: () => T,
2785
- normalizePath: () => I,
2786
- resolveFileSystemHandle: () => Ae
2787
- }), B, q, A, I, Ae, O, T, Ie, M, Oe = De((() => {
2788
- B = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Map(), A = async (e = "") => e && B.has(e) ? B.get(e) : await navigator.storage.getDirectory(), I = (e) => e?.trim?.()?.replace(/\/+/g, "/") || "/", Ae = async (e, t, n = !1) => {
2789
- const s = I(t).split("/").filter((i) => i && i !== ".");
2790
- let r = e;
2791
- for (let i = 0; i < s.length; i++) {
2792
- const o = s[i];
2793
- if (i === s.length - 1) try {
2794
- return await r.getDirectoryHandle(o, { create: n });
2795
- } catch {
2796
- try {
2797
- return await r.getFileHandle(o, { create: n });
2798
- } catch (a) {
2799
- if (n) throw a;
2800
- return null;
2801
- }
2802
- }
2803
- else r = await r.getDirectoryHandle(o, { create: n });
2804
- }
2805
- return r;
2806
- }, O = async (e, t, n) => {
2807
- const s = I(t).split("/").filter((i) => i);
2808
- let r = e;
2809
- for (const i of s) r = await r.getDirectoryHandle(i, { create: n });
2810
- return r;
2811
- }, T = {
2812
- mount: async ({ id: e, handle: t }) => (B.set(e, t), !0),
2813
- unmount: async ({ id: e }) => (B.delete(e), !0),
2814
- readDirectory: async ({ rootId: e, path: t, create: n }) => {
2815
- try {
2816
- const s = await A(e), r = await O(s, t, n), i = [];
2817
- for await (const [o, a] of r.entries()) i.push([o, a]);
2818
- return i;
2819
- } catch (s) {
2820
- return console.warn("Worker readDirectory error:", s), [];
2821
- }
2822
- },
2823
- readFile: async ({ rootId: e, path: t, type: n }) => {
2824
- try {
2825
- const s = await A(e), r = I(t).split("/").filter((c) => c), i = r.pop(), o = r.join("/"), a = await (await (await O(s, o, !1)).getFileHandle(i, { create: !1 })).getFile();
2826
- return n === "text" ? await a.text() : n === "arrayBuffer" ? await a.arrayBuffer() : a;
2827
- } catch (s) {
2828
- return console.warn("Worker readFile error:", s), null;
2829
- }
2830
- },
2831
- writeFile: async ({ rootId: e, path: t, data: n }) => {
2832
- try {
2833
- const s = await A(e), r = I(t).split("/").filter((c) => c), i = r.pop(), o = r.join("/"), a = await (await (await O(s, o, !0)).getFileHandle(i, { create: !0 })).createWritable();
2834
- return await a.write(n), await a.close(), !0;
2835
- } catch (s) {
2836
- return console.warn("Worker writeFile error:", s), !1;
2837
- }
2838
- },
2839
- remove: async ({ rootId: e, path: t, recursive: n }) => {
2840
- try {
2841
- const s = await A(e), r = I(t).split("/").filter((a) => a), i = r.pop(), o = r.join("/");
2842
- return await (await O(s, o, !1)).removeEntry(i, { recursive: n }), !0;
2843
- } catch {
2844
- return !1;
2845
- }
2846
- },
2847
- observe: async ({ rootId: e, path: t, id: n }) => {
2848
- try {
2849
- if (q.has(n)) return !0;
2850
- const s = await A(e), r = await O(s, t, !1);
2851
- if (typeof FileSystemObserver < "u") {
2852
- const i = new FileSystemObserver((o) => {
2853
- const a = o.map((c) => {
2854
- const l = c.changedHandle?.name || c.relativePathComponents?.at(-1);
2855
- return {
2856
- type: c.type,
2857
- name: l,
2858
- kind: c.changedHandle?.kind || (l?.includes(".") ? "file" : "directory"),
2859
- handle: c.changedHandle,
2860
- path: c.relativePathComponents.join("/")
2861
- };
2862
- });
2863
- self.postMessage({
2864
- type: "observation",
2865
- id: n,
2866
- changes: a
2867
- });
2868
- });
2869
- return i.observe(r), q.set(n, i), !0;
2870
- }
2871
- return !1;
2872
- } catch {
2873
- return !1;
2874
- }
2875
- },
2876
- unobserve: async ({ id: e }) => {
2877
- const t = q.get(e);
2878
- return t && (t.disconnect(), q.delete(e)), !0;
2879
- },
2880
- copy: async ({ from: e, to: t }) => {
2881
- try {
2882
- const n = async (s, r) => {
2883
- if (s.kind === "directory") for await (const [i, o] of s.entries()) if (o.kind === "directory") {
2884
- const a = await r.getDirectoryHandle(i, { create: !0 });
2885
- await n(o, a);
2886
- } else {
2887
- const a = await o.getFile(), c = await (await r.getFileHandle(i, { create: !0 })).createWritable();
2888
- await c.write(a), await c.close();
2889
- }
2890
- else {
2891
- const i = await s.getFile(), o = await r.createWritable();
2892
- await o.write(i), await o.close();
2893
- }
2894
- };
2895
- return await n(e, t), !0;
2896
- } catch (n) {
2897
- return console.warn("Worker copy error:", n), !1;
2898
- }
2899
- }
2900
- }, Ie = "opfs-sw-bridge-v1", M = null;
2901
- try {
2902
- typeof BroadcastChannel < "u" && (M = new BroadcastChannel(Ie), M.onmessage = async (e) => {
2903
- const t = e?.data || {};
2904
- if (!t || typeof t != "object" || t?.type !== "opfs-sw-request") return;
2905
- const n = String(t?.requestId || ""), s = String(t?.action || ""), r = t?.payload;
2906
- if (!n || !s) return;
2907
- const i = T[s];
2908
- if (!i) {
2909
- M?.postMessage?.({
2910
- type: "opfs-sw-response",
2911
- requestId: n,
2912
- ok: !1,
2913
- error: `Unknown operation type: ${s}`
2914
- });
2915
- return;
2916
- }
2917
- try {
2918
- const o = await i(r);
2919
- M?.postMessage?.({
2920
- type: "opfs-sw-response",
2921
- requestId: n,
2922
- ok: !0,
2923
- result: o
2924
- });
2925
- } catch (o) {
2926
- M?.postMessage?.({
2927
- type: "opfs-sw-response",
2928
- requestId: n,
2929
- ok: !1,
2930
- error: o?.message || String(o)
2931
- });
2932
- }
2933
- });
2934
- } catch {
2935
- M = null;
2936
- }
2937
- self.addEventListener("message", async (e) => {
2938
- if (!e.data || typeof e.data != "object") return;
2939
- const { id: t, type: n, payload: s } = e.data;
2940
- if (T[n]) try {
2941
- const r = await T[n](s);
2942
- self.postMessage({
2943
- id: t,
2944
- result: r
2945
- });
2946
- } catch (r) {
2947
- self.postMessage({
2948
- id: t,
2949
- error: r?.message || String(r)
2950
- });
2951
- }
2952
- else t && self.postMessage({
2953
- id: t,
2954
- error: `Unknown operation type: ${n}`
2955
- });
2956
- });
2957
- }));
2958
- Oe(), T && Re(T);
2959
- const It = async (e) => {
2960
- try {
2961
- if (e.type === "batch") {
2962
- const t = [];
2963
- for (const n of e.payload) {
2964
- const s = await Me(n);
2965
- t.push(s);
2966
- }
2967
- return t;
2968
- } else return await Me(e);
2969
- } catch (t) {
2970
- throw console.error("[OPFS Worker] Message processing error:", t), t;
2971
- }
2972
- }, Me = async (e) => {
2973
- const t = T[e.type];
2974
- if (!t) throw new Error(`Unknown message type: ${e.type}`);
2975
- return await t(e.payload);
2976
- };
2977
- globalThis.processMessage = It, (async () => {
2978
- try {
2979
- const e = (await Promise.resolve().then(() => (Oe(), At))).handlers;
2980
- e && Re(e), console.log("[OPFS Worker] Initialized with handlers:", Object.keys(e || {}));
2981
- } catch (e) {
2982
- console.error("[OPFS Worker] Failed to initialize:", e);
2983
- }
2984
- })();
2985
- })();