@camstack/sdk 0.1.35 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2185 +1,1349 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const client = require("@trpc/client");
4
+ const types = require("@camstack/types");
5
+ class DoubleIndexedKV {
6
+ constructor() {
7
+ this.keyToValue = /* @__PURE__ */ new Map();
8
+ this.valueToKey = /* @__PURE__ */ new Map();
18
9
  }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- BackendClient: () => BackendClient,
35
- DEFAULT_ENABLED_CLASSES: () => DEFAULT_ENABLED_CLASSES,
36
- DetectionClass: () => DetectionClass,
37
- ELIGIBLE_HA_DOMAINS: () => ELIGIBLE_HA_DOMAINS,
38
- ELIGIBLE_HA_DOMAINS_SET: () => ELIGIBLE_HA_DOMAINS_SET,
39
- ELIGIBLE_SCRYPTED_DEVICE_TYPES: () => ELIGIBLE_SCRYPTED_DEVICE_TYPES,
40
- ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET: () => ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET,
41
- FEATURE_MATRIX: () => FEATURE_MATRIX,
42
- HA_DOMAIN_TYPE_MAP: () => HA_DOMAIN_TYPE_MAP,
43
- RAW_TO_CANONICAL: () => RAW_TO_CANONICAL,
44
- SCRYPTED_TYPE_TO_CANONICAL: () => SCRYPTED_TYPE_TO_CANONICAL,
45
- TIMELINE_PRESET_ALL: () => TIMELINE_PRESET_ALL,
46
- TIMELINE_PRESET_CRITICAL: () => TIMELINE_PRESET_CRITICAL,
47
- TIMELINE_PRESET_IMPORTANT: () => TIMELINE_PRESET_IMPORTANT,
48
- animalClasses: () => animalClasses,
49
- audioClasses: () => audioClasses,
50
- audioLabelClasses: () => audioLabelClasses,
51
- createBackendClient: () => createBackendClient,
52
- defaultDetectionClasses: () => defaultDetectionClasses,
53
- detectionClassesDefaultMap: () => detectionClassesDefaultMap,
54
- doorbellClasses: () => doorbellClasses,
55
- faceClasses: () => faceClasses,
56
- getBackendRequiredFeatures: () => getBackendRequiredFeatures,
57
- getCanonicalDeviceType: () => getCanonicalDeviceType,
58
- getClassesForTimelinePreset: () => getClassesForTimelinePreset,
59
- getNextEvalInterval: () => getNextEvalInterval,
60
- getParentClass: () => getParentClass,
61
- getParentDetectionClass: () => getParentDetectionClass,
62
- getSourceFeatures: () => getSourceFeatures,
63
- isAnimalClassname: () => isAnimalClassname,
64
- isAudioClassname: () => isAudioClassname,
65
- isDoorbellClassname: () => isDoorbellClassname,
66
- isFaceClassname: () => isFaceClassname,
67
- isFeatureAvailable: () => isFeatureAvailable,
68
- isLabelDetection: () => isLabelDetection,
69
- isMotionClassname: () => isMotionClassname,
70
- isPackageClassname: () => isPackageClassname,
71
- isPersonClassname: () => isPersonClassname,
72
- isPlateClassname: () => isPlateClassname,
73
- isSensorLabelClassname: () => isSensorLabelClassname,
74
- isVehicleClassname: () => isVehicleClassname,
75
- licensePlateClasses: () => licensePlateClasses,
76
- motionClasses: () => motionClasses,
77
- packageClasses: () => packageClasses,
78
- personClasses: () => personClasses,
79
- selectOptimalStream: () => selectOptimalStream,
80
- sensorLabelClasses: () => sensorLabelClasses,
81
- vehicleClasses: () => vehicleClasses
82
- });
83
- module.exports = __toCommonJS(index_exports);
84
-
85
- // node_modules/@trpc/client/dist/objectSpread2-BvkFp-_Y.mjs
86
- var __create2 = Object.create;
87
- var __defProp2 = Object.defineProperty;
88
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
89
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
90
- var __getProtoOf2 = Object.getPrototypeOf;
91
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
92
- var __commonJS = /* @__PURE__ */ __name((cb, mod) => function() {
93
- return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
94
- }, "__commonJS");
95
- var __copyProps2 = /* @__PURE__ */ __name((to, from, except, desc) => {
96
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames2(from), i = 0, n = keys.length, key; i < n; i++) {
97
- key = keys[i];
98
- if (!__hasOwnProp2.call(to, key) && key !== except) __defProp2(to, key, {
99
- get: ((k) => from[k]).bind(null, key),
100
- enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable
101
- });
10
+ set(key, value) {
11
+ this.keyToValue.set(key, value);
12
+ this.valueToKey.set(value, key);
102
13
  }
103
- return to;
104
- }, "__copyProps");
105
- var __toESM2 = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", {
106
- value: mod,
107
- enumerable: true
108
- }) : target, mod)), "__toESM");
109
- var require_typeof = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports2, module2) {
110
- function _typeof$2(o) {
111
- "@babel/helpers - typeof";
112
- return module2.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
113
- return typeof o$1;
114
- } : function(o$1) {
115
- return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
116
- }, module2.exports.__esModule = true, module2.exports["default"] = module2.exports, _typeof$2(o);
117
- }
118
- __name(_typeof$2, "_typeof$2");
119
- module2.exports = _typeof$2, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
120
- } });
121
- var require_toPrimitive = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports2, module2) {
122
- var _typeof$1 = require_typeof()["default"];
123
- function toPrimitive$1(t, r) {
124
- if ("object" != _typeof$1(t) || !t) return t;
125
- var e = t[Symbol.toPrimitive];
126
- if (void 0 !== e) {
127
- var i = e.call(t, r || "default");
128
- if ("object" != _typeof$1(i)) return i;
129
- throw new TypeError("@@toPrimitive must return a primitive value.");
130
- }
131
- return ("string" === r ? String : Number)(t);
132
- }
133
- __name(toPrimitive$1, "toPrimitive$1");
134
- module2.exports = toPrimitive$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
135
- } });
136
- var require_toPropertyKey = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports2, module2) {
137
- var _typeof = require_typeof()["default"];
138
- var toPrimitive = require_toPrimitive();
139
- function toPropertyKey$1(t) {
140
- var i = toPrimitive(t, "string");
141
- return "symbol" == _typeof(i) ? i : i + "";
142
- }
143
- __name(toPropertyKey$1, "toPropertyKey$1");
144
- module2.exports = toPropertyKey$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
145
- } });
146
- var require_defineProperty = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports2, module2) {
147
- var toPropertyKey = require_toPropertyKey();
148
- function _defineProperty(e, r, t) {
149
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
150
- value: t,
151
- enumerable: true,
152
- configurable: true,
153
- writable: true
154
- }) : e[r] = t, e;
155
- }
156
- __name(_defineProperty, "_defineProperty");
157
- module2.exports = _defineProperty, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
158
- } });
159
- var require_objectSpread2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports2, module2) {
160
- var defineProperty = require_defineProperty();
161
- function ownKeys(e, r) {
162
- var t = Object.keys(e);
163
- if (Object.getOwnPropertySymbols) {
164
- var o = Object.getOwnPropertySymbols(e);
165
- r && (o = o.filter(function(r$1) {
166
- return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
167
- })), t.push.apply(t, o);
168
- }
169
- return t;
170
- }
171
- __name(ownKeys, "ownKeys");
172
- function _objectSpread2(e) {
173
- for (var r = 1; r < arguments.length; r++) {
174
- var t = null != arguments[r] ? arguments[r] : {};
175
- r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
176
- defineProperty(e, r$1, t[r$1]);
177
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
178
- Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
179
- });
180
- }
181
- return e;
14
+ getByKey(key) {
15
+ return this.keyToValue.get(key);
182
16
  }
183
- __name(_objectSpread2, "_objectSpread2");
184
- module2.exports = _objectSpread2, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
185
- } });
186
-
187
- // node_modules/@trpc/server/dist/observable-UMO3vUa_.mjs
188
- function observable(subscribe) {
189
- const self = {
190
- subscribe(observer) {
191
- let teardownRef = null;
192
- let isDone = false;
193
- let unsubscribed = false;
194
- let teardownImmediately = false;
195
- function unsubscribe() {
196
- if (teardownRef === null) {
197
- teardownImmediately = true;
198
- return;
199
- }
200
- if (unsubscribed) return;
201
- unsubscribed = true;
202
- if (typeof teardownRef === "function") teardownRef();
203
- else if (teardownRef) teardownRef.unsubscribe();
204
- }
205
- __name(unsubscribe, "unsubscribe");
206
- teardownRef = subscribe({
207
- next(value) {
208
- var _observer$next;
209
- if (isDone) return;
210
- (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
211
- },
212
- error(err) {
213
- var _observer$error;
214
- if (isDone) return;
215
- isDone = true;
216
- (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, err);
217
- unsubscribe();
218
- },
219
- complete() {
220
- var _observer$complete;
221
- if (isDone) return;
222
- isDone = true;
223
- (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
224
- unsubscribe();
225
- }
226
- });
227
- if (teardownImmediately) unsubscribe();
228
- return { unsubscribe };
229
- },
230
- pipe(...operations) {
231
- return operations.reduce(pipeReducer, self);
232
- }
233
- };
234
- return self;
235
- }
236
- __name(observable, "observable");
237
- function pipeReducer(prev, fn) {
238
- return fn(prev);
239
- }
240
- __name(pipeReducer, "pipeReducer");
241
- function observableToPromise(observable$1) {
242
- const ac = new AbortController();
243
- const promise = new Promise((resolve, reject) => {
244
- let isDone = false;
245
- function onDone() {
246
- if (isDone) return;
247
- isDone = true;
248
- obs$.unsubscribe();
249
- }
250
- __name(onDone, "onDone");
251
- ac.signal.addEventListener("abort", () => {
252
- reject(ac.signal.reason);
253
- });
254
- const obs$ = observable$1.subscribe({
255
- next(data) {
256
- isDone = true;
257
- resolve(data);
258
- onDone();
259
- },
260
- error(data) {
261
- reject(data);
262
- },
263
- complete() {
264
- ac.abort();
265
- onDone();
266
- }
267
- });
268
- });
269
- return promise;
270
- }
271
- __name(observableToPromise, "observableToPromise");
272
-
273
- // node_modules/@trpc/server/dist/observable-CUiPknO-.mjs
274
- function share(_opts) {
275
- return (source) => {
276
- let refCount = 0;
277
- let subscription = null;
278
- const observers = [];
279
- function startIfNeeded() {
280
- if (subscription) return;
281
- subscription = source.subscribe({
282
- next(value) {
283
- for (const observer of observers) {
284
- var _observer$next;
285
- (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
286
- }
287
- },
288
- error(error) {
289
- for (const observer of observers) {
290
- var _observer$error;
291
- (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, error);
292
- }
293
- },
294
- complete() {
295
- for (const observer of observers) {
296
- var _observer$complete;
297
- (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
298
- }
299
- }
300
- });
301
- }
302
- __name(startIfNeeded, "startIfNeeded");
303
- function resetIfNeeded() {
304
- if (refCount === 0 && subscription) {
305
- const _sub = subscription;
306
- subscription = null;
307
- _sub.unsubscribe();
308
- }
309
- }
310
- __name(resetIfNeeded, "resetIfNeeded");
311
- return observable((subscriber) => {
312
- refCount++;
313
- observers.push(subscriber);
314
- startIfNeeded();
315
- return { unsubscribe() {
316
- refCount--;
317
- resetIfNeeded();
318
- const index = observers.findIndex((v) => v === subscriber);
319
- if (index > -1) observers.splice(index, 1);
320
- } };
321
- });
322
- };
323
- }
324
- __name(share, "share");
325
- function behaviorSubject(initialValue) {
326
- let value = initialValue;
327
- const observerList = [];
328
- const addObserver = /* @__PURE__ */ __name((observer) => {
329
- if (value !== void 0) observer.next(value);
330
- observerList.push(observer);
331
- }, "addObserver");
332
- const removeObserver = /* @__PURE__ */ __name((observer) => {
333
- observerList.splice(observerList.indexOf(observer), 1);
334
- }, "removeObserver");
335
- const obs = observable((observer) => {
336
- addObserver(observer);
337
- return () => {
338
- removeObserver(observer);
339
- };
340
- });
341
- obs.next = (nextValue) => {
342
- if (value === nextValue) return;
343
- value = nextValue;
344
- for (const observer of observerList) observer.next(nextValue);
345
- };
346
- obs.get = () => value;
347
- return obs;
348
- }
349
- __name(behaviorSubject, "behaviorSubject");
350
-
351
- // node_modules/@trpc/client/dist/splitLink-B7Cuf2c_.mjs
352
- function createChain(opts) {
353
- return observable((observer) => {
354
- function execute(index = 0, op = opts.op) {
355
- const next = opts.links[index];
356
- if (!next) throw new Error("No more links to execute - did you forget to add an ending link?");
357
- const subscription = next({
358
- op,
359
- next(nextOp) {
360
- const nextObserver = execute(index + 1, nextOp);
361
- return nextObserver;
362
- }
363
- });
364
- return subscription;
365
- }
366
- __name(execute, "execute");
367
- const obs$ = execute();
368
- return obs$.subscribe(observer);
369
- });
370
- }
371
- __name(createChain, "createChain");
372
-
373
- // node_modules/@trpc/server/dist/codes-DagpWZLc.mjs
374
- function isObject(value) {
375
- return !!value && !Array.isArray(value) && typeof value === "object";
376
- }
377
- __name(isObject, "isObject");
378
- function emptyObject() {
379
- return /* @__PURE__ */ Object.create(null);
380
- }
381
- __name(emptyObject, "emptyObject");
382
- var run = /* @__PURE__ */ __name((fn) => fn(), "run");
383
- function sleep(ms = 0) {
384
- return new Promise((res) => setTimeout(res, ms));
385
- }
386
- __name(sleep, "sleep");
387
- var TRPC_ERROR_CODES_BY_KEY = {
388
- PARSE_ERROR: -32700,
389
- BAD_REQUEST: -32600,
390
- INTERNAL_SERVER_ERROR: -32603,
391
- NOT_IMPLEMENTED: -32603,
392
- BAD_GATEWAY: -32603,
393
- SERVICE_UNAVAILABLE: -32603,
394
- GATEWAY_TIMEOUT: -32603,
395
- UNAUTHORIZED: -32001,
396
- PAYMENT_REQUIRED: -32002,
397
- FORBIDDEN: -32003,
398
- NOT_FOUND: -32004,
399
- METHOD_NOT_SUPPORTED: -32005,
400
- TIMEOUT: -32008,
401
- CONFLICT: -32009,
402
- PRECONDITION_FAILED: -32012,
403
- PAYLOAD_TOO_LARGE: -32013,
404
- UNSUPPORTED_MEDIA_TYPE: -32015,
405
- UNPROCESSABLE_CONTENT: -32022,
406
- PRECONDITION_REQUIRED: -32028,
407
- TOO_MANY_REQUESTS: -32029,
408
- CLIENT_CLOSED_REQUEST: -32099
409
- };
410
- var retryableRpcCodes = [
411
- TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,
412
- TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,
413
- TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,
414
- TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR
415
- ];
416
-
417
- // node_modules/@trpc/server/dist/getErrorShape-vC8mUXJD.mjs
418
- var __create3 = Object.create;
419
- var __defProp3 = Object.defineProperty;
420
- var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
421
- var __getOwnPropNames3 = Object.getOwnPropertyNames;
422
- var __getProtoOf3 = Object.getPrototypeOf;
423
- var __hasOwnProp3 = Object.prototype.hasOwnProperty;
424
- var __commonJS2 = /* @__PURE__ */ __name((cb, mod) => function() {
425
- return mod || (0, cb[__getOwnPropNames3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
426
- }, "__commonJS");
427
- var __copyProps3 = /* @__PURE__ */ __name((to, from, except, desc) => {
428
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames3(from), i = 0, n = keys.length, key; i < n; i++) {
429
- key = keys[i];
430
- if (!__hasOwnProp3.call(to, key) && key !== except) __defProp3(to, key, {
431
- get: ((k) => from[k]).bind(null, key),
432
- enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable
433
- });
17
+ getByValue(value) {
18
+ return this.valueToKey.get(value);
19
+ }
20
+ clear() {
21
+ this.keyToValue.clear();
22
+ this.valueToKey.clear();
434
23
  }
435
- return to;
436
- }, "__copyProps");
437
- var __toESM3 = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", {
438
- value: mod,
439
- enumerable: true
440
- }) : target, mod)), "__toESM");
441
- var noop = /* @__PURE__ */ __name(() => {
442
- }, "noop");
443
- var freezeIfAvailable = /* @__PURE__ */ __name((obj) => {
444
- if (Object.freeze) Object.freeze(obj);
445
- }, "freezeIfAvailable");
446
- function createInnerProxy(callback, path, memo) {
447
- var _memo$cacheKey;
448
- const cacheKey = path.join(".");
449
- (_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== void 0 || (memo[cacheKey] = new Proxy(noop, {
450
- get(_obj, key) {
451
- if (typeof key !== "string" || key === "then") return void 0;
452
- return createInnerProxy(callback, [...path, key], memo);
453
- },
454
- apply(_1, _2, args) {
455
- const lastOfPath = path[path.length - 1];
456
- let opts = {
457
- args,
458
- path
459
- };
460
- if (lastOfPath === "call") opts = {
461
- args: args.length >= 2 ? [args[1]] : [],
462
- path: path.slice(0, -1)
463
- };
464
- else if (lastOfPath === "apply") opts = {
465
- args: args.length >= 2 ? args[1] : [],
466
- path: path.slice(0, -1)
467
- };
468
- freezeIfAvailable(opts.args);
469
- freezeIfAvailable(opts.path);
470
- return callback(opts);
471
- }
472
- }));
473
- return memo[cacheKey];
474
24
  }
475
- __name(createInnerProxy, "createInnerProxy");
476
- var createRecursiveProxy = /* @__PURE__ */ __name((callback) => createInnerProxy(callback, [], emptyObject()), "createRecursiveProxy");
477
- var createFlatProxy = /* @__PURE__ */ __name((callback) => {
478
- return new Proxy(noop, { get(_obj, name) {
479
- if (name === "then") return void 0;
480
- return callback(name);
481
- } });
482
- }, "createFlatProxy");
483
- var require_typeof2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports2, module2) {
484
- function _typeof$2(o) {
485
- "@babel/helpers - typeof";
486
- return module2.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
487
- return typeof o$1;
488
- } : function(o$1) {
489
- return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
490
- }, module2.exports.__esModule = true, module2.exports["default"] = module2.exports, _typeof$2(o);
491
- }
492
- __name(_typeof$2, "_typeof$2");
493
- module2.exports = _typeof$2, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
494
- } });
495
- var require_toPrimitive2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports2, module2) {
496
- var _typeof$1 = require_typeof2()["default"];
497
- function toPrimitive$1(t, r) {
498
- if ("object" != _typeof$1(t) || !t) return t;
499
- var e = t[Symbol.toPrimitive];
500
- if (void 0 !== e) {
501
- var i = e.call(t, r || "default");
502
- if ("object" != _typeof$1(i)) return i;
503
- throw new TypeError("@@toPrimitive must return a primitive value.");
25
+ class Registry {
26
+ constructor(generateIdentifier) {
27
+ this.generateIdentifier = generateIdentifier;
28
+ this.kv = new DoubleIndexedKV();
29
+ }
30
+ register(value, identifier) {
31
+ if (this.kv.getByValue(value)) {
32
+ return;
504
33
  }
505
- return ("string" === r ? String : Number)(t);
506
- }
507
- __name(toPrimitive$1, "toPrimitive$1");
508
- module2.exports = toPrimitive$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
509
- } });
510
- var require_toPropertyKey2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports2, module2) {
511
- var _typeof = require_typeof2()["default"];
512
- var toPrimitive = require_toPrimitive2();
513
- function toPropertyKey$1(t) {
514
- var i = toPrimitive(t, "string");
515
- return "symbol" == _typeof(i) ? i : i + "";
516
- }
517
- __name(toPropertyKey$1, "toPropertyKey$1");
518
- module2.exports = toPropertyKey$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
519
- } });
520
- var require_defineProperty2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports2, module2) {
521
- var toPropertyKey = require_toPropertyKey2();
522
- function _defineProperty(e, r, t) {
523
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
524
- value: t,
525
- enumerable: true,
526
- configurable: true,
527
- writable: true
528
- }) : e[r] = t, e;
529
- }
530
- __name(_defineProperty, "_defineProperty");
531
- module2.exports = _defineProperty, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
532
- } });
533
- var require_objectSpread22 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports2, module2) {
534
- var defineProperty = require_defineProperty2();
535
- function ownKeys(e, r) {
536
- var t = Object.keys(e);
537
- if (Object.getOwnPropertySymbols) {
538
- var o = Object.getOwnPropertySymbols(e);
539
- r && (o = o.filter(function(r$1) {
540
- return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
541
- })), t.push.apply(t, o);
34
+ if (!identifier) {
35
+ identifier = this.generateIdentifier(value);
542
36
  }
543
- return t;
544
- }
545
- __name(ownKeys, "ownKeys");
546
- function _objectSpread2(e) {
547
- for (var r = 1; r < arguments.length; r++) {
548
- var t = null != arguments[r] ? arguments[r] : {};
549
- r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
550
- defineProperty(e, r$1, t[r$1]);
551
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
552
- Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
553
- });
554
- }
555
- return e;
37
+ this.kv.set(identifier, value);
556
38
  }
557
- __name(_objectSpread2, "_objectSpread2");
558
- module2.exports = _objectSpread2, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
559
- } });
560
- var import_objectSpread2 = __toESM3(require_objectSpread22(), 1);
561
-
562
- // node_modules/@trpc/server/dist/tracked-DiE3uR1B.mjs
563
- var import_defineProperty = __toESM3(require_defineProperty2(), 1);
564
- var import_objectSpread2$1 = __toESM3(require_objectSpread22(), 1);
565
- function transformResultInner(response, transformer) {
566
- if ("error" in response) {
567
- const error = transformer.deserialize(response.error);
568
- return {
569
- ok: false,
570
- error: (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response), {}, { error })
571
- };
39
+ clear() {
40
+ this.kv.clear();
572
41
  }
573
- const result = (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response.result), (!response.result.type || response.result.type === "data") && {
574
- type: "data",
575
- data: transformer.deserialize(response.result.data)
576
- });
577
- return {
578
- ok: true,
579
- result
580
- };
581
- }
582
- __name(transformResultInner, "transformResultInner");
583
- var TransformResultError = class extends Error {
584
- static {
585
- __name(this, "TransformResultError");
42
+ getIdentifier(value) {
43
+ return this.kv.getByValue(value);
44
+ }
45
+ getValue(identifier) {
46
+ return this.kv.getByKey(identifier);
586
47
  }
48
+ }
49
+ class ClassRegistry extends Registry {
587
50
  constructor() {
588
- super("Unable to transform response from server");
51
+ super((c) => c.name);
52
+ this.classToAllowedProps = /* @__PURE__ */ new Map();
589
53
  }
590
- };
591
- function transformResult(response, transformer) {
592
- let result;
593
- try {
594
- result = transformResultInner(response, transformer);
595
- } catch (_unused) {
596
- throw new TransformResultError();
54
+ register(value, options) {
55
+ if (typeof options === "object") {
56
+ if (options.allowProps) {
57
+ this.classToAllowedProps.set(value, options.allowProps);
58
+ }
59
+ super.register(value, options.identifier);
60
+ } else {
61
+ super.register(value, options);
62
+ }
63
+ }
64
+ getAllowedProps(value) {
65
+ return this.classToAllowedProps.get(value);
597
66
  }
598
- if (!result.ok && (!isObject(result.error.error) || typeof result.error.error["code"] !== "number")) throw new TransformResultError();
599
- if (result.ok && !isObject(result.result)) throw new TransformResultError();
600
- return result;
601
- }
602
- __name(transformResult, "transformResult");
603
- var import_objectSpread22 = __toESM3(require_objectSpread22(), 1);
604
-
605
- // node_modules/@trpc/client/dist/TRPCClientError-apv8gw59.mjs
606
- var import_defineProperty2 = __toESM2(require_defineProperty(), 1);
607
- var import_objectSpread23 = __toESM2(require_objectSpread2(), 1);
608
- function isTRPCClientError(cause) {
609
- return cause instanceof TRPCClientError;
610
- }
611
- __name(isTRPCClientError, "isTRPCClientError");
612
- function isTRPCErrorResponse(obj) {
613
- return isObject(obj) && isObject(obj["error"]) && typeof obj["error"]["code"] === "number" && typeof obj["error"]["message"] === "string";
614
- }
615
- __name(isTRPCErrorResponse, "isTRPCErrorResponse");
616
- function getMessageFromUnknownError(err, fallback) {
617
- if (typeof err === "string") return err;
618
- if (isObject(err) && typeof err["message"] === "string") return err["message"];
619
- return fallback;
620
67
  }
621
- __name(getMessageFromUnknownError, "getMessageFromUnknownError");
622
- var TRPCClientError = class TRPCClientError2 extends Error {
623
- static {
624
- __name(this, "TRPCClientError");
625
- }
626
- constructor(message, opts) {
627
- var _opts$result, _opts$result2;
628
- const cause = opts === null || opts === void 0 ? void 0 : opts.cause;
629
- super(message, { cause });
630
- (0, import_defineProperty2.default)(this, "cause", void 0);
631
- (0, import_defineProperty2.default)(this, "shape", void 0);
632
- (0, import_defineProperty2.default)(this, "data", void 0);
633
- (0, import_defineProperty2.default)(this, "meta", void 0);
634
- this.meta = opts === null || opts === void 0 ? void 0 : opts.meta;
635
- this.cause = cause;
636
- this.shape = opts === null || opts === void 0 || (_opts$result = opts.result) === null || _opts$result === void 0 ? void 0 : _opts$result.error;
637
- this.data = opts === null || opts === void 0 || (_opts$result2 = opts.result) === null || _opts$result2 === void 0 ? void 0 : _opts$result2.error.data;
638
- this.name = "TRPCClientError";
639
- Object.setPrototypeOf(this, TRPCClientError2.prototype);
640
- }
641
- static from(_cause, opts = {}) {
642
- const cause = _cause;
643
- if (isTRPCClientError(cause)) {
644
- if (opts.meta) cause.meta = (0, import_objectSpread23.default)((0, import_objectSpread23.default)({}, cause.meta), opts.meta);
645
- return cause;
68
+ function valuesOfObj(record) {
69
+ if ("values" in Object) {
70
+ return Object.values(record);
71
+ }
72
+ const values = [];
73
+ for (const key in record) {
74
+ if (record.hasOwnProperty(key)) {
75
+ values.push(record[key]);
646
76
  }
647
- if (isTRPCErrorResponse(cause)) return new TRPCClientError2(cause.error.message, (0, import_objectSpread23.default)((0, import_objectSpread23.default)({}, opts), {}, {
648
- result: cause,
649
- cause: opts.cause
650
- }));
651
- return new TRPCClientError2(getMessageFromUnknownError(cause, "Unknown error"), (0, import_objectSpread23.default)((0, import_objectSpread23.default)({}, opts), {}, { cause }));
652
77
  }
653
- };
654
-
655
- // node_modules/@trpc/client/dist/unstable-internals-Bg7n9BBj.mjs
656
- function getTransformer(transformer) {
657
- const _transformer = transformer;
658
- if (!_transformer) return {
659
- input: {
660
- serialize: /* @__PURE__ */ __name((data) => data, "serialize"),
661
- deserialize: /* @__PURE__ */ __name((data) => data, "deserialize")
662
- },
663
- output: {
664
- serialize: /* @__PURE__ */ __name((data) => data, "serialize"),
665
- deserialize: /* @__PURE__ */ __name((data) => data, "deserialize")
666
- }
667
- };
668
- if ("input" in _transformer) return _transformer;
669
- return {
670
- input: _transformer,
671
- output: _transformer
672
- };
673
- }
674
- __name(getTransformer, "getTransformer");
675
-
676
- // node_modules/@trpc/client/dist/httpUtils-BNq9QC3d.mjs
677
- var isFunction2 = /* @__PURE__ */ __name((fn) => typeof fn === "function", "isFunction");
678
- function getFetch(customFetchImpl) {
679
- if (customFetchImpl) return customFetchImpl;
680
- if (typeof window !== "undefined" && isFunction2(window.fetch)) return window.fetch;
681
- if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) return globalThis.fetch;
682
- throw new Error("No fetch implementation found");
683
- }
684
- __name(getFetch, "getFetch");
685
- var import_objectSpread24 = __toESM2(require_objectSpread2());
686
- function resolveHTTPLinkOptions(opts) {
687
- return {
688
- url: opts.url.toString(),
689
- fetch: opts.fetch,
690
- transformer: getTransformer(opts.transformer),
691
- methodOverride: opts.methodOverride
692
- };
693
- }
694
- __name(resolveHTTPLinkOptions, "resolveHTTPLinkOptions");
695
- function arrayToDict(array) {
696
- const dict = {};
697
- for (let index = 0; index < array.length; index++) {
698
- const element = array[index];
699
- dict[index] = element;
700
- }
701
- return dict;
78
+ return values;
702
79
  }
703
- __name(arrayToDict, "arrayToDict");
704
- var METHOD = {
705
- query: "GET",
706
- mutation: "POST",
707
- subscription: "PATCH"
708
- };
709
- function getInput(opts) {
710
- return "input" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));
711
- }
712
- __name(getInput, "getInput");
713
- var getUrl = /* @__PURE__ */ __name((opts) => {
714
- const parts = opts.url.split("?");
715
- const base = parts[0].replace(/\/$/, "");
716
- let url = base + "/" + opts.path;
717
- const queryParts = [];
718
- if (parts[1]) queryParts.push(parts[1]);
719
- if ("inputs" in opts) queryParts.push("batch=1");
720
- if (opts.type === "query" || opts.type === "subscription") {
721
- const input = getInput(opts);
722
- if (input !== void 0 && opts.methodOverride !== "POST") queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
723
- }
724
- if (queryParts.length) url += "?" + queryParts.join("&");
725
- return url;
726
- }, "getUrl");
727
- var getBody = /* @__PURE__ */ __name((opts) => {
728
- if (opts.type === "query" && opts.methodOverride !== "POST") return void 0;
729
- const input = getInput(opts);
730
- return input !== void 0 ? JSON.stringify(input) : void 0;
731
- }, "getBody");
732
- var jsonHttpRequester = /* @__PURE__ */ __name((opts) => {
733
- return httpRequest((0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts), {}, {
734
- contentTypeHeader: "application/json",
735
- getUrl,
736
- getBody
737
- }));
738
- }, "jsonHttpRequester");
739
- var AbortError = class extends Error {
740
- static {
741
- __name(this, "AbortError");
742
- }
743
- constructor() {
744
- const name = "AbortError";
745
- super(name);
746
- this.name = name;
747
- this.message = name;
80
+ function find(record, predicate) {
81
+ const values = valuesOfObj(record);
82
+ if ("find" in values) {
83
+ return values.find(predicate);
84
+ }
85
+ const valuesNotNever = values;
86
+ for (let i = 0; i < valuesNotNever.length; i++) {
87
+ const value = valuesNotNever[i];
88
+ if (predicate(value)) {
89
+ return value;
90
+ }
748
91
  }
749
- };
750
- var throwIfAborted = /* @__PURE__ */ __name((signal) => {
751
- var _signal$throwIfAborte;
752
- if (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) return;
753
- (_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === void 0 || _signal$throwIfAborte.call(signal);
754
- if (typeof DOMException !== "undefined") throw new DOMException("AbortError", "AbortError");
755
- throw new AbortError();
756
- }, "throwIfAborted");
757
- async function fetchHTTPResponse(opts) {
758
- var _opts$methodOverride, _opts$trpcAcceptHeade;
759
- throwIfAborted(opts.signal);
760
- const url = opts.getUrl(opts);
761
- const body = opts.getBody(opts);
762
- const method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== void 0 ? _opts$methodOverride : METHOD[opts.type];
763
- const resolvedHeaders = await (async () => {
764
- const heads = await opts.headers();
765
- if (Symbol.iterator in heads) return Object.fromEntries(heads);
766
- return heads;
767
- })();
768
- const headers = (0, import_objectSpread24.default)((0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts.contentTypeHeader && method !== "GET" ? { "content-type": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { [(_opts$trpcAcceptHeade = opts.trpcAcceptHeaderKey) !== null && _opts$trpcAcceptHeade !== void 0 ? _opts$trpcAcceptHeade : "trpc-accept"]: opts.trpcAcceptHeader } : void 0), resolvedHeaders);
769
- return getFetch(opts.fetch)(url, {
770
- method,
771
- signal: opts.signal,
772
- body,
773
- headers
774
- });
92
+ return void 0;
775
93
  }
776
- __name(fetchHTTPResponse, "fetchHTTPResponse");
777
- async function httpRequest(opts) {
778
- const meta = {};
779
- const res = await fetchHTTPResponse(opts);
780
- meta.response = res;
781
- const json = await res.json();
782
- meta.responseJSON = json;
783
- return {
784
- json,
785
- meta
786
- };
94
+ function forEach(record, run) {
95
+ Object.entries(record).forEach(([key, value]) => run(value, key));
787
96
  }
788
- __name(httpRequest, "httpRequest");
789
-
790
- // node_modules/@trpc/client/dist/httpLink-oiU8eqFi.mjs
791
- function isOctetType(input) {
792
- return input instanceof Uint8Array || input instanceof Blob;
97
+ function includes(arr, value) {
98
+ return arr.indexOf(value) !== -1;
793
99
  }
794
- __name(isOctetType, "isOctetType");
795
- function isFormData(input) {
796
- return input instanceof FormData;
797
- }
798
- __name(isFormData, "isFormData");
799
- var import_objectSpread25 = __toESM2(require_objectSpread2(), 1);
800
- var universalRequester = /* @__PURE__ */ __name((opts) => {
801
- if ("input" in opts) {
802
- const { input } = opts;
803
- if (isFormData(input)) {
804
- if (opts.type !== "mutation" && opts.methodOverride !== "POST") throw new Error("FormData is only supported for mutations");
805
- return httpRequest((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, {
806
- contentTypeHeader: void 0,
807
- getUrl,
808
- getBody: /* @__PURE__ */ __name(() => input, "getBody")
809
- }));
810
- }
811
- if (isOctetType(input)) {
812
- if (opts.type !== "mutation" && opts.methodOverride !== "POST") throw new Error("Octet type input is only supported for mutations");
813
- return httpRequest((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, {
814
- contentTypeHeader: "application/octet-stream",
815
- getUrl,
816
- getBody: /* @__PURE__ */ __name(() => input, "getBody")
817
- }));
100
+ function findArr(record, predicate) {
101
+ for (let i = 0; i < record.length; i++) {
102
+ const value = record[i];
103
+ if (predicate(value)) {
104
+ return value;
818
105
  }
819
106
  }
820
- return jsonHttpRequester(opts);
821
- }, "universalRequester");
822
- function httpLink(opts) {
823
- const resolvedOpts = resolveHTTPLinkOptions(opts);
824
- return () => {
825
- return (operationOpts) => {
826
- const { op } = operationOpts;
827
- return observable((observer) => {
828
- const { path, input, type } = op;
829
- if (type === "subscription") throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`");
830
- const request = universalRequester((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, resolvedOpts), {}, {
831
- type,
832
- path,
833
- input,
834
- signal: op.signal,
835
- headers() {
836
- if (!opts.headers) return {};
837
- if (typeof opts.headers === "function") return opts.headers({ op });
838
- return opts.headers;
839
- }
840
- }));
841
- let meta = void 0;
842
- request.then((res) => {
843
- meta = res.meta;
844
- const transformed = transformResult(res.json, resolvedOpts.transformer.output);
845
- if (!transformed.ok) {
846
- observer.error(TRPCClientError.from(transformed.error, { meta }));
847
- return;
848
- }
849
- observer.next({
850
- context: res.meta,
851
- result: transformed.result
852
- });
853
- observer.complete();
854
- }).catch((cause) => {
855
- observer.error(TRPCClientError.from(cause, { meta }));
856
- });
857
- return () => {
858
- };
859
- });
860
- };
861
- };
107
+ return void 0;
862
108
  }
863
- __name(httpLink, "httpLink");
864
-
865
- // node_modules/@trpc/client/dist/httpBatchLink-CaWjh1oW.mjs
866
- var import_objectSpread26 = __toESM2(require_objectSpread2(), 1);
867
-
868
- // node_modules/@trpc/client/dist/loggerLink-ineCN1PO.mjs
869
- var import_objectSpread27 = __toESM2(require_objectSpread2(), 1);
870
-
871
- // node_modules/@trpc/client/dist/wsLink-DSf4KOdW.mjs
872
- var jsonEncoder = {
873
- encode: /* @__PURE__ */ __name((data) => JSON.stringify(data), "encode"),
874
- decode: /* @__PURE__ */ __name((data) => {
875
- if (typeof data !== "string") throw new Error("jsonEncoder received binary data. JSON uses text frames. Use a binary encoder for binary data.");
876
- return JSON.parse(data);
877
- }, "decode")
878
- };
879
- var lazyDefaults = {
880
- enabled: false,
881
- closeMs: 0
882
- };
883
- var keepAliveDefaults = {
884
- enabled: false,
885
- pongTimeoutMs: 1e3,
886
- intervalMs: 5e3
887
- };
888
- var exponentialBackoff = /* @__PURE__ */ __name((attemptIndex) => {
889
- return attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4);
890
- }, "exponentialBackoff");
891
- var resultOf = /* @__PURE__ */ __name((value, ...args) => {
892
- return typeof value === "function" ? value(...args) : value;
893
- }, "resultOf");
894
- var import_defineProperty$3 = __toESM2(require_defineProperty(), 1);
895
- var TRPCWebSocketClosedError = class TRPCWebSocketClosedError2 extends Error {
896
- static {
897
- __name(this, "TRPCWebSocketClosedError");
898
- }
899
- constructor(opts) {
900
- super(opts.message, { cause: opts.cause });
901
- this.name = "TRPCWebSocketClosedError";
902
- Object.setPrototypeOf(this, TRPCWebSocketClosedError2.prototype);
109
+ class CustomTransformerRegistry {
110
+ constructor() {
111
+ this.transfomers = {};
903
112
  }
904
- };
905
- var ResettableTimeout = class {
906
- static {
907
- __name(this, "ResettableTimeout");
113
+ register(transformer) {
114
+ this.transfomers[transformer.name] = transformer;
908
115
  }
909
- constructor(onTimeout, timeoutMs) {
910
- this.onTimeout = onTimeout;
911
- this.timeoutMs = timeoutMs;
912
- (0, import_defineProperty$3.default)(this, "timeout", void 0);
116
+ findApplicable(v) {
117
+ return find(this.transfomers, (transformer) => transformer.isApplicable(v));
913
118
  }
914
- /**
915
- * Resets the current timeout, restarting it with the same duration.
916
- * Does nothing if no timeout is active.
917
- */
918
- reset() {
919
- if (!this.timeout) return;
920
- clearTimeout(this.timeout);
921
- this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
922
- }
923
- start() {
924
- clearTimeout(this.timeout);
925
- this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
926
- }
927
- stop() {
928
- clearTimeout(this.timeout);
929
- this.timeout = void 0;
119
+ findByName(name) {
120
+ return this.transfomers[name];
930
121
  }
122
+ }
123
+ const getType$1 = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
124
+ const isUndefined = (payload) => typeof payload === "undefined";
125
+ const isNull = (payload) => payload === null;
126
+ const isPlainObject$1 = (payload) => {
127
+ if (typeof payload !== "object" || payload === null)
128
+ return false;
129
+ if (payload === Object.prototype)
130
+ return false;
131
+ if (Object.getPrototypeOf(payload) === null)
132
+ return true;
133
+ return Object.getPrototypeOf(payload) === Object.prototype;
931
134
  };
932
- function withResolvers() {
933
- let resolve;
934
- let reject;
935
- const promise = new Promise((res, rej) => {
936
- resolve = res;
937
- reject = rej;
938
- });
135
+ const isEmptyObject = (payload) => isPlainObject$1(payload) && Object.keys(payload).length === 0;
136
+ const isArray$1 = (payload) => Array.isArray(payload);
137
+ const isString = (payload) => typeof payload === "string";
138
+ const isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
139
+ const isBoolean = (payload) => typeof payload === "boolean";
140
+ const isRegExp = (payload) => payload instanceof RegExp;
141
+ const isMap = (payload) => payload instanceof Map;
142
+ const isSet = (payload) => payload instanceof Set;
143
+ const isSymbol = (payload) => getType$1(payload) === "Symbol";
144
+ const isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
145
+ const isError = (payload) => payload instanceof Error;
146
+ const isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
147
+ const isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
148
+ const isBigint = (payload) => typeof payload === "bigint";
149
+ const isInfinite = (payload) => payload === Infinity || payload === -Infinity;
150
+ const isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
151
+ const isURL = (payload) => payload instanceof URL;
152
+ const escapeKey = (key) => key.replace(/\\/g, "\\\\").replace(/\./g, "\\.");
153
+ const stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
154
+ const parsePath = (string, legacyPaths) => {
155
+ const result = [];
156
+ let segment = "";
157
+ for (let i = 0; i < string.length; i++) {
158
+ let char = string.charAt(i);
159
+ if (!legacyPaths && char === "\\") {
160
+ const escaped = string.charAt(i + 1);
161
+ if (escaped === "\\") {
162
+ segment += "\\";
163
+ i++;
164
+ continue;
165
+ } else if (escaped !== ".") {
166
+ throw Error("invalid path");
167
+ }
168
+ }
169
+ const isEscapedDot = char === "\\" && string.charAt(i + 1) === ".";
170
+ if (isEscapedDot) {
171
+ segment += ".";
172
+ i++;
173
+ continue;
174
+ }
175
+ const isEndOfSegment = char === ".";
176
+ if (isEndOfSegment) {
177
+ result.push(segment);
178
+ segment = "";
179
+ continue;
180
+ }
181
+ segment += char;
182
+ }
183
+ const lastSegment = segment;
184
+ result.push(lastSegment);
185
+ return result;
186
+ };
187
+ function simpleTransformation(isApplicable, annotation, transform, untransform) {
939
188
  return {
940
- promise,
941
- resolve,
942
- reject
189
+ isApplicable,
190
+ annotation,
191
+ transform,
192
+ untransform
943
193
  };
944
194
  }
945
- __name(withResolvers, "withResolvers");
946
- async function prepareUrl(urlOptions) {
947
- const url = await resultOf(urlOptions.url);
948
- if (!urlOptions.connectionParams) return url;
949
- const prefix = url.includes("?") ? "&" : "?";
950
- const connectionParams = `${prefix}connectionParams=1`;
951
- return url + connectionParams;
952
- }
953
- __name(prepareUrl, "prepareUrl");
954
- async function buildConnectionMessage(connectionParams, encoder) {
955
- const message = {
956
- method: "connectionParams",
957
- data: await resultOf(connectionParams)
195
+ const simpleRules = [
196
+ simpleTransformation(isUndefined, "undefined", () => null, () => void 0),
197
+ simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
198
+ if (typeof BigInt !== "undefined") {
199
+ return BigInt(v);
200
+ }
201
+ console.error("Please add a BigInt polyfill.");
202
+ return v;
203
+ }),
204
+ simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
205
+ simpleTransformation(isError, "Error", (v, superJson) => {
206
+ const baseError = {
207
+ name: v.name,
208
+ message: v.message
209
+ };
210
+ if ("cause" in v) {
211
+ baseError.cause = v.cause;
212
+ }
213
+ superJson.allowedErrorProps.forEach((prop) => {
214
+ baseError[prop] = v[prop];
215
+ });
216
+ return baseError;
217
+ }, (v, superJson) => {
218
+ const e = new Error(v.message, { cause: v.cause });
219
+ e.name = v.name;
220
+ e.stack = v.stack;
221
+ superJson.allowedErrorProps.forEach((prop) => {
222
+ e[prop] = v[prop];
223
+ });
224
+ return e;
225
+ }),
226
+ simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
227
+ const body = regex.slice(1, regex.lastIndexOf("/"));
228
+ const flags = regex.slice(regex.lastIndexOf("/") + 1);
229
+ return new RegExp(body, flags);
230
+ }),
231
+ simpleTransformation(
232
+ isSet,
233
+ "set",
234
+ // (sets only exist in es6+)
235
+ // eslint-disable-next-line es5/no-es6-methods
236
+ (v) => [...v.values()],
237
+ (v) => new Set(v)
238
+ ),
239
+ simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
240
+ simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
241
+ if (isNaNValue(v)) {
242
+ return "NaN";
243
+ }
244
+ if (v > 0) {
245
+ return "Infinity";
246
+ } else {
247
+ return "-Infinity";
248
+ }
249
+ }, Number),
250
+ simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
251
+ return "-0";
252
+ }, Number),
253
+ simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
254
+ ];
255
+ function compositeTransformation(isApplicable, annotation, transform, untransform) {
256
+ return {
257
+ isApplicable,
258
+ annotation,
259
+ transform,
260
+ untransform
958
261
  };
959
- return encoder.encode(message);
960
262
  }
961
- __name(buildConnectionMessage, "buildConnectionMessage");
962
- var import_defineProperty$2 = __toESM2(require_defineProperty(), 1);
963
- var RequestManager = class {
964
- static {
965
- __name(this, "RequestManager");
263
+ const symbolRule = compositeTransformation((s, superJson) => {
264
+ if (isSymbol(s)) {
265
+ const isRegistered = !!superJson.symbolRegistry.getIdentifier(s);
266
+ return isRegistered;
267
+ }
268
+ return false;
269
+ }, (s, superJson) => {
270
+ const identifier = superJson.symbolRegistry.getIdentifier(s);
271
+ return ["symbol", identifier];
272
+ }, (v) => v.description, (_, a, superJson) => {
273
+ const value = superJson.symbolRegistry.getValue(a[1]);
274
+ if (!value) {
275
+ throw new Error("Trying to deserialize unknown symbol");
276
+ }
277
+ return value;
278
+ });
279
+ const constructorToName = [
280
+ Int8Array,
281
+ Uint8Array,
282
+ Int16Array,
283
+ Uint16Array,
284
+ Int32Array,
285
+ Uint32Array,
286
+ Float32Array,
287
+ Float64Array,
288
+ Uint8ClampedArray
289
+ ].reduce((obj, ctor) => {
290
+ obj[ctor.name] = ctor;
291
+ return obj;
292
+ }, {});
293
+ const typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a) => {
294
+ const ctor = constructorToName[a[1]];
295
+ if (!ctor) {
296
+ throw new Error("Trying to deserialize unknown typed array");
297
+ }
298
+ return new ctor(v);
299
+ });
300
+ function isInstanceOfRegisteredClass(potentialClass, superJson) {
301
+ if (potentialClass?.constructor) {
302
+ const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
303
+ return isRegistered;
966
304
  }
967
- constructor() {
968
- (0, import_defineProperty$2.default)(this, "outgoingRequests", new Array());
969
- (0, import_defineProperty$2.default)(this, "pendingRequests", {});
305
+ return false;
306
+ }
307
+ const classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
308
+ const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
309
+ return ["class", identifier];
310
+ }, (clazz, superJson) => {
311
+ const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
312
+ if (!allowedProps) {
313
+ return { ...clazz };
314
+ }
315
+ const result = {};
316
+ allowedProps.forEach((prop) => {
317
+ result[prop] = clazz[prop];
318
+ });
319
+ return result;
320
+ }, (v, a, superJson) => {
321
+ const clazz = superJson.classRegistry.getValue(a[1]);
322
+ if (!clazz) {
323
+ throw new Error(`Trying to deserialize unknown class '${a[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
970
324
  }
971
- /**
972
- * Registers a new request by adding it to the outgoing queue and setting up
973
- * callbacks for lifecycle events such as completion or error.
974
- *
975
- * @param message - The outgoing message to be sent.
976
- * @param callbacks - Callback functions to observe the request's state.
977
- * @returns A cleanup function to manually remove the request.
978
- */
979
- register(message, callbacks) {
980
- const { promise: end, resolve } = withResolvers();
981
- this.outgoingRequests.push({
982
- id: String(message.id),
983
- message,
984
- end,
985
- callbacks: {
986
- next: callbacks.next,
987
- complete: /* @__PURE__ */ __name(() => {
988
- callbacks.complete();
989
- resolve();
990
- }, "complete"),
991
- error: /* @__PURE__ */ __name((e) => {
992
- callbacks.error(e);
993
- resolve();
994
- }, "error")
995
- }
996
- });
997
- return () => {
998
- this.delete(message.id);
999
- callbacks.complete();
1000
- resolve();
325
+ return Object.assign(Object.create(clazz.prototype), v);
326
+ });
327
+ const customRule = compositeTransformation((value, superJson) => {
328
+ return !!superJson.customTransformerRegistry.findApplicable(value);
329
+ }, (value, superJson) => {
330
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
331
+ return ["custom", transformer.name];
332
+ }, (value, superJson) => {
333
+ const transformer = superJson.customTransformerRegistry.findApplicable(value);
334
+ return transformer.serialize(value);
335
+ }, (v, a, superJson) => {
336
+ const transformer = superJson.customTransformerRegistry.findByName(a[1]);
337
+ if (!transformer) {
338
+ throw new Error("Trying to deserialize unknown custom value");
339
+ }
340
+ return transformer.deserialize(v);
341
+ });
342
+ const compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
343
+ const transformValue = (value, superJson) => {
344
+ const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
345
+ if (applicableCompositeRule) {
346
+ return {
347
+ value: applicableCompositeRule.transform(value, superJson),
348
+ type: applicableCompositeRule.annotation(value, superJson)
1001
349
  };
1002
350
  }
1003
- /**
1004
- * Deletes a request from both the outgoing and pending collections, if it exists.
1005
- */
1006
- delete(messageId) {
1007
- if (messageId === null) return;
1008
- this.outgoingRequests = this.outgoingRequests.filter(({ id }) => id !== String(messageId));
1009
- delete this.pendingRequests[String(messageId)];
1010
- }
1011
- /**
1012
- * Moves all outgoing requests to the pending state and clears the outgoing queue.
1013
- *
1014
- * The caller is expected to handle the actual sending of the requests
1015
- * (e.g., sending them over the network) after this method is called.
1016
- *
1017
- * @returns The list of requests that were transitioned to the pending state.
1018
- */
1019
- flush() {
1020
- const requests = this.outgoingRequests;
1021
- this.outgoingRequests = [];
1022
- for (const request of requests) this.pendingRequests[request.id] = request;
1023
- return requests;
1024
- }
1025
- /**
1026
- * Retrieves all currently pending requests, which are in flight awaiting responses
1027
- * or handling ongoing subscriptions.
1028
- */
1029
- getPendingRequests() {
1030
- return Object.values(this.pendingRequests);
1031
- }
1032
- /**
1033
- * Retrieves a specific pending request by its message ID.
1034
- */
1035
- getPendingRequest(messageId) {
1036
- if (messageId === null) return null;
1037
- return this.pendingRequests[String(messageId)];
1038
- }
1039
- /**
1040
- * Retrieves all outgoing requests, which are waiting to be sent.
1041
- */
1042
- getOutgoingRequests() {
1043
- return this.outgoingRequests;
1044
- }
1045
- /**
1046
- * Retrieves all requests, both outgoing and pending, with their respective states.
1047
- *
1048
- * @returns An array of all requests with their state ("outgoing" or "pending").
1049
- */
1050
- getRequests() {
1051
- return [...this.getOutgoingRequests().map((request) => ({
1052
- state: "outgoing",
1053
- message: request.message,
1054
- end: request.end,
1055
- callbacks: request.callbacks
1056
- })), ...this.getPendingRequests().map((request) => ({
1057
- state: "pending",
1058
- message: request.message,
1059
- end: request.end,
1060
- callbacks: request.callbacks
1061
- }))];
1062
- }
1063
- /**
1064
- * Checks if there are any pending requests, including ongoing subscriptions.
1065
- */
1066
- hasPendingRequests() {
1067
- return this.getPendingRequests().length > 0;
1068
- }
1069
- /**
1070
- * Checks if there are any pending subscriptions
1071
- */
1072
- hasPendingSubscriptions() {
1073
- return this.getPendingRequests().some((request) => request.message.method === "subscription");
351
+ const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
352
+ if (applicableSimpleRule) {
353
+ return {
354
+ value: applicableSimpleRule.transform(value, superJson),
355
+ type: applicableSimpleRule.annotation
356
+ };
1074
357
  }
1075
- /**
1076
- * Checks if there are any outgoing requests waiting to be sent.
1077
- */
1078
- hasOutgoingRequests() {
1079
- return this.outgoingRequests.length > 0;
358
+ return void 0;
359
+ };
360
+ const simpleRulesByAnnotation = {};
361
+ simpleRules.forEach((rule) => {
362
+ simpleRulesByAnnotation[rule.annotation] = rule;
363
+ });
364
+ const untransformValue = (json, type, superJson) => {
365
+ if (isArray$1(type)) {
366
+ switch (type[0]) {
367
+ case "symbol":
368
+ return symbolRule.untransform(json, type, superJson);
369
+ case "class":
370
+ return classRule.untransform(json, type, superJson);
371
+ case "custom":
372
+ return customRule.untransform(json, type, superJson);
373
+ case "typed-array":
374
+ return typedArrayRule.untransform(json, type, superJson);
375
+ default:
376
+ throw new Error("Unknown transformation: " + type);
377
+ }
378
+ } else {
379
+ const transformation = simpleRulesByAnnotation[type];
380
+ if (!transformation) {
381
+ throw new Error("Unknown transformation: " + type);
382
+ }
383
+ return transformation.untransform(json, superJson);
1080
384
  }
1081
385
  };
1082
- var import_defineProperty$1 = __toESM2(require_defineProperty(), 1);
1083
- function asyncWsOpen(ws) {
1084
- const { promise, resolve, reject } = withResolvers();
1085
- ws.addEventListener("open", () => {
1086
- ws.removeEventListener("error", reject);
1087
- resolve();
1088
- });
1089
- ws.addEventListener("error", reject);
1090
- return promise;
1091
- }
1092
- __name(asyncWsOpen, "asyncWsOpen");
1093
- function setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {
1094
- let pingTimeout;
1095
- let pongTimeout;
1096
- function start() {
1097
- pingTimeout = setTimeout(() => {
1098
- ws.send("PING");
1099
- pongTimeout = setTimeout(() => {
1100
- ws.close();
1101
- }, pongTimeoutMs);
1102
- }, intervalMs);
1103
- }
1104
- __name(start, "start");
1105
- function reset() {
1106
- clearTimeout(pingTimeout);
1107
- start();
1108
- }
1109
- __name(reset, "reset");
1110
- function pong() {
1111
- clearTimeout(pongTimeout);
1112
- reset();
1113
- }
1114
- __name(pong, "pong");
1115
- ws.addEventListener("open", start);
1116
- ws.addEventListener("message", ({ data }) => {
1117
- clearTimeout(pingTimeout);
1118
- start();
1119
- if (data === "PONG") pong();
1120
- });
1121
- ws.addEventListener("close", () => {
1122
- clearTimeout(pingTimeout);
1123
- clearTimeout(pongTimeout);
1124
- });
1125
- }
1126
- __name(setupPingInterval, "setupPingInterval");
1127
- var WsConnection = class WsConnection2 {
1128
- static {
1129
- __name(this, "WsConnection");
1130
- }
1131
- constructor(opts) {
1132
- var _opts$WebSocketPonyfi;
1133
- (0, import_defineProperty$1.default)(this, "id", ++WsConnection2.connectCount);
1134
- (0, import_defineProperty$1.default)(this, "WebSocketPonyfill", void 0);
1135
- (0, import_defineProperty$1.default)(this, "urlOptions", void 0);
1136
- (0, import_defineProperty$1.default)(this, "keepAliveOpts", void 0);
1137
- (0, import_defineProperty$1.default)(this, "encoder", void 0);
1138
- (0, import_defineProperty$1.default)(this, "wsObservable", behaviorSubject(null));
1139
- (0, import_defineProperty$1.default)(this, "openPromise", null);
1140
- this.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== void 0 ? _opts$WebSocketPonyfi : WebSocket;
1141
- if (!this.WebSocketPonyfill) throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill");
1142
- this.urlOptions = opts.urlOptions;
1143
- this.keepAliveOpts = opts.keepAlive;
1144
- this.encoder = opts.encoder;
1145
- }
1146
- get ws() {
1147
- return this.wsObservable.get();
1148
- }
1149
- set ws(ws) {
1150
- this.wsObservable.next(ws);
386
+ const getNthKey = (value, n) => {
387
+ if (n > value.size)
388
+ throw new Error("index out of bounds");
389
+ const keys = value.keys();
390
+ while (n > 0) {
391
+ keys.next();
392
+ n--;
393
+ }
394
+ return keys.next().value;
395
+ };
396
+ function validatePath(path) {
397
+ if (includes(path, "__proto__")) {
398
+ throw new Error("__proto__ is not allowed as a property");
1151
399
  }
1152
- /**
1153
- * Checks if the WebSocket connection is open and ready to communicate.
1154
- */
1155
- isOpen() {
1156
- return !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;
400
+ if (includes(path, "prototype")) {
401
+ throw new Error("prototype is not allowed as a property");
1157
402
  }
1158
- /**
1159
- * Checks if the WebSocket connection is closed or in the process of closing.
1160
- */
1161
- isClosed() {
1162
- return !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);
1163
- }
1164
- async open() {
1165
- var _this = this;
1166
- if (_this.openPromise) return _this.openPromise;
1167
- _this.id = ++WsConnection2.connectCount;
1168
- const wsPromise = prepareUrl(_this.urlOptions).then((url) => new _this.WebSocketPonyfill(url));
1169
- _this.openPromise = wsPromise.then(async (ws) => {
1170
- _this.ws = ws;
1171
- ws.binaryType = "arraybuffer";
1172
- ws.addEventListener("message", function({ data }) {
1173
- if (data === "PING") this.send("PONG");
1174
- });
1175
- if (_this.keepAliveOpts.enabled) setupPingInterval(ws, _this.keepAliveOpts);
1176
- ws.addEventListener("close", () => {
1177
- if (_this.ws === ws) _this.ws = null;
1178
- });
1179
- await asyncWsOpen(ws);
1180
- if (_this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(_this.urlOptions.connectionParams, _this.encoder));
1181
- });
1182
- try {
1183
- await _this.openPromise;
1184
- } finally {
1185
- _this.openPromise = null;
1186
- }
403
+ if (includes(path, "constructor")) {
404
+ throw new Error("constructor is not allowed as a property");
1187
405
  }
1188
- /**
1189
- * Closes the WebSocket connection gracefully.
1190
- * Waits for any ongoing open operation to complete before closing.
1191
- */
1192
- async close() {
1193
- var _this2 = this;
1194
- try {
1195
- await _this2.openPromise;
1196
- } finally {
1197
- var _this$ws;
1198
- (_this$ws = _this2.ws) === null || _this$ws === void 0 || _this$ws.close();
406
+ }
407
+ const getDeep = (object, path) => {
408
+ validatePath(path);
409
+ for (let i = 0; i < path.length; i++) {
410
+ const key = path[i];
411
+ if (isSet(object)) {
412
+ object = getNthKey(object, +key);
413
+ } else if (isMap(object)) {
414
+ const row = +key;
415
+ const type = +path[++i] === 0 ? "key" : "value";
416
+ const keyOfRow = getNthKey(object, row);
417
+ switch (type) {
418
+ case "key":
419
+ object = keyOfRow;
420
+ break;
421
+ case "value":
422
+ object = object.get(keyOfRow);
423
+ break;
424
+ }
425
+ } else {
426
+ object = object[key];
1199
427
  }
1200
428
  }
429
+ return object;
1201
430
  };
1202
- (0, import_defineProperty$1.default)(WsConnection, "connectCount", 0);
1203
- function backwardCompatibility(connection) {
1204
- if (connection.isOpen()) return {
1205
- id: connection.id,
1206
- state: "open",
1207
- ws: connection.ws
1208
- };
1209
- if (connection.isClosed()) return {
1210
- id: connection.id,
1211
- state: "closed",
1212
- ws: connection.ws
1213
- };
1214
- if (!connection.ws) return null;
1215
- return {
1216
- id: connection.id,
1217
- state: "connecting",
1218
- ws: connection.ws
1219
- };
1220
- }
1221
- __name(backwardCompatibility, "backwardCompatibility");
1222
- var import_defineProperty3 = __toESM2(require_defineProperty(), 1);
1223
- var import_objectSpread28 = __toESM2(require_objectSpread2(), 1);
1224
- var WsClient = class {
1225
- static {
1226
- __name(this, "WsClient");
1227
- }
1228
- constructor(opts) {
1229
- var _opts$experimental_en, _opts$retryDelayMs;
1230
- (0, import_defineProperty3.default)(this, "connectionState", void 0);
1231
- (0, import_defineProperty3.default)(this, "allowReconnect", false);
1232
- (0, import_defineProperty3.default)(this, "requestManager", new RequestManager());
1233
- (0, import_defineProperty3.default)(this, "activeConnection", void 0);
1234
- (0, import_defineProperty3.default)(this, "reconnectRetryDelay", void 0);
1235
- (0, import_defineProperty3.default)(this, "inactivityTimeout", void 0);
1236
- (0, import_defineProperty3.default)(this, "callbacks", void 0);
1237
- (0, import_defineProperty3.default)(this, "lazyMode", void 0);
1238
- (0, import_defineProperty3.default)(this, "encoder", void 0);
1239
- (0, import_defineProperty3.default)(this, "reconnecting", null);
1240
- this.encoder = (_opts$experimental_en = opts.experimental_encoder) !== null && _opts$experimental_en !== void 0 ? _opts$experimental_en : jsonEncoder;
1241
- this.callbacks = {
1242
- onOpen: opts.onOpen,
1243
- onClose: opts.onClose,
1244
- onError: opts.onError
1245
- };
1246
- const lazyOptions = (0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, lazyDefaults), opts.lazy);
1247
- this.inactivityTimeout = new ResettableTimeout(() => {
1248
- if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {
1249
- this.inactivityTimeout.reset();
1250
- return;
431
+ const setDeep = (object, path, mapper) => {
432
+ validatePath(path);
433
+ if (path.length === 0) {
434
+ return mapper(object);
435
+ }
436
+ let parent = object;
437
+ for (let i = 0; i < path.length - 1; i++) {
438
+ const key = path[i];
439
+ if (isArray$1(parent)) {
440
+ const index = +key;
441
+ parent = parent[index];
442
+ } else if (isPlainObject$1(parent)) {
443
+ parent = parent[key];
444
+ } else if (isSet(parent)) {
445
+ const row = +key;
446
+ parent = getNthKey(parent, row);
447
+ } else if (isMap(parent)) {
448
+ const isEnd = i === path.length - 2;
449
+ if (isEnd) {
450
+ break;
451
+ }
452
+ const row = +key;
453
+ const type = +path[++i] === 0 ? "key" : "value";
454
+ const keyOfRow = getNthKey(parent, row);
455
+ switch (type) {
456
+ case "key":
457
+ parent = keyOfRow;
458
+ break;
459
+ case "value":
460
+ parent = parent.get(keyOfRow);
461
+ break;
1251
462
  }
1252
- this.close().catch(() => null);
1253
- }, lazyOptions.closeMs);
1254
- this.activeConnection = new WsConnection({
1255
- WebSocketPonyfill: opts.WebSocket,
1256
- urlOptions: opts,
1257
- keepAlive: (0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, keepAliveDefaults), opts.keepAlive),
1258
- encoder: this.encoder
1259
- });
1260
- this.activeConnection.wsObservable.subscribe({ next: /* @__PURE__ */ __name((ws) => {
1261
- if (!ws) return;
1262
- this.setupWebSocketListeners(ws);
1263
- }, "next") });
1264
- this.reconnectRetryDelay = (_opts$retryDelayMs = opts.retryDelayMs) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : exponentialBackoff;
1265
- this.lazyMode = lazyOptions.enabled;
1266
- this.connectionState = behaviorSubject({
1267
- type: "state",
1268
- state: lazyOptions.enabled ? "idle" : "connecting",
1269
- error: null
1270
- });
1271
- if (!this.lazyMode) this.open().catch(() => null);
1272
- }
1273
- /**
1274
- * Opens the WebSocket connection. Handles reconnection attempts and updates
1275
- * the connection state accordingly.
1276
- */
1277
- async open() {
1278
- var _this = this;
1279
- _this.allowReconnect = true;
1280
- if (_this.connectionState.get().state === "idle") _this.connectionState.next({
1281
- type: "state",
1282
- state: "connecting",
1283
- error: null
1284
- });
1285
- try {
1286
- await _this.activeConnection.open();
1287
- } catch (error) {
1288
- _this.reconnect(new TRPCWebSocketClosedError({
1289
- message: "Initialization error",
1290
- cause: error
1291
- }));
1292
- return _this.reconnecting;
1293
463
  }
1294
464
  }
1295
- /**
1296
- * Closes the WebSocket connection and stops managing requests.
1297
- * Ensures all outgoing and pending requests are properly finalized.
1298
- */
1299
- async close() {
1300
- var _this2 = this;
1301
- _this2.allowReconnect = false;
1302
- _this2.inactivityTimeout.stop();
1303
- const requestsToAwait = [];
1304
- for (const request of _this2.requestManager.getRequests()) if (request.message.method === "subscription") request.callbacks.complete();
1305
- else if (request.state === "outgoing") request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({ message: "Closed before connection was established" })));
1306
- else requestsToAwait.push(request.end);
1307
- await Promise.all(requestsToAwait).catch(() => null);
1308
- await _this2.activeConnection.close().catch(() => null);
1309
- _this2.connectionState.next({
1310
- type: "state",
1311
- state: "idle",
1312
- error: null
1313
- });
1314
- }
1315
- /**
1316
- * Method to request the server.
1317
- * Handles data transformation, batching of requests, and subscription lifecycle.
1318
- *
1319
- * @param op - The operation details including id, type, path, input and signal
1320
- * @param transformer - Data transformer for serializing requests and deserializing responses
1321
- * @param lastEventId - Optional ID of the last received event for subscriptions
1322
- *
1323
- * @returns An observable that emits operation results and handles cleanup
1324
- */
1325
- request({ op: { id, type, path, input, signal }, transformer, lastEventId }) {
1326
- return observable((observer) => {
1327
- const abort = this.batchSend({
1328
- id,
1329
- method: type,
1330
- params: {
1331
- input: transformer.input.serialize(input),
1332
- path,
1333
- lastEventId
1334
- }
1335
- }, (0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, observer), {}, { next(event) {
1336
- const transformed = transformResult(event, transformer.output);
1337
- if (!transformed.ok) {
1338
- observer.error(TRPCClientError.from(transformed.error));
1339
- return;
1340
- }
1341
- observer.next({ result: transformed.result });
1342
- } }));
1343
- return () => {
1344
- abort();
1345
- if (type === "subscription" && this.activeConnection.isOpen()) this.send({
1346
- id,
1347
- method: "subscription.stop"
1348
- });
1349
- signal === null || signal === void 0 || signal.removeEventListener("abort", abort);
1350
- };
1351
- });
1352
- }
1353
- get connection() {
1354
- return backwardCompatibility(this.activeConnection);
465
+ const lastKey = path[path.length - 1];
466
+ if (isArray$1(parent)) {
467
+ parent[+lastKey] = mapper(parent[+lastKey]);
468
+ } else if (isPlainObject$1(parent)) {
469
+ parent[lastKey] = mapper(parent[lastKey]);
470
+ }
471
+ if (isSet(parent)) {
472
+ const oldValue = getNthKey(parent, +lastKey);
473
+ const newValue = mapper(oldValue);
474
+ if (oldValue !== newValue) {
475
+ parent.delete(oldValue);
476
+ parent.add(newValue);
477
+ }
1355
478
  }
1356
- reconnect(closedError) {
1357
- var _this3 = this;
1358
- this.connectionState.next({
1359
- type: "state",
1360
- state: "connecting",
1361
- error: TRPCClientError.from(closedError)
1362
- });
1363
- if (this.reconnecting) return;
1364
- const tryReconnect = /* @__PURE__ */ __name(async (attemptIndex) => {
1365
- try {
1366
- await sleep(_this3.reconnectRetryDelay(attemptIndex));
1367
- if (_this3.allowReconnect) {
1368
- await _this3.activeConnection.close();
1369
- await _this3.activeConnection.open();
1370
- if (_this3.requestManager.hasPendingRequests()) _this3.send(_this3.requestManager.getPendingRequests().map(({ message }) => message));
479
+ if (isMap(parent)) {
480
+ const row = +path[path.length - 2];
481
+ const keyToRow = getNthKey(parent, row);
482
+ const type = +lastKey === 0 ? "key" : "value";
483
+ switch (type) {
484
+ case "key": {
485
+ const newKey = mapper(keyToRow);
486
+ parent.set(newKey, parent.get(keyToRow));
487
+ if (newKey !== keyToRow) {
488
+ parent.delete(keyToRow);
1371
489
  }
1372
- _this3.reconnecting = null;
1373
- } catch (_unused) {
1374
- await tryReconnect(attemptIndex + 1);
490
+ break;
1375
491
  }
1376
- }, "tryReconnect");
1377
- this.reconnecting = tryReconnect(0);
1378
- }
1379
- setupWebSocketListeners(ws) {
1380
- var _this4 = this;
1381
- const handleCloseOrError = /* @__PURE__ */ __name((cause) => {
1382
- const reqs = this.requestManager.getPendingRequests();
1383
- for (const { message, callbacks } of reqs) {
1384
- if (message.method === "subscription") continue;
1385
- callbacks.error(TRPCClientError.from(cause !== null && cause !== void 0 ? cause : new TRPCWebSocketClosedError({
1386
- message: "WebSocket closed",
1387
- cause
1388
- })));
1389
- this.requestManager.delete(message.id);
492
+ case "value": {
493
+ parent.set(keyToRow, mapper(parent.get(keyToRow)));
494
+ break;
1390
495
  }
1391
- }, "handleCloseOrError");
1392
- ws.addEventListener("open", () => {
1393
- run(async () => {
1394
- var _this$callbacks$onOpe, _this$callbacks;
1395
- if (_this4.lazyMode) _this4.inactivityTimeout.start();
1396
- (_this$callbacks$onOpe = (_this$callbacks = _this4.callbacks).onOpen) === null || _this$callbacks$onOpe === void 0 || _this$callbacks$onOpe.call(_this$callbacks);
1397
- _this4.connectionState.next({
1398
- type: "state",
1399
- state: "pending",
1400
- error: null
1401
- });
1402
- }).catch((error) => {
1403
- ws.close(3e3);
1404
- handleCloseOrError(error);
1405
- });
1406
- });
1407
- ws.addEventListener("message", ({ data }) => {
1408
- this.inactivityTimeout.reset();
1409
- if (["PING", "PONG"].includes(data)) return;
1410
- const incomingMessage = this.encoder.decode(data);
1411
- if ("method" in incomingMessage) {
1412
- this.handleIncomingRequest(incomingMessage);
1413
- return;
1414
- }
1415
- this.handleResponseMessage(incomingMessage);
1416
- });
1417
- ws.addEventListener("close", (event) => {
1418
- var _this$callbacks$onClo, _this$callbacks2;
1419
- handleCloseOrError(event);
1420
- (_this$callbacks$onClo = (_this$callbacks2 = this.callbacks).onClose) === null || _this$callbacks$onClo === void 0 || _this$callbacks$onClo.call(_this$callbacks2, event);
1421
- if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) this.reconnect(new TRPCWebSocketClosedError({
1422
- message: "WebSocket closed",
1423
- cause: event
1424
- }));
1425
- });
1426
- ws.addEventListener("error", (event) => {
1427
- var _this$callbacks$onErr, _this$callbacks3;
1428
- handleCloseOrError(event);
1429
- (_this$callbacks$onErr = (_this$callbacks3 = this.callbacks).onError) === null || _this$callbacks$onErr === void 0 || _this$callbacks$onErr.call(_this$callbacks3, event);
1430
- this.reconnect(new TRPCWebSocketClosedError({
1431
- message: "WebSocket closed",
1432
- cause: event
1433
- }));
1434
- });
1435
- }
1436
- handleResponseMessage(message) {
1437
- const request = this.requestManager.getPendingRequest(message.id);
1438
- if (!request) return;
1439
- request.callbacks.next(message);
1440
- let completed = true;
1441
- if ("result" in message && request.message.method === "subscription") {
1442
- if (message.result.type === "data") request.message.params.lastEventId = message.result.id;
1443
- if (message.result.type !== "stopped") completed = false;
1444
- }
1445
- if (completed) {
1446
- request.callbacks.complete();
1447
- this.requestManager.delete(message.id);
1448
496
  }
1449
497
  }
1450
- handleIncomingRequest(message) {
1451
- if (message.method === "reconnect") this.reconnect(new TRPCWebSocketClosedError({ message: "Server requested reconnect" }));
1452
- }
1453
- /**
1454
- * Sends a message or batch of messages directly to the server.
1455
- */
1456
- send(messageOrMessages) {
1457
- if (!this.activeConnection.isOpen()) throw new Error("Active connection is not open");
1458
- const messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages];
1459
- this.activeConnection.ws.send(this.encoder.encode(messages.length === 1 ? messages[0] : messages));
1460
- }
1461
- /**
1462
- * Groups requests for batch sending.
1463
- *
1464
- * @returns A function to abort the batched request.
1465
- */
1466
- batchSend(message, callbacks) {
1467
- var _this5 = this;
1468
- this.inactivityTimeout.reset();
1469
- run(async () => {
1470
- if (!_this5.activeConnection.isOpen()) await _this5.open();
1471
- await sleep(0);
1472
- if (!_this5.requestManager.hasOutgoingRequests()) return;
1473
- _this5.send(_this5.requestManager.flush().map(({ message: message$1 }) => message$1));
1474
- }).catch((err) => {
1475
- this.requestManager.delete(message.id);
1476
- callbacks.error(TRPCClientError.from(err));
498
+ return object;
499
+ };
500
+ const enableLegacyPaths = (version) => version < 1;
501
+ function traverse(tree, walker2, version, origin = []) {
502
+ if (!tree) {
503
+ return;
504
+ }
505
+ const legacyPaths = enableLegacyPaths(version);
506
+ if (!isArray$1(tree)) {
507
+ forEach(tree, (subtree, key) => traverse(subtree, walker2, version, [
508
+ ...origin,
509
+ ...parsePath(key, legacyPaths)
510
+ ]));
511
+ return;
512
+ }
513
+ const [nodeValue, children] = tree;
514
+ if (children) {
515
+ forEach(children, (child, key) => {
516
+ traverse(child, walker2, version, [
517
+ ...origin,
518
+ ...parsePath(key, legacyPaths)
519
+ ]);
1477
520
  });
1478
- return this.requestManager.register(message, callbacks);
1479
521
  }
1480
- };
1481
- function createWSClient(opts) {
1482
- return new WsClient(opts);
522
+ walker2(nodeValue, origin);
1483
523
  }
1484
- __name(createWSClient, "createWSClient");
1485
- function wsLink(opts) {
1486
- const { client } = opts;
1487
- const transformer = getTransformer(opts.transformer);
1488
- return () => {
1489
- return ({ op }) => {
1490
- return observable((observer) => {
1491
- const connStateSubscription = op.type === "subscription" ? client.connectionState.subscribe({ next(result) {
1492
- observer.next({
1493
- result,
1494
- context: op.context
1495
- });
1496
- } }) : null;
1497
- const requestSubscription = client.request({
1498
- op,
1499
- transformer
1500
- }).subscribe(observer);
1501
- return () => {
1502
- requestSubscription.unsubscribe();
1503
- connStateSubscription === null || connStateSubscription === void 0 || connStateSubscription.unsubscribe();
1504
- };
1505
- });
1506
- };
1507
- };
524
+ function applyValueAnnotations(plain, annotations, version, superJson) {
525
+ traverse(annotations, (type, path) => {
526
+ plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
527
+ }, version);
528
+ return plain;
1508
529
  }
1509
- __name(wsLink, "wsLink");
1510
-
1511
- // node_modules/@trpc/client/dist/index.mjs
1512
- var import_defineProperty4 = __toESM2(require_defineProperty(), 1);
1513
- var import_objectSpread2$4 = __toESM2(require_objectSpread2(), 1);
1514
- var TRPCUntypedClient = class {
1515
- static {
1516
- __name(this, "TRPCUntypedClient");
1517
- }
1518
- constructor(opts) {
1519
- (0, import_defineProperty4.default)(this, "links", void 0);
1520
- (0, import_defineProperty4.default)(this, "runtime", void 0);
1521
- (0, import_defineProperty4.default)(this, "requestId", void 0);
1522
- this.requestId = 0;
1523
- this.runtime = {};
1524
- this.links = opts.links.map((link) => link(this.runtime));
1525
- }
1526
- $request(opts) {
1527
- var _opts$context;
1528
- const chain$ = createChain({
1529
- links: this.links,
1530
- op: (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, opts), {}, {
1531
- context: (_opts$context = opts.context) !== null && _opts$context !== void 0 ? _opts$context : {},
1532
- id: ++this.requestId
1533
- })
1534
- });
1535
- return chain$.pipe(share());
1536
- }
1537
- async requestAsPromise(opts) {
1538
- var _this = this;
1539
- try {
1540
- const req$ = _this.$request(opts);
1541
- const envelope = await observableToPromise(req$);
1542
- const data = envelope.result.data;
1543
- return data;
1544
- } catch (err) {
1545
- throw TRPCClientError.from(err);
1546
- }
1547
- }
1548
- query(path, input, opts) {
1549
- return this.requestAsPromise({
1550
- type: "query",
1551
- path,
1552
- input,
1553
- context: opts === null || opts === void 0 ? void 0 : opts.context,
1554
- signal: opts === null || opts === void 0 ? void 0 : opts.signal
530
+ function applyReferentialEqualityAnnotations(plain, annotations, version) {
531
+ const legacyPaths = enableLegacyPaths(version);
532
+ function apply(identicalPaths, path) {
533
+ const object = getDeep(plain, parsePath(path, legacyPaths));
534
+ identicalPaths.map((path2) => parsePath(path2, legacyPaths)).forEach((identicalObjectPath) => {
535
+ plain = setDeep(plain, identicalObjectPath, () => object);
1555
536
  });
1556
537
  }
1557
- mutation(path, input, opts) {
1558
- return this.requestAsPromise({
1559
- type: "mutation",
1560
- path,
1561
- input,
1562
- context: opts === null || opts === void 0 ? void 0 : opts.context,
1563
- signal: opts === null || opts === void 0 ? void 0 : opts.signal
1564
- });
1565
- }
1566
- subscription(path, input, opts) {
1567
- const observable$ = this.$request({
1568
- type: "subscription",
1569
- path,
1570
- input,
1571
- context: opts.context,
1572
- signal: opts.signal
1573
- });
1574
- return observable$.subscribe({
1575
- next(envelope) {
1576
- switch (envelope.result.type) {
1577
- case "state": {
1578
- var _opts$onConnectionSta;
1579
- (_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === void 0 || _opts$onConnectionSta.call(opts, envelope.result);
1580
- break;
1581
- }
1582
- case "started": {
1583
- var _opts$onStarted;
1584
- (_opts$onStarted = opts.onStarted) === null || _opts$onStarted === void 0 || _opts$onStarted.call(opts, { context: envelope.context });
1585
- break;
1586
- }
1587
- case "stopped": {
1588
- var _opts$onStopped;
1589
- (_opts$onStopped = opts.onStopped) === null || _opts$onStopped === void 0 || _opts$onStopped.call(opts);
1590
- break;
1591
- }
1592
- case "data":
1593
- case void 0: {
1594
- var _opts$onData;
1595
- (_opts$onData = opts.onData) === null || _opts$onData === void 0 || _opts$onData.call(opts, envelope.result.data);
1596
- break;
1597
- }
1598
- }
1599
- },
1600
- error(err) {
1601
- var _opts$onError;
1602
- (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, err);
1603
- },
1604
- complete() {
1605
- var _opts$onComplete;
1606
- (_opts$onComplete = opts.onComplete) === null || _opts$onComplete === void 0 || _opts$onComplete.call(opts);
1607
- }
538
+ if (isArray$1(annotations)) {
539
+ const [root, other] = annotations;
540
+ root.forEach((identicalPath) => {
541
+ plain = setDeep(plain, parsePath(identicalPath, legacyPaths), () => plain);
1608
542
  });
543
+ if (other) {
544
+ forEach(other, apply);
545
+ }
546
+ } else {
547
+ forEach(annotations, apply);
1609
548
  }
1610
- };
1611
- var untypedClientSymbol = /* @__PURE__ */ Symbol.for("trpc_untypedClient");
1612
- var clientCallTypeMap = {
1613
- query: "query",
1614
- mutate: "mutation",
1615
- subscribe: "subscription"
1616
- };
1617
- var clientCallTypeToProcedureType = /* @__PURE__ */ __name((clientCallType) => {
1618
- return clientCallTypeMap[clientCallType];
1619
- }, "clientCallTypeToProcedureType");
1620
- function createTRPCClientProxy(client) {
1621
- const proxy = createRecursiveProxy(({ path, args }) => {
1622
- const pathCopy = [...path];
1623
- const procedureType = clientCallTypeToProcedureType(pathCopy.pop());
1624
- const fullPath = pathCopy.join(".");
1625
- return client[procedureType](fullPath, ...args);
1626
- });
1627
- return createFlatProxy((key) => {
1628
- if (key === untypedClientSymbol) return client;
1629
- return proxy[key];
1630
- });
549
+ return plain;
1631
550
  }
1632
- __name(createTRPCClientProxy, "createTRPCClientProxy");
1633
- function createTRPCClient(opts) {
1634
- const client = new TRPCUntypedClient(opts);
1635
- const proxy = createTRPCClientProxy(client);
1636
- return proxy;
551
+ const isDeep = (object, superJson) => isPlainObject$1(object) || isArray$1(object) || isMap(object) || isSet(object) || isError(object) || isInstanceOfRegisteredClass(object, superJson);
552
+ function addIdentity(object, path, identities) {
553
+ const existingSet = identities.get(object);
554
+ if (existingSet) {
555
+ existingSet.push(path);
556
+ } else {
557
+ identities.set(object, [path]);
558
+ }
1637
559
  }
1638
- __name(createTRPCClient, "createTRPCClient");
1639
- var import_objectSpread2$3 = __toESM2(require_objectSpread2(), 1);
1640
- var import_objectSpread2$2 = __toESM2(require_objectSpread2(), 1);
1641
- var require_asyncIterator = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports2, module2) {
1642
- function _asyncIterator$1(r) {
1643
- var n, t, o, e = 2;
1644
- for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--; ) {
1645
- if (t && null != (n = r[t])) return n.call(r);
1646
- if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
1647
- t = "@@asyncIterator", o = "@@iterator";
560
+ function generateReferentialEqualityAnnotations(identitites, dedupe) {
561
+ const result = {};
562
+ let rootEqualityPaths = void 0;
563
+ identitites.forEach((paths) => {
564
+ if (paths.length <= 1) {
565
+ return;
1648
566
  }
1649
- throw new TypeError("Object is not async iterable");
1650
- }
1651
- __name(_asyncIterator$1, "_asyncIterator$1");
1652
- function AsyncFromSyncIterator(r) {
1653
- function AsyncFromSyncIteratorContinuation(r$1) {
1654
- if (Object(r$1) !== r$1) return Promise.reject(new TypeError(r$1 + " is not an object."));
1655
- var n = r$1.done;
1656
- return Promise.resolve(r$1.value).then(function(r$2) {
1657
- return {
1658
- value: r$2,
1659
- done: n
1660
- };
1661
- });
567
+ if (!dedupe) {
568
+ paths = paths.map((path) => path.map(String)).sort((a, b) => a.length - b.length);
1662
569
  }
1663
- __name(AsyncFromSyncIteratorContinuation, "AsyncFromSyncIteratorContinuation");
1664
- return AsyncFromSyncIterator = /* @__PURE__ */ __name(function AsyncFromSyncIterator$1(r$1) {
1665
- this.s = r$1, this.n = r$1.next;
1666
- }, "AsyncFromSyncIterator$1"), AsyncFromSyncIterator.prototype = {
1667
- s: null,
1668
- n: null,
1669
- next: /* @__PURE__ */ __name(function next() {
1670
- return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
1671
- }, "next"),
1672
- "return": /* @__PURE__ */ __name(function _return(r$1) {
1673
- var n = this.s["return"];
1674
- return void 0 === n ? Promise.resolve({
1675
- value: r$1,
1676
- done: true
1677
- }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
1678
- }, "_return"),
1679
- "throw": /* @__PURE__ */ __name(function _throw(r$1) {
1680
- var n = this.s["return"];
1681
- return void 0 === n ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
1682
- }, "_throw")
1683
- }, new AsyncFromSyncIterator(r);
1684
- }
1685
- __name(AsyncFromSyncIterator, "AsyncFromSyncIterator");
1686
- module2.exports = _asyncIterator$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
1687
- } });
1688
- var import_asyncIterator = __toESM2(require_asyncIterator(), 1);
1689
- var import_objectSpread2$12 = __toESM2(require_objectSpread2(), 1);
1690
- var require_usingCtx = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports2, module2) {
1691
- function _usingCtx() {
1692
- var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) {
1693
- var n$1 = Error();
1694
- return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1;
1695
- }, e = {}, n = [];
1696
- function using(r$1, e$1) {
1697
- if (null != e$1) {
1698
- if (Object(e$1) !== e$1) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
1699
- if (r$1) var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
1700
- if (void 0 === o && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1)) var t = o;
1701
- if ("function" != typeof o) throw new TypeError("Object is not disposable.");
1702
- t && (o = /* @__PURE__ */ __name(function o$1() {
1703
- try {
1704
- t.call(e$1);
1705
- } catch (r$2) {
1706
- return Promise.reject(r$2);
1707
- }
1708
- }, "o$1")), n.push({
1709
- v: e$1,
1710
- d: o,
1711
- a: r$1
1712
- });
1713
- } else r$1 && n.push({
1714
- d: e$1,
1715
- a: r$1
1716
- });
1717
- return e$1;
570
+ const [representativePath, ...identicalPaths] = paths;
571
+ if (representativePath.length === 0) {
572
+ rootEqualityPaths = identicalPaths.map(stringifyPath);
573
+ } else {
574
+ result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
1718
575
  }
1719
- __name(using, "using");
1720
- return {
1721
- e,
1722
- u: using.bind(null, false),
1723
- a: using.bind(null, true),
1724
- d: /* @__PURE__ */ __name(function d() {
1725
- var o, t = this.e, s = 0;
1726
- function next() {
1727
- for (; o = n.pop(); ) try {
1728
- if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
1729
- if (o.d) {
1730
- var r$1 = o.d.call(o.v);
1731
- if (o.a) return s |= 2, Promise.resolve(r$1).then(next, err);
1732
- } else s |= 1;
1733
- } catch (r$2) {
1734
- return err(r$2);
1735
- }
1736
- if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
1737
- if (t !== e) throw t;
1738
- }
1739
- __name(next, "next");
1740
- function err(n$1) {
1741
- return t = t !== e ? new r(n$1, t) : n$1, next();
1742
- }
1743
- __name(err, "err");
1744
- return next();
1745
- }, "d")
576
+ });
577
+ if (rootEqualityPaths) {
578
+ if (isEmptyObject(result)) {
579
+ return [rootEqualityPaths];
580
+ } else {
581
+ return [rootEqualityPaths, result];
582
+ }
583
+ } else {
584
+ return isEmptyObject(result) ? void 0 : result;
585
+ }
586
+ }
587
+ const walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = /* @__PURE__ */ new Map()) => {
588
+ const primitive = isPrimitive(object);
589
+ if (!primitive) {
590
+ addIdentity(object, path, identities);
591
+ const seen = seenObjects.get(object);
592
+ if (seen) {
593
+ return dedupe ? {
594
+ transformedValue: null
595
+ } : seen;
596
+ }
597
+ }
598
+ if (!isDeep(object, superJson)) {
599
+ const transformed2 = transformValue(object, superJson);
600
+ const result2 = transformed2 ? {
601
+ transformedValue: transformed2.value,
602
+ annotations: [transformed2.type]
603
+ } : {
604
+ transformedValue: object
1746
605
  };
606
+ if (!primitive) {
607
+ seenObjects.set(object, result2);
608
+ }
609
+ return result2;
1747
610
  }
1748
- __name(_usingCtx, "_usingCtx");
1749
- module2.exports = _usingCtx, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
1750
- } });
1751
- var require_OverloadYield = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports2, module2) {
1752
- function _OverloadYield(e, d) {
1753
- this.v = e, this.k = d;
1754
- }
1755
- __name(_OverloadYield, "_OverloadYield");
1756
- module2.exports = _OverloadYield, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
1757
- } });
1758
- var require_awaitAsyncGenerator = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports2, module2) {
1759
- var OverloadYield$1 = require_OverloadYield();
1760
- function _awaitAsyncGenerator$1(e) {
1761
- return new OverloadYield$1(e, 0);
1762
- }
1763
- __name(_awaitAsyncGenerator$1, "_awaitAsyncGenerator$1");
1764
- module2.exports = _awaitAsyncGenerator$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
1765
- } });
1766
- var require_wrapAsyncGenerator = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports2, module2) {
1767
- var OverloadYield = require_OverloadYield();
1768
- function _wrapAsyncGenerator$1(e) {
1769
- return function() {
1770
- return new AsyncGenerator(e.apply(this, arguments));
611
+ if (includes(objectsInThisPath, object)) {
612
+ return {
613
+ transformedValue: null
1771
614
  };
1772
615
  }
1773
- __name(_wrapAsyncGenerator$1, "_wrapAsyncGenerator$1");
1774
- function AsyncGenerator(e) {
1775
- var r, t;
1776
- function resume(r$1, t$1) {
1777
- try {
1778
- var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield;
1779
- Promise.resolve(u ? o.v : o).then(function(t$2) {
1780
- if (u) {
1781
- var i = "return" === r$1 ? "return" : "next";
1782
- if (!o.k || t$2.done) return resume(i, t$2);
1783
- t$2 = e[i](t$2).value;
1784
- }
1785
- settle(n.done ? "return" : "normal", t$2);
1786
- }, function(e$1) {
1787
- resume("throw", e$1);
1788
- });
1789
- } catch (e$1) {
1790
- settle("throw", e$1);
1791
- }
1792
- }
1793
- __name(resume, "resume");
1794
- function settle(e$1, n) {
1795
- switch (e$1) {
1796
- case "return":
1797
- r.resolve({
1798
- value: n,
1799
- done: true
1800
- });
1801
- break;
1802
- case "throw":
1803
- r.reject(n);
1804
- break;
1805
- default:
1806
- r.resolve({
1807
- value: n,
1808
- done: false
1809
- });
1810
- }
1811
- (r = r.next) ? resume(r.key, r.arg) : t = null;
616
+ const transformationResult = transformValue(object, superJson);
617
+ const transformed = transformationResult?.value ?? object;
618
+ const transformedValue = isArray$1(transformed) ? [] : {};
619
+ const innerAnnotations = {};
620
+ forEach(transformed, (value, index) => {
621
+ if (index === "__proto__" || index === "constructor" || index === "prototype") {
622
+ throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
1812
623
  }
1813
- __name(settle, "settle");
1814
- this._invoke = function(e$1, n) {
1815
- return new Promise(function(o, u) {
1816
- var i = {
1817
- key: e$1,
1818
- arg: n,
1819
- resolve: o,
1820
- reject: u,
1821
- next: null
1822
- };
1823
- t ? t = t.next = i : (r = t = i, resume(e$1, n));
624
+ const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
625
+ transformedValue[index] = recursiveResult.transformedValue;
626
+ if (isArray$1(recursiveResult.annotations)) {
627
+ innerAnnotations[escapeKey(index)] = recursiveResult.annotations;
628
+ } else if (isPlainObject$1(recursiveResult.annotations)) {
629
+ forEach(recursiveResult.annotations, (tree, key) => {
630
+ innerAnnotations[escapeKey(index) + "." + key] = tree;
1824
631
  });
1825
- }, "function" != typeof e["return"] && (this["return"] = void 0);
1826
- }
1827
- __name(AsyncGenerator, "AsyncGenerator");
1828
- AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
1829
- return this;
1830
- }, AsyncGenerator.prototype.next = function(e) {
1831
- return this._invoke("next", e);
1832
- }, AsyncGenerator.prototype["throw"] = function(e) {
1833
- return this._invoke("throw", e);
1834
- }, AsyncGenerator.prototype["return"] = function(e) {
1835
- return this._invoke("return", e);
632
+ }
633
+ });
634
+ const result = isEmptyObject(innerAnnotations) ? {
635
+ transformedValue,
636
+ annotations: !!transformationResult ? [transformationResult.type] : void 0
637
+ } : {
638
+ transformedValue,
639
+ annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
1836
640
  };
1837
- module2.exports = _wrapAsyncGenerator$1, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
1838
- } });
1839
- var import_usingCtx = __toESM2(require_usingCtx(), 1);
1840
- var import_awaitAsyncGenerator = __toESM2(require_awaitAsyncGenerator(), 1);
1841
- var import_wrapAsyncGenerator = __toESM2(require_wrapAsyncGenerator(), 1);
1842
- var import_objectSpread29 = __toESM2(require_objectSpread2(), 1);
1843
-
1844
- // src/backend-client.ts
1845
- var import_superjson = __toESM(require("superjson"), 1);
1846
- var BackendClient = class {
1847
- static {
1848
- __name(this, "BackendClient");
1849
- }
1850
- /** Raw tRPC client — for advanced usage / direct path access */
1851
- trpc;
1852
- serverUrl;
1853
- token;
1854
- wsClient = null;
1855
- constructor(config) {
1856
- this.serverUrl = config.serverUrl.replace(/\/+$/, "");
1857
- this.token = config.token;
1858
- const isBrowser = typeof window !== "undefined";
1859
- const useWs = config.useWebSocket ?? isBrowser;
1860
- const headers = /* @__PURE__ */ __name(() => {
1861
- const h = {};
1862
- if (this.token) {
1863
- h["Authorization"] = `Bearer ${this.token}`;
1864
- }
1865
- return h;
1866
- }, "headers");
1867
- if (useWs) {
1868
- const wsUrl = this.serverUrl.replace(/^http/, "ws") + "/trpc";
1869
- this.wsClient = createWSClient({
1870
- url: wsUrl,
1871
- connectionParams: /* @__PURE__ */ __name(() => ({
1872
- token: this.token
1873
- }), "connectionParams"),
1874
- retryDelayMs: /* @__PURE__ */ __name(() => 2e3, "retryDelayMs")
1875
- });
1876
- this.trpc = createTRPCClient({
1877
- links: [
1878
- wsLink({
1879
- client: this.wsClient,
1880
- transformer: import_superjson.default
1881
- })
1882
- ]
1883
- });
1884
- } else {
1885
- this.trpc = createTRPCClient({
1886
- links: [
1887
- httpLink({
1888
- url: `${this.serverUrl}/trpc`,
1889
- headers,
1890
- transformer: import_superjson.default
1891
- })
1892
- ]
1893
- });
641
+ if (!primitive) {
642
+ seenObjects.set(object, result);
643
+ }
644
+ return result;
645
+ };
646
+ function getType(payload) {
647
+ return Object.prototype.toString.call(payload).slice(8, -1);
648
+ }
649
+ function isArray(payload) {
650
+ return getType(payload) === "Array";
651
+ }
652
+ function isPlainObject(payload) {
653
+ if (getType(payload) !== "Object")
654
+ return false;
655
+ const prototype = Object.getPrototypeOf(payload);
656
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
657
+ }
658
+ function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
659
+ const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
660
+ if (propType === "enumerable")
661
+ carry[key] = newVal;
662
+ if (includeNonenumerable && propType === "nonenumerable") {
663
+ Object.defineProperty(carry, key, {
664
+ value: newVal,
665
+ enumerable: false,
666
+ writable: true,
667
+ configurable: true
668
+ });
669
+ }
670
+ }
671
+ function copy(target, options = {}) {
672
+ if (isArray(target)) {
673
+ return target.map((item) => copy(item, options));
674
+ }
675
+ if (!isPlainObject(target)) {
676
+ return target;
677
+ }
678
+ const props = Object.getOwnPropertyNames(target);
679
+ const symbols = Object.getOwnPropertySymbols(target);
680
+ return [...props, ...symbols].reduce((carry, key) => {
681
+ if (key === "__proto__")
682
+ return carry;
683
+ if (isArray(options.props) && !options.props.includes(key)) {
684
+ return carry;
685
+ }
686
+ const val = target[key];
687
+ const newVal = copy(val, options);
688
+ assignProp(carry, key, newVal, target, options.nonenumerable);
689
+ return carry;
690
+ }, {});
691
+ }
692
+ class SuperJSON {
693
+ /**
694
+ * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
695
+ */
696
+ constructor({ dedupe = false } = {}) {
697
+ this.classRegistry = new ClassRegistry();
698
+ this.symbolRegistry = new Registry((s) => s.description ?? "");
699
+ this.customTransformerRegistry = new CustomTransformerRegistry();
700
+ this.allowedErrorProps = [];
701
+ this.dedupe = dedupe;
702
+ }
703
+ serialize(object) {
704
+ const identities = /* @__PURE__ */ new Map();
705
+ const output = walker(object, identities, this, this.dedupe);
706
+ const res = {
707
+ json: output.transformedValue
708
+ };
709
+ if (output.annotations) {
710
+ res.meta = {
711
+ ...res.meta,
712
+ values: output.annotations
713
+ };
1894
714
  }
715
+ const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
716
+ if (equalityAnnotations) {
717
+ res.meta = {
718
+ ...res.meta,
719
+ referentialEqualities: equalityAnnotations
720
+ };
721
+ }
722
+ if (res.meta)
723
+ res.meta.v = 1;
724
+ return res;
725
+ }
726
+ deserialize(payload, options) {
727
+ const { json, meta } = payload;
728
+ let result = options?.inPlace ? json : copy(json);
729
+ if (meta?.values) {
730
+ result = applyValueAnnotations(result, meta.values, meta.v ?? 0, this);
731
+ }
732
+ if (meta?.referentialEqualities) {
733
+ result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities, meta.v ?? 0);
734
+ }
735
+ return result;
1895
736
  }
1896
- /** Update the auth token (e.g. after login) */
1897
- setToken(token) {
1898
- this.token = token;
737
+ stringify(object) {
738
+ return JSON.stringify(this.serialize(object));
1899
739
  }
1900
- /** Close the WebSocket connection (if using WS transport) */
1901
- close() {
1902
- this.wsClient?.close();
740
+ parse(string) {
741
+ return this.deserialize(JSON.parse(string), { inPlace: true });
1903
742
  }
1904
- // ─── Auth ──────────────────────────────────────────────────────────
1905
- async login(username, password) {
1906
- return this.trpc.auth.login.mutate({
1907
- username,
1908
- password
743
+ registerClass(v, options) {
744
+ this.classRegistry.register(v, options);
745
+ }
746
+ registerSymbol(v, identifier) {
747
+ this.symbolRegistry.register(v, identifier);
748
+ }
749
+ registerCustom(transformer, name) {
750
+ this.customTransformerRegistry.register({
751
+ name,
752
+ ...transformer
1909
753
  });
1910
754
  }
1911
- async getMe() {
1912
- return this.trpc.auth.me.query();
755
+ allowErrorProps(...props) {
756
+ this.allowedErrorProps.push(...props);
1913
757
  }
1914
- async logout() {
1915
- return this.trpc.auth.logout.mutate();
758
+ }
759
+ SuperJSON.defaultInstance = new SuperJSON();
760
+ SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
761
+ SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
762
+ SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
763
+ SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
764
+ SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
765
+ SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
766
+ SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
767
+ SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
768
+ SuperJSON.serialize;
769
+ SuperJSON.deserialize;
770
+ SuperJSON.stringify;
771
+ SuperJSON.parse;
772
+ SuperJSON.registerClass;
773
+ SuperJSON.registerCustom;
774
+ SuperJSON.registerSymbol;
775
+ SuperJSON.allowErrorProps;
776
+ const WS_KEEP_ALIVE_INTERVAL_MS = 1e4;
777
+ const WS_KEEP_ALIVE_PONG_TIMEOUT_MS = 3e3;
778
+ const WS_RECONNECT_RETRY_DELAY_MS = 2e3;
779
+ const WS_RECONNECT_MAX_RETRY_DELAY_MS = 3e4;
780
+ class System {
781
+ /** Active server base URL. Mutable via `switchServerUrl()` so the
782
+ * endpoint-race helper can pivot the transport onto a LAN candidate
783
+ * after the initial public-URL bootstrap. */
784
+ _serverUrl;
785
+ useWs;
786
+ baseRetryMs;
787
+ maxRetryMs;
788
+ onConnectionChange;
789
+ token;
790
+ _trpcClient;
791
+ _wsClient = null;
792
+ // Mirror — owns binding cache + state mirror + lifecycle listeners.
793
+ // Lazily initialised on `init()`. Subsequent `reconnect()` disposes
794
+ // the old mirror and rebuilds against the new tRPC client.
795
+ mirror = null;
796
+ mirrorInit = null;
797
+ // Transport-readiness probe state. `connected` flips true the first
798
+ // time `auth.me` succeeds against the current tRPC client; resets
799
+ // on every `reconnect()` / `close()` so the next consumer waits for
800
+ // a fresh handshake before issuing queries.
801
+ connected = false;
802
+ connectedPromise = null;
803
+ // System-cap namespaces — populated in the constructor from
804
+ // `createSystemProxy(api)`. Each namespace is a `Pick<InferProvider<typeof cap>, …>`
805
+ // shape generated by `scripts/generate-system-proxy.ts`.
806
+ _systemProxy;
807
+ // Connection-version + listener bookkeeping for the admin UI's
808
+ // reconnect watchdog.
809
+ _connectionVersion = 0;
810
+ connectionListeners = /* @__PURE__ */ new Set();
811
+ constructor(config) {
812
+ this._serverUrl = config.serverUrl.replace(/\/+$/, "");
813
+ this.token = config.token;
814
+ const isBrowser = typeof window !== "undefined";
815
+ this.useWs = config.useWebSocket ?? isBrowser;
816
+ this.onConnectionChange = config.onConnectionChange;
817
+ this.baseRetryMs = config.retryDelayMs ?? WS_RECONNECT_RETRY_DELAY_MS;
818
+ this.maxRetryMs = config.maxRetryDelayMs ?? WS_RECONNECT_MAX_RETRY_DELAY_MS;
819
+ this._trpcClient = this.buildTrpcClient();
820
+ this._systemProxy = types.createSystemProxy(this._trpcClient);
1916
821
  }
1917
- // ─── System ────────────────────────────────────────────────────────
1918
- async getSystemInfo() {
1919
- return this.trpc.system.info.query();
822
+ // ── Connection state ─────────────────────────────────────────────
823
+ /** Active server base URL (no trailing slash). */
824
+ get serverUrl() {
825
+ return this._serverUrl;
1920
826
  }
1921
- async getFeatureFlags() {
1922
- return this.trpc.system.featureFlags.query();
827
+ get connectionVersion() {
828
+ return this._connectionVersion;
1923
829
  }
1924
- // ─── Providers ─────────────────────────────────────────────────────
1925
- async listProviders() {
1926
- return this.trpc.providers.list.query();
830
+ /**
831
+ * Subscribe to connection-state transitions. Called with `('connected'
832
+ * | 'disconnected' | 'connecting', version)` whenever the SDK opens,
833
+ * closes, or starts a manual reconnect. Listener errors are swallowed
834
+ * so a misbehaving consumer cannot break the SDK's event loop.
835
+ */
836
+ subscribeConnectionEvents(cb) {
837
+ this.connectionListeners.add(cb);
838
+ return () => {
839
+ this.connectionListeners.delete(cb);
840
+ };
1927
841
  }
1928
- async getProvider(providerId) {
1929
- return this.trpc.providers.get.query({
1930
- id: providerId
1931
- });
842
+ emitConnectionEvent(state) {
843
+ try {
844
+ this.onConnectionChange?.(state);
845
+ } catch {
846
+ }
847
+ for (const l of this.connectionListeners) {
848
+ try {
849
+ l(state, this._connectionVersion);
850
+ } catch {
851
+ }
852
+ }
1932
853
  }
1933
- async startProvider(providerId) {
1934
- return this.trpc.providers.start.mutate({
1935
- id: providerId
1936
- });
854
+ // ── Lifecycle ────────────────────────────────────────────────────
855
+ /**
856
+ * Wait until the underlying tRPC transport is connected AND the
857
+ * server has responded to a cheap auth round-trip (`auth.me`). This
858
+ * is the canonical "ready to issue queries" gate.
859
+ *
860
+ * Why a probe, not just `ws.readyState === OPEN`?
861
+ * The WS handshake completes asynchronously: tRPC's `wsLink`
862
+ * queues outgoing messages and only flushes them after `open()`
863
+ * resolves (post `connectionParams` send). On the server, the
864
+ * tRPC context is created lazily once the connectionParams
865
+ * message is received. A query fired between WS-open and
866
+ * connection-params-processed is technically queued by tRPC, but
867
+ * the auth context for that query is only resolved once the
868
+ * handshake message is decoded server-side. A probe round-trip is
869
+ * the safest way to confirm both sides have agreed on the auth
870
+ * identity before the React tree starts firing parallel queries
871
+ * (which can otherwise land before any addon-side service
872
+ * discovery has settled, returning empty results that get cached).
873
+ *
874
+ * Idempotent — concurrent callers await the same in-flight Promise.
875
+ * Bounded by `timeoutMs` (default 15s) — beyond which a
876
+ * `Error('System.awaitConnected: probe timed out after Xms')` is
877
+ * thrown so the host can render a clear error state instead of
878
+ * hanging on a bricked socket.
879
+ */
880
+ async awaitConnected(timeoutMs) {
881
+ if (this.connected) return;
882
+ if (this.connectedPromise) return this.connectedPromise;
883
+ const effectiveTimeoutMs = timeoutMs ?? 15e3;
884
+ this.connectedPromise = (async () => {
885
+ const probe = this._trpcClient.auth.me.query();
886
+ if (!Number.isFinite(effectiveTimeoutMs)) {
887
+ await probe;
888
+ } else {
889
+ await new Promise((resolve, reject) => {
890
+ const timer = setTimeout(
891
+ () => reject(new Error(`System.awaitConnected: probe timed out after ${effectiveTimeoutMs}ms`)),
892
+ effectiveTimeoutMs
893
+ );
894
+ probe.then(
895
+ () => {
896
+ clearTimeout(timer);
897
+ resolve();
898
+ },
899
+ (err) => {
900
+ clearTimeout(timer);
901
+ reject(err instanceof Error ? err : new Error(String(err)));
902
+ }
903
+ );
904
+ });
905
+ }
906
+ this.connected = true;
907
+ })();
908
+ try {
909
+ await this.connectedPromise;
910
+ } finally {
911
+ this.connectedPromise = null;
912
+ }
1937
913
  }
1938
- async stopProvider(providerId) {
1939
- return this.trpc.providers.stop.mutate({
1940
- id: providerId
914
+ /**
915
+ * Warm-boot the device mirror. Awaits the transport probe first
916
+ * (`awaitConnected`) so the three mirror round-trips
917
+ * (`getAllBindings` + `getAllSnapshots` + `listAll`) cannot race
918
+ * against the WS auth handshake. Subsequent `getDevice(id)` calls
919
+ * are sync; live `device.*` event subscriptions keep the caches
920
+ * fresh.
921
+ *
922
+ * Idempotent — concurrent callers await the same in-flight Promise.
923
+ */
924
+ async init(timeoutMs) {
925
+ if (this.mirror?.isReady()) return;
926
+ if (this.mirrorInit) return this.mirrorInit;
927
+ const m = new types.SystemMirror(this._trpcClient);
928
+ this.mirror = m;
929
+ this.mirrorInit = (async () => {
930
+ await this.awaitConnected(timeoutMs);
931
+ await m.init(timeoutMs);
932
+ })().finally(() => {
933
+ this.mirrorInit = null;
1941
934
  });
935
+ return this.mirrorInit;
1942
936
  }
1943
- async listProviderTypes() {
1944
- return this.trpc.providerConfig.getAvailableTypes.query();
937
+ /** Promise that resolves once `init()` has completed. */
938
+ async awaitReady() {
939
+ if (this.mirror?.isReady()) return;
940
+ if (this.mirrorInit) return this.mirrorInit;
941
+ return this.init();
1945
942
  }
1946
- // ─── Devices ───────────────────────────────────────────────────────
1947
- async listDevices() {
1948
- return this.trpc.devices.list.query();
943
+ /** True after `init()` resolves. */
944
+ isReady() {
945
+ return this.mirror?.isReady() ?? false;
1949
946
  }
1950
- async getDevice(deviceId) {
1951
- return this.trpc.devices.get.query({
1952
- id: deviceId
1953
- });
1954
- }
1955
- async discoverDevices(providerId) {
1956
- return this.trpc.devices.discoverDevices.query({
1957
- providerId
1958
- });
947
+ /** True after the transport probe has succeeded at least once. */
948
+ isConnected() {
949
+ return this.connected;
1959
950
  }
1960
- async adoptDevice(providerId, externalId) {
1961
- return this.trpc.devices.adoptDevice.mutate({
1962
- providerId,
1963
- externalId
1964
- });
951
+ /**
952
+ * Force a fresh WebSocket handshake. Tears down the wsClient + tRPC
953
+ * client + mirror (the mirror captures the tRPC reference at
954
+ * construction time and would otherwise dispatch through a closed
955
+ * client) and rebuilds them. No-op for HTTP transport.
956
+ */
957
+ reconnect() {
958
+ if (!this.useWs) return;
959
+ this.emitConnectionEvent("connecting");
960
+ this._wsClient?.close();
961
+ this.disposeMirror();
962
+ this.connected = false;
963
+ this.connectedPromise = null;
964
+ this._trpcClient = this.buildTrpcClient();
965
+ this._systemProxy = types.createSystemProxy(this._trpcClient);
1965
966
  }
1966
- async createDevice(providerId, config) {
1967
- return this.trpc.devices.createDevice.mutate({
1968
- providerId,
1969
- config
1970
- });
967
+ /**
968
+ * Pivot the underlying tRPC transport onto a different base URL.
969
+ * Used by the endpoint-race flow: the SDK opens against the public
970
+ * URL the operator provided, calls `localNetwork.getConnectionEndpoints`
971
+ * to discover LAN candidates, races them, and (when a faster one wins)
972
+ * calls `switchServerUrl(winner)` to migrate every subsequent query
973
+ * onto the LAN path without losing auth state.
974
+ *
975
+ * Keeps the auth token. Tears down the WS + mirror and rebuilds them
976
+ * against the new URL — same machinery as `reconnect()` but with a
977
+ * different target.
978
+ */
979
+ switchServerUrl(nextUrl) {
980
+ const normalized = nextUrl.replace(/\/+$/, "");
981
+ if (normalized === this._serverUrl) return;
982
+ this._serverUrl = normalized;
983
+ this.reconnect();
1971
984
  }
1972
- /** Returns the URL path for a static asset served by an addon. */
1973
- getAddonAssetUrl(addonId, assetPath) {
1974
- return `/api/addon-assets/${addonId}/${assetPath}`;
985
+ /**
986
+ * Race the candidate base URLs reported by the hub's `local-network`
987
+ * cap, pick the fastest one that responds, and (if it's different
988
+ * from the current URL) pivot the transport onto it.
989
+ *
990
+ * Flow:
991
+ * 1. Query `localNetwork.getConnectionEndpoints({ port })` over the
992
+ * already-authenticated tRPC channel — the cap is auth-gated,
993
+ * so the LAN IPs never leak to anonymous callers.
994
+ * 2. For each candidate, fire a HEAD on `{baseUrl}/trpc/health`
995
+ * with a short timeout (default 1500ms). The first 2xx wins.
996
+ * 3. If the winner differs from `this.serverUrl`, call
997
+ * `switchServerUrl(winner)` and return it. Otherwise return
998
+ * the current URL unchanged.
999
+ *
1000
+ * Bounded — if every candidate times out we keep the current URL.
1001
+ * Idempotent — safe to call on every connect / reconnect / network
1002
+ * change event.
1003
+ */
1004
+ async raceConnectionEndpoints(options) {
1005
+ const timeoutMs = options?.perCandidateTimeoutMs ?? 1500;
1006
+ const url = (() => {
1007
+ try {
1008
+ return new URL(this._serverUrl);
1009
+ } catch {
1010
+ return null;
1011
+ }
1012
+ })();
1013
+ const port = url?.port ? Number(url.port) : url?.protocol === "https:" ? 443 : 80;
1014
+ const scheme = url?.protocol === "https:" ? "https" : "http";
1015
+ const proxy = this._trpcClient;
1016
+ const cap = proxy.localNetwork?.getConnectionEndpoints;
1017
+ if (!cap) {
1018
+ return { winner: this._serverUrl, switched: false };
1019
+ }
1020
+ let endpoints = [];
1021
+ try {
1022
+ const res = await cap.query({ port, ipv4Only: options?.ipv4Only, scheme });
1023
+ endpoints = res.endpoints;
1024
+ } catch {
1025
+ return { winner: this._serverUrl, switched: false };
1026
+ }
1027
+ if (endpoints.length === 0) {
1028
+ return { winner: this._serverUrl, switched: false };
1029
+ }
1030
+ const winner = await raceFastestEndpoint(endpoints.map((e) => e.baseUrl), timeoutMs);
1031
+ if (!winner || winner === this._serverUrl) {
1032
+ return { winner: winner ?? this._serverUrl, switched: false };
1033
+ }
1034
+ this.switchServerUrl(winner);
1035
+ return { winner, switched: true };
1975
1036
  }
1976
- // ─── Addons ────────────────────────────────────────────────────────
1977
- async listAddons() {
1978
- return this.trpc.addons.list.query();
1037
+ /** Tear down WS connection + mirror. The instance is unusable afterwards. */
1038
+ close() {
1039
+ this.disposeMirror();
1040
+ this.connected = false;
1041
+ this.connectedPromise = null;
1042
+ this._wsClient?.close();
1979
1043
  }
1980
- async getAddonConfigSchema(addonId) {
1981
- return this.trpc.addons.getConfigSchema.query({
1982
- addonId
1983
- });
1044
+ disposeMirror() {
1045
+ this.mirror?.dispose();
1046
+ this.mirror = null;
1047
+ this.mirrorInit = null;
1984
1048
  }
1985
- async getAddonConfig(addonId) {
1986
- return this.trpc.addons.getConfig.query({
1987
- addonId
1988
- });
1049
+ // ── Auth ──────────────────────────────────────────────────────────
1050
+ async login(username, password) {
1051
+ const result = await this._trpcClient.auth.login.mutate({ username, password });
1052
+ if (typeof result === "object" && result !== null && "token" in result) {
1053
+ const token = result.token;
1054
+ if (typeof token === "string") this.setToken(token);
1055
+ }
1056
+ return result;
1989
1057
  }
1990
- async updateAddonConfig(addonId, config) {
1991
- return this.trpc.addons.updateConfig.mutate({
1992
- addonId,
1993
- config
1994
- });
1058
+ async logout() {
1059
+ await this._trpcClient.auth.logout.mutate();
1995
1060
  }
1996
- async getAddonLogs(addonId, options) {
1997
- return this.trpc.addons.getLogs.query({
1998
- addonId,
1999
- ...options
2000
- });
1061
+ async getMe() {
1062
+ const me = await this._trpcClient.auth.me.query();
1063
+ return me;
2001
1064
  }
2002
- // ─── Known Faces ───────────────────────────────────────────────────
2003
- async listKnownFaces() {
2004
- return this.trpc.knownFaces.list.query();
1065
+ /** Update the auth token (e.g. after login or token refresh). */
1066
+ setToken(token) {
1067
+ this.token = token;
2005
1068
  }
2006
- async registerFace(label, cropBase64, group) {
2007
- return this.trpc.knownFaces.register.mutate({
2008
- label,
2009
- cropBase64,
2010
- group
2011
- });
1069
+ // ── Devices ──────────────────────────────────────────────────────
1070
+ /**
1071
+ * Synchronous snapshot of every device matching the optional filters.
1072
+ * Backed by the `SystemMirror` warm-boot cache — call `init()` first
1073
+ * (or `awaitReady()`) before invoking. Returns an empty array if the
1074
+ * mirror has not yet been booted.
1075
+ *
1076
+ * Each returned proxy has `binding` populated from the mirror's
1077
+ * binding cache (Phase 5 dedup), so consumers no longer need to
1078
+ * make a separate `deviceManager.getBindings` round-trip.
1079
+ */
1080
+ listDevices(filters) {
1081
+ if (!this.mirror) return [];
1082
+ const proxies = filters ? this.mirror.query(filters) : this.mirror.getAllDevices();
1083
+ return proxies.map((p) => this.attachBinding(p));
2012
1084
  }
2013
- // ─── Pipeline ──────────────────────────────────────────────────────
2014
- async listPipelines() {
2015
- return this.trpc.bridgePipeline.listAddons.query();
1085
+ /**
1086
+ * Sync lookup by numeric id. `null` if the mirror has not been booted
1087
+ * or the device is unknown.
1088
+ */
1089
+ getDevice(deviceId) {
1090
+ const proxy = this.mirror?.getDeviceById(deviceId) ?? null;
1091
+ return proxy ? this.attachBinding(proxy) : null;
1092
+ }
1093
+ /** Sync lookup by display name (exact match). */
1094
+ getDeviceByName(name) {
1095
+ const proxy = this.mirror?.getDeviceByName(name) ?? null;
1096
+ return proxy ? this.attachBinding(proxy) : null;
1097
+ }
1098
+ /** Sync lookup by stableId. */
1099
+ getDeviceByStableId(stableId) {
1100
+ const proxy = this.mirror?.getDeviceByStableId(stableId) ?? null;
1101
+ return proxy ? this.attachBinding(proxy) : null;
2016
1102
  }
2017
- async getPipelineStatus(deviceId) {
2018
- return this.trpc.bridgePipeline.getPipeline.query({
2019
- deviceId
2020
- });
1103
+ /**
1104
+ * Resolve when a device with `deviceId` becomes available. Resolves
1105
+ * immediately if already known; rejects with a timeout error
1106
+ * otherwise (default 30s).
1107
+ */
1108
+ async waitForDevice(deviceId, timeoutMs) {
1109
+ if (!this.mirror) await this.init();
1110
+ const proxy = await this.mirror.waitForDevice(deviceId, timeoutMs ?? 3e4);
1111
+ return this.attachBinding(proxy);
1112
+ }
1113
+ /** Subscribe to `device.registered` events. */
1114
+ onDeviceAdded(cb) {
1115
+ if (!this.mirror) {
1116
+ throw new Error("System.onDeviceAdded: call init() before subscribing");
1117
+ }
1118
+ return this.mirror.onDeviceAdded(cb);
2021
1119
  }
2022
- // ─── Agents ────────────────────────────────────────────────────────
2023
- async listAgents() {
2024
- return this.trpc.agents.listAgents.query();
1120
+ /** Subscribe to `device.unregistered` events. */
1121
+ onDeviceRemoved(cb) {
1122
+ if (!this.mirror) {
1123
+ throw new Error("System.onDeviceRemoved: call init() before subscribing");
1124
+ }
1125
+ return this.mirror.onDeviceRemoved(cb);
2025
1126
  }
2026
- async dispatchTask(agentId, task) {
2027
- return this.trpc.agents.dispatchTask.mutate({
2028
- capability: agentId,
2029
- input: task
2030
- });
1127
+ /**
1128
+ * Patch the proxy's `binding` field from the mirror's cache. The
1129
+ * generated `createDeviceProxy()` already sets `binding` to the
1130
+ * binding it was constructed with — this is a defensive overwrite
1131
+ * that uses the latest cached entry in case a `binding-changed`
1132
+ * event landed between proxy creation and access.
1133
+ */
1134
+ attachBinding(proxy) {
1135
+ const binding = this.lookupBinding(proxy.deviceId);
1136
+ if (binding === proxy.binding) return proxy;
1137
+ const writable = proxy;
1138
+ writable.binding = binding;
1139
+ return proxy;
2031
1140
  }
2032
- async getProcessTree() {
2033
- return this.trpc.agent.processTree.query();
1141
+ /** Fetch the latest cached binding from the mirror, or `null`. */
1142
+ lookupBinding(deviceId) {
1143
+ if (!this.mirror) return null;
1144
+ const proxy = this.mirror.getDeviceById(deviceId);
1145
+ return proxy?.binding ?? null;
2034
1146
  }
2035
- // ─── Bridge Pipeline ───────────────────────────────────────────────
2036
- async bridgeListAddons() {
2037
- return this.trpc.bridgePipeline.listAddons.query();
1147
+ // ── System caps ──────────────────────────────────────────────────
1148
+ //
1149
+ // One getter per `scope: 'system'` capability. The actual surface
1150
+ // comes from `createSystemProxy(api)` (codegen). Adding a new
1151
+ // system cap regenerates the proxy and the new namespace surfaces
1152
+ // automatically via `system.<newCap>.<method>(input)`.
1153
+ get addonPages() {
1154
+ return this._systemProxy.addonPages;
2038
1155
  }
2039
- async bridgeGetPipeline(deviceId) {
2040
- return this.trpc.bridgePipeline.getPipeline.query({
2041
- deviceId
2042
- });
1156
+ get addonSettings() {
1157
+ return this._systemProxy.addonSettings;
2043
1158
  }
2044
- async bridgeSetPipeline(deviceId, config) {
2045
- return this.trpc.bridgePipeline.setPipeline.mutate({
2046
- deviceId,
2047
- config
2048
- });
1159
+ get alerts() {
1160
+ return this._systemProxy.alerts;
2049
1161
  }
2050
- async bridgeValidatePipeline(config) {
2051
- return this.trpc.bridgePipeline.validatePipeline.query(config);
1162
+ get audioAnalyzer() {
1163
+ return this._systemProxy.audioAnalyzer;
2052
1164
  }
2053
- async bridgeGetAddonConfig(addonId) {
2054
- return this.trpc.bridgePipeline.getAddonConfig.query({
2055
- addonId
2056
- });
1165
+ get audioCodec() {
1166
+ return this._systemProxy.audioCodec;
2057
1167
  }
2058
- async bridgeSetAddonConfig(addonId, config) {
2059
- return this.trpc.bridgePipeline.setAddonConfig.mutate({
2060
- addonId,
2061
- config
2062
- });
1168
+ get backup() {
1169
+ return this._systemProxy.backup;
2063
1170
  }
2064
- // ─── Addon Packages ────────────────────────────────────────────────
2065
- async bridgeListPackages() {
2066
- return this.trpc.addons.listPackages.query();
1171
+ get decoder() {
1172
+ return this._systemProxy.decoder;
2067
1173
  }
2068
- async bridgeListAddonsPackages() {
2069
- return this.trpc.addons.list.query();
1174
+ get deviceManager() {
1175
+ return this._systemProxy.deviceManager;
2070
1176
  }
2071
- async bridgeInstallPackage(packageName, version) {
2072
- return this.trpc.addons.installPackage.mutate({
2073
- packageName,
2074
- version
2075
- });
1177
+ get deviceProvider() {
1178
+ return this._systemProxy.deviceProvider;
2076
1179
  }
2077
- async bridgeUninstallPackage(packageName) {
2078
- return this.trpc.addons.uninstallPackage.mutate({
2079
- packageName
2080
- });
1180
+ get deviceState() {
1181
+ return this._systemProxy.deviceState;
2081
1182
  }
2082
- // ─── Recording ─────────────────────────────────────────────────────
2083
- async getRecordingConfig(deviceId) {
2084
- return this.trpc.recording.getConfig.query({
2085
- deviceId
2086
- });
1183
+ get metricsProvider() {
1184
+ return this._systemProxy.metricsProvider;
2087
1185
  }
2088
- async getRecordingPolicy(deviceId) {
2089
- return this.trpc.recording.getPolicy.query({
2090
- deviceId
2091
- });
1186
+ get notificationOutput() {
1187
+ return this._systemProxy.notificationOutput;
2092
1188
  }
2093
- async getRecordingPolicyStatus(deviceId) {
2094
- return this.trpc.recording.getPolicyStatus.query({
2095
- deviceId
2096
- });
1189
+ get pipelineExecutor() {
1190
+ return this._systemProxy.pipelineExecutor;
2097
1191
  }
2098
- async getRecordingSegments(deviceId, streamId, startTime, endTime) {
2099
- return this.trpc.recording.getSegments.query({
2100
- deviceId,
2101
- streamId,
2102
- startTime,
2103
- endTime
2104
- });
1192
+ get pipelineOrchestrator() {
1193
+ return this._systemProxy.pipelineOrchestrator;
2105
1194
  }
2106
- // ─── Events ────────────────────────────────────────────────────────
2107
- async getEvents(deviceId, options) {
2108
- return this.trpc.events.query.query({
2109
- deviceId,
2110
- ...options
2111
- });
1195
+ get pipelineRunner() {
1196
+ return this._systemProxy.pipelineRunner;
2112
1197
  }
2113
- // ─── Logs ──────────────────────────────────────────────────────────
2114
- async getLogs(options) {
2115
- return this.trpc.logs.query.query(options ?? {});
1198
+ get platformProbe() {
1199
+ return this._systemProxy.platformProbe;
2116
1200
  }
2117
- // ─── REPL ──────────────────────────────────────────────────────────
2118
- async replEval(code, scope) {
2119
- return this.trpc.repl.execute.mutate({
2120
- code,
2121
- scope: scope ?? {
2122
- type: "system"
2123
- }
2124
- });
1201
+ get recordingEngine() {
1202
+ return this._systemProxy.recordingEngine;
2125
1203
  }
2126
- // ─── Users ─────────────────────────────────────────────────────────
2127
- async listUsers() {
2128
- return this.trpc.users.list.query();
1204
+ get settingsStore() {
1205
+ return this._systemProxy.settingsStore;
2129
1206
  }
2130
- async createUser(username, password, role) {
2131
- return this.trpc.users.create.mutate({
2132
- username,
2133
- password,
2134
- role
2135
- });
1207
+ get storage() {
1208
+ return this._systemProxy.storage;
2136
1209
  }
2137
- // ─── Session Tracker ───────────────────────────────────────────────
2138
- async getTrackingSessions(deviceId) {
2139
- return this.trpc.session.getActiveTracks.query({
2140
- deviceId
2141
- });
1210
+ get streamBroker() {
1211
+ return this._systemProxy.streamBroker;
2142
1212
  }
2143
- // ─── Processes ─────────────────────────────────────────────────────
2144
- async listProcesses() {
2145
- return this.trpc.processes.listProcesses.query();
1213
+ get turnProvider() {
1214
+ return this._systemProxy.turnProvider;
2146
1215
  }
2147
- async enableProvider(providerId) {
2148
- return this.trpc.processes.enableProvider.mutate({
2149
- id: providerId
2150
- });
1216
+ get userManagement() {
1217
+ return this._systemProxy.userManagement;
2151
1218
  }
2152
- async disableProvider(providerId) {
2153
- return this.trpc.processes.disableProvider.mutate({
2154
- id: providerId
2155
- });
1219
+ // ── Live events ──────────────────────────────────────────────────
1220
+ /**
1221
+ * Subscribe to a single event category. Returns an unsubscribe
1222
+ * handle. Errors thrown by the listener are swallowed so a single
1223
+ * misbehaving consumer cannot tear down the WS subscription.
1224
+ *
1225
+ * Categories should be values from the `EventCategory` enum
1226
+ * (`@camstack/types`) — passing a raw string works for forward-compat
1227
+ * but loses type safety. The SDK forwards the value verbatim to the
1228
+ * server's `live.onEvent` subscription.
1229
+ */
1230
+ subscribeEvent(category, cb) {
1231
+ const sub = this._trpcClient.live.onEvent.subscribe(
1232
+ { category },
1233
+ {
1234
+ onData: (event) => {
1235
+ try {
1236
+ cb(event);
1237
+ } catch {
1238
+ }
1239
+ }
1240
+ }
1241
+ );
1242
+ return () => {
1243
+ try {
1244
+ sub.unsubscribe();
1245
+ } catch {
1246
+ }
1247
+ };
2156
1248
  }
2157
- // ─── Settings ──────────────────────────────────────────────────────
2158
- /** Fetch the UI schema for a single section, or all sections if omitted. */
2159
- async getSettingsSchema(section) {
2160
- return this.trpc.settings.getSchema.query({
2161
- section
2162
- });
1249
+ // ── Escape hatches ───────────────────────────────────────────────
1250
+ //
1251
+ // Kept public so the ui-library `<TrpcProvider>` can seed React
1252
+ // Query with the same WebSocket connection during Phase 2. Phase 4
1253
+ // is expected to revisit whether either field can be hidden.
1254
+ /** Direct tRPC client. Read once per call; rebuilt on `reconnect()`. */
1255
+ get trpcClient() {
1256
+ return this._trpcClient;
2163
1257
  }
2164
- async getSettings(section) {
2165
- return this.trpc.settings.get.query({
2166
- section
1258
+ /**
1259
+ * Underlying WSClient (or `null` for HTTP transport). Used by
1260
+ * advanced consumers that need direct access to the WebSocket
1261
+ * (e.g. for keep-alive metrics). Rebuilt on `reconnect()`.
1262
+ */
1263
+ get wsClient() {
1264
+ return this._wsClient;
1265
+ }
1266
+ // ── Internals ────────────────────────────────────────────────────
1267
+ buildTrpcClient() {
1268
+ const headers = () => {
1269
+ const h = {};
1270
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
1271
+ return h;
1272
+ };
1273
+ if (this.useWs) {
1274
+ const wsUrl = this._serverUrl.replace(/^http/, "ws") + "/trpc";
1275
+ const baseRetryMs = this.baseRetryMs;
1276
+ const maxRetryMs = this.maxRetryMs;
1277
+ this._wsClient = client.createWSClient({
1278
+ url: wsUrl,
1279
+ connectionParams: () => ({ token: this.token }),
1280
+ retryDelayMs: (attemptIndex) => Math.min(baseRetryMs * Math.pow(2, attemptIndex), maxRetryMs),
1281
+ keepAlive: {
1282
+ enabled: true,
1283
+ intervalMs: WS_KEEP_ALIVE_INTERVAL_MS,
1284
+ pongTimeoutMs: WS_KEEP_ALIVE_PONG_TIMEOUT_MS
1285
+ },
1286
+ onOpen: () => {
1287
+ this._connectionVersion += 1;
1288
+ this.emitConnectionEvent("connected");
1289
+ },
1290
+ onClose: () => {
1291
+ this.emitConnectionEvent("disconnected");
1292
+ }
1293
+ });
1294
+ return client.createTRPCClient({
1295
+ links: [client.wsLink({ client: this._wsClient, transformer: SuperJSON })]
1296
+ });
1297
+ }
1298
+ this._wsClient = null;
1299
+ return client.createTRPCClient({
1300
+ links: [client.httpLink({ url: `${this._serverUrl}/trpc`, headers, transformer: SuperJSON })]
2167
1301
  });
2168
1302
  }
2169
- async updateSettings(section, data) {
2170
- return this.trpc.settings.update.mutate({
2171
- section,
2172
- data
2173
- });
1303
+ }
1304
+ function createSystem(config) {
1305
+ return new System(config);
1306
+ }
1307
+ async function raceFastestEndpoint(candidates, timeoutMs) {
1308
+ if (candidates.length === 0) return null;
1309
+ if (typeof fetch !== "function") return candidates[0] ?? null;
1310
+ const pageIsHttps = typeof window !== "undefined" && typeof window.location !== "undefined" && window.location.protocol === "https:";
1311
+ const reachable = pageIsHttps ? candidates.filter((u) => u.toLowerCase().startsWith("https://")) : candidates;
1312
+ if (reachable.length === 0) return null;
1313
+ const controllers = reachable.map(() => new AbortController());
1314
+ const probes = reachable.map(async (baseUrl, i) => {
1315
+ const ctrl = controllers[i];
1316
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
1317
+ try {
1318
+ const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/trpc/health`, {
1319
+ method: "GET",
1320
+ signal: ctrl.signal,
1321
+ // Cross-origin probes from a browser sandbox are fine — the
1322
+ // /trpc/health response is open-CORS by the Fastify default.
1323
+ // No credentials needed (this is a transport-quality probe,
1324
+ // not an auth round-trip).
1325
+ credentials: "omit"
1326
+ });
1327
+ if (!res.ok) throw new Error(`${res.status}`);
1328
+ return baseUrl;
1329
+ } finally {
1330
+ clearTimeout(timer);
1331
+ }
1332
+ });
1333
+ try {
1334
+ const winner = await Promise.any(probes);
1335
+ for (const c of controllers) {
1336
+ try {
1337
+ c.abort();
1338
+ } catch {
1339
+ }
1340
+ }
1341
+ return winner;
1342
+ } catch {
1343
+ return null;
2174
1344
  }
2175
- };
2176
- function createBackendClient(config) {
2177
- return new BackendClient(config);
2178
1345
  }
2179
- __name(createBackendClient, "createBackendClient");
2180
-
2181
- // src/detection.ts
2182
- var DetectionClass = /* @__PURE__ */ (function(DetectionClass2) {
1346
+ var DetectionClass = /* @__PURE__ */ ((DetectionClass2) => {
2183
1347
  DetectionClass2["Motion"] = "motion";
2184
1348
  DetectionClass2["Person"] = "person";
2185
1349
  DetectionClass2["Vehicle"] = "vehicle";
@@ -2191,8 +1355,8 @@ var DetectionClass = /* @__PURE__ */ (function(DetectionClass2) {
2191
1355
  DetectionClass2["Doorbell"] = "doorbell";
2192
1356
  DetectionClass2["Sensor"] = "sensor";
2193
1357
  return DetectionClass2;
2194
- })({});
2195
- var animalClasses = [
1358
+ })(DetectionClass || {});
1359
+ const animalClasses = [
2196
1360
  "animal",
2197
1361
  "dog_cat",
2198
1362
  "dog",
@@ -2220,7 +1384,7 @@ var animalClasses = [
2220
1384
  "turtle",
2221
1385
  "lizard"
2222
1386
  ];
2223
- var personClasses = [
1387
+ const personClasses = [
2224
1388
  "person",
2225
1389
  "people",
2226
1390
  "pedestrian",
@@ -2234,7 +1398,7 @@ var personClasses = [
2234
1398
  "head",
2235
1399
  "body"
2236
1400
  ];
2237
- var vehicleClasses = [
1401
+ const vehicleClasses = [
2238
1402
  "vehicle",
2239
1403
  "car",
2240
1404
  "truck",
@@ -2253,7 +1417,7 @@ var vehicleClasses = [
2253
1417
  "ship",
2254
1418
  "helicopter"
2255
1419
  ];
2256
- var faceClasses = [
1420
+ const faceClasses = [
2257
1421
  "face",
2258
1422
  "eyes",
2259
1423
  "nose",
@@ -2281,7 +1445,7 @@ var faceClasses = [
2281
1445
  "facial_landmark",
2282
1446
  "facial_keypoint"
2283
1447
  ];
2284
- var licensePlateClasses = [
1448
+ const licensePlateClasses = [
2285
1449
  "plate",
2286
1450
  "license_plate",
2287
1451
  "front_plate",
@@ -2305,19 +1469,13 @@ var licensePlateClasses = [
2305
1469
  "obscured_plate",
2306
1470
  "dirty_plate"
2307
1471
  ];
2308
- var motionClasses = [
2309
- "motion",
2310
- "movement",
2311
- "other"
2312
- ];
2313
- var packageClasses = [
2314
- "package",
2315
- "packet"
2316
- ];
2317
- var audioClasses = [
1472
+ const motionClasses = ["motion", "movement", "other"];
1473
+ const packageClasses = ["package", "packet"];
1474
+ const audioClasses = [
2318
1475
  "audio"
1476
+ /* Audio */
2319
1477
  ];
2320
- var audioLabelClasses = [
1478
+ const audioLabelClasses = [
2321
1479
  "speech",
2322
1480
  "scream",
2323
1481
  "babbling",
@@ -2378,11 +1536,8 @@ var audioLabelClasses = [
2378
1536
  "dog",
2379
1537
  "dogs"
2380
1538
  ];
2381
- var doorbellClasses = [
2382
- "doorbell",
2383
- "ring"
2384
- ];
2385
- var sensorLabelClasses = [
1539
+ const doorbellClasses = ["doorbell", "ring"];
1540
+ const sensorLabelClasses = [
2386
1541
  "lock",
2387
1542
  "binary",
2388
1543
  "flood",
@@ -2393,92 +1548,113 @@ var sensorLabelClasses = [
2393
1548
  "flooded",
2394
1549
  "entry_open"
2395
1550
  ];
2396
- var detectionClassesDefaultMap = {
1551
+ const detectionClassesDefaultMap = {
2397
1552
  ...animalClasses.reduce((tot, curr) => ({
2398
1553
  ...tot,
2399
1554
  [curr]: "animal"
1555
+ /* Animal */
2400
1556
  }), {}),
2401
1557
  ...personClasses.reduce((tot, curr) => ({
2402
1558
  ...tot,
2403
1559
  [curr]: "person"
1560
+ /* Person */
2404
1561
  }), {}),
2405
1562
  ...vehicleClasses.reduce((tot, curr) => ({
2406
1563
  ...tot,
2407
1564
  [curr]: "vehicle"
1565
+ /* Vehicle */
2408
1566
  }), {}),
2409
1567
  ...motionClasses.reduce((tot, curr) => ({
2410
1568
  ...tot,
2411
1569
  [curr]: "motion"
1570
+ /* Motion */
2412
1571
  }), {}),
2413
1572
  ...packageClasses.reduce((tot, curr) => ({
2414
1573
  ...tot,
2415
1574
  [curr]: "package"
1575
+ /* Package */
2416
1576
  }), {}),
2417
1577
  ...faceClasses.reduce((tot, curr) => ({
2418
1578
  ...tot,
2419
1579
  [curr]: "face"
1580
+ /* Face */
2420
1581
  }), {}),
2421
1582
  ...licensePlateClasses.reduce((tot, curr) => ({
2422
1583
  ...tot,
2423
1584
  [curr]: "plate"
1585
+ /* Plate */
2424
1586
  }), {}),
2425
1587
  ...audioClasses.reduce((tot, curr) => ({
2426
1588
  ...tot,
2427
1589
  [curr]: "audio"
1590
+ /* Audio */
2428
1591
  }), {}),
2429
1592
  ...audioLabelClasses.reduce((tot, curr) => ({
2430
1593
  ...tot,
2431
1594
  [curr]: "audio"
1595
+ /* Audio */
2432
1596
  }), {}),
2433
1597
  ...doorbellClasses.reduce((tot, curr) => ({
2434
1598
  ...tot,
2435
1599
  [curr]: "doorbell"
1600
+ /* Doorbell */
2436
1601
  }), {}),
2437
1602
  ...sensorLabelClasses.reduce((tot, curr) => ({
2438
1603
  ...tot,
2439
1604
  [curr]: "sensor"
1605
+ /* Sensor */
2440
1606
  }), {})
2441
1607
  };
2442
- var isFaceClassname = /* @__PURE__ */ __name((c) => faceClasses.includes(c), "isFaceClassname");
2443
- var isPlateClassname = /* @__PURE__ */ __name((c) => licensePlateClasses.includes(c), "isPlateClassname");
2444
- var isAnimalClassname = /* @__PURE__ */ __name((c) => animalClasses.includes(c), "isAnimalClassname");
2445
- var isPersonClassname = /* @__PURE__ */ __name((c) => personClasses.includes(c), "isPersonClassname");
2446
- var isVehicleClassname = /* @__PURE__ */ __name((c) => vehicleClasses.includes(c), "isVehicleClassname");
2447
- var isMotionClassname = /* @__PURE__ */ __name((c) => motionClasses.includes(c), "isMotionClassname");
2448
- var isDoorbellClassname = /* @__PURE__ */ __name((c) => doorbellClasses.includes(c), "isDoorbellClassname");
2449
- var isPackageClassname = /* @__PURE__ */ __name((c) => packageClasses.includes(c), "isPackageClassname");
2450
- var isAudioClassname = /* @__PURE__ */ __name((c) => audioClasses.includes(c) || audioLabelClasses.includes(c), "isAudioClassname");
2451
- var isSensorLabelClassname = /* @__PURE__ */ __name((c) => sensorLabelClasses.includes(c), "isSensorLabelClassname");
2452
- var isLabelDetection = /* @__PURE__ */ __name((c) => isFaceClassname(c) || isPlateClassname(c), "isLabelDetection");
2453
- var getParentClass = /* @__PURE__ */ __name((className) => detectionClassesDefaultMap[className], "getParentClass");
2454
- var getParentDetectionClass = /* @__PURE__ */ __name((det) => {
1608
+ const isFaceClassname = (c) => faceClasses.includes(c);
1609
+ const isPlateClassname = (c) => licensePlateClasses.includes(c);
1610
+ const isAnimalClassname = (c) => animalClasses.includes(c);
1611
+ const isPersonClassname = (c) => personClasses.includes(c);
1612
+ const isVehicleClassname = (c) => vehicleClasses.includes(c);
1613
+ const isMotionClassname = (c) => motionClasses.includes(c);
1614
+ const isDoorbellClassname = (c) => doorbellClasses.includes(c);
1615
+ const isPackageClassname = (c) => packageClasses.includes(c);
1616
+ const isAudioClassname = (c) => audioClasses.includes(c) || audioLabelClasses.includes(c);
1617
+ const isSensorLabelClassname = (c) => sensorLabelClasses.includes(c);
1618
+ const isLabelDetection = (c) => isFaceClassname(c) || isPlateClassname(c);
1619
+ const getParentClass = (className) => detectionClassesDefaultMap[className];
1620
+ const getParentDetectionClass = (det) => {
2455
1621
  const { className } = det;
2456
1622
  const baseMap = {
2457
- ["face"]: "person",
2458
- ["plate"]: "vehicle"
1623
+ [
1624
+ "face"
1625
+ /* Face */
1626
+ ]: "person",
1627
+ [
1628
+ "plate"
1629
+ /* Plate */
1630
+ ]: "vehicle"
1631
+ /* Vehicle */
2459
1632
  };
2460
1633
  const parentGroup = detectionClassesDefaultMap[className];
2461
1634
  if (parentGroup && parentGroup !== className) return parentGroup;
2462
1635
  return baseMap[className];
2463
- }, "getParentDetectionClass");
2464
- var defaultDetectionClasses = Object.values(DetectionClass);
2465
- var DEFAULT_ENABLED_CLASSES = defaultDetectionClasses.filter((c) => c !== "motion");
2466
- var TIMELINE_PRESET_CRITICAL = [
1636
+ };
1637
+ const defaultDetectionClasses = Object.values(DetectionClass);
1638
+ const DEFAULT_ENABLED_CLASSES = defaultDetectionClasses.filter(
1639
+ (c) => c !== "motion"
1640
+ /* Motion */
1641
+ );
1642
+ const TIMELINE_PRESET_CRITICAL = [
2467
1643
  "person",
2468
1644
  "doorbell",
2469
1645
  "package"
1646
+ /* Package */
2470
1647
  ];
2471
- var TIMELINE_PRESET_IMPORTANT = [
1648
+ const TIMELINE_PRESET_IMPORTANT = [
2472
1649
  ...TIMELINE_PRESET_CRITICAL,
2473
1650
  "vehicle",
2474
1651
  "animal",
2475
1652
  "audio",
2476
1653
  "face",
2477
1654
  "plate"
1655
+ /* Plate */
2478
1656
  ];
2479
- var TIMELINE_PRESET_ALL = [
2480
- ...DEFAULT_ENABLED_CLASSES
2481
- ];
1657
+ const TIMELINE_PRESET_ALL = [...DEFAULT_ENABLED_CLASSES];
2482
1658
  function getClassesForTimelinePreset(preset, customClasses) {
2483
1659
  switch (preset) {
2484
1660
  case "critical":
@@ -2493,10 +1669,7 @@ function getClassesForTimelinePreset(preset, customClasses) {
2493
1669
  return DEFAULT_ENABLED_CLASSES;
2494
1670
  }
2495
1671
  }
2496
- __name(getClassesForTimelinePreset, "getClassesForTimelinePreset");
2497
-
2498
- // src/devices.ts
2499
- var RAW_TO_CANONICAL = {
1672
+ const RAW_TO_CANONICAL = {
2500
1673
  // Scrypted PascalCase
2501
1674
  Light: "light",
2502
1675
  Switch: "switch",
@@ -2527,7 +1700,7 @@ var RAW_TO_CANONICAL = {
2527
1700
  media_player: "media_player",
2528
1701
  script: "script"
2529
1702
  };
2530
- var HA_DOMAIN_TYPE_MAP = {
1703
+ const HA_DOMAIN_TYPE_MAP = {
2531
1704
  light: "light",
2532
1705
  switch: "switch",
2533
1706
  input_boolean: "switch",
@@ -2555,7 +1728,7 @@ var HA_DOMAIN_TYPE_MAP = {
2555
1728
  weather: "weather",
2556
1729
  water_heater: "climate"
2557
1730
  };
2558
- var SCRYPTED_TYPE_TO_CANONICAL = {
1731
+ const SCRYPTED_TYPE_TO_CANONICAL = {
2559
1732
  Light: "light",
2560
1733
  Switch: "switch",
2561
1734
  WindowCovering: "cover",
@@ -2579,8 +1752,7 @@ function getCanonicalDeviceType(rawType) {
2579
1752
  const lower = rawType.toLowerCase();
2580
1753
  return RAW_TO_CANONICAL[lower] ?? null;
2581
1754
  }
2582
- __name(getCanonicalDeviceType, "getCanonicalDeviceType");
2583
- var ELIGIBLE_SCRYPTED_DEVICE_TYPES = [
1755
+ const ELIGIBLE_SCRYPTED_DEVICE_TYPES = [
2584
1756
  "Entry",
2585
1757
  "Light",
2586
1758
  "Switch",
@@ -2593,8 +1765,8 @@ var ELIGIBLE_SCRYPTED_DEVICE_TYPES = [
2593
1765
  "Select",
2594
1766
  "Program"
2595
1767
  ];
2596
- var ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET = new Set(ELIGIBLE_SCRYPTED_DEVICE_TYPES);
2597
- var ELIGIBLE_HA_DOMAINS = [
1768
+ const ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET = new Set(ELIGIBLE_SCRYPTED_DEVICE_TYPES);
1769
+ const ELIGIBLE_HA_DOMAINS = [
2598
1770
  "light",
2599
1771
  "switch",
2600
1772
  "input_boolean",
@@ -2609,179 +1781,109 @@ var ELIGIBLE_HA_DOMAINS = [
2609
1781
  "media_player",
2610
1782
  "script"
2611
1783
  ];
2612
- var ELIGIBLE_HA_DOMAINS_SET = new Set(ELIGIBLE_HA_DOMAINS);
2613
-
2614
- // src/features.ts
2615
- var FEATURE_MATRIX = [
1784
+ const ELIGIBLE_HA_DOMAINS_SET = new Set(ELIGIBLE_HA_DOMAINS);
1785
+ const FEATURE_MATRIX = [
2616
1786
  {
2617
1787
  id: "liveStream",
2618
1788
  label: "Live Stream",
2619
- sources: {
2620
- frigate: true,
2621
- scrypted: true,
2622
- rtsp: true
2623
- },
1789
+ sources: { frigate: true, scrypted: true, rtsp: true },
2624
1790
  adapterMethod: "getLiveStream"
2625
1791
  },
2626
1792
  {
2627
1793
  id: "multiResolution",
2628
1794
  label: "Multi-Resolution",
2629
- sources: {
2630
- frigate: true,
2631
- scrypted: true,
2632
- rtsp: false
2633
- },
1795
+ sources: { frigate: true, scrypted: true, rtsp: false },
2634
1796
  adapterMethod: "getResolutions"
2635
1797
  },
2636
1798
  {
2637
1799
  id: "motion",
2638
1800
  label: "Motion Detection",
2639
- sources: {
2640
- frigate: false,
2641
- scrypted: true,
2642
- rtsp: false
2643
- },
1801
+ sources: { frigate: false, scrypted: true, rtsp: false },
2644
1802
  adapterMethod: "getMotion"
2645
1803
  },
2646
1804
  {
2647
1805
  id: "objectDetection",
2648
1806
  label: "Object Detection",
2649
- sources: {
2650
- frigate: false,
2651
- scrypted: true,
2652
- rtsp: false
2653
- },
1807
+ sources: { frigate: false, scrypted: true, rtsp: false },
2654
1808
  adapterMethod: "getObjectDetections"
2655
1809
  },
2656
1810
  {
2657
1811
  id: "audioVolume",
2658
1812
  label: "Audio Level",
2659
- sources: {
2660
- frigate: false,
2661
- scrypted: true,
2662
- rtsp: false
2663
- },
1813
+ sources: { frigate: false, scrypted: true, rtsp: false },
2664
1814
  adapterMethod: "getAudioVolume"
2665
1815
  },
2666
1816
  {
2667
1817
  id: "audioVolumes",
2668
1818
  label: "Audio Volumes (dBFS)",
2669
- sources: {
2670
- frigate: false,
2671
- scrypted: true,
2672
- rtsp: false
2673
- },
1819
+ sources: { frigate: false, scrypted: true, rtsp: false },
2674
1820
  adapterMethod: "getAudioVolumes"
2675
1821
  },
2676
1822
  {
2677
1823
  id: "ptz",
2678
1824
  label: "PTZ Control",
2679
- sources: {
2680
- frigate: false,
2681
- scrypted: true,
2682
- rtsp: false
2683
- },
1825
+ sources: { frigate: false, scrypted: true, rtsp: false },
2684
1826
  adapterMethod: "getPTZ"
2685
1827
  },
2686
1828
  {
2687
1829
  id: "intercom",
2688
1830
  label: "Intercom (Mic)",
2689
- sources: {
2690
- frigate: false,
2691
- scrypted: true,
2692
- rtsp: false
2693
- },
1831
+ sources: { frigate: false, scrypted: true, rtsp: false },
2694
1832
  adapterMethod: "getIntercomSupport"
2695
1833
  },
2696
1834
  {
2697
1835
  id: "deviceStatus",
2698
1836
  label: "Device Status",
2699
- sources: {
2700
- frigate: false,
2701
- scrypted: true,
2702
- rtsp: false
2703
- },
1837
+ sources: { frigate: false, scrypted: true, rtsp: false },
2704
1838
  adapterMethod: "getStatus"
2705
1839
  },
2706
1840
  {
2707
1841
  id: "timeline",
2708
1842
  label: "Detection Timeline",
2709
- sources: {
2710
- frigate: true,
2711
- scrypted: true,
2712
- rtsp: false
2713
- },
1843
+ sources: { frigate: true, scrypted: true, rtsp: false },
2714
1844
  adapterMethod: "getCameraDayData"
2715
1845
  },
2716
1846
  {
2717
1847
  id: "clusteredTimeline",
2718
1848
  label: "Clustered Timeline",
2719
- sources: {
2720
- frigate: true,
2721
- scrypted: true,
2722
- rtsp: false
2723
- },
1849
+ sources: { frigate: true, scrypted: true, rtsp: false },
2724
1850
  requiresBackend: true,
2725
1851
  adapterMethod: "getClusteredDayData"
2726
1852
  },
2727
1853
  {
2728
1854
  id: "detectionClasses",
2729
1855
  label: "Detection Classes",
2730
- sources: {
2731
- frigate: true,
2732
- scrypted: true,
2733
- rtsp: false
2734
- },
1856
+ sources: { frigate: true, scrypted: true, rtsp: false },
2735
1857
  adapterMethod: "getDetectionClasses"
2736
1858
  },
2737
1859
  {
2738
1860
  id: "videoClips",
2739
1861
  label: "Video Clips",
2740
- sources: {
2741
- frigate: true,
2742
- scrypted: true,
2743
- rtsp: false
2744
- },
1862
+ sources: { frigate: true, scrypted: true, rtsp: false },
2745
1863
  adapterMethod: "getVideoClips"
2746
1864
  },
2747
1865
  {
2748
1866
  id: "nvrPlayback",
2749
1867
  label: "NVR Playback",
2750
- sources: {
2751
- frigate: true,
2752
- scrypted: true,
2753
- rtsp: false
2754
- },
1868
+ sources: { frigate: true, scrypted: true, rtsp: false },
2755
1869
  adapterMethod: "getNvrPlaybackSupported"
2756
1870
  },
2757
1871
  {
2758
1872
  id: "nvrScrub",
2759
1873
  label: "NVR Scrub/Seek",
2760
- sources: {
2761
- frigate: false,
2762
- scrypted: true,
2763
- rtsp: false
2764
- },
1874
+ sources: { frigate: false, scrypted: true, rtsp: false },
2765
1875
  adapterMethod: "seekRecordingStream"
2766
1876
  },
2767
1877
  {
2768
1878
  id: "recordingThumbnail",
2769
1879
  label: "Recording Thumbnails",
2770
- sources: {
2771
- frigate: true,
2772
- scrypted: true,
2773
- rtsp: false
2774
- },
1880
+ sources: { frigate: true, scrypted: true, rtsp: false },
2775
1881
  adapterMethod: "getRecordingStreamThumbnail"
2776
1882
  },
2777
1883
  {
2778
1884
  id: "nvrSeekToLive",
2779
1885
  label: "Seek to Live",
2780
- sources: {
2781
- frigate: false,
2782
- scrypted: true,
2783
- rtsp: false
2784
- },
1886
+ sources: { frigate: false, scrypted: true, rtsp: false },
2785
1887
  adapterMethod: "seekNvrToLive"
2786
1888
  }
2787
1889
  ];
@@ -2792,17 +1894,12 @@ function isFeatureAvailable(featureId, source, platform) {
2792
1894
  if (entry.platforms && entry.platforms[platform] === false) return false;
2793
1895
  return true;
2794
1896
  }
2795
- __name(isFeatureAvailable, "isFeatureAvailable");
2796
1897
  function getSourceFeatures(source) {
2797
1898
  return FEATURE_MATRIX.filter((f) => f.sources[source]);
2798
1899
  }
2799
- __name(getSourceFeatures, "getSourceFeatures");
2800
1900
  function getBackendRequiredFeatures() {
2801
1901
  return FEATURE_MATRIX.filter((f) => f.requiresBackend);
2802
1902
  }
2803
- __name(getBackendRequiredFeatures, "getBackendRequiredFeatures");
2804
-
2805
- // src/adaptive-stream.ts
2806
1903
  function selectOptimalStream(streams, constraints, defaultTransport) {
2807
1904
  if (streams.length === 0) return null;
2808
1905
  const viewportPixels = constraints.viewportWidth * constraints.viewportHeight * (constraints.pixelRatio ?? 1);
@@ -2843,90 +1940,72 @@ function selectOptimalStream(streams, constraints, defaultTransport) {
2843
1940
  if (bw < 5 && s.metadata.codec.includes("265")) score += 10;
2844
1941
  if (bw >= 10 && s.metadata.codec.includes("264")) score += 5;
2845
1942
  }
2846
- return {
2847
- ...s,
2848
- score,
2849
- targetTier
2850
- };
1943
+ return { ...s, score, targetTier };
2851
1944
  });
2852
1945
  scored.sort((a, b) => b.score - a.score);
2853
1946
  const best = scored[0];
2854
- const tierNames = {
2855
- high: "main",
2856
- medium: "sub",
2857
- low: "ext"
2858
- };
2859
1947
  return {
2860
1948
  streamName: best.streamName,
2861
1949
  profile: best.profile,
2862
1950
  transport: best.transport,
2863
1951
  label: best.label,
2864
1952
  metadata: best.metadata,
2865
- reason: `${best.targetTier} quality \u2192 ${best.profile}/${best.transport} (score: ${best.score})`
1953
+ reason: `${best.targetTier} quality ${best.profile}/${best.transport} (score: ${best.score})`
2866
1954
  };
2867
1955
  }
2868
- __name(selectOptimalStream, "selectOptimalStream");
2869
1956
  function getNextEvalInterval(constraints, wasSwitch) {
2870
1957
  if (wasSwitch) return 10;
2871
1958
  if (constraints.isCellular) return 15;
2872
1959
  if ((constraints.packetLoss ?? 0) > 0.02) return 15;
2873
1960
  return 30;
2874
1961
  }
2875
- __name(getNextEvalInterval, "getNextEvalInterval");
2876
- // Annotate the CommonJS export names for ESM import in node:
2877
- 0 && (module.exports = {
2878
- BackendClient,
2879
- DEFAULT_ENABLED_CLASSES,
2880
- DetectionClass,
2881
- ELIGIBLE_HA_DOMAINS,
2882
- ELIGIBLE_HA_DOMAINS_SET,
2883
- ELIGIBLE_SCRYPTED_DEVICE_TYPES,
2884
- ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET,
2885
- FEATURE_MATRIX,
2886
- HA_DOMAIN_TYPE_MAP,
2887
- RAW_TO_CANONICAL,
2888
- SCRYPTED_TYPE_TO_CANONICAL,
2889
- TIMELINE_PRESET_ALL,
2890
- TIMELINE_PRESET_CRITICAL,
2891
- TIMELINE_PRESET_IMPORTANT,
2892
- animalClasses,
2893
- audioClasses,
2894
- audioLabelClasses,
2895
- createBackendClient,
2896
- defaultDetectionClasses,
2897
- detectionClassesDefaultMap,
2898
- doorbellClasses,
2899
- faceClasses,
2900
- getBackendRequiredFeatures,
2901
- getCanonicalDeviceType,
2902
- getClassesForTimelinePreset,
2903
- getNextEvalInterval,
2904
- getParentClass,
2905
- getParentDetectionClass,
2906
- getSourceFeatures,
2907
- isAnimalClassname,
2908
- isAudioClassname,
2909
- isDoorbellClassname,
2910
- isFaceClassname,
2911
- isFeatureAvailable,
2912
- isLabelDetection,
2913
- isMotionClassname,
2914
- isPackageClassname,
2915
- isPersonClassname,
2916
- isPlateClassname,
2917
- isSensorLabelClassname,
2918
- isVehicleClassname,
2919
- licensePlateClasses,
2920
- motionClasses,
2921
- packageClasses,
2922
- personClasses,
2923
- selectOptimalStream,
2924
- sensorLabelClasses,
2925
- vehicleClasses
2926
- });
2927
- /*! Bundled license information:
2928
-
2929
- @trpc/client/dist/httpLink-oiU8eqFi.mjs:
2930
- (* istanbul ignore if -- @preserve *)
2931
- */
2932
- //# sourceMappingURL=index.cjs.map
1962
+ exports.DEFAULT_ENABLED_CLASSES = DEFAULT_ENABLED_CLASSES;
1963
+ exports.DetectionClass = DetectionClass;
1964
+ exports.ELIGIBLE_HA_DOMAINS = ELIGIBLE_HA_DOMAINS;
1965
+ exports.ELIGIBLE_HA_DOMAINS_SET = ELIGIBLE_HA_DOMAINS_SET;
1966
+ exports.ELIGIBLE_SCRYPTED_DEVICE_TYPES = ELIGIBLE_SCRYPTED_DEVICE_TYPES;
1967
+ exports.ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET = ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET;
1968
+ exports.FEATURE_MATRIX = FEATURE_MATRIX;
1969
+ exports.HA_DOMAIN_TYPE_MAP = HA_DOMAIN_TYPE_MAP;
1970
+ exports.RAW_TO_CANONICAL = RAW_TO_CANONICAL;
1971
+ exports.SCRYPTED_TYPE_TO_CANONICAL = SCRYPTED_TYPE_TO_CANONICAL;
1972
+ exports.System = System;
1973
+ exports.TIMELINE_PRESET_ALL = TIMELINE_PRESET_ALL;
1974
+ exports.TIMELINE_PRESET_CRITICAL = TIMELINE_PRESET_CRITICAL;
1975
+ exports.TIMELINE_PRESET_IMPORTANT = TIMELINE_PRESET_IMPORTANT;
1976
+ exports.animalClasses = animalClasses;
1977
+ exports.audioClasses = audioClasses;
1978
+ exports.audioLabelClasses = audioLabelClasses;
1979
+ exports.createSystem = createSystem;
1980
+ exports.defaultDetectionClasses = defaultDetectionClasses;
1981
+ exports.detectionClassesDefaultMap = detectionClassesDefaultMap;
1982
+ exports.doorbellClasses = doorbellClasses;
1983
+ exports.faceClasses = faceClasses;
1984
+ exports.getBackendRequiredFeatures = getBackendRequiredFeatures;
1985
+ exports.getCanonicalDeviceType = getCanonicalDeviceType;
1986
+ exports.getClassesForTimelinePreset = getClassesForTimelinePreset;
1987
+ exports.getNextEvalInterval = getNextEvalInterval;
1988
+ exports.getParentClass = getParentClass;
1989
+ exports.getParentDetectionClass = getParentDetectionClass;
1990
+ exports.getSourceFeatures = getSourceFeatures;
1991
+ exports.isAnimalClassname = isAnimalClassname;
1992
+ exports.isAudioClassname = isAudioClassname;
1993
+ exports.isDoorbellClassname = isDoorbellClassname;
1994
+ exports.isFaceClassname = isFaceClassname;
1995
+ exports.isFeatureAvailable = isFeatureAvailable;
1996
+ exports.isLabelDetection = isLabelDetection;
1997
+ exports.isMotionClassname = isMotionClassname;
1998
+ exports.isPackageClassname = isPackageClassname;
1999
+ exports.isPersonClassname = isPersonClassname;
2000
+ exports.isPlateClassname = isPlateClassname;
2001
+ exports.isSensorLabelClassname = isSensorLabelClassname;
2002
+ exports.isVehicleClassname = isVehicleClassname;
2003
+ exports.licensePlateClasses = licensePlateClasses;
2004
+ exports.motionClasses = motionClasses;
2005
+ exports.packageClasses = packageClasses;
2006
+ exports.personClasses = personClasses;
2007
+ exports.raceFastestEndpoint = raceFastestEndpoint;
2008
+ exports.selectOptimalStream = selectOptimalStream;
2009
+ exports.sensorLabelClasses = sensorLabelClasses;
2010
+ exports.vehicleClasses = vehicleClasses;
2011
+ //# sourceMappingURL=index.cjs.map