@freedome/client 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4185 @@
1
+ import {
2
+ webSocketConnector
3
+ } from "./chunk-YB5V2MMF.js";
4
+ import {
5
+ uuidV7
6
+ } from "./chunk-HYGH4JIY.js";
7
+ import {
8
+ Sha256,
9
+ base64,
10
+ sha256Hex
11
+ } from "./chunk-J7A5LF32.js";
12
+ import {
13
+ FetchTransport,
14
+ FreedomeEndpoint,
15
+ FreedomeResponse,
16
+ PairingLink,
17
+ requestUrl
18
+ } from "./chunk-K3G5AG65.js";
19
+ import {
20
+ ConflictError,
21
+ ForbiddenError,
22
+ FreedomeError,
23
+ IncompatibleServerError,
24
+ NetworkError,
25
+ NotFoundError,
26
+ OfflineError,
27
+ PayloadTooLargeError,
28
+ QueuedForReplayError,
29
+ RateLimitedError,
30
+ RequestTimeoutError,
31
+ ServerError,
32
+ TlsPinMismatchError,
33
+ UnauthorizedError,
34
+ UnsupportedCapabilityError,
35
+ UnsupportedFormatError,
36
+ ValidationError,
37
+ errorFromProblem,
38
+ isUnreachable
39
+ } from "./chunk-CAEBM4AN.js";
40
+
41
+ // src/api.ts
42
+ import { expandPath } from "@freedome/protocol";
43
+ var enc = new TextEncoder();
44
+ var clean = (o) => {
45
+ const out = {};
46
+ for (const [k, v] of Object.entries(o ?? {})) if (v !== void 0) out[k] = v;
47
+ return out;
48
+ };
49
+ var ApiCaller = class _ApiCaller {
50
+ constructor(transport, userAgent, timeoutMs, logger) {
51
+ this.transport = transport;
52
+ this.userAgent = userAgent;
53
+ this.timeoutMs = timeoutMs;
54
+ this.logger = logger;
55
+ }
56
+ transport;
57
+ userAgent;
58
+ timeoutMs;
59
+ logger;
60
+ /** `Bearer …` of the session. */
61
+ authorization;
62
+ onUnauthorized;
63
+ realtime;
64
+ isOffline;
65
+ onTransportFailure;
66
+ /** Operations served at the server root (unversioned). */
67
+ static unversionedOps = /* @__PURE__ */ new Set(["getHealth", "getReady", "getMetrics"]);
68
+ /** Live-control operations: fail fast while offline (never queued). */
69
+ static liveOps = /* @__PURE__ */ new Set([
70
+ "play",
71
+ "pause",
72
+ "resume",
73
+ "stop",
74
+ "next",
75
+ "previous",
76
+ "seek",
77
+ "patchPlayer",
78
+ "patchOutput",
79
+ "setParameter",
80
+ "fireCue",
81
+ "setActiveShow",
82
+ "setTestPattern",
83
+ "identifyDisplay",
84
+ "setDisplayPower",
85
+ "submitCalibrationCapture",
86
+ "applyCalibrationJob",
87
+ "startCalibrationJob",
88
+ "sendOsc",
89
+ "publishAppPayload",
90
+ "clearAppPayloads",
91
+ "patchAudio",
92
+ "setGenerator",
93
+ "stopGenerator",
94
+ "patchAudioZone",
95
+ "startAudioSession",
96
+ "stopAudioSession",
97
+ "pauseAudioSession",
98
+ "resumeAudioSession",
99
+ "startAudioDeviceSweep",
100
+ "setSourcePosition"
101
+ ]);
102
+ async call(op, o = {}) {
103
+ if (_ApiCaller.liveOps.has(op.id) && this.isOffline?.()) {
104
+ throw new OfflineError(
105
+ `${op.id}: the media server is not reachable (live control is never queued)`
106
+ );
107
+ }
108
+ const rt = o.preferRealtime && !o.bytes ? this.realtime?.() : void 0;
109
+ if (rt?.supportsCalls) return this.viaRealtime(rt, op, o);
110
+ const payload = o.bytes ?? (o.body === void 0 ? void 0 : enc.encode(JSON.stringify(o.body)));
111
+ const headers = {
112
+ accept: "application/json, application/problem+json",
113
+ "x-freedome-client": this.userAgent,
114
+ ...payload ? {
115
+ "content-type": o.contentType ?? (op.method === "PATCH" ? "application/merge-patch+json" : "application/json")
116
+ } : {},
117
+ ...op.method === "POST" ? { "idempotency-key": o.idempotencyKey ?? uuidV7() } : {},
118
+ ...clean(o.headers)
119
+ };
120
+ const path = expandPath(op, o.params ?? {});
121
+ const once = () => this.transport.send(
122
+ {
123
+ method: op.method,
124
+ path,
125
+ query: clean(o.query),
126
+ headers: {
127
+ ...headers,
128
+ ...o.authenticated !== false && this.authorization ? { authorization: this.authorization } : {}
129
+ },
130
+ body: payload,
131
+ operationId: op.id,
132
+ rootRelative: _ApiCaller.unversionedOps.has(op.id)
133
+ },
134
+ o.timeoutMs ?? this.timeoutMs
135
+ );
136
+ this.logger?.({ level: "debug", message: `\u2192 ${op.method} ${path} (${op.id})` });
137
+ let res;
138
+ try {
139
+ res = await once();
140
+ } catch (e) {
141
+ if (e instanceof NetworkError || e instanceof RequestTimeoutError)
142
+ this.onTransportFailure?.(e);
143
+ throw e;
144
+ }
145
+ if (res.status === 401 && o.authenticated !== false && this.onUnauthorized) {
146
+ this.logger?.({ level: "info", message: `${op.id}: 401 \u2014 refreshing credentials` });
147
+ if (await this.onUnauthorized()) res = await once();
148
+ }
149
+ this.logger?.({ level: "debug", message: `\u2190 ${res.status} ${op.id}` });
150
+ if (!res.ok) throw _ApiCaller.errorOf(op, res);
151
+ return res;
152
+ }
153
+ async viaRealtime(rt, op, o) {
154
+ this.logger?.({ level: "debug", message: `\u21E2 realtime call ${op.id}` });
155
+ try {
156
+ const r = await rt.call(op.id, {
157
+ params: o.params ?? {},
158
+ body: o.body,
159
+ ...o.headers?.["if-match"] ? { ifMatch: o.headers["if-match"] } : {},
160
+ timeoutMs: o.timeoutMs ?? this.timeoutMs
161
+ });
162
+ if (r.status >= 400) {
163
+ throw _ApiCaller.errorOf(op, FreedomeResponse.json(r.status, r.body));
164
+ }
165
+ return r.body === void 0 || r.body === null ? new FreedomeResponse(r.status, r.etag ? { etag: r.etag } : {}) : FreedomeResponse.json(r.status, r.body, r.etag ? { etag: r.etag } : {});
166
+ } catch (e) {
167
+ if (e instanceof NetworkError || e instanceof UnsupportedCapabilityError) {
168
+ return this.call(op, { ...o, preferRealtime: false });
169
+ }
170
+ throw e;
171
+ }
172
+ }
173
+ /** JSON object body of [op]. */
174
+ async json(op, o = {}) {
175
+ return _ApiCaller.decodeBody(op, await this.call(op, o));
176
+ }
177
+ /** Decodes a JSON object body; a non-object → ServerError(internal). */
178
+ static decodeBody(op, res) {
179
+ let j;
180
+ try {
181
+ j = res.json;
182
+ } catch (e) {
183
+ throw new ServerError(`${op.id}: response is not JSON (${e.message})`, {
184
+ code: "internal",
185
+ status: res.status
186
+ });
187
+ }
188
+ if (typeof j !== "object" || j === null || Array.isArray(j)) {
189
+ throw new ServerError(`${op.id}: response is not a JSON object`, {
190
+ code: "internal",
191
+ status: res.status
192
+ });
193
+ }
194
+ return j;
195
+ }
196
+ /** Maps an error response of [op]. */
197
+ static errorOf(op, res) {
198
+ let p;
199
+ try {
200
+ const j = res.json;
201
+ if (j && typeof j.code === "string" && typeof j.title === "string")
202
+ p = { type: "about:blank", ...j };
203
+ } catch {
204
+ p = void 0;
205
+ }
206
+ return errorFromProblem(res.status, p, op.id, res.headers["retry-after"]);
207
+ }
208
+ };
209
+ async function readPage(api, op, o = {}) {
210
+ const page = await api.json(op, {
211
+ ...o,
212
+ query: {
213
+ ...o.query,
214
+ limit: o.limit === void 0 ? void 0 : String(o.limit),
215
+ cursor: o.cursor
216
+ }
217
+ });
218
+ if (!Array.isArray(page.items))
219
+ throw new ServerError(`${op.id}: page without items`, { code: "internal" });
220
+ return {
221
+ items: page.items,
222
+ nextCursor: typeof page.nextCursor === "string" && page.nextCursor ? page.nextCursor : null
223
+ };
224
+ }
225
+ async function readAllPages(api, op, o = {}) {
226
+ const out = [];
227
+ let cursor;
228
+ do {
229
+ const p = await readPage(api, op, { ...o, limit: o.limit ?? 200, cursor });
230
+ out.push(...p.items);
231
+ cursor = p.nextCursor ?? void 0;
232
+ } while (cursor);
233
+ return out;
234
+ }
235
+
236
+ // src/auth.ts
237
+ import { RoleScopes } from "@freedome/protocol";
238
+ var Credentials = {
239
+ guest: () => ({ kind: "guest" }),
240
+ password: (username, password) => ({
241
+ kind: "password",
242
+ username,
243
+ password
244
+ }),
245
+ apiKey: (key) => ({ kind: "apiKey", key }),
246
+ pairing: (o) => ({ kind: "pairing", ...o }),
247
+ cloud: (token) => ({
248
+ kind: "cloud",
249
+ token: typeof token === "string" ? () => Promise.resolve(token) : token
250
+ })
251
+ };
252
+ var InMemoryTokenStore = class {
253
+ m = /* @__PURE__ */ new Map();
254
+ async read(k) {
255
+ return this.m.get(k);
256
+ }
257
+ async write(k, t) {
258
+ this.m.set(k, t);
259
+ }
260
+ async delete(k) {
261
+ this.m.delete(k);
262
+ }
263
+ };
264
+ var NO_SESSION = { role: "none", scopes: /* @__PURE__ */ new Set() };
265
+ var ROLES = ["guest", "operator", "admin", "superadmin"];
266
+ var scopesOfRole = (role) => new Set(RoleScopes[role] ?? []);
267
+ var can = (session, scope) => session.scopes.has(scope);
268
+ function roleOf(scopes) {
269
+ if (!scopes) return "guest";
270
+ for (const r of ROLES) {
271
+ const s = scopesOfRole(r);
272
+ if (scopes.every((x) => s.has(x))) return r;
273
+ }
274
+ return "superadmin";
275
+ }
276
+ function sessionFromTokens(t, user) {
277
+ const tt = t;
278
+ const p = tt.principal;
279
+ const role = p?.role ?? roleOf(tt.scopes);
280
+ const scopes = tt.scopes ?? p?.scopes;
281
+ const name = p?.name ?? user;
282
+ return {
283
+ role,
284
+ scopes: scopes ? new Set(scopes) : scopesOfRole(role),
285
+ ...typeof tt.expiresIn === "number" ? { expiresAt: new Date(Date.now() + tt.expiresIn * 1e3).toISOString() } : {},
286
+ ...name ? { user: name } : {}
287
+ };
288
+ }
289
+ function sessionFromPrincipal(p) {
290
+ const x = p;
291
+ const user = x.name ?? x.subject;
292
+ return {
293
+ role: x.role,
294
+ scopes: new Set(x.scopes),
295
+ ...x.expiresAt ? { expiresAt: x.expiresAt } : {},
296
+ ...user ? { user } : {}
297
+ };
298
+ }
299
+ function storedTokensOf(t) {
300
+ const tt = t;
301
+ return {
302
+ accessToken: tt.accessToken,
303
+ ...tt.refreshToken ? { refreshToken: tt.refreshToken } : {},
304
+ ...typeof tt.expiresIn === "number" ? { expiresAt: new Date(Date.now() + tt.expiresIn * 1e3).toISOString() } : {}
305
+ };
306
+ }
307
+
308
+ // src/backoff.ts
309
+ var BackoffPolicy = class {
310
+ constructor(initialMs = 500, maxMs = 3e4, factor = 2, jitter = true) {
311
+ this.initialMs = initialMs;
312
+ this.maxMs = maxMs;
313
+ this.factor = factor;
314
+ this.jitter = jitter;
315
+ }
316
+ initialMs;
317
+ maxMs;
318
+ factor;
319
+ jitter;
320
+ /** Upper bound of attempt [n] (0-based). */
321
+ cap(n) {
322
+ const ms = this.initialMs * this.factor ** n;
323
+ return Number.isFinite(ms) && ms < this.maxMs ? Math.round(ms) : this.maxMs;
324
+ }
325
+ /** Delay of attempt [n]: uniform in [0, cap] with jitter, else cap. */
326
+ delay(n, random = Math.random) {
327
+ const c = this.cap(n);
328
+ return this.jitter ? Math.round(random() * c) : c;
329
+ }
330
+ };
331
+
332
+ // src/client.ts
333
+ import {
334
+ Operations as Operations13,
335
+ ProtocolVersions as ProtocolVersions2,
336
+ SemVer as SemVer2,
337
+ WS_SUBPROTOCOL
338
+ } from "@freedome/protocol";
339
+
340
+ // src/context.ts
341
+ import { Operations, jsonMergePatch } from "@freedome/protocol";
342
+
343
+ // src/emitter.ts
344
+ var Emitter = class {
345
+ listeners = /* @__PURE__ */ new Set();
346
+ closedFlag = false;
347
+ on(fn) {
348
+ this.listeners.add(fn);
349
+ return () => this.listeners.delete(fn);
350
+ }
351
+ emit(v) {
352
+ if (this.closedFlag) return;
353
+ for (const l of [...this.listeners]) l(v);
354
+ }
355
+ get size() {
356
+ return this.listeners.size;
357
+ }
358
+ close() {
359
+ this.closedFlag = true;
360
+ this.listeners.clear();
361
+ }
362
+ };
363
+ function nextValue(e, pred = () => true, timeoutMs = 5e3) {
364
+ return new Promise((resolve, reject) => {
365
+ const t = setTimeout(() => {
366
+ off();
367
+ reject(new Error(`no value within ${timeoutMs} ms`));
368
+ }, timeoutMs);
369
+ const off = e.on((v) => {
370
+ if (!pred(v)) return;
371
+ clearTimeout(t);
372
+ off();
373
+ resolve(v);
374
+ });
375
+ });
376
+ }
377
+
378
+ // src/context.ts
379
+ var RepositoryContext = class {
380
+ constructor(api, hub, cache, outbox, offline, isOffline, cacheScope, realtimeUp, positionHz, onEngineHealth, logger, contractVersion = () => void 0) {
381
+ this.api = api;
382
+ this.hub = hub;
383
+ this.cache = cache;
384
+ this.outbox = outbox;
385
+ this.offline = offline;
386
+ this.isOffline = isOffline;
387
+ this.cacheScope = cacheScope;
388
+ this.realtimeUp = realtimeUp;
389
+ this.positionHz = positionHz;
390
+ this.onEngineHealth = onEngineHealth;
391
+ this.logger = logger;
392
+ this.contractVersion = contractVersion;
393
+ }
394
+ api;
395
+ hub;
396
+ cache;
397
+ outbox;
398
+ offline;
399
+ isOffline;
400
+ cacheScope;
401
+ realtimeUp;
402
+ positionHz;
403
+ onEngineHealth;
404
+ logger;
405
+ contractVersion;
406
+ outboxOutcomes = new Emitter();
407
+ /** Whether the server reports a contract of at least [version]. False while it is not known. */
408
+ contractAtLeast(version) {
409
+ const v = this.contractVersion();
410
+ return v !== void 0 && v.compareTo(version) >= 0;
411
+ }
412
+ /**
413
+ * Whether the server reports a contract older than [version]. False while it is not known: the call is then sent,
414
+ * and the server's answer decides.
415
+ */
416
+ contractBelow(version) {
417
+ const v = this.contractVersion();
418
+ return v !== void 0 && v.compareTo(version) < 0;
419
+ }
420
+ log(level, message, error) {
421
+ this.logger?.({ level, message, ...error === void 0 ? {} : { error } });
422
+ }
423
+ /** Read through the cache: fresh when reachable, `stale` copy when not (02f §7.4). */
424
+ async cachedRead(name, read, stale) {
425
+ const key = `${this.cacheScope()}/${name}`;
426
+ if (this.isOffline() && this.offline.staleReads) {
427
+ const c = await this.cache.read(key);
428
+ if (c) return stale(c.json, new Date(c.asOf));
429
+ throw new OfflineError(`${name}: offline and nothing cached`);
430
+ }
431
+ try {
432
+ const [value, json] = await read();
433
+ await this.cache.write(key, { json, asOf: (/* @__PURE__ */ new Date()).toISOString() });
434
+ return value;
435
+ } catch (e) {
436
+ if (!this.offline.staleReads || !isUnreachable(e)) throw e;
437
+ const c = await this.cache.read(key);
438
+ if (!c) throw e;
439
+ this.log("info", `${name} served from cache`);
440
+ return stale(c.json, new Date(c.asOf));
441
+ }
442
+ }
443
+ /** Idempotent write; queued in the outbox when unreachable (QueuedForReplayError). */
444
+ async idempotentWrite(op, o = {}) {
445
+ const ob = this.outbox;
446
+ const canQueue = ob !== void 0 && this.offline.queueWrites;
447
+ const queue = async () => {
448
+ const e = {
449
+ id: uuidV7(),
450
+ scope: this.cacheScope(),
451
+ operationId: op.id,
452
+ params: o.params ?? {},
453
+ headers: o.headers ?? {},
454
+ ...o.body !== void 0 ? { body: o.body } : {},
455
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
456
+ };
457
+ await ob.add(e);
458
+ throw new QueuedForReplayError(`${op.id} queued for replay after reconnect`, e.id);
459
+ };
460
+ if (this.isOffline() && canQueue) return queue();
461
+ try {
462
+ return await this.api.call(op, o);
463
+ } catch (e) {
464
+ if (canQueue && isUnreachable(e)) return queue();
465
+ throw e;
466
+ }
467
+ }
468
+ /** Replays the outbox in order; conflicts carry the latest server version (`latestOf`). */
469
+ async replayOutbox(latestOf) {
470
+ const ob = this.outbox;
471
+ if (!ob) return;
472
+ for (const e of await ob.list(this.cacheScope())) {
473
+ const op = Operations[e.operationId];
474
+ if (!op) {
475
+ await ob.remove(e.id);
476
+ this.outboxOutcomes.emit({
477
+ entry: e,
478
+ error: new UnsupportedCapabilityError(`unknown operation ${e.operationId}`)
479
+ });
480
+ continue;
481
+ }
482
+ try {
483
+ const res = await this.api.call(op, {
484
+ params: e.params,
485
+ headers: e.headers,
486
+ body: e.body,
487
+ idempotencyKey: e.id
488
+ });
489
+ await ob.remove(e.id);
490
+ this.outboxOutcomes.emit({
491
+ entry: e,
492
+ status: res.status,
493
+ body: res.body.length ? res.json : void 0
494
+ });
495
+ } catch (err) {
496
+ if (isUnreachable(err)) return;
497
+ await ob.remove(e.id);
498
+ let error = err;
499
+ if (err instanceof ConflictError && latestOf) {
500
+ let latest;
501
+ try {
502
+ latest = await latestOf(e);
503
+ } catch {
504
+ latest = void 0;
505
+ }
506
+ error = new ConflictError(err.message, {
507
+ latest,
508
+ ...err.problem ? { problem: err.problem } : {},
509
+ ...err.code ? { code: err.code } : {}
510
+ });
511
+ }
512
+ this.outboxOutcomes.emit({ entry: e, error });
513
+ }
514
+ }
515
+ }
516
+ /**
517
+ * Watches a resource: initial read, then `resource` / `patch` events of [topic] (merge-patched), re-read after
518
+ * resync, polling every [intervalMs] while realtime is down. Returns the stop function.
519
+ */
520
+ watchResource(topic, fetch, obs, o = {}) {
521
+ let last;
522
+ let emitted = false;
523
+ let busy = false;
524
+ let again = false;
525
+ let stopped = false;
526
+ const emit = (v) => {
527
+ if (stopped) return;
528
+ if (emitted && JSON.stringify(v) === JSON.stringify(last)) return;
529
+ last = v;
530
+ emitted = true;
531
+ obs.next(v);
532
+ if (o.isFinal?.(v)) stop();
533
+ };
534
+ const read = async () => {
535
+ if (stopped) return;
536
+ if (busy) {
537
+ again = true;
538
+ return;
539
+ }
540
+ busy = true;
541
+ try {
542
+ emit(await fetch());
543
+ } catch (e) {
544
+ if (!stopped) obs.error?.(e);
545
+ } finally {
546
+ busy = false;
547
+ }
548
+ if (again) {
549
+ again = false;
550
+ await read();
551
+ }
552
+ };
553
+ const offEvents = this.hub.on([topic], (e) => {
554
+ if (o.kinds?.size && !o.kinds.has(e.kind)) return;
555
+ if (e.resource && typeof e.resource === "object") emit(e.resource);
556
+ else if (e.patch && emitted) emit(jsonMergePatch(last, e.patch));
557
+ });
558
+ const offSnap = this.hub.onSnapshot(topic, read);
559
+ void read();
560
+ const poll = setInterval(() => {
561
+ if (!this.realtimeUp()) void read();
562
+ }, o.intervalMs ?? 2e3);
563
+ poll.unref?.();
564
+ const stop = () => {
565
+ if (stopped) return;
566
+ stopped = true;
567
+ clearInterval(poll);
568
+ offSnap();
569
+ offEvents();
570
+ };
571
+ return stop;
572
+ }
573
+ close() {
574
+ this.outboxOutcomes.close();
575
+ }
576
+ };
577
+
578
+ // src/graphql.ts
579
+ var GRAPHQL_OPERATION = {
580
+ id: "graphql",
581
+ method: "POST",
582
+ path: "/graphql",
583
+ scope: "any",
584
+ tags: [],
585
+ params: [],
586
+ requestContentTypes: ["application/json"]
587
+ };
588
+ var GraphqlClient = class {
589
+ constructor(api) {
590
+ this.api = api;
591
+ }
592
+ api;
593
+ async query(document, variables = {}, operationName) {
594
+ const res = await this.api.call(GRAPHQL_OPERATION, {
595
+ body: {
596
+ query: document,
597
+ ...Object.keys(variables).length ? { variables } : {},
598
+ ...operationName ? { operationName } : {}
599
+ }
600
+ });
601
+ const j = res.json;
602
+ if (!j || typeof j !== "object")
603
+ throw new ServerError("graphql: response is not an object", { code: "internal" });
604
+ const first = j.errors?.[0];
605
+ if (first) {
606
+ const p = first.extensions?.problem;
607
+ if (p && typeof p === "object")
608
+ throw ApiCaller.errorOf(GRAPHQL_OPERATION, FreedomeResponse.json(p.status ?? 500, p));
609
+ throw new ServerError(`graphql: ${first.message ?? JSON.stringify(first)}`, {
610
+ code: "graphql"
611
+ });
612
+ }
613
+ return j.data ?? {};
614
+ }
615
+ };
616
+
617
+ // src/hub.ts
618
+ import { topicMatches } from "@freedome/protocol";
619
+ var EventHub = class {
620
+ /** Resolves when the server acknowledged [filters]; `false` = no live channel, so nothing was acknowledged. */
621
+ onSubscribe;
622
+ onUnsubscribe;
623
+ refs = /* @__PURE__ */ new Map();
624
+ listeners = /* @__PURE__ */ new Set();
625
+ snapshots = /* @__PURE__ */ new Set();
626
+ last;
627
+ epoch;
628
+ /** Last seen `seq` (resume point). */
629
+ get lastSeq() {
630
+ return this.last;
631
+ }
632
+ /** Active filters. */
633
+ get filters() {
634
+ return [...this.refs.keys()];
635
+ }
636
+ /** Listens to events matching any of [filters]. */
637
+ on(filters, fn) {
638
+ const l = { filters: new Set(filters), fn };
639
+ this.listeners.add(l);
640
+ this.retain(l.filters);
641
+ let done = false;
642
+ return () => {
643
+ if (done) return;
644
+ done = true;
645
+ this.listeners.delete(l);
646
+ this.release(l.filters);
647
+ };
648
+ }
649
+ /** Registers a re-read for topics overlapping [filter] (after resync / restart / reconnect). */
650
+ onSnapshot(filter, fn) {
651
+ const e = { filter, fn };
652
+ this.snapshots.add(e);
653
+ return () => this.snapshots.delete(e);
654
+ }
655
+ retain(filters) {
656
+ const add = [];
657
+ for (const f of filters) {
658
+ const n = (this.refs.get(f) ?? 0) + 1;
659
+ this.refs.set(f, n);
660
+ if (n === 1) add.push(f);
661
+ }
662
+ if (!add.length) return;
663
+ void this.onSubscribe?.(add).then(
664
+ (acknowledged) => acknowledged === false ? void 0 : this.snapshot(add),
665
+ () => void 0
666
+ );
667
+ }
668
+ release(filters) {
669
+ const drop = [];
670
+ for (const f of filters) {
671
+ const n = (this.refs.get(f) ?? 1) - 1;
672
+ if (n <= 0) {
673
+ this.refs.delete(f);
674
+ drop.push(f);
675
+ } else this.refs.set(f, n);
676
+ }
677
+ if (drop.length) void this.onUnsubscribe?.(drop).catch(() => void 0);
678
+ }
679
+ /** Delivers an event (drops duplicates of a resume; a lower seq = server restart → snapshot everything). */
680
+ dispatch(e) {
681
+ const last = this.last;
682
+ if (last !== void 0 && e.seq < last) {
683
+ this.last = e.seq;
684
+ void this.snapshot(["#"]);
685
+ } else if (last === void 0 || e.seq > last) {
686
+ this.last = e.seq;
687
+ } else return;
688
+ for (const l of [...this.listeners]) {
689
+ for (const f of l.filters) {
690
+ if (topicMatches(f, e.topic)) {
691
+ l.fn(e);
692
+ break;
693
+ }
694
+ }
695
+ }
696
+ }
697
+ /** Seeds the resume point (from `GET /events` lastSeq) when none is known. */
698
+ seed(lastSeq) {
699
+ this.last ??= lastSeq;
700
+ }
701
+ /** Records the server instance; a different one → the seq space restarted. */
702
+ newEpoch(serverId) {
703
+ if (!serverId) return false;
704
+ const changed = this.epoch !== void 0 && this.epoch !== serverId;
705
+ this.epoch = serverId;
706
+ if (changed) this.last = void 0;
707
+ return changed;
708
+ }
709
+ /** Runs the snapshot handlers overlapping [topics]. */
710
+ async snapshot(topics) {
711
+ const ts = [...topics];
712
+ const run = /* @__PURE__ */ new Set();
713
+ for (const s of this.snapshots)
714
+ if (ts.some((t) => t === "#" || overlap(s.filter, t))) run.add(s.fn);
715
+ for (const fn of run) {
716
+ try {
717
+ await fn();
718
+ } catch {
719
+ }
720
+ }
721
+ }
722
+ close() {
723
+ this.listeners.clear();
724
+ this.refs.clear();
725
+ this.snapshots.clear();
726
+ }
727
+ };
728
+ function overlap(a, b) {
729
+ const x = a.split("/");
730
+ const y = b.split("/");
731
+ for (let i = 0; i < x.length && i < y.length; i++) {
732
+ if (x[i] === "#" || y[i] === "#") return true;
733
+ if (x[i] !== "+" && y[i] !== "+" && x[i] !== y[i]) return false;
734
+ }
735
+ return x.length === y.length;
736
+ }
737
+
738
+ // src/offline.ts
739
+ var DEFAULT_OFFLINE_POLICY = {
740
+ staleReads: true,
741
+ queueWrites: true,
742
+ failAfterAttempts: 3
743
+ };
744
+ var InMemoryCacheStore = class {
745
+ m = /* @__PURE__ */ new Map();
746
+ async read(k) {
747
+ return this.m.get(k);
748
+ }
749
+ async write(k, v) {
750
+ this.m.set(k, v);
751
+ }
752
+ async delete(k) {
753
+ this.m.delete(k);
754
+ }
755
+ };
756
+ var InMemoryOutboxStore = class {
757
+ q = [];
758
+ async add(e) {
759
+ this.q.push(e);
760
+ }
761
+ async list(scope) {
762
+ return this.q.filter((e) => e.scope === scope);
763
+ }
764
+ async remove(id) {
765
+ this.q = this.q.filter((e) => e.id !== id);
766
+ }
767
+ };
768
+
769
+ // src/realtime/channel.ts
770
+ var isAuthFailure = (c) => c.code === 4401 || c.code === 4403;
771
+
772
+ // src/realtime/graphql-ws.ts
773
+ import { WsCloseCodes } from "@freedome/protocol";
774
+ var GRAPHQL_WS_SUBPROTOCOL = "graphql-transport-ws";
775
+ var GRAPHQL_EVENTS_SUBSCRIPTION = "subscription Events($topics: [String!]!, $sinceSeq: Int) { events(topics: $topics, sinceSeq: $sinceSeq) { seq topic kind ts data } }";
776
+ var GraphqlWsChannel = class _GraphqlWsChannel {
777
+ constructor(socket, heartbeatMs, logger) {
778
+ this.socket = socket;
779
+ this.heartbeatMs = heartbeatMs;
780
+ this.logger = logger;
781
+ this.closed = new Promise((r) => this.resolveClosed = r);
782
+ this.ack = new Promise((res, rej) => {
783
+ this.ackResolve = res;
784
+ this.ackReject = rej;
785
+ });
786
+ this.ack.catch(() => void 0);
787
+ socket.listen(
788
+ (t) => this.onFrame(t),
789
+ (c, r) => this.onDone(c, r)
790
+ );
791
+ }
792
+ socket;
793
+ heartbeatMs;
794
+ logger;
795
+ kind = "graphqlWs";
796
+ supportsCalls = false;
797
+ welcome = void 0;
798
+ events = new Emitter();
799
+ resyncs = new Emitter();
800
+ closed;
801
+ resolveClosed;
802
+ ackResolve;
803
+ ackReject;
804
+ ack;
805
+ ops = /* @__PURE__ */ new Map();
806
+ hb;
807
+ lastSeen = Date.now();
808
+ closing = false;
809
+ acked = false;
810
+ done = false;
811
+ static async open(socket, hello, opts = {}) {
812
+ const ch = new _GraphqlWsChannel(socket, opts.heartbeatMs ?? 15e3, opts.logger);
813
+ ch.send({
814
+ type: "connection_init",
815
+ payload: {
816
+ app: hello.app,
817
+ ...hello.appVersion ? { appVersion: hello.appVersion } : {},
818
+ ...hello.sdk ? { sdk: hello.sdk } : {},
819
+ ...hello.token ? { token: hello.token } : {}
820
+ }
821
+ });
822
+ const timeoutMs = opts.timeoutMs ?? 1e4;
823
+ let timer;
824
+ try {
825
+ await Promise.race([
826
+ ch.ack,
827
+ new Promise((_, rej) => {
828
+ timer = setTimeout(
829
+ () => rej(new NetworkError(`graphql-ws: no connection_ack within ${timeoutMs} ms`)),
830
+ timeoutMs
831
+ );
832
+ })
833
+ ]);
834
+ } catch (e) {
835
+ await ch.close();
836
+ throw e;
837
+ } finally {
838
+ clearTimeout(timer);
839
+ }
840
+ ch.startHeartbeat();
841
+ return ch;
842
+ }
843
+ send(m) {
844
+ this.socket.send(JSON.stringify(m));
845
+ }
846
+ onFrame(frame) {
847
+ this.lastSeen = Date.now();
848
+ let j;
849
+ try {
850
+ j = JSON.parse(frame);
851
+ } catch {
852
+ return;
853
+ }
854
+ switch (j.type) {
855
+ case "connection_ack":
856
+ this.acked = true;
857
+ this.ackResolve();
858
+ return;
859
+ case "ping":
860
+ this.send({ type: "pong" });
861
+ return;
862
+ case "next": {
863
+ const payload = j.payload;
864
+ const ev = payload?.data?.events;
865
+ if (ev && typeof ev.seq === "number" && typeof ev.topic === "string" && typeof ev.kind === "string") {
866
+ const data = {
867
+ ...ev.data ?? {},
868
+ seq: ev.seq,
869
+ kind: ev.kind
870
+ };
871
+ const e = {
872
+ id: uuidV7(),
873
+ topic: ev.topic,
874
+ seq: ev.seq,
875
+ kind: ev.kind,
876
+ ts: String(ev.ts ?? ""),
877
+ data
878
+ };
879
+ if ("resource" in data) e.resource = data.resource;
880
+ if (typeof data.patch === "object" && data.patch !== null)
881
+ e.patch = data.patch;
882
+ if (typeof data.revision === "number") e.revision = data.revision;
883
+ this.events.emit(e);
884
+ } else if (ev) {
885
+ this.logger?.({ level: "warning", message: "graphql-ws: malformed event" });
886
+ }
887
+ if (payload?.errors?.length) this.onErrors(j.id, payload.errors);
888
+ return;
889
+ }
890
+ case "error":
891
+ this.onErrors(j.id, j.payload ?? []);
892
+ return;
893
+ case "complete": {
894
+ const topics = this.ops.get(j.id);
895
+ this.ops.delete(j.id);
896
+ if (topics && !this.closing) this.resyncs.emit({ topics, reason: "complete" });
897
+ return;
898
+ }
899
+ }
900
+ }
901
+ onErrors(id, errors) {
902
+ const first = errors[0];
903
+ const code = first?.extensions?.problem?.code;
904
+ this.logger?.({
905
+ level: "warning",
906
+ message: `graphql-ws: subscription ${id} error ${code ?? JSON.stringify(first)}`
907
+ });
908
+ if (code === "resync" || code === "gap-too-old")
909
+ this.resyncs.emit({ topics: this.ops.get(id) ?? ["#"], reason: code });
910
+ }
911
+ onDone(code, reason) {
912
+ if (this.done) return;
913
+ this.done = true;
914
+ if (this.hb) clearInterval(this.hb);
915
+ if (!this.acked) {
916
+ this.ackReject(
917
+ code === 4401 || code === 4403 ? new UnauthorizedError(`graphql-ws: ${reason ?? "unauthorized"}`) : new NetworkError(`graphql-ws closed during handshake (${code ?? "network"})`)
918
+ );
919
+ }
920
+ this.resolveClosed({ code, reason, byServer: !this.closing });
921
+ this.events.close();
922
+ this.resyncs.close();
923
+ }
924
+ startHeartbeat() {
925
+ this.lastSeen = Date.now();
926
+ this.hb = setInterval(() => {
927
+ if (Date.now() - this.lastSeen >= this.heartbeatMs * 2) {
928
+ void this.close(WsCloseCodes.heartbeatTimeout, "heartbeat timeout");
929
+ return;
930
+ }
931
+ this.send({ type: "ping" });
932
+ }, this.heartbeatMs);
933
+ this.hb.unref?.();
934
+ }
935
+ async subscribe(topics, o = {}) {
936
+ if (this.done) throw new NetworkError("graphql-ws session closed");
937
+ const id = uuidV7();
938
+ this.ops.set(id, topics);
939
+ this.send({
940
+ id,
941
+ type: "subscribe",
942
+ payload: {
943
+ query: GRAPHQL_EVENTS_SUBSCRIPTION,
944
+ variables: { topics, ...o.sinceSeq !== void 0 ? { sinceSeq: o.sinceSeq } : {} }
945
+ }
946
+ });
947
+ return { topics };
948
+ }
949
+ async unsubscribe(topics) {
950
+ for (const [id, t] of [...this.ops]) {
951
+ if (t.every((x) => topics.includes(x))) {
952
+ this.ops.delete(id);
953
+ this.send({ id, type: "complete" });
954
+ }
955
+ }
956
+ }
957
+ call(op) {
958
+ return Promise.reject(
959
+ new UnsupportedCapabilityError(
960
+ `graphql-ws carries no REST calls (${op}) \u2014 the client uses REST`
961
+ )
962
+ );
963
+ }
964
+ async close(code, reason) {
965
+ if (this.closing) return;
966
+ this.closing = true;
967
+ if (this.hb) clearInterval(this.hb);
968
+ try {
969
+ this.socket.close(code ?? 1e3, reason);
970
+ } catch {
971
+ }
972
+ this.onDone(code ?? 1e3, reason);
973
+ }
974
+ };
975
+
976
+ // src/realtime/socketio.ts
977
+ import { eventFromMessage, parseWsMessage } from "@freedome/protocol";
978
+ import { io } from "socket.io-client";
979
+
980
+ // src/realtime/problem-error.ts
981
+ function realtimeError(data, context) {
982
+ const p = typeof data === "object" && data !== null ? { type: "about:blank", ...data } : { type: "about:blank" };
983
+ return errorFromProblem(typeof p.status === "number" ? p.status : 500, p, context);
984
+ }
985
+
986
+ // src/realtime/socketio.ts
987
+ var SocketIoChannel = class _SocketIoChannel {
988
+ constructor(socket, timeoutMs, logger) {
989
+ this.socket = socket;
990
+ this.timeoutMs = timeoutMs;
991
+ this.logger = logger;
992
+ this.closed = new Promise((r) => this.resolveClosed = r);
993
+ }
994
+ socket;
995
+ timeoutMs;
996
+ logger;
997
+ kind = "socketIo";
998
+ supportsCalls = true;
999
+ welcome = void 0;
1000
+ events = new Emitter();
1001
+ resyncs = new Emitter();
1002
+ closed;
1003
+ resolveClosed;
1004
+ closing = false;
1005
+ done = false;
1006
+ static open(endpoint, hello, opts = {}) {
1007
+ const timeoutMs = opts.timeoutMs ?? 1e4;
1008
+ const s = io(`${endpoint.baseUrl}/v1`, {
1009
+ path: "/socket.io/",
1010
+ transports: ["websocket"],
1011
+ auth: {
1012
+ app: hello.app,
1013
+ ...hello.appVersion ? { appVersion: hello.appVersion } : {},
1014
+ ...hello.sdk ? { sdk: hello.sdk } : {},
1015
+ ...hello.token ? { token: hello.token } : {}
1016
+ },
1017
+ autoConnect: false,
1018
+ forceNew: true,
1019
+ reconnection: false,
1020
+ timeout: timeoutMs
1021
+ });
1022
+ const ch = new _SocketIoChannel(s, timeoutMs, opts.logger);
1023
+ s.on("disconnect", (reason) => ch.finish(void 0, reason));
1024
+ s.on("event", (data) => {
1025
+ try {
1026
+ ch.events.emit(eventFromMessage(parseWsMessage(data)));
1027
+ } catch (e) {
1028
+ ch.logger?.({
1029
+ level: "warning",
1030
+ message: `socket.io: malformed event (${e.message})`
1031
+ });
1032
+ }
1033
+ });
1034
+ s.on("resync", (data) => {
1035
+ if (Array.isArray(data?.topics))
1036
+ ch.resyncs.emit({ topics: data.topics, reason: String(data.reason ?? "gap") });
1037
+ });
1038
+ return new Promise((resolve, reject) => {
1039
+ const timer = setTimeout(() => {
1040
+ s.disconnect();
1041
+ reject(new NetworkError(`socket.io: no connect within ${timeoutMs} ms`));
1042
+ }, timeoutMs);
1043
+ s.once("connect", () => {
1044
+ clearTimeout(timer);
1045
+ resolve(ch);
1046
+ });
1047
+ s.once("connect_error", (e) => {
1048
+ clearTimeout(timer);
1049
+ s.disconnect();
1050
+ reject(
1051
+ String(e?.message).includes("unauthenticated") ? new UnauthorizedError(`socket.io: ${e.message}`) : new NetworkError(`socket.io connect failed: ${e?.message ?? e}`, { cause: e })
1052
+ );
1053
+ });
1054
+ s.connect();
1055
+ });
1056
+ }
1057
+ finish(code, reason) {
1058
+ if (this.done) return;
1059
+ this.done = true;
1060
+ this.resolveClosed({ code, reason, byServer: !this.closing });
1061
+ this.events.close();
1062
+ this.resyncs.close();
1063
+ }
1064
+ emitAck(event, data, timeoutMs) {
1065
+ if (this.done) return Promise.reject(new NetworkError("socket.io session closed"));
1066
+ const t = timeoutMs ?? this.timeoutMs;
1067
+ return new Promise((resolve, reject) => {
1068
+ const timer = setTimeout(
1069
+ () => reject(new RequestTimeoutError(`socket.io ${event}: no ack within ${t} ms`, t)),
1070
+ t
1071
+ );
1072
+ this.socket.emit(event, data, (...args) => {
1073
+ clearTimeout(timer);
1074
+ const [err, result] = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
1075
+ if (err !== null && err !== void 0) reject(realtimeError(err, `socket.io ${event}`));
1076
+ else resolve(result);
1077
+ });
1078
+ });
1079
+ }
1080
+ async subscribe(topics, o = {}) {
1081
+ const r = await this.emitAck("subscribe", {
1082
+ topics,
1083
+ ...o.sinceSeq !== void 0 ? { sinceSeq: o.sinceSeq } : {},
1084
+ ...o.positionHz !== void 0 ? { options: { positionHz: o.positionHz } } : {}
1085
+ });
1086
+ return typeof r === "object" && r !== null ? r : { topics };
1087
+ }
1088
+ async unsubscribe(topics) {
1089
+ await this.emitAck("unsubscribe", { topics });
1090
+ }
1091
+ async call(op, o) {
1092
+ const r = await this.emitAck(
1093
+ "call",
1094
+ {
1095
+ op,
1096
+ ...o.params && Object.keys(o.params).length ? { params: o.params } : {},
1097
+ ...o.body !== void 0 ? { body: o.body } : {},
1098
+ ...o.ifMatch ? { ifMatch: o.ifMatch } : {},
1099
+ ...o.id ? { id: o.id } : {}
1100
+ },
1101
+ o.timeoutMs
1102
+ );
1103
+ return { status: r?.status ?? 200, body: r?.body, ...r?.etag ? { etag: r.etag } : {} };
1104
+ }
1105
+ async close() {
1106
+ if (this.closing) return;
1107
+ this.closing = true;
1108
+ this.socket.disconnect();
1109
+ this.finish(1e3, "closed by client");
1110
+ }
1111
+ };
1112
+
1113
+ // src/realtime/ws.ts
1114
+ import {
1115
+ MessageTypes,
1116
+ WsCloseCodes as WsCloseCodes2,
1117
+ eventFromMessage as eventFromMessage2,
1118
+ parseWsMessage as parseWsMessage2,
1119
+ rfc3339Millis
1120
+ } from "@freedome/protocol";
1121
+ var WsChannel = class _WsChannel {
1122
+ constructor(socket, heartbeatMs, timeoutMs, logger) {
1123
+ this.socket = socket;
1124
+ this.heartbeatMs = heartbeatMs;
1125
+ this.timeoutMs = timeoutMs;
1126
+ this.logger = logger;
1127
+ this.closed = new Promise((r) => this.resolveClosed = r);
1128
+ socket.listen(
1129
+ (t) => this.onFrame(t),
1130
+ (code, reason) => this.onDone(code, reason)
1131
+ );
1132
+ }
1133
+ socket;
1134
+ heartbeatMs;
1135
+ timeoutMs;
1136
+ logger;
1137
+ kind = "ws";
1138
+ supportsCalls = true;
1139
+ events = new Emitter();
1140
+ resyncs = new Emitter();
1141
+ closed;
1142
+ welcome;
1143
+ resolveClosed;
1144
+ pending = /* @__PURE__ */ new Map();
1145
+ hb;
1146
+ lastSeen = Date.now();
1147
+ closing = false;
1148
+ done = false;
1149
+ bye;
1150
+ /** Sends `hello`, waits for `welcome`, starts the heartbeat. */
1151
+ static async open(socket, hello, opts = {}) {
1152
+ const ch = new _WsChannel(
1153
+ socket,
1154
+ opts.heartbeatMs ?? 15e3,
1155
+ opts.timeoutMs ?? 1e4,
1156
+ opts.logger
1157
+ );
1158
+ const id = uuidV7();
1159
+ const reply = ch.expect(id, ch.timeoutMs);
1160
+ ch.sendMsg(
1161
+ MessageTypes.hello,
1162
+ {
1163
+ app: hello.app,
1164
+ ...hello.appVersion ? { appVersion: hello.appVersion } : {},
1165
+ ...hello.sdk ? { sdk: hello.sdk } : {},
1166
+ ...hello.token ? { token: hello.token } : {},
1167
+ ...hello.sinceSeq !== void 0 ? { resume: { sinceSeq: hello.sinceSeq } } : {}
1168
+ },
1169
+ { id }
1170
+ );
1171
+ let m;
1172
+ try {
1173
+ m = await reply;
1174
+ } catch (e) {
1175
+ await ch.close();
1176
+ throw e;
1177
+ }
1178
+ if (m.type !== MessageTypes.welcome) {
1179
+ await ch.close();
1180
+ throw new NetworkError(`expected welcome, got ${m.type}`);
1181
+ }
1182
+ if (typeof m.data !== "object" || m.data === null) {
1183
+ await ch.close();
1184
+ throw new ServerError("welcome does not match the contract", { code: "internal" });
1185
+ }
1186
+ const d = m.data;
1187
+ const server = d.server ?? {};
1188
+ ch.welcome = {
1189
+ ...d,
1190
+ ...typeof server.instanceId === "string" ? { instanceId: server.instanceId } : {},
1191
+ ...typeof d.heartbeatSec === "number" ? { heartbeatSec: d.heartbeatSec } : {}
1192
+ };
1193
+ ch.startHeartbeat();
1194
+ return ch;
1195
+ }
1196
+ log(level, message) {
1197
+ this.logger?.({ level, message: `ws: ${message}` });
1198
+ }
1199
+ onFrame(frame) {
1200
+ this.lastSeen = Date.now();
1201
+ let m;
1202
+ try {
1203
+ m = parseWsMessage2(JSON.parse(frame));
1204
+ } catch (e) {
1205
+ this.log("warning", `dropping malformed frame (${e.message})`);
1206
+ return;
1207
+ }
1208
+ switch (m.type) {
1209
+ case MessageTypes.event:
1210
+ try {
1211
+ this.events.emit(eventFromMessage2(m));
1212
+ } catch (e) {
1213
+ this.log("warning", `malformed event (${e.message})`);
1214
+ }
1215
+ return;
1216
+ case MessageTypes.resync: {
1217
+ const d = m.data;
1218
+ if (Array.isArray(d?.topics))
1219
+ this.resyncs.emit({ topics: d.topics, reason: String(d.reason ?? "gap") });
1220
+ return;
1221
+ }
1222
+ case MessageTypes.ping:
1223
+ this.sendMsg(MessageTypes.pong, {}, { replyTo: m.id });
1224
+ return;
1225
+ case MessageTypes.bye: {
1226
+ const d = m.data ?? {};
1227
+ this.bye = d;
1228
+ this.log("info", `server says bye: ${d.reason ?? ""}`);
1229
+ return;
1230
+ }
1231
+ default: {
1232
+ const p = m.replyTo ? this.pending.get(m.replyTo) : void 0;
1233
+ if (p) {
1234
+ this.pending.delete(m.replyTo);
1235
+ clearTimeout(p.timer);
1236
+ if (m.type === MessageTypes.error) p.reject(realtimeError(m.data, "realtime"));
1237
+ else p.resolve(m);
1238
+ } else if (m.type === MessageTypes.error) {
1239
+ this.log("warning", `unsolicited error: ${JSON.stringify(m.data)}`);
1240
+ }
1241
+ }
1242
+ }
1243
+ }
1244
+ onDone(code, reason) {
1245
+ if (this.done) return;
1246
+ this.done = true;
1247
+ if (this.hb) clearInterval(this.hb);
1248
+ const rec = {
1249
+ code: this.bye?.code ?? code ?? (this.bye ? 1e3 : void 0),
1250
+ reason: this.bye?.reason ?? reason,
1251
+ byServer: !this.closing
1252
+ };
1253
+ const auth = rec.code === WsCloseCodes2.unauthenticated || rec.code === WsCloseCodes2.forbidden;
1254
+ for (const p of this.pending.values()) {
1255
+ clearTimeout(p.timer);
1256
+ p.reject(
1257
+ auth ? new UnauthorizedError(`realtime session closed: ${rec.reason ?? ""}`) : new NetworkError(
1258
+ `realtime session closed (${rec.code ?? "network"}${rec.reason ? ` ${rec.reason}` : ""})`
1259
+ )
1260
+ );
1261
+ }
1262
+ this.pending.clear();
1263
+ this.resolveClosed(rec);
1264
+ this.events.close();
1265
+ this.resyncs.close();
1266
+ }
1267
+ startHeartbeat() {
1268
+ let every = this.heartbeatMs;
1269
+ const s = this.welcome?.heartbeatSec;
1270
+ if (typeof s === "number" && s > 0 && s * 1e3 < every) every = s * 1e3;
1271
+ this.lastSeen = Date.now();
1272
+ this.hb = setInterval(() => {
1273
+ if (Date.now() - this.lastSeen >= every * 2) {
1274
+ this.log("warning", "two heartbeats missed \u2014 closing");
1275
+ void this.close(WsCloseCodes2.heartbeatTimeout, "heartbeat timeout");
1276
+ return;
1277
+ }
1278
+ this.sendMsg(MessageTypes.ping, {});
1279
+ }, every);
1280
+ this.hb.unref?.();
1281
+ }
1282
+ sendMsg(type, data, o = {}) {
1283
+ const m = {
1284
+ type,
1285
+ id: o.id ?? uuidV7(),
1286
+ ts: rfc3339Millis(),
1287
+ ...o.topic ? { topic: o.topic } : {},
1288
+ ...o.replyTo ? { replyTo: o.replyTo } : {},
1289
+ data
1290
+ };
1291
+ this.socket.send(JSON.stringify(m));
1292
+ }
1293
+ expect(id, timeoutMs) {
1294
+ return new Promise((resolve, reject) => {
1295
+ const timer = setTimeout(() => {
1296
+ this.pending.delete(id);
1297
+ reject(new RequestTimeoutError(`realtime: no reply within ${timeoutMs} ms`, timeoutMs));
1298
+ }, timeoutMs);
1299
+ this.pending.set(id, { resolve, reject, timer });
1300
+ });
1301
+ }
1302
+ request(type, data, id, timeoutMs) {
1303
+ if (this.done) return Promise.reject(new NetworkError("realtime session closed"));
1304
+ const mid = id ?? uuidV7();
1305
+ const f = this.expect(mid, timeoutMs ?? this.timeoutMs);
1306
+ this.sendMsg(type, data, { id: mid });
1307
+ return f;
1308
+ }
1309
+ async subscribe(topics, o = {}) {
1310
+ const m = await this.request(MessageTypes.subscribe, {
1311
+ topics,
1312
+ ...o.sinceSeq !== void 0 ? { sinceSeq: o.sinceSeq } : {},
1313
+ ...o.positionHz !== void 0 ? { options: { positionHz: o.positionHz } } : {}
1314
+ });
1315
+ const body = m.data?.body;
1316
+ return typeof body === "object" && body !== null ? body : { topics };
1317
+ }
1318
+ async unsubscribe(topics) {
1319
+ await this.request(MessageTypes.unsubscribe, { topics });
1320
+ }
1321
+ async call(op, o) {
1322
+ const m = await this.request(
1323
+ MessageTypes.call,
1324
+ {
1325
+ op,
1326
+ ...o.params && Object.keys(o.params).length ? { params: o.params } : {},
1327
+ ...o.body !== void 0 ? { body: o.body } : {},
1328
+ ...o.ifMatch ? { ifMatch: o.ifMatch } : {}
1329
+ },
1330
+ o.id,
1331
+ o.timeoutMs
1332
+ );
1333
+ const d = m.data ?? {};
1334
+ return { status: d.status ?? 200, body: d.body, ...d.etag ? { etag: d.etag } : {} };
1335
+ }
1336
+ async close(code, reason) {
1337
+ if (this.closing) return;
1338
+ this.closing = true;
1339
+ if (this.hb) clearInterval(this.hb);
1340
+ try {
1341
+ this.socket.close(code ?? 1e3, reason);
1342
+ } catch {
1343
+ }
1344
+ this.onDone(code ?? 1e3, reason);
1345
+ }
1346
+ };
1347
+
1348
+ // src/repositories/audio-reactive.ts
1349
+ import {
1350
+ DomeTopics,
1351
+ EventKinds,
1352
+ Operations as Operations2
1353
+ } from "@freedome/protocol";
1354
+ var AudioReactiveRepository = class _AudioReactiveRepository {
1355
+ constructor(c, venueId = "default") {
1356
+ this.c = c;
1357
+ this.venueId = venueId;
1358
+ }
1359
+ c;
1360
+ venueId;
1361
+ venues = /* @__PURE__ */ new Map();
1362
+ get v() {
1363
+ return { venueId: this.venueId };
1364
+ }
1365
+ /** The same repository for another venue. */
1366
+ venue(id) {
1367
+ if (id === this.venueId) return this;
1368
+ let r = this.venues.get(id);
1369
+ if (!r) {
1370
+ r = new _AudioReactiveRepository(this.c, id);
1371
+ this.venues.set(id, r);
1372
+ }
1373
+ return r;
1374
+ }
1375
+ // ---- analysis ----
1376
+ /** Analysed inputs and whether the audio engine runs them. */
1377
+ analysis() {
1378
+ return this.c.api.json(Operations2.getAudioAnalysis, { params: this.v });
1379
+ }
1380
+ /**
1381
+ * Replaces the inputs and starts or stops the analysis (scope `audio:control`; live control, never queued offline).
1382
+ * 503 `engine-unavailable` when the audio engine cannot be reached.
1383
+ */
1384
+ setAnalysis(settings) {
1385
+ return this.c.api.json(Operations2.setAudioAnalysis, {
1386
+ params: this.v,
1387
+ body: settings
1388
+ });
1389
+ }
1390
+ /** Follows the analysis state (polled every [intervalMs] only while realtime is down). */
1391
+ analysisStates(obs, o = {}) {
1392
+ return this.c.watchResource(
1393
+ DomeTopics.audioAnalysis(this.venueId),
1394
+ () => this.analysis(),
1395
+ obs,
1396
+ { intervalMs: o.intervalMs ?? 2e3, kinds: /* @__PURE__ */ new Set([EventKinds.audioAnalysisState]) }
1397
+ );
1398
+ }
1399
+ /**
1400
+ * Analysis frames of [inputId], or of every input (server default 15 Hz). Events only: nothing arrives while realtime
1401
+ * is down, and the ring buffer does not keep frames, so a gap is not replayed.
1402
+ */
1403
+ frames(fn, o = {}) {
1404
+ return this.decoded(
1405
+ o.inputId === void 0 ? `${DomeTopics.audioAnalysis(this.venueId)}/+` : DomeTopics.audioAnalysisInput(o.inputId, this.venueId),
1406
+ EventKinds.audioAnalysis,
1407
+ fn
1408
+ );
1409
+ }
1410
+ /** Detected attacks of [inputId], or of every input. */
1411
+ onsets(fn, o = {}) {
1412
+ return this.decoded(
1413
+ o.inputId === void 0 ? `${DomeTopics.audio(this.venueId)}/onsets/+` : DomeTopics.audioOnsets(o.inputId, this.venueId),
1414
+ EventKinds.audioOnset,
1415
+ fn
1416
+ );
1417
+ }
1418
+ // ---- AudioReactive service ----
1419
+ /** Active scene, master intensity, service status. */
1420
+ get() {
1421
+ return this.c.api.json(Operations2.getAudioReactive, { params: this.v });
1422
+ }
1423
+ /** Follows the state (polled every [intervalMs] only while realtime is down). */
1424
+ states(obs, o = {}) {
1425
+ return this.c.watchResource(DomeTopics.audioReactive(this.venueId), () => this.get(), obs, {
1426
+ intervalMs: o.intervalMs ?? 2e3,
1427
+ kinds: /* @__PURE__ */ new Set([EventKinds.audioReactiveState])
1428
+ });
1429
+ }
1430
+ /**
1431
+ * Selects a scene, enables the service or sets the intensity (scope `playback:control`; next frame). `activeSceneId:
1432
+ * null` stops the running scene. 422 for an unknown scene or one whose gateway or input does not exist.
1433
+ */
1434
+ update(o) {
1435
+ return this.c.api.json(Operations2.patchAudioReactive, {
1436
+ params: this.v,
1437
+ body: o
1438
+ });
1439
+ }
1440
+ // ---- scenes ----
1441
+ /** Scenes stored for this venue. */
1442
+ scenes() {
1443
+ return readAllPages(this.c.api, Operations2.listAudioReactiveScenes, {
1444
+ params: this.v
1445
+ });
1446
+ }
1447
+ /** One scene with its ETag. */
1448
+ async scene(sceneId) {
1449
+ const res = await this.c.api.call(Operations2.getAudioReactiveScene, {
1450
+ params: { ...this.v, sceneId }
1451
+ });
1452
+ return {
1453
+ value: ApiCaller.decodeBody(Operations2.getAudioReactiveScene, res),
1454
+ etag: res.headers.etag
1455
+ };
1456
+ }
1457
+ /**
1458
+ * Stores a scene (scope `content:write`): with [ifMatch] it replaces that revision, without it the scene must be
1459
+ * new (`If-None-Match: *`).
1460
+ */
1461
+ async saveScene(sceneId, input, o = {}) {
1462
+ const res = await this.c.api.call(Operations2.putAudioReactiveScene, {
1463
+ params: { ...this.v, sceneId },
1464
+ body: input,
1465
+ headers: o.ifMatch === void 0 ? { "if-none-match": "*" } : { "if-match": o.ifMatch }
1466
+ });
1467
+ return {
1468
+ value: ApiCaller.decodeBody(Operations2.putAudioReactiveScene, res),
1469
+ etag: res.headers.etag
1470
+ };
1471
+ }
1472
+ /** Removes a scene ([ifMatch] read when absent). 409 while it is active. */
1473
+ async deleteScene(sceneId, o = {}) {
1474
+ const etag = o.ifMatch ?? (await this.scene(sceneId)).etag;
1475
+ await this.c.api.call(Operations2.deleteAudioReactiveScene, {
1476
+ params: { ...this.v, sceneId },
1477
+ headers: { "if-match": etag }
1478
+ });
1479
+ }
1480
+ // ---- texture sources ----
1481
+ /** Senders the engines of this venue can see. To show one, register a `stream` asset with the matching `src`. */
1482
+ textureSources() {
1483
+ return readAllPages(this.c.api, Operations2.listTextureSources, {
1484
+ params: this.v
1485
+ });
1486
+ }
1487
+ /** Changes of any texture source of this venue (events only). */
1488
+ textureSourceChanges(fn) {
1489
+ return this.decoded(
1490
+ `${DomeTopics.venue(this.venueId)}/texture-sources/+`,
1491
+ EventKinds.textureSourceState,
1492
+ fn
1493
+ );
1494
+ }
1495
+ /** `resource` of the [kind] events of [filter]; events without one are skipped. */
1496
+ decoded(filter, kind, fn) {
1497
+ return this.c.hub.on([filter], (e) => {
1498
+ if (e.kind === kind && e.resource && typeof e.resource === "object") fn(e.resource);
1499
+ });
1500
+ }
1501
+ };
1502
+
1503
+ // src/repositories/audio.ts
1504
+ import {
1505
+ DomeTopics as DomeTopics2,
1506
+ EventKinds as EventKinds2,
1507
+ Operations as Operations3,
1508
+ ProtocolVersions,
1509
+ jsonMergePatch as jsonMergePatch2,
1510
+ rfc3339Millis as rfc3339Millis2
1511
+ } from "@freedome/protocol";
1512
+ var ENDED = /* @__PURE__ */ new Set(["finished", "stopped", "failed"]);
1513
+ function audioSessionEnded(status) {
1514
+ return ENDED.has(String(status));
1515
+ }
1516
+ var AudioRepository = class _AudioRepository {
1517
+ constructor(c, venueId = "default") {
1518
+ this.c = c;
1519
+ this.venueId = venueId;
1520
+ }
1521
+ c;
1522
+ venueId;
1523
+ venues = /* @__PURE__ */ new Map();
1524
+ /** @internal */
1525
+ get ctx() {
1526
+ return this.c;
1527
+ }
1528
+ get v() {
1529
+ return { venueId: this.venueId };
1530
+ }
1531
+ /**
1532
+ * Whether the server has the audio additions of contract 1.1.0: [pauseSession], [resumeSession], [startDeviceSweep],
1533
+ * `roleZones` of [startSession] and the `multi` block of the generator. False against a 1.0 server and while its
1534
+ * contract version is not known.
1535
+ */
1536
+ get supportsAudioControl() {
1537
+ return this.c.contractAtLeast(ProtocolVersions.audioControl);
1538
+ }
1539
+ /** @internal A 1.0 server would answer 404 or 422: says why instead. Sent as it is when the version is not known. */
1540
+ requireAudioControl(what) {
1541
+ if (this.c.contractBelow(ProtocolVersions.audioControl))
1542
+ throw new UnsupportedCapabilityError(
1543
+ `${what} needs contract ${ProtocolVersions.audioControl.toString()}; the server reports ${String(this.c.contractVersion())}`
1544
+ );
1545
+ }
1546
+ /** The same repository for another venue. */
1547
+ venue(id) {
1548
+ if (id === this.venueId) return this;
1549
+ let r = this.venues.get(id);
1550
+ if (!r) {
1551
+ r = new _AudioRepository(this.c, id);
1552
+ this.venues.set(id, r);
1553
+ }
1554
+ return r;
1555
+ }
1556
+ // ---- state ----
1557
+ /** Mode, master gain / mute, engine status. */
1558
+ get() {
1559
+ return this.c.api.json(Operations3.getAudio, { params: this.v });
1560
+ }
1561
+ /**
1562
+ * Follows the audio state: `audio.state` events of `venues/{v}/audio`, re-read after resync, polled every
1563
+ * [intervalMs] only while realtime is down. Returns the stop function.
1564
+ */
1565
+ state(obs, o = {}) {
1566
+ return this.c.watchResource(DomeTopics2.audio(this.venueId), () => this.get(), obs, {
1567
+ intervalMs: o.intervalMs ?? 2e3,
1568
+ kinds: /* @__PURE__ */ new Set([EventKinds2.audioState])
1569
+ });
1570
+ }
1571
+ /** Changes mode / master gain / mute (live control, scope `audio:control`; never queued offline). */
1572
+ setMaster(o) {
1573
+ const body = {};
1574
+ if (o.masterGainDb !== void 0) body.masterGainDb = o.masterGainDb;
1575
+ if (o.mute !== void 0) body.mute = o.mute;
1576
+ if (o.mode !== void 0) body.mode = o.mode;
1577
+ return this.c.api.json(Operations3.patchAudio, {
1578
+ params: this.v,
1579
+ body,
1580
+ preferRealtime: true
1581
+ });
1582
+ }
1583
+ /**
1584
+ * Meters (`audio.levels` of `venues/{v}/audio/levels`, server rate ≤ 10 Hz), decimated here to at most [maxHz]:
1585
+ * intermediate values are dropped, the latest one is always delivered at the end of the window.
1586
+ */
1587
+ levels(fn, o = {}) {
1588
+ const windowMs = 1e3 / Math.max(1e-3, o.maxHz ?? 10);
1589
+ let lastSent;
1590
+ let pending;
1591
+ let timer;
1592
+ let stopped = false;
1593
+ const flush = () => {
1594
+ timer = void 0;
1595
+ const p = pending;
1596
+ if (!p || stopped) return;
1597
+ pending = void 0;
1598
+ lastSent = Date.now();
1599
+ fn(p);
1600
+ };
1601
+ const off = this.c.hub.on([DomeTopics2.audioLevels(this.venueId)], (e) => {
1602
+ if (e.kind !== EventKinds2.audioLevels) return;
1603
+ const l = e.resource?.levels;
1604
+ if (!l || typeof l !== "object") return;
1605
+ const next = {};
1606
+ for (const [k, x] of Object.entries(l))
1607
+ if (typeof x === "number") next[k] = x;
1608
+ pending = next;
1609
+ const since = lastSent === void 0 ? windowMs : Date.now() - lastSent;
1610
+ if (since >= windowMs) {
1611
+ if (timer) clearTimeout(timer);
1612
+ flush();
1613
+ } else timer ??= setTimeout(flush, windowMs - since);
1614
+ });
1615
+ return () => {
1616
+ if (stopped) return;
1617
+ stopped = true;
1618
+ if (timer) clearTimeout(timer);
1619
+ off();
1620
+ };
1621
+ }
1622
+ // ---- layout ----
1623
+ /** Speaker layout with its ETag. */
1624
+ async layout() {
1625
+ const res = await this.c.api.call(Operations3.getSpeakerLayout, { params: this.v });
1626
+ return {
1627
+ value: ApiCaller.decodeBody(Operations3.getSpeakerLayout, res),
1628
+ etag: res.headers.etag
1629
+ };
1630
+ }
1631
+ /** Replaces the speaker layout (scope `venues:write`; [ifMatch] = ETag of [layout], read when absent). */
1632
+ async saveLayout(layout, o = {}) {
1633
+ const etag = o.ifMatch ?? (await this.layout()).etag;
1634
+ const res = await this.c.api.call(Operations3.putSpeakerLayout, {
1635
+ params: this.v,
1636
+ body: layout,
1637
+ headers: { "if-match": etag }
1638
+ });
1639
+ return {
1640
+ value: ApiCaller.decodeBody(Operations3.putSpeakerLayout, res),
1641
+ etag: res.headers.etag
1642
+ };
1643
+ }
1644
+ // ---- zones ----
1645
+ /** Zones of the venue. */
1646
+ zones() {
1647
+ return readAllPages(this.c.api, Operations3.listAudioZones, { params: this.v });
1648
+ }
1649
+ /** One zone. */
1650
+ zone(zoneId) {
1651
+ return this.c.api.json(Operations3.getAudioZone, {
1652
+ params: { ...this.v, zoneId }
1653
+ });
1654
+ }
1655
+ /** Zone gain in dB (live control). */
1656
+ setZoneGain(zoneId, db) {
1657
+ return this.patchZone(zoneId, { gainDb: db });
1658
+ }
1659
+ /** Mutes / unmutes a zone (live control). */
1660
+ setMute(zoneId, muted) {
1661
+ return this.patchZone(zoneId, { mute: muted });
1662
+ }
1663
+ /** Merge-patches a zone (gain, delay, EQ, mute, speakers; live control). */
1664
+ patchZone(zoneId, patch) {
1665
+ return this.c.api.json(Operations3.patchAudioZone, {
1666
+ params: { ...this.v, zoneId },
1667
+ body: patch,
1668
+ preferRealtime: true
1669
+ });
1670
+ }
1671
+ /** Creates ([ifMatch] absent → `If-None-Match: *`) or replaces a zone. */
1672
+ saveZone(zoneId, body, o = {}) {
1673
+ return this.c.api.json(Operations3.putAudioZone, {
1674
+ params: { ...this.v, zoneId },
1675
+ body,
1676
+ headers: o.ifMatch ? { "if-match": o.ifMatch } : { "if-none-match": "*" }
1677
+ });
1678
+ }
1679
+ /** Deletes a zone ([ifMatch] = `"r<revision>"`, read when absent). */
1680
+ async deleteZone(zoneId, o = {}) {
1681
+ const etag = o.ifMatch ?? `"r${(await this.zone(zoneId)).revision}"`;
1682
+ await this.c.api.call(Operations3.deleteAudioZone, {
1683
+ params: { ...this.v, zoneId },
1684
+ headers: { "if-match": etag }
1685
+ });
1686
+ }
1687
+ /** Follows a zone (`zone.state` merge patches applied); stops after `zone.deleted` (`obs.deleted` is called). */
1688
+ zoneState(zoneId, obs, o = {}) {
1689
+ const topic = DomeTopics2.audioZone(zoneId, this.venueId);
1690
+ const stop = this.c.watchResource(topic, () => this.zone(zoneId), obs, {
1691
+ intervalMs: o.intervalMs ?? 2e3,
1692
+ kinds: /* @__PURE__ */ new Set([EventKinds2.zoneState])
1693
+ });
1694
+ const offDeleted = this.c.hub.on([topic], (e) => {
1695
+ if (e.kind !== EventKinds2.zoneDeleted) return;
1696
+ done();
1697
+ obs.deleted?.();
1698
+ });
1699
+ const done = () => {
1700
+ stop();
1701
+ offDeleted();
1702
+ };
1703
+ return done;
1704
+ }
1705
+ // ---- devices ----
1706
+ /** Audio devices (speakers, amps, microphones, QRD hubs, Patefon units …), optionally of one [kind]. */
1707
+ async devices(o = {}) {
1708
+ const all = await readAllPages(this.c.api, Operations3.listAudioDevices, {
1709
+ params: this.v,
1710
+ query: { kind: o.kind }
1711
+ });
1712
+ return o.kind === void 0 ? all : all.filter((d) => d.kind === o.kind);
1713
+ }
1714
+ /** One device. */
1715
+ device(deviceId) {
1716
+ return this.c.api.json(Operations3.getAudioDevice, {
1717
+ params: { ...this.v, deviceId }
1718
+ });
1719
+ }
1720
+ /** Operator gain / mute / name / config of a device. */
1721
+ patchDevice(deviceId, patch) {
1722
+ return this.c.api.json(Operations3.patchAudioDevice, {
1723
+ params: { ...this.v, deviceId },
1724
+ body: patch
1725
+ });
1726
+ }
1727
+ /**
1728
+ * Resonance sweep of one resonator channel of [deviceId] (scope `audio:calibrate`): answers a calibration job of kind
1729
+ * `audio-device-sweep`. Follow it with `client.calibration.progress`; progress is elapsed time, not measurement, and
1730
+ * the job's `sweep` member holds `peaks`, and with `modelHz` also `partials` and `warnings`, once it has succeeded.
1731
+ * There is nothing to apply. 409 while a session uses the device, another sweep runs or the device is in emergency
1732
+ * stop; 422 without such a resonator channel. Needs [supportsAudioControl].
1733
+ */
1734
+ async startDeviceSweep(deviceId, sweep = {}) {
1735
+ this.requireAudioControl("startDeviceSweep");
1736
+ return this.c.api.json(Operations3.startAudioDeviceSweep, {
1737
+ params: { ...this.v, deviceId },
1738
+ body: sweep
1739
+ });
1740
+ }
1741
+ /** Ping / tone / self-test / strike of a device. */
1742
+ testDevice(deviceId, test = { kind: "ping" }) {
1743
+ return this.c.api.json(Operations3.testAudioDevice, {
1744
+ params: { ...this.v, deviceId },
1745
+ body: test
1746
+ });
1747
+ }
1748
+ /** Follows a device (`audioDevice.state`, telemetry patches ≤ 1 Hz). */
1749
+ deviceState(deviceId, obs, o = {}) {
1750
+ return this.c.watchResource(
1751
+ DomeTopics2.audioDevice(deviceId, this.venueId),
1752
+ () => this.device(deviceId),
1753
+ obs,
1754
+ { intervalMs: o.intervalMs ?? 2e3, kinds: /* @__PURE__ */ new Set([EventKinds2.audioDeviceState]) }
1755
+ );
1756
+ }
1757
+ // ---- presets ----
1758
+ /** Installed presets (summaries). */
1759
+ presets() {
1760
+ return readAllPages(this.c.api, Operations3.listAudioPresets, {
1761
+ params: this.v
1762
+ });
1763
+ }
1764
+ /** One preset with its document and ETag. */
1765
+ async preset(presetId) {
1766
+ const res = await this.c.api.call(Operations3.getAudioPreset, {
1767
+ params: { ...this.v, presetId }
1768
+ });
1769
+ return {
1770
+ value: ApiCaller.decodeBody(Operations3.getAudioPreset, res),
1771
+ etag: res.headers.etag
1772
+ };
1773
+ }
1774
+ /**
1775
+ * Installs / replaces an ananta/1.0 programme, pattern or session document (scope `content:write`). Without
1776
+ * [ifMatch] an existing preset is overwritten (last writer wins).
1777
+ */
1778
+ async savePreset(presetId, input, o = {}) {
1779
+ const res = await this.c.api.call(Operations3.putAudioPreset, {
1780
+ params: { ...this.v, presetId },
1781
+ body: input,
1782
+ headers: { "if-match": o.ifMatch }
1783
+ });
1784
+ return {
1785
+ value: ApiCaller.decodeBody(Operations3.putAudioPreset, res),
1786
+ etag: res.headers.etag
1787
+ };
1788
+ }
1789
+ /** Removes a preset ([ifMatch] read when absent). */
1790
+ async deletePreset(presetId, o = {}) {
1791
+ const etag = o.ifMatch ?? (await this.preset(presetId)).etag;
1792
+ await this.c.api.call(Operations3.deleteAudioPreset, {
1793
+ params: { ...this.v, presetId },
1794
+ headers: { "if-match": etag }
1795
+ });
1796
+ }
1797
+ // ---- sessions ----
1798
+ /** Runs an installed preset (live control). */
1799
+ async startSession(s) {
1800
+ if (s.roleZones !== void 0) this.requireAudioControl("roleZones");
1801
+ const body = { presetId: s.presetId };
1802
+ if (s.gainDb !== void 0) body.gainDb = s.gainDb;
1803
+ if (s.targets !== void 0) body.targets = s.targets;
1804
+ if (s.roleZones !== void 0) body.roleZones = s.roleZones;
1805
+ if (s.at !== void 0) body.at = s.at instanceof Date ? rfc3339Millis2(s.at) : s.at;
1806
+ if (s.loop !== void 0) body.loop = s.loop;
1807
+ return this.c.api.json(Operations3.startAudioSession, {
1808
+ params: this.v,
1809
+ body,
1810
+ preferRealtime: true
1811
+ });
1812
+ }
1813
+ /** Sessions of the venue. */
1814
+ sessions() {
1815
+ return readAllPages(this.c.api, Operations3.listAudioSessions, {
1816
+ params: this.v
1817
+ });
1818
+ }
1819
+ /** One session. */
1820
+ session(sessionId) {
1821
+ return this.c.api.json(Operations3.getAudioSession, {
1822
+ params: { ...this.v, sessionId }
1823
+ });
1824
+ }
1825
+ /** Follows a session until it ends (`finished` / `stopped` / `failed`), then stops by itself. */
1826
+ sessionState(sessionId, obs, o = {}) {
1827
+ return this.c.watchResource(
1828
+ DomeTopics2.audioSession(sessionId, this.venueId),
1829
+ () => this.session(sessionId),
1830
+ obs,
1831
+ {
1832
+ intervalMs: o.intervalMs ?? 1e3,
1833
+ kinds: /* @__PURE__ */ new Set([EventKinds2.audioSessionState]),
1834
+ isFinal: (s) => audioSessionEnded(s.status)
1835
+ }
1836
+ );
1837
+ }
1838
+ /**
1839
+ * Pauses a session (live control, scope `audio:control`): every engine holds its position, `audioSession.state`
1840
+ * follows. A paused session answers as it is; 409 for one that is starting or has ended. Needs
1841
+ * [supportsAudioControl].
1842
+ */
1843
+ async pauseSession(sessionId) {
1844
+ this.requireAudioControl("pauseSession");
1845
+ return this.c.api.json(Operations3.pauseAudioSession, {
1846
+ params: { ...this.v, sessionId },
1847
+ preferRealtime: true
1848
+ });
1849
+ }
1850
+ /**
1851
+ * Resumes a paused session from its position (live control, scope `audio:control`). A running session answers as it
1852
+ * is; 409 for one that is starting or has ended. Needs [supportsAudioControl].
1853
+ */
1854
+ async resumeSession(sessionId) {
1855
+ this.requireAudioControl("resumeSession");
1856
+ return this.c.api.json(Operations3.resumeAudioSession, {
1857
+ params: { ...this.v, sessionId },
1858
+ preferRealtime: true
1859
+ });
1860
+ }
1861
+ /** Stops a session (live control). */
1862
+ async stopSession(sessionId) {
1863
+ await this.c.api.call(Operations3.stopAudioSession, {
1864
+ params: { ...this.v, sessionId },
1865
+ preferRealtime: true
1866
+ });
1867
+ }
1868
+ // ---- generator / sources ----
1869
+ /** The venue's test / MULTI generator (backs the dome sound engine). Close it when done. */
1870
+ generator() {
1871
+ return new GeneratorSession(this);
1872
+ }
1873
+ /** Moves interactive source [sourceId] (spherical, listener at the dome centre; live control). */
1874
+ async setSourcePosition(sourceId, position) {
1875
+ await this.c.api.call(Operations3.setSourcePosition, {
1876
+ params: { ...this.v, sourceId },
1877
+ body: position,
1878
+ preferRealtime: true
1879
+ });
1880
+ }
1881
+ };
1882
+ var GeneratorSession = class {
1883
+ constructor(r) {
1884
+ this.r = r;
1885
+ const topic = DomeTopics2.audioGenerator(r.venueId);
1886
+ this.offEvents = r.ctx.hub.on([topic], (e) => {
1887
+ if (e.kind !== EventKinds2.generatorState) return;
1888
+ if (e.resource && typeof e.resource === "object") this.push(e.resource);
1889
+ else if (e.patch && this.value)
1890
+ this.push(jsonMergePatch2(this.value, e.patch));
1891
+ });
1892
+ this.offSnapshot = r.ctx.hub.onSnapshot(topic, () => this.refreshQuietly());
1893
+ }
1894
+ r;
1895
+ /** State changes. */
1896
+ states = new Emitter();
1897
+ value;
1898
+ offEvents;
1899
+ offSnapshot;
1900
+ poll;
1901
+ closed = false;
1902
+ get v() {
1903
+ return { venueId: this.r.venueId };
1904
+ }
1905
+ /** Latest known state (undefined before the first read / event). */
1906
+ get last() {
1907
+ return this.value;
1908
+ }
1909
+ push(s) {
1910
+ if (this.closed) return;
1911
+ const same = this.value !== void 0 && JSON.stringify(this.value) === JSON.stringify(s);
1912
+ this.value = s;
1913
+ if (!same) this.states.emit(s);
1914
+ }
1915
+ /**
1916
+ * Watches the state (replays the latest; reads once when unknown). Polls every [pollMs] only while realtime is
1917
+ * down. Returns the unsubscribe function.
1918
+ */
1919
+ watch(fn, o = {}) {
1920
+ const off = this.states.on(fn);
1921
+ if (!this.poll && !this.closed) {
1922
+ this.poll = setInterval(() => {
1923
+ if (!this.r.ctx.realtimeUp()) void this.refreshQuietly();
1924
+ }, o.pollMs ?? 2e3);
1925
+ this.poll.unref?.();
1926
+ }
1927
+ if (this.value) fn(this.value);
1928
+ else void this.refreshQuietly();
1929
+ return off;
1930
+ }
1931
+ /** Reads the state over REST. */
1932
+ async get() {
1933
+ const s = await this.r.ctx.api.json(Operations3.getGenerator, {
1934
+ params: this.v
1935
+ });
1936
+ this.push(s);
1937
+ return s;
1938
+ }
1939
+ /**
1940
+ * Starts the generator or replaces its settings (live control, scope `audio:control`). The `multi` block needs
1941
+ * [AudioRepository.supportsAudioControl].
1942
+ */
1943
+ async start(settings) {
1944
+ if (settings.multi !== void 0) this.r.requireAudioControl("generator multi");
1945
+ const s = await this.r.ctx.api.json(Operations3.setGenerator, {
1946
+ params: this.v,
1947
+ body: settings,
1948
+ preferRealtime: true
1949
+ });
1950
+ this.push(s);
1951
+ return s;
1952
+ }
1953
+ /**
1954
+ * Plays a MULTI programme: `signal: multi` with the block [multi], the same object a phone gives to `setParams`
1955
+ * (contract 1.1.0, `docs/audio-control.md`).
1956
+ */
1957
+ startMulti(multi, o = {}) {
1958
+ return this.start({
1959
+ ...o,
1960
+ signal: "multi",
1961
+ multi: { ...multi, compatJava: multi.compatJava ?? false }
1962
+ });
1963
+ }
1964
+ /** Stops the generator (live control). */
1965
+ async stop() {
1966
+ await this.r.ctx.api.call(Operations3.stopGenerator, { params: this.v, preferRealtime: true });
1967
+ this.push({ running: false });
1968
+ }
1969
+ async refreshQuietly() {
1970
+ if (this.closed) return;
1971
+ try {
1972
+ await this.get();
1973
+ } catch (e) {
1974
+ this.r.ctx.log("warning", "generator: read failed", e);
1975
+ }
1976
+ }
1977
+ /** Stops following the generator (does not stop it). */
1978
+ close() {
1979
+ if (this.closed) return;
1980
+ this.closed = true;
1981
+ if (this.poll) clearInterval(this.poll);
1982
+ this.offSnapshot();
1983
+ this.offEvents();
1984
+ this.states.close();
1985
+ }
1986
+ };
1987
+
1988
+ // src/repositories/calibration.ts
1989
+ import {
1990
+ DomeTopics as DomeTopics3,
1991
+ Operations as Operations4
1992
+ } from "@freedome/protocol";
1993
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
1994
+ function multipart(parts) {
1995
+ const boundary = `freedome-${Math.random().toString(16).slice(2)}${Date.now().toString(16)}`;
1996
+ const enc2 = new TextEncoder();
1997
+ const chunks = [];
1998
+ for (const p of parts) {
1999
+ if ("value" in p) {
2000
+ chunks.push(
2001
+ enc2.encode(
2002
+ `--${boundary}\r
2003
+ Content-Disposition: form-data; name="${p.name}"\r
2004
+ \r
2005
+ ${p.value}\r
2006
+ `
2007
+ )
2008
+ );
2009
+ } else {
2010
+ chunks.push(
2011
+ enc2.encode(
2012
+ `--${boundary}\r
2013
+ Content-Disposition: form-data; name="${p.name}"; filename="${p.fileName}"\r
2014
+ Content-Type: ${p.contentType}\r
2015
+ \r
2016
+ `
2017
+ ),
2018
+ p.bytes,
2019
+ enc2.encode("\r\n")
2020
+ );
2021
+ }
2022
+ }
2023
+ chunks.push(enc2.encode(`--${boundary}--\r
2024
+ `));
2025
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
2026
+ let o = 0;
2027
+ for (const c of chunks) {
2028
+ out.set(c, o);
2029
+ o += c.length;
2030
+ }
2031
+ return [`multipart/form-data; boundary=${boundary}`, out];
2032
+ }
2033
+ var CalibrationRepository = class {
2034
+ constructor(c) {
2035
+ this.c = c;
2036
+ }
2037
+ c;
2038
+ start(request, venueId = "default") {
2039
+ return this.c.api.json(Operations4.startCalibrationJob, { params: { venueId }, body: request });
2040
+ }
2041
+ /**
2042
+ * Audio room calibration (speakers play → microphones capture → the solver proposes delay / gain / EQ per speaker):
2043
+ * job kind `audio-room`, scope `audio:calibrate`.
2044
+ */
2045
+ startAudioRoom(o = {}) {
2046
+ return this.start(
2047
+ {
2048
+ kind: "audio-room",
2049
+ ...o.speakers ? { speakers: o.speakers } : {},
2050
+ ...o.options ? { options: o.options } : {}
2051
+ },
2052
+ o.venueId ?? "default"
2053
+ );
2054
+ }
2055
+ get(jobId, venueId = "default") {
2056
+ return this.c.api.json(Operations4.getCalibrationJob, { params: { venueId, jobId } });
2057
+ }
2058
+ /** Follows a job until it is terminal. */
2059
+ progress(jobId, obs, venueId = "default", intervalMs = 500) {
2060
+ return this.c.watchResource(
2061
+ DomeTopics3.calibrationJob(jobId, venueId),
2062
+ () => this.get(jobId, venueId),
2063
+ obs,
2064
+ {
2065
+ intervalMs,
2066
+ isFinal: (j) => TERMINAL.has(String(j.status))
2067
+ }
2068
+ );
2069
+ }
2070
+ /** Submits a camera frame (≤ 32 MB, multipart). */
2071
+ async submitCapture(jobId, frame, venueId = "default") {
2072
+ if (frame.bytes.length > 32 * 1024 * 1024)
2073
+ throw new PayloadTooLargeError("capture frames are limited to 32 MB");
2074
+ const [type, body] = multipart([
2075
+ {
2076
+ name: "image",
2077
+ fileName: frame.fileName ?? "capture.jpg",
2078
+ contentType: frame.contentType ?? "image/jpeg",
2079
+ bytes: frame.bytes
2080
+ },
2081
+ ...frame.stepId ? [{ name: "stepId", value: frame.stepId }] : []
2082
+ ]);
2083
+ return this.c.api.json(Operations4.submitCalibrationCapture, {
2084
+ params: { venueId, jobId },
2085
+ bytes: body,
2086
+ contentType: type,
2087
+ timeoutMs: 6e4
2088
+ });
2089
+ }
2090
+ cancel(jobId, venueId = "default") {
2091
+ return this.c.api.json(Operations4.cancelCalibrationJob, { params: { venueId, jobId } });
2092
+ }
2093
+ /** Writes the job result into the venue calibration. */
2094
+ apply(jobId, venueId = "default") {
2095
+ return this.c.api.json(Operations4.applyCalibrationJob, { params: { venueId, jobId } });
2096
+ }
2097
+ /** The venue's calibration block. */
2098
+ results(venueId = "default") {
2099
+ return this.c.api.json(Operations4.getCalibration, { params: { venueId } });
2100
+ }
2101
+ /** Calibration jobs of the venue. */
2102
+ async jobs(venueId = "default") {
2103
+ const p = await this.c.api.json(Operations4.listCalibrationJobs, {
2104
+ params: { venueId }
2105
+ });
2106
+ return p.items;
2107
+ }
2108
+ };
2109
+
2110
+ // src/repositories/clients.ts
2111
+ import {
2112
+ DomeTopics as DomeTopics4,
2113
+ Operations as Operations5
2114
+ } from "@freedome/protocol";
2115
+ var ClientsRepository = class {
2116
+ constructor(c) {
2117
+ this.c = c;
2118
+ }
2119
+ c;
2120
+ register(registration) {
2121
+ return this.c.api.json(Operations5.registerClient, { body: registration });
2122
+ }
2123
+ list() {
2124
+ return readAllPages(this.c.api, Operations5.listClients);
2125
+ }
2126
+ async telemetry(clientId, batch) {
2127
+ await this.c.api.call(Operations5.postClientTelemetry, { params: { clientId }, body: batch });
2128
+ }
2129
+ async unregister(clientId) {
2130
+ await this.c.api.call(Operations5.unregisterClient, { params: { clientId } });
2131
+ }
2132
+ /** Commands the dome sends to this device (`clients/{id}/commands`). */
2133
+ commands(clientId, fn) {
2134
+ return this.c.hub.on([DomeTopics4.clientCommands(clientId)], (e) => {
2135
+ const r = e.resource ?? {};
2136
+ if (typeof r.command === "string") fn(r.command, r.args);
2137
+ });
2138
+ }
2139
+ };
2140
+
2141
+ // src/repositories/content.ts
2142
+ import {
2143
+ DomeTopics as DomeTopics5,
2144
+ Operations as Operations7
2145
+ } from "@freedome/protocol";
2146
+
2147
+ // src/repositories/upload.ts
2148
+ import { Operations as Operations6 } from "@freedome/protocol";
2149
+ var MAX_UPLOAD_CHUNK = 95 * 1024 * 1024;
2150
+ var BytesContentSource = class {
2151
+ constructor(bytes, name, contentType) {
2152
+ this.bytes = bytes;
2153
+ this.name = name;
2154
+ this.contentType = contentType;
2155
+ }
2156
+ bytes;
2157
+ name;
2158
+ contentType;
2159
+ get length() {
2160
+ return this.bytes.length;
2161
+ }
2162
+ async read(start, end) {
2163
+ return this.bytes.subarray(start, end);
2164
+ }
2165
+ };
2166
+ var BlobContentSource = class {
2167
+ constructor(blob, name = blob.name ?? "upload", contentType = blob.type || void 0) {
2168
+ this.blob = blob;
2169
+ this.name = name;
2170
+ this.contentType = contentType;
2171
+ }
2172
+ blob;
2173
+ name;
2174
+ contentType;
2175
+ get length() {
2176
+ return this.blob.size;
2177
+ }
2178
+ async read(start, end) {
2179
+ return new Uint8Array(await this.blob.slice(start, end).arrayBuffer());
2180
+ }
2181
+ };
2182
+ var b64 = (s) => base64(new TextEncoder().encode(s));
2183
+ var UploadTask = class {
2184
+ constructor(c, source, o = {}) {
2185
+ this.c = c;
2186
+ this.source = source;
2187
+ this.o = o;
2188
+ this.chunkSize = o.chunkSize ?? 8 * 1024 * 1024;
2189
+ if (this.chunkSize <= 0 || this.chunkSize > MAX_UPLOAD_CHUNK)
2190
+ throw new RangeError(`chunkSize 1..${MAX_UPLOAD_CHUNK}`);
2191
+ this.uploadIdValue = o.uploadId;
2192
+ this.sha = o.sha256;
2193
+ this.done = new Promise((res, rej) => {
2194
+ this.resolveDone = res;
2195
+ this.rejectDone = rej;
2196
+ });
2197
+ this.done.catch(() => void 0);
2198
+ }
2199
+ c;
2200
+ source;
2201
+ o;
2202
+ progress = new Emitter();
2203
+ done;
2204
+ resolveDone;
2205
+ rejectDone;
2206
+ finished = false;
2207
+ uploadIdValue;
2208
+ sha;
2209
+ offset = 0;
2210
+ stateValue = "pending";
2211
+ paused = false;
2212
+ running = false;
2213
+ wake;
2214
+ resumeRequested = false;
2215
+ chunkSize;
2216
+ get uploadId() {
2217
+ return this.uploadIdValue;
2218
+ }
2219
+ get sha256() {
2220
+ return this.sha;
2221
+ }
2222
+ get sent() {
2223
+ return this.offset;
2224
+ }
2225
+ get state() {
2226
+ return this.stateValue;
2227
+ }
2228
+ set(s) {
2229
+ this.stateValue = s;
2230
+ this.progress.emit({ state: s, sent: this.offset, total: this.source.length });
2231
+ }
2232
+ start() {
2233
+ if (!this.running && !this.finished) void this.run();
2234
+ return this.done;
2235
+ }
2236
+ pause() {
2237
+ this.paused = true;
2238
+ }
2239
+ resume() {
2240
+ this.paused = false;
2241
+ const w = this.wake;
2242
+ this.wake = void 0;
2243
+ if (w) w();
2244
+ else this.resumeRequested = this.running;
2245
+ if (!this.running && !this.finished) void this.run();
2246
+ }
2247
+ /** Terminates the upload on the server (tus DELETE) and rejects `done`. */
2248
+ async cancel() {
2249
+ this.paused = true;
2250
+ const id = this.uploadIdValue;
2251
+ if (id) {
2252
+ try {
2253
+ await this.c.api.call(Operations6.deleteUpload, {
2254
+ params: { uploadId: id },
2255
+ headers: { "tus-resumable": "1.0.0" }
2256
+ });
2257
+ } catch (e) {
2258
+ this.c.log("warning", `upload ${id}: terminate failed`, e);
2259
+ }
2260
+ }
2261
+ this.set("cancelled");
2262
+ this.fail(new ServerError("upload cancelled", { code: "cancelled" }));
2263
+ const w = this.wake;
2264
+ this.wake = void 0;
2265
+ w?.();
2266
+ this.progress.close();
2267
+ }
2268
+ fail(e) {
2269
+ if (this.finished) return;
2270
+ this.finished = true;
2271
+ this.rejectDone(e);
2272
+ }
2273
+ waitForResume() {
2274
+ if (this.resumeRequested) {
2275
+ this.resumeRequested = false;
2276
+ return Promise.resolve();
2277
+ }
2278
+ this.set("paused");
2279
+ return new Promise((r) => this.wake = r);
2280
+ }
2281
+ async run() {
2282
+ this.running = true;
2283
+ try {
2284
+ while (!this.finished) {
2285
+ try {
2286
+ await this.step();
2287
+ return;
2288
+ } catch (e) {
2289
+ if (isUnreachable(e)) {
2290
+ this.c.log("info", `upload paused (${e.message})`);
2291
+ await this.waitForResume();
2292
+ continue;
2293
+ }
2294
+ this.set("failed");
2295
+ this.fail(e);
2296
+ return;
2297
+ }
2298
+ }
2299
+ } finally {
2300
+ this.running = false;
2301
+ }
2302
+ }
2303
+ async step() {
2304
+ const total = this.source.length;
2305
+ if (!this.sha) {
2306
+ this.set("hashing");
2307
+ const h = new Sha256();
2308
+ for (let p = 0; p < total; p += this.chunkSize)
2309
+ h.update(await this.source.read(p, Math.min(total, p + this.chunkSize)));
2310
+ this.sha = h.hex();
2311
+ }
2312
+ const api = this.c.api;
2313
+ if (!this.uploadIdValue) {
2314
+ const res = await api.call(Operations6.createUpload, {
2315
+ headers: {
2316
+ "tus-resumable": "1.0.0",
2317
+ "upload-length": String(total),
2318
+ "upload-metadata": this.metadata()
2319
+ }
2320
+ });
2321
+ const loc = res.headers.location;
2322
+ const id = loc ? loc.split("?")[0].split("/").filter(Boolean).at(-1) : res.body.length ? res.json?.id : void 0;
2323
+ if (!id) throw new ServerError("createUpload: no Location / id", { code: "internal" });
2324
+ this.uploadIdValue = id;
2325
+ this.offset = Number.parseInt(res.headers["upload-offset"] ?? "0", 10) || 0;
2326
+ } else {
2327
+ this.offset = await this.headOffset();
2328
+ }
2329
+ this.set("uploading");
2330
+ while (this.offset < total) {
2331
+ if (this.paused) {
2332
+ await this.waitForResume();
2333
+ if (this.finished) return;
2334
+ this.offset = await this.headOffset();
2335
+ this.set("uploading");
2336
+ continue;
2337
+ }
2338
+ const end = Math.min(total, this.offset + this.chunkSize);
2339
+ const chunk = await this.source.read(this.offset, end);
2340
+ let res;
2341
+ try {
2342
+ res = await api.call(Operations6.appendUpload, {
2343
+ params: { uploadId: this.uploadIdValue },
2344
+ bytes: chunk,
2345
+ contentType: "application/offset+octet-stream",
2346
+ headers: {
2347
+ "tus-resumable": "1.0.0",
2348
+ "upload-offset": String(this.offset),
2349
+ "upload-checksum": `sha256 ${base64(new Sha256().update(chunk).digest())}`
2350
+ }
2351
+ });
2352
+ } catch (e) {
2353
+ if (e instanceof ConflictError) {
2354
+ this.offset = await this.headOffset();
2355
+ continue;
2356
+ }
2357
+ throw e;
2358
+ }
2359
+ this.offset = Number.parseInt(res.headers["upload-offset"] ?? "", 10) || this.offset + chunk.length;
2360
+ this.set("uploading");
2361
+ }
2362
+ this.set("completing");
2363
+ let asset;
2364
+ if ((this.o.purpose ?? "asset") === "asset") {
2365
+ const req = {
2366
+ ...this.o.asset,
2367
+ uploadId: this.uploadIdValue,
2368
+ name: this.o.asset?.name ?? this.source.name
2369
+ };
2370
+ asset = await api.json(Operations6.createAsset, { body: req });
2371
+ }
2372
+ this.set("done");
2373
+ if (!this.finished) {
2374
+ this.finished = true;
2375
+ this.resolveDone({
2376
+ uploadId: this.uploadIdValue,
2377
+ sha256: this.sha,
2378
+ ...asset ? { asset } : {}
2379
+ });
2380
+ }
2381
+ this.progress.close();
2382
+ }
2383
+ async headOffset() {
2384
+ const res = await this.c.api.call(Operations6.getUploadOffset, {
2385
+ params: { uploadId: this.uploadIdValue },
2386
+ headers: { "tus-resumable": "1.0.0" }
2387
+ });
2388
+ const o = Number.parseInt(res.headers["upload-offset"] ?? "", 10);
2389
+ if (!Number.isFinite(o))
2390
+ throw new ServerError("HEAD upload: no Upload-Offset", { code: "internal" });
2391
+ return o;
2392
+ }
2393
+ metadata() {
2394
+ const parts = [`filename ${b64(this.source.name)}`];
2395
+ if (this.source.contentType) parts.push(`contentType ${b64(this.source.contentType)}`);
2396
+ parts.push(`sha256 ${b64(this.sha)}`, `purpose ${b64(this.o.purpose ?? "asset")}`);
2397
+ const assetId = this.o.asset?.id;
2398
+ if (assetId) parts.push(`assetId ${b64(assetId)}`);
2399
+ return parts.join(",");
2400
+ }
2401
+ };
2402
+
2403
+ // src/repositories/content.ts
2404
+ var ContentRepository = class {
2405
+ constructor(c) {
2406
+ this.c = c;
2407
+ this.parts = new ShowParts(c);
2408
+ c.hub.onSnapshot("#", async () => {
2409
+ for (const t of this.tasks) if (t.state === "paused") t.resume();
2410
+ });
2411
+ }
2412
+ c;
2413
+ tasks = /* @__PURE__ */ new Set();
2414
+ parts;
2415
+ /** One page of assets (first pages cache-backed). */
2416
+ list(query = {}, cursor) {
2417
+ const q = { type: query.type, tag: query.tag, q: query.q, status: query.status };
2418
+ const read = () => readPage(this.c.api, Operations7.listAssets, {
2419
+ query: q,
2420
+ cursor,
2421
+ limit: query.limit
2422
+ });
2423
+ if (cursor) return read();
2424
+ const key = `assets?${Object.entries(q).filter(([, v]) => v !== void 0).map(([k, v]) => `${k}=${v}`).join("&")}`;
2425
+ return this.c.cachedRead(
2426
+ key,
2427
+ async () => {
2428
+ const p = await read();
2429
+ return [p, p];
2430
+ },
2431
+ (json, asOf) => ({ ...json, stale: true, asOf })
2432
+ );
2433
+ }
2434
+ get(assetId) {
2435
+ return this.c.api.json(Operations7.getAsset, { params: { assetId } });
2436
+ }
2437
+ /** Starts a resumable upload creating an asset (await `task.done`). */
2438
+ upload(source, o = {}) {
2439
+ const src = source instanceof Uint8Array ? new BytesContentSource(source, o.name ?? "upload") : source;
2440
+ return this.track(
2441
+ new UploadTask(this.c, src, {
2442
+ purpose: "asset",
2443
+ ...o.asset ? { asset: o.asset } : {},
2444
+ ...o.chunkSize ? { chunkSize: o.chunkSize } : {}
2445
+ })
2446
+ );
2447
+ }
2448
+ /** Continues a persisted upload (same [source]). */
2449
+ resumeUpload(uploadId, source, o = {}) {
2450
+ return this.track(
2451
+ new UploadTask(this.c, source, { uploadId, purpose: o.purpose ?? "asset", ...o })
2452
+ );
2453
+ }
2454
+ /** Uploads for another purpose (import / restore / capture), no asset. */
2455
+ uploadFor(purpose, source) {
2456
+ return this.track(new UploadTask(this.c, source, { purpose }));
2457
+ }
2458
+ track(t) {
2459
+ this.tasks.add(t);
2460
+ void t.done.then(
2461
+ () => this.tasks.delete(t),
2462
+ () => this.tasks.delete(t)
2463
+ );
2464
+ void t.start();
2465
+ return t;
2466
+ }
2467
+ /** Uploads in progress. */
2468
+ get uploads() {
2469
+ return [...this.tasks];
2470
+ }
2471
+ /** Uploads [source] and runs an import job; returns the finished job (rejects when it failed). */
2472
+ async importFile(source, format, o = {}) {
2473
+ const up = await this.uploadFor("import", source).done;
2474
+ const job = await this.c.api.json(Operations7.startImport, {
2475
+ body: {
2476
+ uploadId: up.uploadId,
2477
+ format,
2478
+ ...o.target ? { target: o.target } : {}
2479
+ }
2480
+ });
2481
+ return this.waitJob(job, { timeoutMs: o.timeoutMs ?? 6e5 });
2482
+ }
2483
+ /** Imports `.dome` bytes (kind show / bundle) and returns the created show. */
2484
+ async publishShow(dome, name = "show.dome") {
2485
+ const job = await this.importFile(
2486
+ new BytesContentSource(dome, name, "application/vnd.nativemind.freedome.dome+zip"),
2487
+ "dome"
2488
+ );
2489
+ const showId = job.result?.showId;
2490
+ if (!showId)
2491
+ throw new ServerError(`import job ${job.id} finished without a showId`, {
2492
+ code: "job-failed"
2493
+ });
2494
+ return (await this.getShow(showId)).value;
2495
+ }
2496
+ /** Polls a job until terminal; failed / cancelled reject. */
2497
+ async waitJob(job, o = {}) {
2498
+ const deadline = Date.now() + (o.timeoutMs ?? 6e5);
2499
+ let j = job;
2500
+ for (; ; ) {
2501
+ if (j.status === "succeeded") return j;
2502
+ if (j.status === "failed" || j.status === "cancelled") {
2503
+ throw new ServerError(`job ${j.id} ${j.status}: ${j.problem?.detail ?? j.message ?? ""}`, {
2504
+ code: j.problem?.code ?? "job-failed"
2505
+ });
2506
+ }
2507
+ if (Date.now() > deadline)
2508
+ throw new RequestTimeoutError(`job ${j.id} not finished in time`, o.timeoutMs);
2509
+ await new Promise((r) => setTimeout(r, o.pollMs ?? 500));
2510
+ j = await this.c.api.json(Operations7.getJob, { params: { jobId: j.id } });
2511
+ }
2512
+ }
2513
+ /** Merge-patches an asset (ETag read first when not given). */
2514
+ async patch(assetId, patch, ifMatch) {
2515
+ const etag = ifMatch ?? `"r${(await this.get(assetId)).revision}"`;
2516
+ return this.c.api.json(Operations7.patchAsset, {
2517
+ params: { assetId },
2518
+ body: patch,
2519
+ headers: { "if-match": etag }
2520
+ });
2521
+ }
2522
+ /** Deletes an asset (409 while referenced unless [force]). */
2523
+ async delete(assetId, o = {}) {
2524
+ const etag = o.ifMatch ?? `"r${(await this.get(assetId)).revision}"`;
2525
+ await this.c.api.call(Operations7.deleteAsset, {
2526
+ params: { assetId },
2527
+ query: o.force ? { force: "true" } : {},
2528
+ headers: { "if-match": etag }
2529
+ });
2530
+ }
2531
+ async thumbnail(assetId, size) {
2532
+ return (await this.c.api.call(Operations7.getAssetThumbnail, {
2533
+ params: { assetId },
2534
+ query: { size: size?.toString() }
2535
+ })).body;
2536
+ }
2537
+ async download(assetId) {
2538
+ return (await this.c.api.call(Operations7.downloadAsset, { params: { assetId }, timeoutMs: 18e5 })).body;
2539
+ }
2540
+ storage() {
2541
+ return this.c.api.json(Operations7.getStorageStats);
2542
+ }
2543
+ /** Changes of the content store. */
2544
+ changes(fn) {
2545
+ return this.c.hub.on(["assets/+"], (e) => {
2546
+ const p = e.patch?.progress;
2547
+ fn({
2548
+ kind: e.kind,
2549
+ assetId: e.topic.split("/").at(-1),
2550
+ ...e.resource && typeof e.resource === "object" ? { asset: e.resource } : {},
2551
+ ...typeof p === "number" ? { progress: p } : {}
2552
+ });
2553
+ });
2554
+ }
2555
+ listShows(o = {}) {
2556
+ return readPage(this.c.api, Operations7.listShows, {
2557
+ query: { q: o.q },
2558
+ cursor: o.cursor,
2559
+ limit: o.limit
2560
+ });
2561
+ }
2562
+ async getShow(showId) {
2563
+ const res = await this.c.api.call(Operations7.getShow, { params: { showId } });
2564
+ return {
2565
+ value: ApiCaller.decodeBody(Operations7.getShow, res),
2566
+ etag: res.headers.etag
2567
+ };
2568
+ }
2569
+ async createShow(body) {
2570
+ const res = await this.c.api.call(Operations7.createShow, { body });
2571
+ return {
2572
+ value: ApiCaller.decodeBody(Operations7.createShow, res),
2573
+ etag: res.headers.etag
2574
+ };
2575
+ }
2576
+ /** Replaces a show (`ifMatch`; without: create with If-None-Match: *). Queued in the outbox while offline. */
2577
+ async saveShow(showId, body, ifMatch) {
2578
+ const res = await this.c.idempotentWrite(Operations7.putShow, {
2579
+ params: { showId },
2580
+ body,
2581
+ headers: ifMatch ? { "if-match": ifMatch } : { "if-none-match": "*" }
2582
+ });
2583
+ return {
2584
+ value: ApiCaller.decodeBody(Operations7.putShow, res),
2585
+ etag: res.headers.etag
2586
+ };
2587
+ }
2588
+ async patchShow(showId, patch, ifMatch) {
2589
+ const etag = ifMatch ?? (await this.getShow(showId)).etag;
2590
+ const res = await this.c.api.call(Operations7.patchShow, {
2591
+ params: { showId },
2592
+ body: patch,
2593
+ headers: { "if-match": etag }
2594
+ });
2595
+ return {
2596
+ value: ApiCaller.decodeBody(Operations7.patchShow, res),
2597
+ etag: res.headers.etag
2598
+ };
2599
+ }
2600
+ async deleteShow(showId, ifMatch) {
2601
+ await this.c.api.call(Operations7.deleteShow, {
2602
+ params: { showId },
2603
+ headers: { "if-match": ifMatch }
2604
+ });
2605
+ }
2606
+ /** Exports a show as `.dome` bytes. */
2607
+ async exportShow(showId, embedAssets = false) {
2608
+ return (await this.c.api.call(Operations7.exportShow, {
2609
+ params: { showId },
2610
+ query: embedAssets ? { embedAssets: "true" } : {},
2611
+ timeoutMs: 18e5
2612
+ })).body;
2613
+ }
2614
+ /** tus capabilities. */
2615
+ async uploadCapabilities() {
2616
+ const res = await this.c.api.call(Operations7.getUploadCapabilities);
2617
+ const list = (h) => (res.headers[h] ?? "").split(",").map((x) => x.trim()).filter(Boolean);
2618
+ const max = Number.parseInt(res.headers["tus-max-size"] ?? "", 10);
2619
+ return {
2620
+ version: list("tus-version"),
2621
+ extensions: list("tus-extension"),
2622
+ ...Number.isFinite(max) ? { maxSize: max } : {},
2623
+ ...res.headers["tus-checksum-algorithm"] ? { checksumAlgorithms: list("tus-checksum-algorithm") } : {}
2624
+ };
2625
+ }
2626
+ uploadStatus(uploadId) {
2627
+ return this.c.api.json(Operations7.getUpload, { params: { uploadId } });
2628
+ }
2629
+ /** Watch hook used by apps showing one asset. */
2630
+ watchAsset(assetId, fn) {
2631
+ return this.c.watchResource(DomeTopics5.asset(assetId), () => this.get(assetId), { next: fn });
2632
+ }
2633
+ };
2634
+ var ShowParts = class {
2635
+ constructor(c) {
2636
+ this.c = c;
2637
+ }
2638
+ c;
2639
+ async etag(showId, ifMatch) {
2640
+ return ifMatch ?? (await this.c.api.call(Operations7.getShow, { params: { showId } })).headers.etag;
2641
+ }
2642
+ get(part, showId, itemId) {
2643
+ return this.c.api.json(Operations7[`get${part}`], { params: { showId, itemId } });
2644
+ }
2645
+ async put(part, showId, item, ifMatch) {
2646
+ return this.c.api.json(Operations7[`put${part}`], {
2647
+ params: { showId, itemId: item.id },
2648
+ body: item,
2649
+ headers: { "if-match": await this.etag(showId, ifMatch) }
2650
+ });
2651
+ }
2652
+ async delete(part, showId, itemId, ifMatch) {
2653
+ await this.c.api.call(Operations7[`delete${part}`], {
2654
+ params: { showId, itemId },
2655
+ headers: { "if-match": await this.etag(showId, ifMatch) }
2656
+ });
2657
+ }
2658
+ matrix(showId) {
2659
+ return this.c.api.json(Operations7.getMatrix, { params: { showId } });
2660
+ }
2661
+ async putMatrix(showId, matrix, ifMatch) {
2662
+ return this.c.api.json(Operations7.putMatrix, {
2663
+ params: { showId },
2664
+ body: matrix,
2665
+ headers: { "if-match": await this.etag(showId, ifMatch) }
2666
+ });
2667
+ }
2668
+ };
2669
+
2670
+ // src/repositories/engine.ts
2671
+ import {
2672
+ DomeTopics as DomeTopics6,
2673
+ EventKinds as EventKinds3,
2674
+ Operations as Operations8
2675
+ } from "@freedome/protocol";
2676
+ var EngineRepository = class {
2677
+ constructor(c) {
2678
+ this.c = c;
2679
+ }
2680
+ c;
2681
+ /** Every engine (visual, audio, …; `name@node` on multi-node installations). */
2682
+ engines() {
2683
+ return readAllPages(this.c.api, Operations8.listEngines);
2684
+ }
2685
+ /** Displays of a venue. */
2686
+ outputs(venueId = "default") {
2687
+ return readAllPages(this.c.api, Operations8.listDisplays, {
2688
+ params: { venueId }
2689
+ });
2690
+ }
2691
+ /** One display. */
2692
+ display(displayId, venueId = "default") {
2693
+ return this.c.api.json(Operations8.getDisplay, {
2694
+ params: { venueId, displayId }
2695
+ });
2696
+ }
2697
+ /** Shows a test pattern on a display. */
2698
+ showTestPattern(displayId, pattern, venueId = "default") {
2699
+ return this.c.api.json(Operations8.setTestPattern, {
2700
+ params: { venueId, displayId },
2701
+ body: pattern,
2702
+ preferRealtime: true
2703
+ });
2704
+ }
2705
+ /** Clears the test pattern. */
2706
+ clearTestPattern(displayId, venueId = "default") {
2707
+ return this.showTestPattern(
2708
+ displayId,
2709
+ { kind: "off" },
2710
+ venueId
2711
+ );
2712
+ }
2713
+ /** Flashes the id overlay. */
2714
+ async identify(displayId, durationMs, venueId = "default") {
2715
+ await this.c.api.call(Operations8.identifyDisplay, {
2716
+ params: { venueId, displayId },
2717
+ body: durationMs === void 0 ? {} : { durationS: durationMs / 1e3 }
2718
+ });
2719
+ }
2720
+ /** Power / shutter (what `state.capabilities` lists). */
2721
+ setPower(displayId, request, venueId = "default") {
2722
+ return this.c.api.json(Operations8.setDisplayPower, {
2723
+ params: { venueId, displayId },
2724
+ body: request
2725
+ });
2726
+ }
2727
+ /** Status of engine [name]. */
2728
+ async engineStatus(name = "visual") {
2729
+ const s = await this.c.api.json(Operations8.getEngine, { params: { name } });
2730
+ if (name === "visual") this.c.onEngineHealth?.(String(s.status));
2731
+ return s;
2732
+ }
2733
+ /** Watches an engine (feeds the `degraded` state for the visual engine). */
2734
+ status(obs, name = "visual", intervalMs = 2e3) {
2735
+ return this.c.watchResource(
2736
+ DomeTopics6.engine(name),
2737
+ () => this.engineStatus(name),
2738
+ {
2739
+ next: (s) => {
2740
+ if (name === "visual")
2741
+ this.c.onEngineHealth?.(String(s.status));
2742
+ obs.next(s);
2743
+ },
2744
+ ...obs.error ? { error: obs.error } : {}
2745
+ },
2746
+ { intervalMs, kinds: /* @__PURE__ */ new Set([EventKinds3.engineStatus]) }
2747
+ );
2748
+ }
2749
+ };
2750
+
2751
+ // src/repositories/gateways.ts
2752
+ import { Operations as Operations9 } from "@freedome/protocol";
2753
+ var GatewaysRepository = class {
2754
+ constructor(c) {
2755
+ this.c = c;
2756
+ }
2757
+ c;
2758
+ /** Every gateway. */
2759
+ list() {
2760
+ return readAllPages(this.c.api, Operations9.listGateways, {});
2761
+ }
2762
+ /** One gateway with its ETag. */
2763
+ async get(gatewayId) {
2764
+ const res = await this.c.api.call(Operations9.getGateway, { params: { gatewayId } });
2765
+ return {
2766
+ value: ApiCaller.decodeBody(Operations9.getGateway, res),
2767
+ etag: res.headers.etag
2768
+ };
2769
+ }
2770
+ /**
2771
+ * Merge-patches a gateway ([ifMatch] read when absent). The server validates `config` for the gateway's protocol
2772
+ * and answers 422 when it refuses it.
2773
+ */
2774
+ async patch(gatewayId, patch, o = {}) {
2775
+ const etag = o.ifMatch ?? (await this.get(gatewayId)).etag;
2776
+ const res = await this.c.api.call(Operations9.patchGateway, {
2777
+ params: { gatewayId },
2778
+ body: patch,
2779
+ headers: { "if-match": etag }
2780
+ });
2781
+ return {
2782
+ value: ApiCaller.decodeBody(Operations9.patchGateway, res),
2783
+ etag: res.headers.etag
2784
+ };
2785
+ }
2786
+ /** Runs the gateway's connectivity test. */
2787
+ test(gatewayId) {
2788
+ return this.c.api.json(Operations9.testGateway, { params: { gatewayId } });
2789
+ }
2790
+ };
2791
+
2792
+ // src/repositories/osc.ts
2793
+ import { DomeTopics as DomeTopics7, Operations as Operations10 } from "@freedome/protocol";
2794
+ function oscArg(a) {
2795
+ if (a !== null && typeof a === "object" && "type" in a && !(a instanceof Uint8Array) && !(a instanceof Date))
2796
+ return a;
2797
+ if (a === null || a === void 0) return { type: "N" };
2798
+ if (typeof a === "boolean") return { type: a ? "T" : "F" };
2799
+ if (typeof a === "number")
2800
+ return Number.isInteger(a) && Math.abs(a) <= 2147483647 ? { type: "i", value: a } : { type: "f", value: a };
2801
+ if (typeof a === "bigint") return { type: "h", value: a.toString() };
2802
+ if (typeof a === "string") return { type: "s", value: a };
2803
+ if (a instanceof Uint8Array) {
2804
+ let s = "";
2805
+ for (const b of a) s += String.fromCharCode(b);
2806
+ return { type: "b", value: btoa(s) };
2807
+ }
2808
+ if (a instanceof Date) return { type: "t", value: a.toISOString() };
2809
+ throw new TypeError(`unsupported OSC argument ${typeof a}`);
2810
+ }
2811
+ var OscRepository = class {
2812
+ constructor(c) {
2813
+ this.c = c;
2814
+ }
2815
+ c;
2816
+ /** Sends [address] [args] to the configured OSC [target] (gateway / target id). */
2817
+ async send(address, args, target) {
2818
+ if (!address.startsWith("/")) throw new TypeError("OSC address must start with /");
2819
+ const body = { target, address, args: args.map(oscArg) };
2820
+ await this.c.api.call(Operations10.sendOsc, { body, preferRealtime: true });
2821
+ }
2822
+ /** OSC traffic of gateways (`gateway.message` events). */
2823
+ messages(fn, gatewayId = "+") {
2824
+ return this.c.hub.on(
2825
+ [gatewayId === "+" ? "gateways/+" : DomeTopics7.gateway(gatewayId)],
2826
+ (e) => {
2827
+ const r = e.resource ?? e.data;
2828
+ if (typeof r?.address === "string")
2829
+ fn({ address: r.address, args: r.args ?? [], target: e.topic.split("/")[1] ?? "" });
2830
+ }
2831
+ );
2832
+ }
2833
+ };
2834
+
2835
+ // src/repositories/playback.ts
2836
+ import {
2837
+ DomeTopics as DomeTopics8,
2838
+ EventKinds as EventKinds4,
2839
+ Operations as Operations11,
2840
+ jsonMergePatch as jsonMergePatch3,
2841
+ rfc3339Millis as rfc3339Millis3
2842
+ } from "@freedome/protocol";
2843
+ var PlayTargets = {
2844
+ show: (showId, o = {}) => ({
2845
+ kind: "show",
2846
+ showId,
2847
+ ...o
2848
+ }),
2849
+ playlist: (playlistId, o = {}) => ({
2850
+ kind: "playlist",
2851
+ playlistId,
2852
+ ...o
2853
+ }),
2854
+ asset: (assetId) => ({ kind: "asset", assetId }),
2855
+ app: (app, payload) => ({ kind: "app", app, payload }),
2856
+ current: () => ({ kind: "current" })
2857
+ };
2858
+ var Fader = class {
2859
+ constructor(send) {
2860
+ this.send = send;
2861
+ }
2862
+ send;
2863
+ busy = false;
2864
+ pending;
2865
+ waiters = [];
2866
+ set(body) {
2867
+ return new Promise((resolve, reject) => {
2868
+ this.waiters.push({ resolve, reject });
2869
+ this.pending = { body };
2870
+ if (!this.busy) void this.pump();
2871
+ });
2872
+ }
2873
+ async pump() {
2874
+ this.busy = true;
2875
+ try {
2876
+ while (this.pending) {
2877
+ const { body } = this.pending;
2878
+ this.pending = void 0;
2879
+ const waiters = this.waiters;
2880
+ this.waiters = [];
2881
+ try {
2882
+ const r = await this.send(body);
2883
+ if (!this.pending) for (const w of waiters) w.resolve(r);
2884
+ else this.waiters.unshift(...waiters);
2885
+ } catch (e) {
2886
+ if (e instanceof RateLimitedError) {
2887
+ await new Promise((r) => setTimeout(r, e.retryAfterMs ?? 250));
2888
+ this.pending ??= { body };
2889
+ this.waiters.unshift(...waiters);
2890
+ } else if (this.pending) {
2891
+ this.waiters.unshift(...waiters);
2892
+ } else for (const w of waiters) w.reject(e);
2893
+ }
2894
+ }
2895
+ } finally {
2896
+ this.busy = false;
2897
+ }
2898
+ }
2899
+ };
2900
+ var PlayerHandle = class {
2901
+ constructor(c, venueId, playerId) {
2902
+ this.c = c;
2903
+ this.venueId = venueId;
2904
+ this.playerId = playerId;
2905
+ }
2906
+ c;
2907
+ venueId;
2908
+ playerId;
2909
+ states = new Emitter();
2910
+ last;
2911
+ listeners = 0;
2912
+ offEvents;
2913
+ offSnapshot;
2914
+ faders = /* @__PURE__ */ new Map();
2915
+ get params() {
2916
+ return { venueId: this.venueId, playerId: this.playerId };
2917
+ }
2918
+ /** Latest known state. */
2919
+ get value() {
2920
+ return this.last;
2921
+ }
2922
+ push(s) {
2923
+ this.last = s;
2924
+ this.states.emit(s);
2925
+ }
2926
+ /** Follows the player's state (subscribes while at least one watcher). */
2927
+ watch(fn) {
2928
+ const off = this.states.on(fn);
2929
+ if (this.listeners++ === 0) {
2930
+ const topic = DomeTopics8.player(this.playerId, this.venueId);
2931
+ this.offEvents = this.c.hub.on([topic], (e) => {
2932
+ if (e.kind === EventKinds4.playerState || e.kind === EventKinds4.playerError) {
2933
+ if (e.resource && typeof e.resource === "object")
2934
+ this.push({ state: e.resource });
2935
+ } else if (e.kind === EventKinds4.playerPosition && e.patch && this.last) {
2936
+ this.push({ state: jsonMergePatch3(this.last.state, e.patch) });
2937
+ }
2938
+ });
2939
+ this.offSnapshot = this.c.hub.onSnapshot(topic, async () => {
2940
+ await this.refresh();
2941
+ });
2942
+ if (!this.last)
2943
+ void this.refresh().catch(
2944
+ (e) => this.c.log("warning", `player ${this.playerId}: initial read failed`, e)
2945
+ );
2946
+ }
2947
+ if (this.last) fn(this.last);
2948
+ let done = false;
2949
+ return () => {
2950
+ if (done) return;
2951
+ done = true;
2952
+ off();
2953
+ if (--this.listeners === 0) {
2954
+ this.offEvents?.();
2955
+ this.offSnapshot?.();
2956
+ }
2957
+ };
2958
+ }
2959
+ /** Re-reads the state (cache-backed). */
2960
+ async refresh() {
2961
+ const snap = await this.c.cachedRead(
2962
+ `players/${this.venueId}/${this.playerId}`,
2963
+ async () => {
2964
+ const s = await this.c.api.json(Operations11.getPlayer, { params: this.params });
2965
+ return [{ state: s }, s];
2966
+ },
2967
+ (json, asOf) => ({ state: json, stale: true, asOf })
2968
+ );
2969
+ this.push(snap);
2970
+ return snap;
2971
+ }
2972
+ async command(op, body) {
2973
+ const res = await this.c.api.call(op, {
2974
+ params: this.params,
2975
+ ...body === void 0 ? {} : { body },
2976
+ preferRealtime: true
2977
+ });
2978
+ const j = res.body.length ? res.json : void 0;
2979
+ if (j && typeof j === "object" && "status" in j && !("kind" in j && "progress" in j)) {
2980
+ this.push({ state: j });
2981
+ return j;
2982
+ }
2983
+ return void 0;
2984
+ }
2985
+ fader(key, body, send) {
2986
+ let f = this.faders.get(key);
2987
+ if (!f) {
2988
+ f = new Fader(send);
2989
+ this.faders.set(key, f);
2990
+ }
2991
+ return f.set(body);
2992
+ }
2993
+ /** Plays [target] (optionally from [positionMs], at server time [at] for multi-node sync). */
2994
+ async play(target, o = {}) {
2995
+ if (target.kind === "app") {
2996
+ await this.c.api.call(Operations11.publishAppPayload, {
2997
+ params: { app: target.app },
2998
+ body: target.payload,
2999
+ preferRealtime: true
3000
+ });
3001
+ return void 0;
3002
+ }
3003
+ const req = {};
3004
+ if (target.kind === "show") {
3005
+ req.showId = target.showId;
3006
+ if (target.playlistId) req.playlistId = target.playlistId;
3007
+ if (target.itemIndex !== void 0) req.itemIndex = target.itemIndex;
3008
+ } else if (target.kind === "playlist") {
3009
+ req.playlistId = target.playlistId;
3010
+ if (target.showId) req.showId = target.showId;
3011
+ if (target.itemIndex !== void 0) req.itemIndex = target.itemIndex;
3012
+ } else if (target.kind === "asset") req.assetId = target.assetId;
3013
+ if (o.positionMs !== void 0) req.position = o.positionMs / 1e3;
3014
+ if (o.at) req.at = rfc3339Millis3(o.at);
3015
+ return this.command(Operations11.play, req);
3016
+ }
3017
+ pause() {
3018
+ return this.command(Operations11.pause);
3019
+ }
3020
+ resume() {
3021
+ return this.command(Operations11.resume);
3022
+ }
3023
+ stop() {
3024
+ return this.command(Operations11.stop);
3025
+ }
3026
+ next() {
3027
+ return this.command(Operations11.next);
3028
+ }
3029
+ previous() {
3030
+ return this.command(Operations11.previous);
3031
+ }
3032
+ /** Seeks (coalesced while scrubbing). */
3033
+ seek(positionMs) {
3034
+ return this.fader(
3035
+ "seek",
3036
+ { position: positionMs / 1e3 },
3037
+ (b) => this.command(Operations11.seek, b)
3038
+ );
3039
+ }
3040
+ seekToMarker(marker) {
3041
+ return this.command(Operations11.seek, { marker });
3042
+ }
3043
+ patch(body) {
3044
+ return this.fader(
3045
+ `patch:${Object.keys(body).join(",")}`,
3046
+ body,
3047
+ (b) => this.command(Operations11.patchPlayer, b)
3048
+ );
3049
+ }
3050
+ /** Player volume 0..1 (fader). */
3051
+ setVolume(v) {
3052
+ return this.patch({ volume: unit(v) });
3053
+ }
3054
+ setOpacity(v) {
3055
+ return this.patch({ opacity: unit(v) });
3056
+ }
3057
+ setRate(rate) {
3058
+ return this.patch({ rate });
3059
+ }
3060
+ setLoop(loop) {
3061
+ return this.patch({ loop });
3062
+ }
3063
+ dispose() {
3064
+ this.offEvents?.();
3065
+ this.offSnapshot?.();
3066
+ this.states.close();
3067
+ }
3068
+ };
3069
+ var unit = (v) => Number.isNaN(v) ? 0 : Math.min(1, Math.max(0, v));
3070
+ var PlaybackRepository = class {
3071
+ constructor(c) {
3072
+ this.c = c;
3073
+ }
3074
+ c;
3075
+ players = /* @__PURE__ */ new Map();
3076
+ outputFaders = /* @__PURE__ */ new Map();
3077
+ /** Handle of a player (`main` of the active venue by default). */
3078
+ player(venueId = "default", playerId = "main") {
3079
+ const k = `${venueId}/${playerId}`;
3080
+ let p = this.players.get(k);
3081
+ if (!p) {
3082
+ p = new PlayerHandle(this.c, venueId, playerId);
3083
+ this.players.set(k, p);
3084
+ }
3085
+ return p;
3086
+ }
3087
+ get main() {
3088
+ return this.player();
3089
+ }
3090
+ get value() {
3091
+ return this.main.value;
3092
+ }
3093
+ watch(fn) {
3094
+ return this.main.watch(fn);
3095
+ }
3096
+ list(venueId = "default") {
3097
+ return readAllPages(this.c.api, Operations11.listPlayers, { params: { venueId } });
3098
+ }
3099
+ play(target, o = {}) {
3100
+ return this.main.play(target, o);
3101
+ }
3102
+ pause() {
3103
+ return this.main.pause();
3104
+ }
3105
+ resume() {
3106
+ return this.main.resume();
3107
+ }
3108
+ stop() {
3109
+ return this.main.stop();
3110
+ }
3111
+ seek(positionMs) {
3112
+ return this.main.seek(positionMs);
3113
+ }
3114
+ next() {
3115
+ return this.main.next();
3116
+ }
3117
+ previous() {
3118
+ return this.main.previous();
3119
+ }
3120
+ /** Fires cue [cueId] of the active show (or of [showId]). */
3121
+ async cue(cueId, o = {}) {
3122
+ await this.c.api.call(Operations11.fireCue, {
3123
+ params: { venueId: o.venueId ?? "default", cueId },
3124
+ body: o.showId ? { showId: o.showId } : {},
3125
+ preferRealtime: true
3126
+ });
3127
+ }
3128
+ /** Loads a show onto the venue. */
3129
+ async setActiveShow(showId, o = {}) {
3130
+ await this.c.api.call(Operations11.setActiveShow, {
3131
+ params: { venueId: o.venueId ?? "default" },
3132
+ body: { showId, autoplay: o.autoplay ?? false }
3133
+ });
3134
+ }
3135
+ activeShow(venueId = "default") {
3136
+ return this.c.api.json(Operations11.getActiveShow, { params: { venueId } });
3137
+ }
3138
+ parameters(venueId = "default") {
3139
+ return readAllPages(this.c.api, Operations11.listParameters, {
3140
+ params: { venueId }
3141
+ });
3142
+ }
3143
+ parameter(path, venueId = "default") {
3144
+ return this.c.api.json(Operations11.getParameter, { params: { venueId, path } });
3145
+ }
3146
+ /** Sets a parameter (fader; coalesced). */
3147
+ async setParameter(path, value, venueId = "default") {
3148
+ const k = `param:${venueId}:${path}`;
3149
+ let f = this.outputFaders.get(k);
3150
+ if (!f) {
3151
+ f = new Fader(async (b) => {
3152
+ await this.c.api.call(Operations11.setParameter, {
3153
+ params: { venueId, path },
3154
+ body: b,
3155
+ preferRealtime: true
3156
+ });
3157
+ return void 0;
3158
+ });
3159
+ this.outputFaders.set(k, f);
3160
+ }
3161
+ await f.set({ value });
3162
+ }
3163
+ /** Removes every payload an app published. */
3164
+ async clearAppPayloads(app) {
3165
+ await this.c.api.call(Operations11.clearAppPayloads, { params: { app }, preferRealtime: true });
3166
+ }
3167
+ /** Master output of a venue. */
3168
+ readOutput(venueId = "default") {
3169
+ return this.c.cachedRead(
3170
+ `output/${venueId}`,
3171
+ async () => {
3172
+ const o = await this.c.api.json(Operations11.getOutput, { params: { venueId } });
3173
+ return [o, o];
3174
+ },
3175
+ (json) => json
3176
+ );
3177
+ }
3178
+ /** Follows the master output (`output.changed` events / patches). */
3179
+ watchOutput(fn, venueId = "default") {
3180
+ let last;
3181
+ const off = this.c.hub.on([DomeTopics8.output(venueId)], (e) => {
3182
+ if (e.resource && typeof e.resource === "object") last = e.resource;
3183
+ else if (e.patch && last) last = jsonMergePatch3(last, e.patch);
3184
+ else return;
3185
+ fn(last);
3186
+ });
3187
+ void this.readOutput(venueId).then(
3188
+ (o) => {
3189
+ last ??= o;
3190
+ fn(o);
3191
+ },
3192
+ () => void 0
3193
+ );
3194
+ return off;
3195
+ }
3196
+ patchOutput(p, venueId) {
3197
+ const k = `output:${venueId}:${Object.keys(p).join(",")}`;
3198
+ let f = this.outputFaders.get(k);
3199
+ if (!f) {
3200
+ f = new Fader(
3201
+ (b) => this.c.api.json(Operations11.patchOutput, {
3202
+ params: { venueId },
3203
+ body: b,
3204
+ preferRealtime: true
3205
+ })
3206
+ );
3207
+ this.outputFaders.set(k, f);
3208
+ }
3209
+ return f.set(p);
3210
+ }
3211
+ /** Master volume 0..1. */
3212
+ setVolume(v, venueId = "default") {
3213
+ return this.patchOutput({ volume: unit(v) }, venueId);
3214
+ }
3215
+ /** Master brightness 0..1. */
3216
+ setBrightness(v, venueId = "default") {
3217
+ return this.patchOutput({ brightness: unit(v) }, venueId);
3218
+ }
3219
+ setBlackout(on, venueId = "default") {
3220
+ return this.patchOutput({ blackout: on }, venueId);
3221
+ }
3222
+ /** Dome rotation in degrees. */
3223
+ setRotation(degrees, venueId = "default") {
3224
+ return this.patchOutput({ rotation: degrees }, venueId);
3225
+ }
3226
+ dispose() {
3227
+ for (const p of this.players.values()) p.dispose();
3228
+ }
3229
+ };
3230
+
3231
+ // src/repositories/venues.ts
3232
+ import {
3233
+ DomeTopics as DomeTopics9,
3234
+ EventKinds as EventKinds5,
3235
+ Operations as Operations12
3236
+ } from "@freedome/protocol";
3237
+ var CALIBRATION_FILE_TYPES = {
3238
+ warp: "application/vnd.nativemind.freedome.fdmesh",
3239
+ blend: "image/png",
3240
+ colour: "text/plain"
3241
+ };
3242
+ var VenuesRepository = class {
3243
+ constructor(c) {
3244
+ this.c = c;
3245
+ }
3246
+ c;
3247
+ get api() {
3248
+ return this.c.api;
3249
+ }
3250
+ /** All venues (cache-backed: `stale` while offline). */
3251
+ async list() {
3252
+ return this.c.cachedRead(
3253
+ "venues",
3254
+ async () => {
3255
+ const l = await readAllPages(this.api, Operations12.listVenues);
3256
+ return [{ value: l, etag: void 0 }, l];
3257
+ },
3258
+ (json, asOf) => ({ value: json, etag: void 0, stale: true, asOf })
3259
+ );
3260
+ }
3261
+ /** One venue with its ETag (`default` = the active venue). */
3262
+ async get(venueId = "default") {
3263
+ const res = await this.api.call(Operations12.getVenue, { params: { venueId } });
3264
+ return { value: ApiCaller.decodeBody(Operations12.getVenue, res), etag: res.headers.etag };
3265
+ }
3266
+ /** The venue the server runs now. */
3267
+ async current() {
3268
+ return (await this.get("default")).value;
3269
+ }
3270
+ /** Creates a venue (`POST /venues`; id = `meta.id`). */
3271
+ async create(body) {
3272
+ const res = await this.api.call(Operations12.createVenue, { body });
3273
+ return {
3274
+ value: ApiCaller.decodeBody(Operations12.createVenue, res),
3275
+ etag: res.headers.etag
3276
+ };
3277
+ }
3278
+ /** Replaces a venue (`ifMatch` = ETag; without it: create with If-None-Match: *). 409 / 412 → ConflictError with `latest`. */
3279
+ async save(venueId, body, ifMatch) {
3280
+ try {
3281
+ const res = await this.api.call(Operations12.putVenue, {
3282
+ params: { venueId },
3283
+ body,
3284
+ headers: ifMatch ? { "if-match": ifMatch } : { "if-none-match": "*" }
3285
+ });
3286
+ return {
3287
+ value: ApiCaller.decodeBody(Operations12.putVenue, res),
3288
+ etag: res.headers.etag
3289
+ };
3290
+ } catch (e) {
3291
+ if (!(e instanceof ConflictError)) throw e;
3292
+ let latest;
3293
+ try {
3294
+ latest = await this.get(venueId);
3295
+ } catch (x) {
3296
+ if (!(x instanceof FreedomeError)) throw x;
3297
+ }
3298
+ throw new ConflictError(e.message, {
3299
+ latest,
3300
+ ...e.problem ? { problem: e.problem } : {},
3301
+ ...e.code ? { code: e.code } : {}
3302
+ });
3303
+ }
3304
+ }
3305
+ /** Merge-patches a venue (reads the ETag when not given). */
3306
+ async patch(venueId, patch, ifMatch) {
3307
+ const etag = ifMatch ?? (await this.get(venueId)).etag;
3308
+ const res = await this.api.call(Operations12.patchVenue, {
3309
+ params: { venueId },
3310
+ body: patch,
3311
+ headers: { "if-match": etag }
3312
+ });
3313
+ return {
3314
+ value: ApiCaller.decodeBody(Operations12.patchVenue, res),
3315
+ etag: res.headers.etag
3316
+ };
3317
+ }
3318
+ /** Watches a venue (events, resync re-read, polling while realtime is down). */
3319
+ watch(venueId, obs, intervalMs = 5e3) {
3320
+ return this.c.watchResource(
3321
+ DomeTopics9.venue(venueId),
3322
+ async () => (await this.get(venueId)).value,
3323
+ obs,
3324
+ {
3325
+ intervalMs,
3326
+ kinds: /* @__PURE__ */ new Set([EventKinds5.venueUpdated])
3327
+ }
3328
+ );
3329
+ }
3330
+ /** Exports the venue as `.dome` bytes. */
3331
+ async export(venueId = "default") {
3332
+ const res = await this.api.call(Operations12.exportVenue, {
3333
+ params: { venueId },
3334
+ headers: { accept: "application/vnd.nativemind.freedome.dome+zip, application/problem+json" },
3335
+ timeoutMs: 3e5
3336
+ });
3337
+ return res.body;
3338
+ }
3339
+ /** Calibration block with the venue ETag. */
3340
+ async calibration(venueId = "default") {
3341
+ const res = await this.api.call(Operations12.getCalibration, { params: { venueId } });
3342
+ return {
3343
+ value: ApiCaller.decodeBody(Operations12.getCalibration, res),
3344
+ etag: res.headers.etag
3345
+ };
3346
+ }
3347
+ /** Bytes of a calibration sidecar. */
3348
+ async calibrationFile(venueId, displayId, file) {
3349
+ return (await this.api.call(Operations12.getCalibrationFile, {
3350
+ params: { venueId, displayId, file },
3351
+ headers: { accept: "*/*" }
3352
+ })).body;
3353
+ }
3354
+ /** Uploads a calibration sidecar (If-Match = venue ETag, read when not given). */
3355
+ async putCalibrationFile(venueId, displayId, file, bytes, ifMatch) {
3356
+ const etag = ifMatch ?? (await this.calibration(venueId)).etag;
3357
+ const res = await this.api.call(Operations12.putCalibrationFile, {
3358
+ params: { venueId, displayId, file },
3359
+ bytes,
3360
+ contentType: CALIBRATION_FILE_TYPES[file],
3361
+ headers: { "if-match": etag }
3362
+ });
3363
+ return {
3364
+ value: ApiCaller.decodeBody(Operations12.putCalibrationFile, res),
3365
+ etag: res.headers.etag
3366
+ };
3367
+ }
3368
+ };
3369
+
3370
+ // src/client.ts
3371
+ var FREEDOME_CLIENT_VERSION = "1.1.0";
3372
+ function defaultTransports() {
3373
+ return { rest: (e) => new FetchTransport(e), sockets: webSocketConnector() };
3374
+ }
3375
+ var FreedomeClient = class {
3376
+ credentials;
3377
+ options;
3378
+ tokenStore;
3379
+ cache;
3380
+ outbox;
3381
+ logger;
3382
+ venues;
3383
+ engine;
3384
+ calibration;
3385
+ playback;
3386
+ content;
3387
+ osc;
3388
+ clients;
3389
+ audio;
3390
+ audioReactive;
3391
+ gateways;
3392
+ graphql;
3393
+ /** Connection state changes. */
3394
+ states = new Emitter();
3395
+ /** Session changes. */
3396
+ sessions = new Emitter();
3397
+ transports;
3398
+ api;
3399
+ hub = new EventHub();
3400
+ ctx;
3401
+ random;
3402
+ customConnector;
3403
+ endpointValue;
3404
+ serverInfo;
3405
+ sessionValue = NO_SESSION;
3406
+ stateValue = "idle";
3407
+ reason;
3408
+ refreshing;
3409
+ channel;
3410
+ offChannel = [];
3411
+ retry;
3412
+ background;
3413
+ attempt = 0;
3414
+ suspended = false;
3415
+ engineDegraded = false;
3416
+ connecting = false;
3417
+ constructor(init) {
3418
+ const o = init.options ?? {};
3419
+ this.options = {
3420
+ realtime: o.realtime ?? "ws",
3421
+ requestTimeoutMs: o.requestTimeoutMs ?? 1e4,
3422
+ heartbeatMs: o.heartbeatMs ?? 15e3,
3423
+ reconnect: o.reconnect ?? new BackoffPolicy(),
3424
+ offline: { ...DEFAULT_OFFLINE_POLICY, ...o.offline },
3425
+ appName: o.appName ?? "app",
3426
+ appVersion: o.appVersion ?? "0",
3427
+ pairingPollIntervalMs: o.pairingPollIntervalMs ?? 1e3,
3428
+ backgroundGraceMs: o.backgroundGraceMs ?? 3e4,
3429
+ ...o.positionHz !== void 0 ? { positionHz: o.positionHz } : {}
3430
+ };
3431
+ this.endpointValue = init.endpoint;
3432
+ this.credentials = init.credentials ?? { kind: "guest" };
3433
+ this.tokenStore = init.tokenStore ?? new InMemoryTokenStore();
3434
+ this.cache = init.cache ?? new InMemoryCacheStore();
3435
+ this.outbox = init.outbox;
3436
+ this.logger = init.logger;
3437
+ this.transports = init.transports ?? defaultTransports();
3438
+ this.customConnector = init.realtimeConnector;
3439
+ this.random = init.random ?? Math.random;
3440
+ this.api = new ApiCaller(
3441
+ this.transports.rest(init.endpoint),
3442
+ this.userAgent,
3443
+ this.options.requestTimeoutMs,
3444
+ init.logger
3445
+ );
3446
+ this.api.onUnauthorized = () => this.refresh();
3447
+ this.api.realtime = () => this.channel;
3448
+ this.api.isOffline = () => this.stateValue === "offline";
3449
+ this.api.onTransportFailure = () => this.onTransportFailure();
3450
+ this.hub.onSubscribe = (f) => this.subscribeFilters(f);
3451
+ this.hub.onUnsubscribe = async (f) => {
3452
+ await this.channel?.unsubscribe(f);
3453
+ };
3454
+ this.ctx = new RepositoryContext(
3455
+ this.api,
3456
+ this.hub,
3457
+ this.cache,
3458
+ this.outbox,
3459
+ this.options.offline,
3460
+ () => this.stateValue === "offline",
3461
+ () => this.endpointValue.storageKey,
3462
+ () => this.channel !== void 0,
3463
+ this.options.positionHz,
3464
+ (s) => this.onEngineHealth(s),
3465
+ init.logger,
3466
+ () => this.contractVersion
3467
+ );
3468
+ this.graphql = new GraphqlClient(this.api);
3469
+ this.venues = new VenuesRepository(this.ctx);
3470
+ this.engine = new EngineRepository(this.ctx);
3471
+ this.calibration = new CalibrationRepository(this.ctx);
3472
+ this.playback = new PlaybackRepository(this.ctx);
3473
+ this.content = new ContentRepository(this.ctx);
3474
+ this.osc = new OscRepository(this.ctx);
3475
+ this.clients = new ClientsRepository(this.ctx);
3476
+ this.audio = new AudioRepository(this.ctx);
3477
+ this.audioReactive = new AudioReactiveRepository(this.ctx);
3478
+ this.gateways = new GatewaysRepository(this.ctx);
3479
+ }
3480
+ get userAgent() {
3481
+ return `${this.options.appName}/${this.options.appVersion} @freedome/client/${FREEDOME_CLIENT_VERSION}`;
3482
+ }
3483
+ get endpoint() {
3484
+ return this.endpointValue;
3485
+ }
3486
+ get server() {
3487
+ return this.serverInfo;
3488
+ }
3489
+ /**
3490
+ * Contract version the server reports (`contractVersion` of `GET /info`); undefined before [open], or when the server
3491
+ * reports none or an unreadable one. This is how an app tells what a server offers: a 1.0 server has no audio control
3492
+ * (`ProtocolVersions.audioControl`, `AudioRepository.supportsAudioControl`).
3493
+ */
3494
+ get contractVersion() {
3495
+ const v = this.serverInfo?.contractVersion;
3496
+ return typeof v === "string" ? SemVer2.tryParse(v) ?? void 0 : void 0;
3497
+ }
3498
+ get state() {
3499
+ return this.stateValue;
3500
+ }
3501
+ /** Reason of `degraded` / `offline` / `reconnecting`. */
3502
+ get stateReason() {
3503
+ return this.reason;
3504
+ }
3505
+ get session() {
3506
+ return this.sessionValue;
3507
+ }
3508
+ /** Transport of the open realtime channel. */
3509
+ get realtimeTransport() {
3510
+ return this.channel?.kind;
3511
+ }
3512
+ /** Replay results of queued writes. */
3513
+ get outboxOutcomes() {
3514
+ return this.ctx.outboxOutcomes;
3515
+ }
3516
+ /** Whether the server advertises [capability] (`transport.ws`, `audio`, dotted paths into `capabilities`). */
3517
+ supports(capability) {
3518
+ const info = this.serverInfo;
3519
+ if (!info) return false;
3520
+ const transport = capability.startsWith("transport.");
3521
+ let node = transport ? info.transports : info.capabilities;
3522
+ for (const seg of (transport ? capability.slice(10) : capability).split(".")) {
3523
+ if (Array.isArray(node)) return node.includes(seg);
3524
+ if (typeof node === "object" && node !== null) node = node[seg];
3525
+ else return false;
3526
+ }
3527
+ if (node === void 0 || node === null || node === false) return false;
3528
+ if (Array.isArray(node)) return node.length > 0;
3529
+ if (typeof node === "object") return Object.keys(node).length > 0;
3530
+ return true;
3531
+ }
3532
+ /** Events matching [filters] (`+` / `#` wildcards); subscribes while listened to. */
3533
+ on(filters, fn) {
3534
+ return this.hub.on(typeof filters === "string" ? [filters] : filters, fn);
3535
+ }
3536
+ /** Raw contract call (escape hatch for operations without a repository method). */
3537
+ send(op, o = {}) {
3538
+ return this.api.call(op, o);
3539
+ }
3540
+ /** Raw call returning parsed JSON. */
3541
+ async request(op, o = {}) {
3542
+ const res = await this.api.call(op, {
3543
+ ...o,
3544
+ headers: { ...o.headers, ...o.ifMatch ? { "if-match": o.ifMatch } : {} }
3545
+ });
3546
+ return res.body.length ? res.json : void 0;
3547
+ }
3548
+ set(s, reason) {
3549
+ this.reason = s === "degraded" || s === "offline" || s === "reconnecting" ? reason ?? this.reason : void 0;
3550
+ if (this.stateValue === s) return;
3551
+ this.stateValue = s;
3552
+ this.states.emit(s);
3553
+ this.log("info", `state \u2192 ${s}${reason ? ` (${reason})` : ""}`);
3554
+ }
3555
+ setSession(s) {
3556
+ this.sessionValue = s;
3557
+ this.sessions.emit(s);
3558
+ }
3559
+ log(level, message, error) {
3560
+ this.logger?.({ level, message, ...error === void 0 ? {} : { error } });
3561
+ }
3562
+ /** Negotiates, authenticates and starts realtime. */
3563
+ async open() {
3564
+ if (this.stateValue === "closed") throw new Error("client is closed");
3565
+ await this.negotiate();
3566
+ this.set("authenticating");
3567
+ try {
3568
+ await this.authenticate();
3569
+ } catch (e) {
3570
+ if (e instanceof UnauthorizedError || e instanceof ForbiddenError) this.set("unauthorized");
3571
+ else if (e instanceof NetworkError) this.set("offline", "server not reachable");
3572
+ throw e;
3573
+ }
3574
+ await this.startRealtime(true);
3575
+ }
3576
+ async negotiate() {
3577
+ this.set("negotiating");
3578
+ let info;
3579
+ try {
3580
+ info = await this.api.json(Operations13.getInfo, { authenticated: false });
3581
+ } catch (e) {
3582
+ if (e instanceof NetworkError) {
3583
+ this.set("offline", "server not reachable");
3584
+ throw e;
3585
+ }
3586
+ if (e instanceof RequestTimeoutError) {
3587
+ this.set("offline", "server not answering");
3588
+ throw e;
3589
+ }
3590
+ this.set("incompatible");
3591
+ throw new IncompatibleServerError(
3592
+ `no Freedome API v1 at ${this.endpointValue.apiBase} (${e.message})`,
3593
+ [],
3594
+ ProtocolVersions2.apiMajors
3595
+ );
3596
+ }
3597
+ const versions = (info.apiVersions ?? []).map(String);
3598
+ const majors = versions.map((v) => Number.parseInt(v.replace(/^v/, ""), 10));
3599
+ if (!majors.some((m) => ProtocolVersions2.apiMajors.includes(m))) {
3600
+ this.set("incompatible");
3601
+ throw new IncompatibleServerError(
3602
+ `server speaks ${versions.join(", ")}, this client v${ProtocolVersions2.apiMajors.join(", v")}`,
3603
+ versions,
3604
+ ProtocolVersions2.apiMajors
3605
+ );
3606
+ }
3607
+ this.serverInfo = info;
3608
+ const id = info.instanceId;
3609
+ if (!this.endpointValue.id && id) this.endpointValue = this.endpointValue.withId(id);
3610
+ return info;
3611
+ }
3612
+ async authenticate() {
3613
+ const key = this.endpointValue.storageKey;
3614
+ const c = this.credentials;
3615
+ const client = { app: this.options.appName, appVersion: this.options.appVersion };
3616
+ switch (c.kind) {
3617
+ case "guest":
3618
+ this.api.authorization = void 0;
3619
+ this.setSession({ role: "guest", scopes: scopesOfRole("guest") });
3620
+ return;
3621
+ case "apiKey":
3622
+ this.api.authorization = `Bearer ${c.key}`;
3623
+ this.setSession(sessionFromPrincipal(await this.api.json(Operations13.getMe)));
3624
+ return;
3625
+ case "password": {
3626
+ const stored = await this.tokenStore.read(key);
3627
+ if (stored && await this.tryStored(stored)) return;
3628
+ const t = await this.api.json(Operations13.createSession, {
3629
+ body: { username: c.username, password: c.password, client },
3630
+ authenticated: false
3631
+ });
3632
+ await this.adopt(t, c.username);
3633
+ return;
3634
+ }
3635
+ case "pairing": {
3636
+ const stored = await this.tokenStore.read(key);
3637
+ if (stored && await this.tryStored(stored)) return;
3638
+ await this.pair(c);
3639
+ return;
3640
+ }
3641
+ case "cloud": {
3642
+ const stored = await this.tokenStore.read(key);
3643
+ if (stored && await this.tryStored(stored)) return;
3644
+ const t = await this.api.json(Operations13.exchangeCloudToken, {
3645
+ body: { subjectToken: await c.token(), client },
3646
+ authenticated: false
3647
+ });
3648
+ await this.adopt(t);
3649
+ return;
3650
+ }
3651
+ }
3652
+ }
3653
+ async tryStored(t) {
3654
+ this.api.authorization = `Bearer ${t.accessToken}`;
3655
+ try {
3656
+ this.setSession(sessionFromPrincipal(await this.api.json(Operations13.getMe)));
3657
+ return true;
3658
+ } catch (e) {
3659
+ if (!(e instanceof UnauthorizedError)) throw e;
3660
+ await this.tokenStore.delete(this.endpointValue.storageKey);
3661
+ this.api.authorization = void 0;
3662
+ return false;
3663
+ }
3664
+ }
3665
+ async adopt(t, user) {
3666
+ this.api.authorization = `Bearer ${t.accessToken}`;
3667
+ await this.tokenStore.write(this.endpointValue.storageKey, storedTokensOf(t));
3668
+ this.setSession(sessionFromTokens(t, user ?? this.sessionValue.user));
3669
+ }
3670
+ async pair(p) {
3671
+ let pairing = await this.api.json(Operations13.createPairing, {
3672
+ body: {
3673
+ app: p.app,
3674
+ deviceName: p.deviceName,
3675
+ ...p.requestedRole ? { requestedRole: p.requestedRole } : {}
3676
+ },
3677
+ authenticated: false
3678
+ });
3679
+ const pr = () => pairing;
3680
+ const linkCode = p.code ?? this.endpointValue.pairingCode;
3681
+ const code = pr().code;
3682
+ if (code) {
3683
+ if (linkCode && linkCode !== code)
3684
+ this.log(
3685
+ "warning",
3686
+ `pairing code from the link differs from the server's \u2014 approve ${code} on the dome`
3687
+ );
3688
+ if (pr().status !== "approved") p.onCode?.(code);
3689
+ }
3690
+ const deadline = Date.now() + (p.timeoutMs ?? 12e4);
3691
+ while (!["approved", "denied", "expired", "revoked"].includes(pr().status)) {
3692
+ if (Date.now() > deadline) throw new UnauthorizedError("pairing was not approved in time");
3693
+ await new Promise((r) => setTimeout(r, this.options.pairingPollIntervalMs));
3694
+ pairing = await this.api.json(Operations13.getPairing, {
3695
+ params: { pairingId: pr().pairingId },
3696
+ authenticated: false
3697
+ });
3698
+ }
3699
+ const tokens = pr().tokens;
3700
+ if (pr().status !== "approved" || !tokens)
3701
+ throw new UnauthorizedError(`pairing ${pr().status}`);
3702
+ await this.adopt(tokens, p.deviceName);
3703
+ }
3704
+ refresh() {
3705
+ this.refreshing ??= (async () => {
3706
+ try {
3707
+ if (this.credentials.kind === "apiKey" || this.credentials.kind === "guest") return false;
3708
+ const stored = await this.tokenStore.read(this.endpointValue.storageKey);
3709
+ const rt = stored?.refreshToken;
3710
+ if (!rt) return await this.reauthenticate();
3711
+ try {
3712
+ const t = await this.api.json(Operations13.refreshSession, {
3713
+ body: { refreshToken: rt },
3714
+ authenticated: false
3715
+ });
3716
+ await this.adopt(t);
3717
+ return true;
3718
+ } catch (e) {
3719
+ if (!(e instanceof UnauthorizedError)) throw e;
3720
+ this.log("warning", "refresh rejected", e);
3721
+ await this.tokenStore.delete(this.endpointValue.storageKey);
3722
+ return await this.reauthenticate();
3723
+ }
3724
+ } finally {
3725
+ this.refreshing = void 0;
3726
+ }
3727
+ })();
3728
+ return this.refreshing;
3729
+ }
3730
+ async reauthenticate() {
3731
+ if (this.credentials.kind === "cloud") {
3732
+ try {
3733
+ this.api.authorization = void 0;
3734
+ await this.authenticate();
3735
+ return true;
3736
+ } catch (e) {
3737
+ this.log("warning", "cloud re-authentication failed", e);
3738
+ }
3739
+ }
3740
+ this.api.authorization = void 0;
3741
+ this.setSession(NO_SESSION);
3742
+ this.set("unauthorized");
3743
+ await this.dropRealtime();
3744
+ return false;
3745
+ }
3746
+ /** Ends the session on the server and locally. */
3747
+ async logout() {
3748
+ if (this.api.authorization && this.credentials.kind !== "apiKey") {
3749
+ try {
3750
+ await this.api.call(Operations13.deleteSession);
3751
+ } catch (e) {
3752
+ this.log("warning", "logout", e);
3753
+ }
3754
+ }
3755
+ await this.tokenStore.delete(this.endpointValue.storageKey);
3756
+ this.api.authorization = void 0;
3757
+ this.setSession(NO_SESSION);
3758
+ if (this.retry) clearTimeout(this.retry);
3759
+ await this.dropRealtime();
3760
+ this.set("unauthorized");
3761
+ }
3762
+ get token() {
3763
+ const a = this.api.authorization;
3764
+ return a?.startsWith("Bearer ") ? a.slice(7) : void 0;
3765
+ }
3766
+ connector() {
3767
+ if (this.customConnector) return this.customConnector;
3768
+ const kind = this.options.realtime;
3769
+ if (kind === "none") return void 0;
3770
+ const log = this.logger ? { logger: this.logger } : {};
3771
+ if (kind === "socketIo") {
3772
+ return (_k, hello, o) => SocketIoChannel.open(this.endpointValue, hello, { timeoutMs: o.timeoutMs, ...log });
3773
+ }
3774
+ const sockets = this.transports.sockets;
3775
+ if (!sockets) return void 0;
3776
+ return async (k, hello, o) => {
3777
+ if (k === "graphqlWs") {
3778
+ const s2 = await sockets(
3779
+ this.endpointValue,
3780
+ "/api/v1/graphql",
3781
+ [GRAPHQL_WS_SUBPROTOCOL],
3782
+ o.timeoutMs
3783
+ );
3784
+ return GraphqlWsChannel.open(s2, hello, { ...o, ...log });
3785
+ }
3786
+ const s = await sockets(this.endpointValue, "/api/v1/ws", [WS_SUBPROTOCOL], o.timeoutMs);
3787
+ return WsChannel.open(s, hello, { ...o, ...log });
3788
+ };
3789
+ }
3790
+ async startRealtime(initial = false) {
3791
+ const connect = this.connector();
3792
+ if (!connect) {
3793
+ const none = this.options.realtime === "none";
3794
+ this.set(
3795
+ none ? "online" : "degraded",
3796
+ none ? void 0 : `realtime transport ${this.options.realtime} not available`
3797
+ );
3798
+ void this.replayOutbox();
3799
+ return;
3800
+ }
3801
+ if (this.connecting) return;
3802
+ this.connecting = true;
3803
+ try {
3804
+ if (!initial) this.set("resyncing");
3805
+ let ch;
3806
+ try {
3807
+ const token = this.token;
3808
+ const since = this.hub.lastSeq;
3809
+ ch = await connect(
3810
+ this.options.realtime,
3811
+ {
3812
+ app: this.options.appName,
3813
+ appVersion: this.options.appVersion,
3814
+ sdk: `@freedome/client/${FREEDOME_CLIENT_VERSION}`,
3815
+ ...token ? { token } : {},
3816
+ ...since !== void 0 ? { sinceSeq: since } : {}
3817
+ },
3818
+ { timeoutMs: this.options.requestTimeoutMs, heartbeatMs: this.options.heartbeatMs }
3819
+ );
3820
+ } catch (e) {
3821
+ if (e instanceof UnauthorizedError) {
3822
+ if (await this.refresh()) {
3823
+ this.connecting = false;
3824
+ return await this.startRealtime(initial);
3825
+ }
3826
+ return;
3827
+ }
3828
+ if (e instanceof FreedomeError) {
3829
+ this.log("warning", "realtime connect failed", e);
3830
+ this.set("degraded", `realtime unavailable: ${e.message}`);
3831
+ this.scheduleReconnect();
3832
+ return;
3833
+ }
3834
+ throw e;
3835
+ }
3836
+ if (this.stateValue === "closed") {
3837
+ await ch.close();
3838
+ return;
3839
+ }
3840
+ this.channel = ch;
3841
+ this.attempt = 0;
3842
+ const epochChanged = this.hub.newEpoch(
3843
+ ch.welcome?.instanceId ?? this.serverInfo?.instanceId
3844
+ );
3845
+ this.offChannel = [
3846
+ ch.events.on((e) => this.hub.dispatch(e)),
3847
+ ch.resyncs.on((r) => {
3848
+ this.log("info", `resync ${r.reason}: ${r.topics.join(",")}`);
3849
+ void this.hub.snapshot(r.topics);
3850
+ })
3851
+ ];
3852
+ void ch.closed.then((c) => this.onRealtimeClosed(ch, c));
3853
+ const filters = this.hub.filters;
3854
+ if (filters.length) {
3855
+ try {
3856
+ const since = this.hub.lastSeq;
3857
+ await ch.subscribe(filters, {
3858
+ ...since !== void 0 ? { sinceSeq: since } : {},
3859
+ ...this.options.positionHz !== void 0 ? { positionHz: this.options.positionHz } : {}
3860
+ });
3861
+ } catch (e) {
3862
+ this.log("warning", "re-subscribe failed", e);
3863
+ }
3864
+ await this.seedSeq(filters);
3865
+ }
3866
+ if (!initial || epochChanged) await this.hub.snapshot(["#"]);
3867
+ if (this.stateValue !== "closed" && this.channel === ch) {
3868
+ this.set(
3869
+ this.engineDegraded ? "degraded" : "online",
3870
+ this.engineDegraded ? "engine degraded" : void 0
3871
+ );
3872
+ void this.replayOutbox();
3873
+ }
3874
+ } finally {
3875
+ this.connecting = false;
3876
+ }
3877
+ }
3878
+ async replayOutbox() {
3879
+ if (!this.outbox) return;
3880
+ await this.ctx.replayOutbox(async (e) => {
3881
+ const op = Operations13[e.operationId];
3882
+ if (!op || op.method !== "PUT" && op.method !== "PATCH") return void 0;
3883
+ const get = Object.values(Operations13).find(
3884
+ (o) => o.method === "GET" && o.path === op.path
3885
+ );
3886
+ if (!get) return void 0;
3887
+ const res = await this.api.call(get, { params: e.params });
3888
+ return { value: res.json, etag: res.headers.etag };
3889
+ });
3890
+ }
3891
+ async subscribeFilters(filters) {
3892
+ const ch = this.channel;
3893
+ if (!ch) return false;
3894
+ await ch.subscribe(
3895
+ filters,
3896
+ this.options.positionHz !== void 0 ? { positionHz: this.options.positionHz } : {}
3897
+ );
3898
+ await this.seedSeq(filters);
3899
+ return true;
3900
+ }
3901
+ async seedSeq(filters) {
3902
+ if (this.hub.lastSeq !== void 0) return;
3903
+ try {
3904
+ const page = await this.api.json(Operations13.listEvents, {
3905
+ query: { topics: filters.join(","), limit: "1" }
3906
+ });
3907
+ if (typeof page.lastSeq === "number") this.hub.seed(page.lastSeq);
3908
+ } catch (e) {
3909
+ this.log("debug", `no resume point (${e.code ?? e})`);
3910
+ }
3911
+ }
3912
+ async dropRealtime() {
3913
+ const ch = this.channel;
3914
+ this.channel = void 0;
3915
+ for (const off of this.offChannel) off();
3916
+ this.offChannel = [];
3917
+ await ch?.close();
3918
+ }
3919
+ onRealtimeClosed(ch, c) {
3920
+ if (this.channel !== ch) return;
3921
+ this.channel = void 0;
3922
+ for (const off of this.offChannel) off();
3923
+ this.offChannel = [];
3924
+ if (this.stateValue === "closed" || this.suspended) return;
3925
+ this.log("warning", `realtime lost: ${c.code ?? ""} ${c.reason ?? ""}`);
3926
+ if (isAuthFailure(c)) {
3927
+ void this.refresh().then((ok) => {
3928
+ if (ok) this.scheduleReconnect(true);
3929
+ else if (this.stateValue !== "unauthorized" && this.stateValue !== "closed") {
3930
+ this.api.authorization = void 0;
3931
+ this.setSession(NO_SESSION);
3932
+ this.set("unauthorized", c.reason);
3933
+ }
3934
+ });
3935
+ return;
3936
+ }
3937
+ this.set("reconnecting", c.reason);
3938
+ this.scheduleReconnect();
3939
+ }
3940
+ onTransportFailure() {
3941
+ if (this.stateValue === "online" || this.stateValue === "degraded")
3942
+ this.scheduleReconnect(this.channel === void 0);
3943
+ }
3944
+ onEngineHealth(status) {
3945
+ const degraded = status !== "up";
3946
+ if (degraded === this.engineDegraded) return;
3947
+ this.engineDegraded = degraded;
3948
+ if (this.stateValue === "online" && degraded) this.set("degraded", `engine ${status}`);
3949
+ else if (this.stateValue === "degraded" && !degraded && this.channel) this.set("online");
3950
+ }
3951
+ scheduleReconnect(immediate = false) {
3952
+ if (this.stateValue === "closed" || this.suspended) return;
3953
+ if (this.retry) clearTimeout(this.retry);
3954
+ const delay = immediate ? 0 : this.options.reconnect.delay(this.attempt, this.random);
3955
+ this.retry = setTimeout(() => void this.reconnect(), delay);
3956
+ }
3957
+ async reconnect() {
3958
+ if (this.stateValue === "closed" || this.suspended || this.connecting) return;
3959
+ if (this.channel && this.stateValue === "online") return;
3960
+ this.attempt++;
3961
+ try {
3962
+ const info = await this.negotiate();
3963
+ if (this.hub.newEpoch(info.instanceId))
3964
+ this.log("info", "server instance changed \u2014 full resync");
3965
+ } catch (e) {
3966
+ if (e instanceof IncompatibleServerError) return;
3967
+ this.set(
3968
+ this.attempt >= this.options.offline.failAfterAttempts ? "offline" : "reconnecting",
3969
+ e.message
3970
+ );
3971
+ this.scheduleReconnect();
3972
+ return;
3973
+ }
3974
+ await this.startRealtime();
3975
+ }
3976
+ /** The OS reports connectivity: reconnect now. */
3977
+ networkAvailable() {
3978
+ this.attempt = 0;
3979
+ if (this.stateValue !== "online" && this.stateValue !== "idle") this.scheduleReconnect(true);
3980
+ }
3981
+ /** The OS reports no network: go offline (reads served from cache). */
3982
+ networkLost() {
3983
+ if (this.stateValue === "closed" || this.stateValue === "idle") return;
3984
+ void this.dropRealtime();
3985
+ this.set("offline", "no network");
3986
+ this.scheduleReconnect();
3987
+ }
3988
+ /** App moved to the background: realtime is suspended after the grace period. */
3989
+ enterBackground() {
3990
+ if (this.background) clearTimeout(this.background);
3991
+ this.background = setTimeout(() => {
3992
+ this.suspended = true;
3993
+ if (this.retry) clearTimeout(this.retry);
3994
+ void this.dropRealtime();
3995
+ this.log("info", "background: realtime suspended");
3996
+ }, this.options.backgroundGraceMs);
3997
+ }
3998
+ /** App back in the foreground. */
3999
+ resume() {
4000
+ if (this.background) clearTimeout(this.background);
4001
+ const was = this.suspended;
4002
+ this.suspended = false;
4003
+ this.attempt = 0;
4004
+ if (was || !this.channel) this.scheduleReconnect(true);
4005
+ }
4006
+ /** Closes everything (terminal). */
4007
+ async close() {
4008
+ if (this.stateValue === "closed") return;
4009
+ this.set("closed");
4010
+ if (this.retry) clearTimeout(this.retry);
4011
+ if (this.background) clearTimeout(this.background);
4012
+ await this.dropRealtime();
4013
+ this.playback.dispose();
4014
+ this.hub.close();
4015
+ this.ctx.close();
4016
+ await this.api.transport.close();
4017
+ this.states.close();
4018
+ this.sessions.close();
4019
+ }
4020
+ };
4021
+
4022
+ // src/discovery.ts
4023
+ import { Operations as Operations14 } from "@freedome/protocol";
4024
+ async function probe(endpoint, timeoutMs = 2e3) {
4025
+ const t = new FetchTransport(endpoint);
4026
+ try {
4027
+ const res = await t.send(
4028
+ {
4029
+ method: Operations14.getInfo.method,
4030
+ path: Operations14.getInfo.path,
4031
+ headers: { accept: "application/json" }
4032
+ },
4033
+ timeoutMs
4034
+ );
4035
+ return res.ok ? res.json : void 0;
4036
+ } catch {
4037
+ return void 0;
4038
+ } finally {
4039
+ await t.close();
4040
+ }
4041
+ }
4042
+ var StaticDiscovery = class {
4043
+ constructor(addresses, verify = true) {
4044
+ this.addresses = addresses;
4045
+ this.verify = verify;
4046
+ }
4047
+ addresses;
4048
+ verify;
4049
+ async scan(timeoutMs = 2e3) {
4050
+ const out = [];
4051
+ await Promise.all(
4052
+ this.addresses.map(async (a) => {
4053
+ const endpoint = typeof a === "string" ? FreedomeEndpoint.parse(a) : a;
4054
+ if (!this.verify) {
4055
+ out.push({ endpoint, source: "static" });
4056
+ return;
4057
+ }
4058
+ const info = await probe(endpoint, timeoutMs);
4059
+ if (info) {
4060
+ const id = info.instanceId;
4061
+ const name = info.name;
4062
+ out.push({
4063
+ endpoint: id ? endpoint.withId(id) : endpoint,
4064
+ source: "static",
4065
+ info,
4066
+ ...name ? { name } : {}
4067
+ });
4068
+ }
4069
+ })
4070
+ );
4071
+ return out;
4072
+ }
4073
+ };
4074
+ var CompositeDiscovery = class {
4075
+ constructor(sources) {
4076
+ this.sources = sources;
4077
+ }
4078
+ sources;
4079
+ async scan(timeoutMs = 2e3) {
4080
+ const all = (await Promise.all(this.sources.map((s) => s.scan(timeoutMs).catch(() => [])))).flat();
4081
+ const seen = /* @__PURE__ */ new Set();
4082
+ return all.filter((d) => {
4083
+ const k = d.endpoint.id ?? d.endpoint.baseUrl;
4084
+ if (seen.has(k)) return false;
4085
+ seen.add(k);
4086
+ return true;
4087
+ });
4088
+ }
4089
+ };
4090
+
4091
+ // src/index.ts
4092
+ import { Operations as Operations15, DomeTopics as DomeTopics10, EventKinds as EventKinds6, ProtocolVersions as ProtocolVersions3, SemVer as SemVer3 } from "@freedome/protocol";
4093
+ var PACKAGE_NAME = "@freedome/client";
4094
+ export {
4095
+ ApiCaller,
4096
+ AudioReactiveRepository,
4097
+ AudioRepository,
4098
+ BackoffPolicy,
4099
+ BlobContentSource,
4100
+ BytesContentSource,
4101
+ CALIBRATION_FILE_TYPES,
4102
+ CalibrationRepository,
4103
+ ClientsRepository,
4104
+ CompositeDiscovery,
4105
+ ConflictError,
4106
+ ContentRepository,
4107
+ Credentials,
4108
+ DEFAULT_OFFLINE_POLICY,
4109
+ DomeTopics10 as DomeTopics,
4110
+ Emitter,
4111
+ EngineRepository,
4112
+ EventHub,
4113
+ EventKinds6 as EventKinds,
4114
+ FREEDOME_CLIENT_VERSION,
4115
+ FetchTransport,
4116
+ ForbiddenError,
4117
+ FreedomeClient,
4118
+ FreedomeEndpoint,
4119
+ FreedomeError,
4120
+ FreedomeResponse,
4121
+ GRAPHQL_EVENTS_SUBSCRIPTION,
4122
+ GRAPHQL_OPERATION,
4123
+ GRAPHQL_WS_SUBPROTOCOL,
4124
+ GatewaysRepository,
4125
+ GeneratorSession,
4126
+ GraphqlClient,
4127
+ GraphqlWsChannel,
4128
+ InMemoryCacheStore,
4129
+ InMemoryOutboxStore,
4130
+ InMemoryTokenStore,
4131
+ IncompatibleServerError,
4132
+ MAX_UPLOAD_CHUNK,
4133
+ NO_SESSION,
4134
+ NetworkError,
4135
+ NotFoundError,
4136
+ OfflineError,
4137
+ Operations15 as Operations,
4138
+ OscRepository,
4139
+ PACKAGE_NAME,
4140
+ PairingLink,
4141
+ PayloadTooLargeError,
4142
+ PlayTargets,
4143
+ PlaybackRepository,
4144
+ PlayerHandle,
4145
+ ProtocolVersions3 as ProtocolVersions,
4146
+ QueuedForReplayError,
4147
+ RateLimitedError,
4148
+ RepositoryContext,
4149
+ RequestTimeoutError,
4150
+ SemVer3 as SemVer,
4151
+ ServerError,
4152
+ Sha256,
4153
+ ShowParts,
4154
+ SocketIoChannel,
4155
+ StaticDiscovery,
4156
+ TlsPinMismatchError,
4157
+ UnauthorizedError,
4158
+ UnsupportedCapabilityError,
4159
+ UnsupportedFormatError,
4160
+ UploadTask,
4161
+ ValidationError,
4162
+ VenuesRepository,
4163
+ WsChannel,
4164
+ audioSessionEnded,
4165
+ base64,
4166
+ can,
4167
+ defaultTransports,
4168
+ errorFromProblem,
4169
+ isAuthFailure,
4170
+ isUnreachable,
4171
+ multipart,
4172
+ nextValue,
4173
+ oscArg,
4174
+ probe,
4175
+ readAllPages,
4176
+ readPage,
4177
+ requestUrl,
4178
+ scopesOfRole,
4179
+ sessionFromPrincipal,
4180
+ sessionFromTokens,
4181
+ sha256Hex,
4182
+ storedTokensOf,
4183
+ uuidV7,
4184
+ webSocketConnector
4185
+ };