@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.
@@ -0,0 +1,1813 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/testing.ts
21
+ var testing_exports = {};
22
+ __export(testing_exports, {
23
+ FakeDomeServer: () => FakeDomeServer,
24
+ createFakeTransport: () => createFakeTransport
25
+ });
26
+ module.exports = __toCommonJS(testing_exports);
27
+ var import_protocol3 = require("@freedome/protocol");
28
+
29
+ // src/endpoint.ts
30
+ var FreedomeEndpoint = class _FreedomeEndpoint {
31
+ constructor(baseUrl, opts = {}) {
32
+ this.opts = opts;
33
+ const u = new URL(String(baseUrl));
34
+ this.baseUrl = `${u.protocol}//${u.host}`;
35
+ }
36
+ opts;
37
+ baseUrl;
38
+ /** `host[:port]`, `http(s)://…` or a `freedome://pair?…` link (default port 8080 / 443). */
39
+ static parse(text) {
40
+ const t = text.trim();
41
+ if (t.startsWith("freedome://")) return PairingLink.parse(t).endpoint;
42
+ const u = new URL(t.includes("://") ? t : `http://${t}`);
43
+ if (u.protocol !== "http:" && u.protocol !== "https:")
44
+ throw new TypeError(`unsupported scheme "${u.protocol}"`);
45
+ if (!u.hostname) throw new TypeError("no host");
46
+ if (!u.port) u.port = u.protocol === "https:" ? "443" : "8080";
47
+ return new _FreedomeEndpoint(u);
48
+ }
49
+ get id() {
50
+ return this.opts.id;
51
+ }
52
+ get tlsFingerprint() {
53
+ return this.opts.tlsFingerprint;
54
+ }
55
+ get pairingCode() {
56
+ return this.opts.pairingCode;
57
+ }
58
+ /** `<base>/api/v1`. */
59
+ get apiBase() {
60
+ return `${this.baseUrl}/api/v1`;
61
+ }
62
+ /** WebSocket base (`ws://` / `wss://`). */
63
+ get wsBase() {
64
+ return this.baseUrl.replace(/^http/, "ws");
65
+ }
66
+ /** Key of the stored tokens / caches (server instance id once known). */
67
+ get storageKey() {
68
+ return this.opts.id ?? this.baseUrl;
69
+ }
70
+ withId(id) {
71
+ return new _FreedomeEndpoint(this.baseUrl, { ...this.opts, id });
72
+ }
73
+ toString() {
74
+ return `FreedomeEndpoint(${this.baseUrl}${this.opts.id ? `, id: ${this.opts.id}` : ""})`;
75
+ }
76
+ };
77
+ var HOST = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*|\[[0-9A-Fa-f:.]+\]|[0-9A-Fa-f:]+:[0-9A-Fa-f:.]*)$/;
78
+ var PairingLink = class _PairingLink {
79
+ constructor(host, port = 8080, opts = {}) {
80
+ this.host = host;
81
+ this.port = port;
82
+ this.opts = opts;
83
+ }
84
+ host;
85
+ port;
86
+ opts;
87
+ static parse(text) {
88
+ let u;
89
+ try {
90
+ u = new URL(text.trim());
91
+ } catch {
92
+ throw new TypeError("not a pairing link");
93
+ }
94
+ if (u.protocol !== "freedome:" || u.hostname !== "pair" && u.host !== "pair")
95
+ throw new TypeError("not a freedome://pair link");
96
+ const q = u.searchParams;
97
+ const host = q.get("host");
98
+ if (!host || !HOST.test(host)) throw new TypeError("pairing link: bad or missing host");
99
+ const portText = q.get("port");
100
+ const port = portText === null ? 8080 : Number(portText);
101
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
102
+ throw new TypeError("pairing link: bad port");
103
+ const id = q.get("id");
104
+ if (id !== null && !/^[A-Za-z0-9._-]{1,64}$/.test(id))
105
+ throw new TypeError("pairing link: bad id");
106
+ const code = q.get("code");
107
+ if (code !== null && !/^[0-9]{6}$/.test(code))
108
+ throw new TypeError("pairing link: code must be 6 digits");
109
+ const fp = q.get("fp");
110
+ if (fp !== null && !/^(?:[0-9A-Fa-f]{2}:?){8,32}$/.test(fp))
111
+ throw new TypeError("pairing link: fp must be \u2265 16 hex digits");
112
+ const name = q.get("name");
113
+ if (name !== null && name.length > 128) throw new TypeError("pairing link: name too long");
114
+ return new _PairingLink(host, port, {
115
+ ...id !== null ? { id } : {},
116
+ ...code !== null ? { code } : {},
117
+ ...fp !== null ? { fingerprint: fp } : {},
118
+ tls: q.get("tls") === "1" || fp !== null,
119
+ ...name !== null ? { name } : {}
120
+ });
121
+ }
122
+ static tryParse(text) {
123
+ try {
124
+ return _PairingLink.parse(text);
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+ get endpoint() {
130
+ const h = this.host.includes(":") && !this.host.startsWith("[") ? `[${this.host}]` : this.host;
131
+ return new FreedomeEndpoint(`${this.opts.tls ? "https" : "http"}://${h}:${this.port}`, {
132
+ ...this.opts.id ? { id: this.opts.id } : {},
133
+ ...this.opts.name ? { name: this.opts.name } : {},
134
+ ...this.opts.fingerprint ? { tlsFingerprint: this.opts.fingerprint } : {},
135
+ ...this.opts.code ? { pairingCode: this.opts.code } : {}
136
+ });
137
+ }
138
+ toString() {
139
+ const q = new URLSearchParams({ host: this.host, port: String(this.port) });
140
+ if (this.opts.id) q.set("id", this.opts.id);
141
+ if (this.opts.code) q.set("code", this.opts.code);
142
+ if (this.opts.fingerprint) q.set("fp", this.opts.fingerprint);
143
+ else if (this.opts.tls) q.set("tls", "1");
144
+ if (this.opts.name) q.set("name", this.opts.name);
145
+ return `freedome://pair?${q.toString()}`;
146
+ }
147
+ };
148
+
149
+ // src/errors.ts
150
+ var FreedomeError = class extends Error {
151
+ code;
152
+ problem;
153
+ constructor(message, opts = {}) {
154
+ super(message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
155
+ this.name = new.target.name;
156
+ this.code = opts.code;
157
+ this.problem = opts.problem;
158
+ }
159
+ };
160
+ var NetworkError = class extends FreedomeError {
161
+ };
162
+
163
+ // src/ids.ts
164
+ var lastMs = 0;
165
+ var seq = 0;
166
+ function randomBytes(n) {
167
+ const b = new Uint8Array(n);
168
+ globalThis.crypto.getRandomValues(b);
169
+ return b;
170
+ }
171
+ function uuidV7(now = Date.now()) {
172
+ if (now === lastMs) seq = seq + 1 & 4095;
173
+ else {
174
+ lastMs = now;
175
+ seq = randomBytes(2).reduce((a, x) => a << 8 | x, 0) & 2047;
176
+ }
177
+ const b = randomBytes(16);
178
+ let t = now;
179
+ for (let i = 5; i >= 0; i--) {
180
+ b[i] = t % 256;
181
+ t = Math.floor(t / 256);
182
+ }
183
+ b[6] = 112 | seq >> 8 & 15;
184
+ b[7] = seq & 255;
185
+ b[8] = 128 | b[8] & 63;
186
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
187
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
188
+ }
189
+
190
+ // src/sha256.ts
191
+ var K = new Uint32Array([
192
+ 1116352408,
193
+ 1899447441,
194
+ 3049323471,
195
+ 3921009573,
196
+ 961987163,
197
+ 1508970993,
198
+ 2453635748,
199
+ 2870763221,
200
+ 3624381080,
201
+ 310598401,
202
+ 607225278,
203
+ 1426881987,
204
+ 1925078388,
205
+ 2162078206,
206
+ 2614888103,
207
+ 3248222580,
208
+ 3835390401,
209
+ 4022224774,
210
+ 264347078,
211
+ 604807628,
212
+ 770255983,
213
+ 1249150122,
214
+ 1555081692,
215
+ 1996064986,
216
+ 2554220882,
217
+ 2821834349,
218
+ 2952996808,
219
+ 3210313671,
220
+ 3336571891,
221
+ 3584528711,
222
+ 113926993,
223
+ 338241895,
224
+ 666307205,
225
+ 773529912,
226
+ 1294757372,
227
+ 1396182291,
228
+ 1695183700,
229
+ 1986661051,
230
+ 2177026350,
231
+ 2456956037,
232
+ 2730485921,
233
+ 2820302411,
234
+ 3259730800,
235
+ 3345764771,
236
+ 3516065817,
237
+ 3600352804,
238
+ 4094571909,
239
+ 275423344,
240
+ 430227734,
241
+ 506948616,
242
+ 659060556,
243
+ 883997877,
244
+ 958139571,
245
+ 1322822218,
246
+ 1537002063,
247
+ 1747873779,
248
+ 1955562222,
249
+ 2024104815,
250
+ 2227730452,
251
+ 2361852424,
252
+ 2428436474,
253
+ 2756734187,
254
+ 3204031479,
255
+ 3329325298
256
+ ]);
257
+ var Sha256 = class {
258
+ h = new Uint32Array([
259
+ 1779033703,
260
+ 3144134277,
261
+ 1013904242,
262
+ 2773480762,
263
+ 1359893119,
264
+ 2600822924,
265
+ 528734635,
266
+ 1541459225
267
+ ]);
268
+ buf = new Uint8Array(64);
269
+ w = new Uint32Array(64);
270
+ bufLen = 0;
271
+ total = 0;
272
+ finished = false;
273
+ update(data) {
274
+ if (this.finished) throw new Error("sha256: already finished");
275
+ let i = 0;
276
+ this.total += data.length;
277
+ if (this.bufLen) {
278
+ const n = Math.min(64 - this.bufLen, data.length);
279
+ this.buf.set(data.subarray(0, n), this.bufLen);
280
+ this.bufLen += n;
281
+ i = n;
282
+ if (this.bufLen === 64) {
283
+ this.block(this.buf, 0);
284
+ this.bufLen = 0;
285
+ }
286
+ }
287
+ for (; i + 64 <= data.length; i += 64) this.block(data, i);
288
+ if (i < data.length) {
289
+ this.buf.set(data.subarray(i), 0);
290
+ this.bufLen = data.length - i;
291
+ }
292
+ return this;
293
+ }
294
+ digest() {
295
+ if (!this.finished) {
296
+ const bits = this.total * 8;
297
+ const pad = new Uint8Array((this.bufLen < 56 ? 56 : 120) - this.bufLen + 8);
298
+ pad[0] = 128;
299
+ const dv2 = new DataView(pad.buffer);
300
+ dv2.setUint32(pad.length - 8, Math.floor(bits / 2 ** 32));
301
+ dv2.setUint32(pad.length - 4, bits >>> 0);
302
+ const t = this.total;
303
+ this.update(pad);
304
+ this.total = t;
305
+ this.finished = true;
306
+ }
307
+ const out = new Uint8Array(32);
308
+ const dv = new DataView(out.buffer);
309
+ for (let j = 0; j < 8; j++) dv.setUint32(j * 4, this.h[j]);
310
+ return out;
311
+ }
312
+ hex() {
313
+ return Array.from(this.digest(), (b) => b.toString(16).padStart(2, "0")).join("");
314
+ }
315
+ block(d, o) {
316
+ const w = this.w;
317
+ for (let j = 0; j < 16; j++)
318
+ w[j] = d[o + j * 4] << 24 | d[o + j * 4 + 1] << 16 | d[o + j * 4 + 2] << 8 | d[o + j * 4 + 3];
319
+ for (let j = 16; j < 64; j++) {
320
+ const a2 = w[j - 15];
321
+ const b2 = w[j - 2];
322
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
323
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
324
+ w[j] = w[j - 16] + s0 + w[j - 7] + s1 | 0;
325
+ }
326
+ let [a, b, c, dd, e, f, g, h] = this.h;
327
+ for (let j = 0; j < 64; j++) {
328
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
329
+ const ch = e & f ^ ~e & g;
330
+ const t1 = h + S1 + ch + K[j] + w[j] | 0;
331
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
332
+ const maj = a & b ^ a & c ^ b & c;
333
+ const t2 = S0 + maj | 0;
334
+ h = g;
335
+ g = f;
336
+ f = e;
337
+ e = dd + t1 | 0;
338
+ dd = c;
339
+ c = b;
340
+ b = a;
341
+ a = t1 + t2 | 0;
342
+ }
343
+ const H = this.h;
344
+ H[0] = H[0] + a | 0;
345
+ H[1] = H[1] + b | 0;
346
+ H[2] = H[2] + c | 0;
347
+ H[3] = H[3] + dd | 0;
348
+ H[4] = H[4] + e | 0;
349
+ H[5] = H[5] + f | 0;
350
+ H[6] = H[6] + g | 0;
351
+ H[7] = H[7] + h | 0;
352
+ }
353
+ };
354
+ var sha256Hex = (data) => new Sha256().update(data).hex();
355
+
356
+ // src/testing/fake-audio.ts
357
+ var import_protocol = require("@freedome/protocol");
358
+
359
+ // src/transport.ts
360
+ var FreedomeResponse = class _FreedomeResponse {
361
+ constructor(status, headers = {}, body = new Uint8Array(0)) {
362
+ this.status = status;
363
+ this.headers = headers;
364
+ this.body = body;
365
+ }
366
+ status;
367
+ headers;
368
+ body;
369
+ get ok() {
370
+ return this.status >= 200 && this.status < 300;
371
+ }
372
+ get text() {
373
+ return new TextDecoder().decode(this.body);
374
+ }
375
+ /** Parsed JSON body (`undefined` when empty). */
376
+ get json() {
377
+ if (this.body.length === 0) return void 0;
378
+ return JSON.parse(this.text);
379
+ }
380
+ static json(status, value, headers = {}) {
381
+ return new _FreedomeResponse(
382
+ status,
383
+ { "content-type": "application/json", ...headers },
384
+ new TextEncoder().encode(JSON.stringify(value))
385
+ );
386
+ }
387
+ };
388
+
389
+ // src/testing/fake-audio.ts
390
+ var ENDED = /* @__PURE__ */ new Set(["finished", "stopped", "failed"]);
391
+ var JOB_ENDED = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
392
+ var FakeAudio = class {
393
+ constructor(publish, problem2, jobs = /* @__PURE__ */ new Map(), audioControl = () => true) {
394
+ this.publish = publish;
395
+ this.problem = problem2;
396
+ this.jobs = jobs;
397
+ this.audioControl = audioControl;
398
+ this.zones.set("front", {
399
+ id: "front",
400
+ name: "Front",
401
+ speakers: ["s1", "s2"],
402
+ gainDb: 0,
403
+ delayMs: 0,
404
+ eq: [],
405
+ mute: false,
406
+ revision: 1
407
+ });
408
+ this.devices.set("spk-1", {
409
+ id: "spk-1",
410
+ kind: "speaker",
411
+ name: "Speaker 1",
412
+ state: { online: true, gainDb: 0, mute: false }
413
+ });
414
+ this.devices.set("qrd-1", {
415
+ id: "qrd-1",
416
+ kind: "qrd",
417
+ name: "QRD hub",
418
+ state: { online: true }
419
+ });
420
+ this.presets.set("calm-7", {
421
+ id: "calm-7",
422
+ kind: "session",
423
+ revision: 1,
424
+ title: { en: "Calm 7" },
425
+ document: {
426
+ format: "ananta-session",
427
+ formatVersion: "1.0.0",
428
+ id: "calm-7",
429
+ title: { en: "Calm 7" },
430
+ items: [{ programme: { id: "tone-432" } }]
431
+ },
432
+ updatedAt: (0, import_protocol.rfc3339Millis)()
433
+ });
434
+ }
435
+ publish;
436
+ problem;
437
+ jobs;
438
+ audioControl;
439
+ state = {
440
+ venueId: "default",
441
+ mode: "combined",
442
+ masterGainDb: 0,
443
+ mute: false,
444
+ engines: { anantasound: { status: "up" }, anantadigital: { status: "up" } },
445
+ layoutRevision: 1,
446
+ revision: 1
447
+ };
448
+ layout = {
449
+ body: {
450
+ ambisonics: { order: 3 },
451
+ speakers: [
452
+ { id: "s1", position: { azimuth: -30, elevation: 0, distance: 5 } },
453
+ { id: "s2", position: { azimuth: 30, elevation: 0, distance: 5 } },
454
+ { id: "s3", position: { azimuth: 0, elevation: 90, distance: 5 } }
455
+ ]
456
+ },
457
+ revision: 1
458
+ };
459
+ zones = /* @__PURE__ */ new Map();
460
+ devices = /* @__PURE__ */ new Map();
461
+ presets = /* @__PURE__ */ new Map();
462
+ sessions = /* @__PURE__ */ new Map();
463
+ generator = { running: false };
464
+ /** Last position per source id. */
465
+ sources = /* @__PURE__ */ new Map();
466
+ /** Devices in emergency stop: a sweep answers 409. */
467
+ estopped = /* @__PURE__ */ new Set();
468
+ /** What a sweep of a device finds (`{hz, db, q?}`); without an entry, the model's partials. */
469
+ sweepPeaks = /* @__PURE__ */ new Map();
470
+ /** Milliseconds between the steps of a sweep. */
471
+ sweepStepMs = 1;
472
+ /** Test hook: publishes `audio.levels` (`{meter id: dBFS}`) on `venues/{v}/audio/levels`. */
473
+ emitLevels(levels) {
474
+ this.publish("audio/levels", "audio.levels", { resource: { levels } });
475
+ }
476
+ /** Test hook: advances session [id] to [positionSec] (and optionally a new [status]); publishes the state. */
477
+ advanceSession(id, positionSec, status) {
478
+ const s = this.sessions.get(id);
479
+ if (!s) throw new Error(`fake: no audio session ${id}`);
480
+ s.position = positionSec;
481
+ if (status) {
482
+ s.status = status;
483
+ if (ENDED.has(status)) s.endedAt = (0, import_protocol.rfc3339Millis)();
484
+ }
485
+ this.publishSession(s);
486
+ return s;
487
+ }
488
+ bumpState() {
489
+ this.state = { ...this.state, revision: this.state.revision + 1 };
490
+ this.publish("audio", "audio.state", { resource: this.state, revision: this.state.revision });
491
+ }
492
+ publishZone(z) {
493
+ this.publish(`audio/zones/${z.id}`, "zone.state", { resource: z, revision: z.revision });
494
+ }
495
+ publishSession(s) {
496
+ this.publish(`audio/sessions/${s.id}`, "audioSession.state", { resource: s });
497
+ }
498
+ /** 422 for a `roleZones` a 1.0 server would refuse, a role not of class `speakers` or an unknown zone; 409 without speakers. */
499
+ checkRoleZones(body) {
500
+ const roleZones = body?.roleZones;
501
+ if (roleZones === void 0) return void 0;
502
+ if (!this.audioControl())
503
+ return this.problem(422, "validation-failed", "unknown member roleZones");
504
+ if (!this.layout.body.speakers?.length)
505
+ return this.problem(409, "conflict", "the venue has no speakers");
506
+ const roles = this.presets.get(body.presetId)?.document?.roles;
507
+ for (const [role, zones] of Object.entries(roleZones)) {
508
+ if (roles && !roles[role]) return this.problem(422, "validation-failed", `no role ${role}`);
509
+ if (roles && roles[role].class !== "speakers")
510
+ return this.problem(422, "validation-failed", `role ${role} is not of class speakers`);
511
+ for (const z of zones)
512
+ if (!this.zones.has(z)) return this.problem(422, "validation-failed", `no zone ${z}`);
513
+ }
514
+ return void 0;
515
+ }
516
+ /** 422 for a `multi` block a 1.0 server would refuse, next to anything but `signal: multi`, or with `frequencies`. */
517
+ checkGeneratorMulti(body) {
518
+ if (body?.multi === void 0) return void 0;
519
+ if (!this.audioControl()) return this.problem(422, "validation-failed", "unknown member multi");
520
+ if (body.signal !== "multi")
521
+ return this.problem(422, "validation-failed", "multi needs signal: multi");
522
+ if (body.frequencies !== void 0)
523
+ return this.problem(422, "validation-failed", "multi excludes frequencies");
524
+ return void 0;
525
+ }
526
+ /** The state table of `docs/audio-control.md`. */
527
+ sessionControl(sessionId, pause) {
528
+ const s = this.sessions.get(sessionId);
529
+ if (!this.audioControl() || !s) return this.problem(404, "not-found", "session");
530
+ const [from, to] = pause ? ["running", "paused"] : ["paused", "running"];
531
+ if (s.status === from) {
532
+ s.status = to;
533
+ this.publishSession(s);
534
+ } else if (s.status !== to) {
535
+ return this.problem(409, "conflict", `session is ${s.status}`);
536
+ }
537
+ return FreedomeResponse.json(200, s);
538
+ }
539
+ startSweep(p, body) {
540
+ if (!this.audioControl()) return this.problem(404, "not-found", "no such route");
541
+ const deviceId = p.deviceId;
542
+ const d = this.devices.get(deviceId);
543
+ if (!d) return this.problem(404, "not-found", "device");
544
+ const from = body?.fromHz ?? 20;
545
+ const to = body?.toHz ?? 2e3;
546
+ const actuators = d.config?.actuators;
547
+ if (d.kind !== "resonator" || body?.actuator && actuators?.includes(body.actuator) === false)
548
+ return this.problem(422, "validation-failed", `no resonator channel on ${deviceId}`);
549
+ if (to <= from) return this.problem(422, "validation-failed", "toHz not above fromHz");
550
+ if (this.estopped.has(deviceId))
551
+ return this.problem(409, "conflict", `${deviceId} is in emergency stop`);
552
+ for (const s of this.sessions.values())
553
+ if (!ENDED.has(s.status) && s.targets?.devices?.includes(deviceId))
554
+ return this.problem(409, "conflict", `a session uses ${deviceId}`);
555
+ for (const j2 of this.jobs.values())
556
+ if (j2.kind === "audio-device-sweep" && !JOB_ENDED.has(j2.status))
557
+ return this.problem(409, "conflict", "another sweep runs");
558
+ const id = uuidV7();
559
+ const now = (0, import_protocol.rfc3339Millis)();
560
+ const j = {
561
+ id,
562
+ venueId: p.venueId,
563
+ kind: "audio-device-sweep",
564
+ status: "queued",
565
+ progress: 0,
566
+ steps: [{ id: "sweep", status: "pending" }],
567
+ currentStep: null,
568
+ awaiting: null,
569
+ result: null,
570
+ sweep: {
571
+ deviceId,
572
+ ...body?.actuator ? { actuator: body.actuator } : {},
573
+ fromHz: from,
574
+ toHz: to,
575
+ durationS: body?.durationS ?? 5,
576
+ level: body?.level ?? 0.3
577
+ },
578
+ createdAt: now,
579
+ updatedAt: now
580
+ };
581
+ this.jobs.set(id, j);
582
+ const answer = FreedomeResponse.json(202, structuredClone(j), {
583
+ location: `/api/v1/venues/${p.venueId}/calibration/jobs/${id}`
584
+ });
585
+ this.runSweep(j, body?.modelHz ?? [], body?.tolerance ?? 0.01, 0);
586
+ return answer;
587
+ }
588
+ /** queued → running, progress in steps of a third (time in the real server), then the result. */
589
+ runSweep(j, modelHz, tolerance, tick) {
590
+ const timer = setTimeout(() => {
591
+ if (JOB_ENDED.has(j.status)) return;
592
+ const step = j.steps[0];
593
+ j.updatedAt = (0, import_protocol.rfc3339Millis)();
594
+ const topic = `calibration/jobs/${j.id}`;
595
+ if (tick === 0) {
596
+ step.status = "running";
597
+ j.status = "running";
598
+ j.currentStep = "sweep";
599
+ this.publish(topic, "calibrationJob.state", { resource: j });
600
+ } else if (tick < 3) {
601
+ j.progress = tick / 3;
602
+ this.publish(topic, "calibrationJob.progress", { patch: { progress: j.progress } });
603
+ } else {
604
+ step.status = "done";
605
+ this.finishSweep(j, modelHz, tolerance);
606
+ j.status = "succeeded";
607
+ j.progress = 1;
608
+ j.currentStep = null;
609
+ this.publish(topic, "calibrationJob.state", { resource: j });
610
+ return;
611
+ }
612
+ this.runSweep(j, modelHz, tolerance, tick + 1);
613
+ }, this.sweepStepMs);
614
+ timer.unref?.();
615
+ }
616
+ /** `detuned`: a partial further than `tolerance` from its model. `cracked`: no peak within four times `tolerance`. */
617
+ finishSweep(j, modelHz, tolerance) {
618
+ const found = this.sweepPeaks.get(j.sweep.deviceId) ?? (modelHz.length ? modelHz : [440]).map((hz) => ({ hz, db: -6, q: 40 }));
619
+ const peaks = [...found].sort((a, b) => b.db - a.db);
620
+ j.sweep.peaks = peaks;
621
+ if (!modelHz.length) return;
622
+ const warnings = /* @__PURE__ */ new Set();
623
+ j.sweep.partials = modelHz.map((modelHz2) => {
624
+ const off = (hz) => Math.abs(hz - modelHz2) / modelHz2;
625
+ const near = peaks.map((x) => x.hz).sort((a, b) => off(a) - off(b))[0];
626
+ if (near === void 0 || off(near) > 4 * tolerance) {
627
+ warnings.add("cracked");
628
+ return { modelHz: modelHz2 };
629
+ }
630
+ if (off(near) > tolerance) warnings.add("detuned");
631
+ return { modelHz: modelHz2, measuredHz: near };
632
+ });
633
+ j.sweep.warnings = [...warnings];
634
+ }
635
+ publishGenerator() {
636
+ this.publish("audio/generator", "generator.state", { resource: this.generator });
637
+ }
638
+ page(items) {
639
+ return FreedomeResponse.json(200, { items, nextCursor: null });
640
+ }
641
+ /** Serves audio operation [op]; undefined = not an audio operation. */
642
+ handle(op, p, body, h, q) {
643
+ const json = (s, v, hd = {}) => FreedomeResponse.json(s, v, hd);
644
+ const etag = (rev) => ({ etag: `"r${rev}"` });
645
+ const noContent = () => new FreedomeResponse(204);
646
+ switch (op) {
647
+ case "getAudio":
648
+ return json(200, { ...this.state, venueId: p.venueId });
649
+ case "patchAudio":
650
+ for (const k of ["mode", "masterGainDb", "mute"])
651
+ if (body?.[k] !== void 0) this.state[k] = body[k];
652
+ this.bumpState();
653
+ return json(200, { ...this.state, venueId: p.venueId });
654
+ case "getSpeakerLayout":
655
+ return json(200, this.layout.body, etag(this.layout.revision));
656
+ case "putSpeakerLayout": {
657
+ if (!h["if-match"]) return this.problem(428, "precondition-required", "If-Match required");
658
+ if (h["if-match"] !== `"r${this.layout.revision}"`)
659
+ return this.problem(412, "precondition-failed", `revision is ${this.layout.revision}`);
660
+ this.layout = { body, revision: this.layout.revision + 1 };
661
+ this.state.layoutRevision = this.layout.revision;
662
+ this.publish("audio/layout", "audio.layout", {
663
+ resource: body,
664
+ revision: this.layout.revision
665
+ });
666
+ this.bumpState();
667
+ return json(200, body, etag(this.layout.revision));
668
+ }
669
+ case "listAudioZones":
670
+ return this.page([...this.zones.values()]);
671
+ case "getAudioZone": {
672
+ const z = this.zones.get(p.zoneId);
673
+ return z ? json(200, z, etag(z.revision)) : this.problem(404, "not-found", "zone");
674
+ }
675
+ case "putAudioZone": {
676
+ const z = this.zones.get(p.zoneId);
677
+ if (!z) {
678
+ if (h["if-match"]) return this.problem(412, "precondition-failed", "zone does not exist");
679
+ const n2 = { id: p.zoneId, gainDb: 0, mute: false, ...body, revision: 1 };
680
+ this.zones.set(p.zoneId, n2);
681
+ this.publishZone(n2);
682
+ return json(201, n2, etag(1));
683
+ }
684
+ if (h["if-none-match"] === "*")
685
+ return this.problem(412, "precondition-failed", `zone ${p.zoneId} exists`);
686
+ if (h["if-match"] && h["if-match"] !== `"r${z.revision}"`)
687
+ return this.problem(412, "precondition-failed", `revision is ${z.revision}`);
688
+ const n = { id: p.zoneId, gainDb: 0, mute: false, ...body, revision: z.revision + 1 };
689
+ this.zones.set(p.zoneId, n);
690
+ this.publishZone(n);
691
+ return json(200, n, etag(n.revision));
692
+ }
693
+ case "patchAudioZone": {
694
+ const z = this.zones.get(p.zoneId);
695
+ if (!z) return this.problem(404, "not-found", "zone");
696
+ if (!body || !Object.keys(body).length)
697
+ return this.problem(422, "validation", "empty patch");
698
+ Object.assign(z, body, { revision: z.revision + 1 });
699
+ this.publish(`audio/zones/${z.id}`, "zone.state", {
700
+ patch: { ...body, revision: z.revision },
701
+ revision: z.revision
702
+ });
703
+ return json(200, z, etag(z.revision));
704
+ }
705
+ case "deleteAudioZone": {
706
+ const z = this.zones.get(p.zoneId);
707
+ if (!z) return this.problem(404, "not-found", "zone");
708
+ if (!h["if-match"]) return this.problem(428, "precondition-required", "If-Match required");
709
+ if (h["if-match"] !== `"r${z.revision}"`)
710
+ return this.problem(412, "precondition-failed", `revision is ${z.revision}`);
711
+ this.zones.delete(p.zoneId);
712
+ this.publish(`audio/zones/${z.id}`, "zone.deleted", { resource: { id: z.id } });
713
+ return noContent();
714
+ }
715
+ case "listAudioDevices":
716
+ return this.page([...this.devices.values()].filter((d) => !q.kind || d.kind === q.kind));
717
+ case "getAudioDevice": {
718
+ const d = this.devices.get(p.deviceId);
719
+ return d ? json(200, d) : this.problem(404, "not-found", "device");
720
+ }
721
+ case "patchAudioDevice": {
722
+ const d = this.devices.get(p.deviceId);
723
+ if (!d) return this.problem(404, "not-found", "device");
724
+ if (body?.name !== void 0) d.name = body.name;
725
+ if (body?.config !== void 0) d.config = { ...d.config ?? {}, ...body.config };
726
+ const st = {};
727
+ if (body?.gainDb !== void 0) st.gainDb = body.gainDb;
728
+ if (body?.mute !== void 0) st.mute = body.mute;
729
+ d.state = { ...d.state, ...st };
730
+ this.publish(`audio/devices/${d.id}`, "audioDevice.state", { resource: d });
731
+ return json(200, d);
732
+ }
733
+ case "testAudioDevice": {
734
+ const d = this.devices.get(p.deviceId);
735
+ if (!d) return this.problem(404, "not-found", "device");
736
+ return json(200, {
737
+ deviceId: d.id,
738
+ ok: d.state?.online !== false,
739
+ latencyMs: 4,
740
+ detail: `${body?.kind ?? "ping"} ok`
741
+ });
742
+ }
743
+ case "listAudioPresets":
744
+ return this.page(
745
+ [...this.presets.values()].filter((x) => !q.kind || x.kind === q.kind).map(({ document: _d, ...summary }) => summary)
746
+ );
747
+ case "getAudioPreset": {
748
+ const x = this.presets.get(p.presetId);
749
+ return x ? json(200, x, etag(x.revision)) : this.problem(404, "not-found", "preset");
750
+ }
751
+ case "putAudioPreset": {
752
+ const x = this.presets.get(p.presetId);
753
+ if (x && h["if-none-match"] === "*")
754
+ return this.problem(412, "precondition-failed", `preset ${p.presetId} exists`);
755
+ if (h["if-match"] && (!x || h["if-match"] !== `"r${x.revision}"`))
756
+ return this.problem(412, "precondition-failed", `revision is ${x?.revision ?? 0}`);
757
+ if (!body?.kind || !body?.document)
758
+ return this.problem(422, "validation", "kind and document are required");
759
+ const n = {
760
+ id: p.presetId,
761
+ kind: body.kind,
762
+ revision: (x?.revision ?? 0) + 1,
763
+ document: body.document,
764
+ ...body.document?.title ? { title: body.document.title } : {},
765
+ updatedAt: (0, import_protocol.rfc3339Millis)()
766
+ };
767
+ this.presets.set(p.presetId, n);
768
+ return json(x ? 200 : 201, n, etag(n.revision));
769
+ }
770
+ case "deleteAudioPreset": {
771
+ const x = this.presets.get(p.presetId);
772
+ if (!x) return this.problem(404, "not-found", "preset");
773
+ if (h["if-match"] && h["if-match"] !== `"r${x.revision}"`)
774
+ return this.problem(412, "precondition-failed", `revision is ${x.revision}`);
775
+ this.presets.delete(p.presetId);
776
+ return noContent();
777
+ }
778
+ case "listAudioSessions":
779
+ return this.page([...this.sessions.values()]);
780
+ case "startAudioSession": {
781
+ if (!this.presets.has(body?.presetId))
782
+ return this.problem(404, "not-found", `preset ${body?.presetId}`);
783
+ const bad = this.checkRoleZones(body);
784
+ if (bad) return bad;
785
+ const s = {
786
+ id: uuidV7(),
787
+ venueId: p.venueId,
788
+ presetId: body.presetId,
789
+ status: "running",
790
+ engines: ["anantadigital"],
791
+ position: 0,
792
+ itemIndex: 0,
793
+ ...body.targets ? { targets: body.targets } : {},
794
+ ...body.roleZones ? { roleZones: body.roleZones } : {},
795
+ startedAt: body.at ?? (0, import_protocol.rfc3339Millis)()
796
+ };
797
+ this.sessions.set(s.id, s);
798
+ this.publishSession(s);
799
+ return json(201, s, { location: `/api/v1/venues/${p.venueId}/audio/sessions/${s.id}` });
800
+ }
801
+ case "getAudioSession": {
802
+ const s = this.sessions.get(p.sessionId);
803
+ return s ? json(200, s) : this.problem(404, "not-found", "session");
804
+ }
805
+ case "stopAudioSession": {
806
+ const s = this.sessions.get(p.sessionId);
807
+ if (!s) return this.problem(404, "not-found", "session");
808
+ if (!ENDED.has(s.status)) {
809
+ s.status = "stopped";
810
+ s.endedAt = (0, import_protocol.rfc3339Millis)();
811
+ this.publishSession(s);
812
+ }
813
+ return noContent();
814
+ }
815
+ case "pauseAudioSession":
816
+ return this.sessionControl(p.sessionId, true);
817
+ case "resumeAudioSession":
818
+ return this.sessionControl(p.sessionId, false);
819
+ case "startAudioDeviceSweep":
820
+ return this.startSweep(p, body);
821
+ case "getGenerator":
822
+ return json(200, this.generator);
823
+ case "setGenerator": {
824
+ if (!body?.signal) return this.problem(422, "validation", "signal is required");
825
+ const bad = this.checkGeneratorMulti(body);
826
+ if (bad) return bad;
827
+ this.generator = {
828
+ running: true,
829
+ settings: body,
830
+ startedAt: this.generator.running ? this.generator.startedAt : (0, import_protocol.rfc3339Millis)()
831
+ };
832
+ this.publishGenerator();
833
+ return json(200, this.generator);
834
+ }
835
+ case "stopGenerator":
836
+ this.generator = { running: false };
837
+ this.publishGenerator();
838
+ return noContent();
839
+ case "setSourcePosition":
840
+ if (typeof body?.azimuth !== "number" || typeof body?.elevation !== "number")
841
+ return this.problem(422, "validation", "azimuth and elevation are required");
842
+ this.sources.set(p.sourceId, body);
843
+ return noContent();
844
+ default:
845
+ return void 0;
846
+ }
847
+ }
848
+ };
849
+
850
+ // src/testing/fake-audio-reactive.ts
851
+ var import_protocol2 = require("@freedome/protocol");
852
+ var FakeAudioReactive = class {
853
+ constructor(publishVenue, publish, problem2) {
854
+ this.publishVenue = publishVenue;
855
+ this.publish = publish;
856
+ this.problem = problem2;
857
+ }
858
+ publishVenue;
859
+ publish;
860
+ problem;
861
+ analysis = { venueId: "default", enabled: false, status: "disabled", inputs: [] };
862
+ enabled = true;
863
+ activeSceneId = null;
864
+ intensity = 1;
865
+ scenes = /* @__PURE__ */ new Map();
866
+ textureSources = /* @__PURE__ */ new Map();
867
+ gateways = /* @__PURE__ */ new Map();
868
+ /** The driver takes `config` at run time (the media server's 422 on `/config` otherwise). */
869
+ runtimeSettings = true;
870
+ /** The Resolume machine answers. */
871
+ reachable = true;
872
+ /** Test hook: one running `resolume` gateway and the scene `vocal-aura` reading input `vocal`. */
873
+ seed() {
874
+ this.gateways.set("resolume", {
875
+ id: "resolume",
876
+ direction: "outbound",
877
+ protocol: "resolume",
878
+ vendor: "Resolume",
879
+ enabled: true,
880
+ status: "up",
881
+ revision: 1,
882
+ config: { host: "192.168.1.50", oscPort: 7e3, restPort: 8080, ws: true }
883
+ });
884
+ this.scenes.set("vocal-aura", {
885
+ id: "vocal-aura",
886
+ title: { en: "Vocal aura" },
887
+ revision: 1,
888
+ mappings: [],
889
+ updatedAt: (0, import_protocol2.rfc3339Millis)()
890
+ });
891
+ this.analysis = { ...this.analysis, inputs: [{ id: "vocal" }] };
892
+ }
893
+ /** Test hook: publishes an analysis frame of [inputId]. */
894
+ publishFrame(inputId, frame = {}) {
895
+ this.publishVenue(`audio/analysis/${inputId}`, "audio.analysis", {
896
+ resource: { inputId, ...frame }
897
+ });
898
+ }
899
+ /** Test hook: publishes a detected attack of [inputId]. */
900
+ publishOnset(inputId, onset = {}) {
901
+ this.publishVenue(`audio/onsets/${inputId}`, "audio.onset", {
902
+ resource: { inputId, ...onset }
903
+ });
904
+ }
905
+ /** Test hook: adds or changes a sender and publishes the change. */
906
+ setTextureSource(s) {
907
+ this.textureSources.set(s.id, s);
908
+ this.publishVenue(`texture-sources/${s.id}`, "textureSource.state", { resource: s });
909
+ }
910
+ state() {
911
+ return {
912
+ venueId: "default",
913
+ enabled: this.enabled,
914
+ status: this.enabled ? "running" : "disabled",
915
+ activeSceneId: this.activeSceneId,
916
+ intensity: this.intensity
917
+ };
918
+ }
919
+ publishState() {
920
+ this.publishVenue("audio/reactive", "audioReactive.state", { resource: this.state() });
921
+ }
922
+ /** Serves operation [op]; undefined = not one of these. */
923
+ handle(op, p, body, h) {
924
+ const json = (s, v, hd = {}) => FreedomeResponse.json(s, v, hd);
925
+ const etag = (rev) => ({ etag: `"r${rev}"` });
926
+ const page = (items) => json(200, { items, nextCursor: null });
927
+ switch (op) {
928
+ case "getAudioAnalysis":
929
+ return json(200, this.analysis);
930
+ case "setAudioAnalysis":
931
+ this.analysis = {
932
+ ...this.analysis,
933
+ enabled: body.enabled,
934
+ status: body.enabled ? "running" : "disabled",
935
+ inputs: body.inputs ?? []
936
+ };
937
+ this.publishVenue("audio/analysis", "audioAnalysis.state", { resource: this.analysis });
938
+ return json(200, this.analysis);
939
+ case "getAudioReactive":
940
+ return json(200, this.state());
941
+ case "patchAudioReactive": {
942
+ if (typeof body.activeSceneId === "string" && !this.scenes.has(body.activeSceneId))
943
+ return this.problem(422, "validation-failed", `no scene ${body.activeSceneId}`);
944
+ if ("activeSceneId" in body) this.activeSceneId = body.activeSceneId;
945
+ if (typeof body.enabled === "boolean") this.enabled = body.enabled;
946
+ if (typeof body.intensity === "number") this.intensity = body.intensity;
947
+ this.publishState();
948
+ return json(200, this.state());
949
+ }
950
+ case "listAudioReactiveScenes":
951
+ return page([...this.scenes.values()]);
952
+ case "getAudioReactiveScene": {
953
+ const s = this.scenes.get(p.sceneId);
954
+ return s ? json(200, s, etag(s.revision)) : this.problem(404, "not-found", "scene");
955
+ }
956
+ case "putAudioReactiveScene": {
957
+ const cur = this.scenes.get(p.sceneId);
958
+ if (h["if-none-match"] === "*" && cur)
959
+ return this.problem(412, "precondition-failed", "the scene exists");
960
+ if (h["if-match"] && h["if-match"] !== `"r${cur?.revision}"`)
961
+ return this.problem(412, "precondition-failed", `revision is ${cur?.revision}`);
962
+ const s = {
963
+ ...body,
964
+ id: p.sceneId,
965
+ revision: (cur?.revision ?? 0) + 1,
966
+ updatedAt: (0, import_protocol2.rfc3339Millis)()
967
+ };
968
+ this.scenes.set(p.sceneId, s);
969
+ this.publishVenue("audio/reactive/scenes", "audioReactiveScene.updated", { resource: s });
970
+ return json(cur ? 200 : 201, s, etag(s.revision));
971
+ }
972
+ case "deleteAudioReactiveScene": {
973
+ const s = this.scenes.get(p.sceneId);
974
+ if (!s) return this.problem(404, "not-found", "scene");
975
+ if (h["if-match"] !== `"r${s.revision}"`)
976
+ return this.problem(412, "precondition-failed", `revision is ${s.revision}`);
977
+ if (this.activeSceneId === p.sceneId)
978
+ return this.problem(409, "conflict", "the scene is active");
979
+ this.scenes.delete(p.sceneId);
980
+ return new FreedomeResponse(204);
981
+ }
982
+ case "listTextureSources":
983
+ return page([...this.textureSources.values()]);
984
+ case "listGateways":
985
+ return page([...this.gateways.values()]);
986
+ case "getGateway": {
987
+ const g = this.gateways.get(p.gatewayId);
988
+ return g ? json(200, g, etag(g.revision)) : this.problem(404, "not-found", "gateway");
989
+ }
990
+ case "patchGateway": {
991
+ const g = this.gateways.get(p.gatewayId);
992
+ if (!g) return this.problem(404, "not-found", "gateway");
993
+ if (h["if-match"] && h["if-match"] !== `"r${g.revision}"`)
994
+ return this.problem(412, "precondition-failed", `revision is ${g.revision}`);
995
+ if (body.config && !this.runtimeSettings)
996
+ return this.problem(422, "validation-failed", "config is not a run-time setting");
997
+ const enabled = body.enabled ?? g.enabled;
998
+ const next = {
999
+ ...g,
1000
+ enabled,
1001
+ status: enabled ? "up" : "disabled",
1002
+ config: { ...g.config, ...body.config },
1003
+ revision: g.revision + 1
1004
+ };
1005
+ this.gateways.set(g.id, next);
1006
+ this.publish(`gateways/${g.id}`, "gateway.state", { resource: next });
1007
+ return json(200, next, etag(next.revision));
1008
+ }
1009
+ case "testGateway": {
1010
+ const g = this.gateways.get(p.gatewayId);
1011
+ if (!g) return this.problem(404, "not-found", "gateway");
1012
+ return json(200, {
1013
+ ok: g.enabled && this.reachable,
1014
+ ...g.enabled && this.reachable ? { latencyMs: 3, remoteVersion: "7.22.0" } : {}
1015
+ });
1016
+ }
1017
+ default:
1018
+ return void 0;
1019
+ }
1020
+ }
1021
+ };
1022
+
1023
+ // src/testing.ts
1024
+ var ROLE_SCOPES = {
1025
+ guest: ["info:read", "events:subscribe", "playback:read", "content:read"],
1026
+ operator: [
1027
+ "info:read",
1028
+ "events:subscribe",
1029
+ "playback:read",
1030
+ "content:read",
1031
+ "playback:control",
1032
+ "apps:publish",
1033
+ "content:write",
1034
+ "audio:control",
1035
+ "displays:control"
1036
+ ],
1037
+ admin: [
1038
+ "info:read",
1039
+ "events:subscribe",
1040
+ "playback:read",
1041
+ "content:read",
1042
+ "playback:control",
1043
+ "apps:publish",
1044
+ "content:write",
1045
+ "audio:control",
1046
+ "displays:control",
1047
+ "calibration:run",
1048
+ "audio:calibrate",
1049
+ "venues:write",
1050
+ "gateways:manage",
1051
+ "system:read",
1052
+ "users:manage",
1053
+ "keys:manage"
1054
+ ]
1055
+ };
1056
+ var problem = (status, code, detail, extra = {}) => FreedomeResponse.json(
1057
+ status,
1058
+ {
1059
+ type: `https://freedome.nativemind.us/problems/${code}`,
1060
+ title: code,
1061
+ status,
1062
+ code,
1063
+ detail,
1064
+ ...extra
1065
+ },
1066
+ { "content-type": "application/problem+json" }
1067
+ );
1068
+ var FakeDomeServer = class {
1069
+ endpoint = new FreedomeEndpoint("http://fake-dome.local:8080");
1070
+ /** Every REST request received (WS calls included as operationId-only records). */
1071
+ requests = [];
1072
+ instanceId = uuidV7();
1073
+ /** Users (password = username). */
1074
+ users = /* @__PURE__ */ new Map([
1075
+ ["admin", "admin"],
1076
+ ["operator", "operator"]
1077
+ ]);
1078
+ /** Accepted API keys → role. */
1079
+ apiKeys = /* @__PURE__ */ new Map();
1080
+ networkDown = false;
1081
+ realtimeAvailable = true;
1082
+ accessTtlSec = 900;
1083
+ seq = 0;
1084
+ history = [];
1085
+ sessions = /* @__PURE__ */ new Map();
1086
+ refreshTokens = /* @__PURE__ */ new Map();
1087
+ failures = /* @__PURE__ */ new Map();
1088
+ sockets = /* @__PURE__ */ new Set();
1089
+ venues = /* @__PURE__ */ new Map();
1090
+ activeVenue = "";
1091
+ shows = /* @__PURE__ */ new Map();
1092
+ assets = /* @__PURE__ */ new Map();
1093
+ assetBytes = /* @__PURE__ */ new Map();
1094
+ uploads = /* @__PURE__ */ new Map();
1095
+ jobs = /* @__PURE__ */ new Map();
1096
+ player = {
1097
+ id: "main",
1098
+ status: "idle",
1099
+ position: 0,
1100
+ rate: 1,
1101
+ volume: 1,
1102
+ opacity: 1,
1103
+ loop: false,
1104
+ revision: 0
1105
+ };
1106
+ output = { brightness: 1, volume: 1, blackout: false, rotation: 0, lighting: false };
1107
+ /** Live app payloads per app (cleared by `clearAppPayloads`). */
1108
+ appPayloads = /* @__PURE__ */ new Map();
1109
+ /** Pairing requests by id. */
1110
+ pairings = /* @__PURE__ */ new Map();
1111
+ /** Approve every pairing request at once (role = requested role or operator). */
1112
+ autoApprovePairings = false;
1113
+ /**
1114
+ * Contract version the fake reports in `getInfo` and behaves as: below 1.1.0 the operations of 1.1.0 answer 404 and
1115
+ * its members 422, as a 1.0 server does.
1116
+ */
1117
+ contractVersion = "1.1.0";
1118
+ /** Calibration jobs by id. */
1119
+ calibrationJobs = /* @__PURE__ */ new Map();
1120
+ /** Audio model + hooks (`emitLevels`, `advanceSession`). */
1121
+ audio = new FakeAudio(
1122
+ (t, kind, data) => {
1123
+ for (const v of /* @__PURE__ */ new Set(["default", this.activeVenue]))
1124
+ this.publish(`venues/${v}/${t}`, kind, data);
1125
+ },
1126
+ (status, code, detail) => problem(status, code, detail),
1127
+ this.calibrationJobs,
1128
+ () => {
1129
+ const v = import_protocol3.SemVer.tryParse(this.contractVersion);
1130
+ return v !== null && v.compareTo(import_protocol3.ProtocolVersions.audioControl) >= 0;
1131
+ }
1132
+ );
1133
+ /** Live analysis, AudioReactive scenes, texture sources and gateways (`seed`, `publishFrame`). */
1134
+ audioReactive = new FakeAudioReactive(
1135
+ (t, kind, data) => {
1136
+ for (const v of /* @__PURE__ */ new Set(["default", this.activeVenue]))
1137
+ this.publish(`venues/${v}/${t}`, kind, data);
1138
+ },
1139
+ (t, kind, data) => this.publish(t, kind, data),
1140
+ (status, code, detail) => problem(status, code, detail)
1141
+ );
1142
+ constructor() {
1143
+ const id = "0192f3a4-5b6c-7d8e-9f01-0000000000d4";
1144
+ this.addVenue({
1145
+ meta: { id, title: { en: "Fake venue" } },
1146
+ dome: { mode: "classical", shape: "hemisphere", radius: 5 },
1147
+ displays: [
1148
+ {
1149
+ id: "p1",
1150
+ type: "projector",
1151
+ resolution: [1920, 1080],
1152
+ output: { host: "node-1", connector: "HDMI-1" }
1153
+ }
1154
+ ]
1155
+ });
1156
+ this.activeVenue = id;
1157
+ }
1158
+ addVenue(body) {
1159
+ this.venues.set(body.meta.id, { body, revision: 1 });
1160
+ if (!this.activeVenue) this.activeVenue = body.meta.id;
1161
+ }
1162
+ addShow(body) {
1163
+ this.shows.set(body.meta.id, { body, revision: 1 });
1164
+ }
1165
+ /** The next call of [operationId] answers [status] ([times] times). */
1166
+ failNext(operationId, status = 503, times = 1) {
1167
+ this.failures.set(operationId, { status, times });
1168
+ }
1169
+ /** Closes every realtime session (the client reconnects with resume). */
1170
+ dropRealtime(code = 1006) {
1171
+ for (const s of [...this.sockets]) s.serverClose(code, "dropped");
1172
+ }
1173
+ /** Simulates a server restart: new instance id, seq space restarts, sessions survive (persistent tokens). */
1174
+ restart() {
1175
+ this.instanceId = uuidV7();
1176
+ this.seq = 0;
1177
+ this.history.length = 0;
1178
+ this.dropRealtime(1012);
1179
+ }
1180
+ /** Approves (or denies) pairing [pairingId] as an administrator would on the dome; returns the pairing. */
1181
+ approvePairing(pairingId, o = {}) {
1182
+ const x = this.pairings.get(pairingId);
1183
+ if (!x) throw new Error(`fake: no pairing ${pairingId}`);
1184
+ if (x.status !== "pending") return x;
1185
+ if (o.approve === false) x.status = "denied";
1186
+ else {
1187
+ const role = o.role ?? x.requestedRole ?? "operator";
1188
+ x.status = "approved";
1189
+ x.role = role;
1190
+ x.tokens = this.issue(x.deviceName, role);
1191
+ }
1192
+ return x;
1193
+ }
1194
+ /** Invalidates every access token (refresh tokens stay valid). */
1195
+ expireTokens() {
1196
+ this.sessions.clear();
1197
+ }
1198
+ /** Publishes an event on [topic]. */
1199
+ publish(topic, kind, data) {
1200
+ const e = {
1201
+ type: "event",
1202
+ id: uuidV7(),
1203
+ ts: (0, import_protocol3.rfc3339Millis)(),
1204
+ topic,
1205
+ data: { seq: ++this.seq, kind, ...data }
1206
+ };
1207
+ this.history.push(e);
1208
+ if (this.history.length > 1e3) this.history.shift();
1209
+ for (const s of this.sockets) s.deliver(e);
1210
+ }
1211
+ get transports() {
1212
+ const connector = async (_e, path, protocols) => {
1213
+ if (this.networkDown || !this.realtimeAvailable)
1214
+ throw new NetworkError("fake: realtime unavailable");
1215
+ if (path !== "/api/v1/ws" || !protocols.includes("freedome.v1"))
1216
+ throw new NetworkError(`fake: no socket at ${path}`);
1217
+ const s = new FakeSocketSession(this);
1218
+ this.sockets.add(s);
1219
+ return s.client;
1220
+ };
1221
+ return { rest: () => new FakeTransport(this), sockets: connector };
1222
+ }
1223
+ /** @internal */
1224
+ forget(s) {
1225
+ this.sockets.delete(s);
1226
+ }
1227
+ /** @internal Events after [since] matching any filter. */
1228
+ replay(since) {
1229
+ return this.history.filter((e) => e.data.seq > since);
1230
+ }
1231
+ /** @internal */
1232
+ get lastSeq() {
1233
+ return this.seq;
1234
+ }
1235
+ /** @internal Bearer → session. */
1236
+ principal(auth) {
1237
+ if (!auth?.startsWith("Bearer ")) return void 0;
1238
+ const t = auth.slice(7);
1239
+ const role = this.apiKeys.get(t);
1240
+ if (role) return { token: t, refresh: "", user: "api-key", role };
1241
+ return this.sessions.get(t);
1242
+ }
1243
+ issue(user, role) {
1244
+ const s = { token: `at_${uuidV7()}`, refresh: `rt_${uuidV7()}`, user, role };
1245
+ this.sessions.set(s.token, s);
1246
+ this.refreshTokens.set(s.refresh, s);
1247
+ return {
1248
+ accessToken: s.token,
1249
+ tokenType: "Bearer",
1250
+ expiresIn: this.accessTtlSec,
1251
+ refreshToken: s.refresh,
1252
+ scopes: ROLE_SCOPES[role] ?? [],
1253
+ principal: { kind: "user", subject: user, name: user, role, scopes: ROLE_SCOPES[role] ?? [] }
1254
+ };
1255
+ }
1256
+ venueId(v) {
1257
+ return v === "default" ? this.activeVenue : v;
1258
+ }
1259
+ etag(rev) {
1260
+ return { etag: `"r${rev}"` };
1261
+ }
1262
+ publishPlayer() {
1263
+ this.player = { ...this.player, revision: this.player.revision + 1 };
1264
+ for (const v of ["default", this.activeVenue])
1265
+ this.publish(`venues/${v}/players/main`, "player.state", {
1266
+ resource: this.player,
1267
+ revision: this.player.revision
1268
+ });
1269
+ }
1270
+ /** Handles one request (REST or a WS `call`). */
1271
+ async handle(r) {
1272
+ this.requests.push(r);
1273
+ if (this.networkDown) throw new NetworkError("fake: network down");
1274
+ let op;
1275
+ let p = {};
1276
+ for (const o of Object.values(import_protocol3.Operations)) {
1277
+ const m = (0, import_protocol3.matchOperation)(o, r.method, r.path);
1278
+ if (m) {
1279
+ op = o;
1280
+ p = m;
1281
+ break;
1282
+ }
1283
+ }
1284
+ if (!op) return problem(404, "not-found", `no route ${r.method} ${r.path}`);
1285
+ const f = this.failures.get(op.id);
1286
+ if (f) {
1287
+ if (--f.times <= 0) this.failures.delete(op.id);
1288
+ return problem(
1289
+ f.status,
1290
+ f.status === 429 ? "rate-limited" : "internal",
1291
+ `injected ${f.status}`,
1292
+ {}
1293
+ );
1294
+ }
1295
+ const who = this.principal(r.headers.authorization);
1296
+ if (op.scope !== "anon") {
1297
+ if (!who) return problem(401, "unauthenticated", "sign in first");
1298
+ if (op.scope !== "any" && !(ROLE_SCOPES[who.role] ?? []).includes(op.scope))
1299
+ return problem(403, "forbidden", `needs ${op.scope}`);
1300
+ }
1301
+ const body = r.body?.length && (r.headers["content-type"] ?? "").includes("json") ? JSON.parse(new TextDecoder().decode(r.body)) : void 0;
1302
+ const json = (s, v, h = {}) => FreedomeResponse.json(s, v, h);
1303
+ switch (op.id) {
1304
+ case "getInfo":
1305
+ return json(200, {
1306
+ name: "Fake dome",
1307
+ instanceId: this.instanceId,
1308
+ apiVersions: ["v1"],
1309
+ version: "1.0.0-rc.1",
1310
+ contractVersion: this.contractVersion,
1311
+ capabilities: { realtime: ["ws"], audio: true },
1312
+ transports: { ws: true, graphql: false, socketIo: false }
1313
+ });
1314
+ case "createSession": {
1315
+ if (this.users.get(body?.username) !== body?.password)
1316
+ return problem(401, "unauthenticated", "wrong username or password");
1317
+ return json(
1318
+ 201,
1319
+ this.issue(body.username, body.username === "admin" ? "admin" : "operator")
1320
+ );
1321
+ }
1322
+ case "refreshSession": {
1323
+ const s = this.refreshTokens.get(body?.refreshToken);
1324
+ if (!s) return problem(401, "unauthenticated", "refresh token invalid");
1325
+ this.refreshTokens.delete(body.refreshToken);
1326
+ return json(200, this.issue(s.user, s.role));
1327
+ }
1328
+ case "deleteSession":
1329
+ if (who) this.sessions.delete(who.token);
1330
+ return new FreedomeResponse(204);
1331
+ case "getMe":
1332
+ return json(200, {
1333
+ kind: who.user === "api-key" ? "apiKey" : "user",
1334
+ subject: who.user,
1335
+ name: who.user,
1336
+ role: who.role,
1337
+ scopes: ROLE_SCOPES[who.role] ?? []
1338
+ });
1339
+ case "listEvents":
1340
+ return json(200, { items: [], nextCursor: null, lastSeq: this.seq });
1341
+ case "listVenues":
1342
+ return json(200, {
1343
+ items: [...this.venues.entries()].map(([id, v]) => ({
1344
+ id,
1345
+ revision: v.revision,
1346
+ ...v.body
1347
+ })),
1348
+ nextCursor: null
1349
+ });
1350
+ case "getVenue": {
1351
+ const id = this.venueId(p.venueId);
1352
+ const v = this.venues.get(id);
1353
+ if (!v) return problem(404, "not-found", `venue ${id}`);
1354
+ return json(200, { id, revision: v.revision, ...v.body }, this.etag(v.revision));
1355
+ }
1356
+ case "putVenue": {
1357
+ const id = this.venueId(p.venueId);
1358
+ const v = this.venues.get(id);
1359
+ if (!v) {
1360
+ if (r.headers["if-none-match"] !== "*")
1361
+ return problem(428, "precondition-required", "create needs If-None-Match: *");
1362
+ this.venues.set(id, { body, revision: 1 });
1363
+ return json(201, { id, revision: 1, ...body }, this.etag(1));
1364
+ }
1365
+ if (r.headers["if-none-match"] === "*")
1366
+ return problem(412, "precondition-failed", `venue ${id} exists`);
1367
+ if (!r.headers["if-match"])
1368
+ return problem(428, "precondition-required", "If-Match required");
1369
+ if (r.headers["if-match"] !== `"r${v.revision}"`)
1370
+ return problem(412, "precondition-failed", `revision is ${v.revision}`);
1371
+ v.body = body;
1372
+ v.revision++;
1373
+ this.publish(`venues/${id}`, "venue.updated", {
1374
+ resource: { id, revision: v.revision, ...body },
1375
+ revision: v.revision
1376
+ });
1377
+ return json(200, { id, revision: v.revision, ...body }, this.etag(v.revision));
1378
+ }
1379
+ case "getPlayer":
1380
+ return json(200, this.player);
1381
+ case "play":
1382
+ this.player = {
1383
+ ...this.player,
1384
+ status: "playing",
1385
+ ...body?.showId ? { showId: body.showId } : {},
1386
+ ...body?.assetId ? { assetId: body.assetId } : {},
1387
+ position: body?.position ?? 0
1388
+ };
1389
+ this.publishPlayer();
1390
+ return json(200, this.player);
1391
+ case "pause":
1392
+ case "resume":
1393
+ case "stop":
1394
+ case "next":
1395
+ case "previous":
1396
+ this.player = {
1397
+ ...this.player,
1398
+ status: { pause: "paused", resume: "playing", stop: "stopped" }[op.id] ?? this.player.status
1399
+ };
1400
+ this.publishPlayer();
1401
+ return json(200, this.player);
1402
+ case "seek":
1403
+ this.player = { ...this.player, position: body?.position ?? 0 };
1404
+ this.publishPlayer();
1405
+ return json(200, this.player);
1406
+ case "patchPlayer":
1407
+ this.player = { ...this.player, ...body };
1408
+ this.publishPlayer();
1409
+ return json(200, this.player);
1410
+ case "getOutput":
1411
+ return json(200, this.output);
1412
+ case "patchOutput":
1413
+ this.output = { ...this.output, ...body };
1414
+ this.publish("venues/default/output", "output.changed", { resource: this.output });
1415
+ return json(200, this.output);
1416
+ case "publishAppPayload": {
1417
+ this.publish(`apps/${p.app}`, "app.payload", { resource: { app: p.app, ...body } });
1418
+ const created = {
1419
+ id: uuidV7(),
1420
+ app: p.app,
1421
+ ...body,
1422
+ expiresAt: (0, import_protocol3.rfc3339Millis)(new Date(Date.now() + (body?.ttlSec ?? 3600) * 1e3))
1423
+ };
1424
+ this.appPayloads.set(p.app, [...this.appPayloads.get(p.app) ?? [], created]);
1425
+ return json(201, created);
1426
+ }
1427
+ case "clearAppPayloads":
1428
+ this.appPayloads.delete(p.app);
1429
+ this.publish(`apps/${p.app}`, "app.cleared", { resource: { app: p.app } });
1430
+ return new FreedomeResponse(204);
1431
+ case "createPairing": {
1432
+ if (!body?.app || !body?.deviceName)
1433
+ return problem(422, "validation", "app and deviceName are required");
1434
+ const id = uuidV7();
1435
+ const code = String(1e5 + Math.floor(Math.random() * 9e5));
1436
+ const x = {
1437
+ pairingId: id,
1438
+ status: "pending",
1439
+ code,
1440
+ qr: `freedome://pair?host=fake-dome.local&code=${code}`,
1441
+ app: body.app,
1442
+ deviceName: body.deviceName,
1443
+ ...body.requestedRole ? { requestedRole: body.requestedRole } : {},
1444
+ expiresAt: (0, import_protocol3.rfc3339Millis)(new Date(Date.now() + 3e5))
1445
+ };
1446
+ this.pairings.set(id, x);
1447
+ if (this.autoApprovePairings) this.approvePairing(id);
1448
+ const { requestedRole: _r, ...out } = this.pairings.get(id);
1449
+ return json(201, out);
1450
+ }
1451
+ case "getPairing": {
1452
+ const x = this.pairings.get(p.pairingId);
1453
+ if (!x) return problem(404, "not-found", "pairing");
1454
+ const { requestedRole: _r, ...out } = x;
1455
+ return json(200, out);
1456
+ }
1457
+ case "listPairings":
1458
+ return json(200, {
1459
+ items: [...this.pairings.values()].map(({ tokens: _t, requestedRole: _r, ...x }) => x),
1460
+ nextCursor: null
1461
+ });
1462
+ case "approvePairing": {
1463
+ if (!this.pairings.has(p.pairingId)) return problem(404, "not-found", "pairing");
1464
+ const {
1465
+ tokens: _t,
1466
+ requestedRole: _r,
1467
+ ...x
1468
+ } = this.approvePairing(p.pairingId, {
1469
+ approve: body?.approve !== false,
1470
+ ...body?.role ? { role: body.role } : {}
1471
+ });
1472
+ return json(200, x);
1473
+ }
1474
+ case "startCalibrationJob": {
1475
+ if (body?.kind === "audio-device-sweep")
1476
+ return problem(422, "validation-failed", "a sweep starts with startAudioDeviceSweep");
1477
+ const id = uuidV7();
1478
+ const now = (0, import_protocol3.rfc3339Millis)();
1479
+ const j = {
1480
+ id,
1481
+ venueId: p.venueId,
1482
+ kind: body?.kind,
1483
+ status: "running",
1484
+ progress: 0,
1485
+ ...body?.speakers ? { speakers: body.speakers } : {},
1486
+ ...body?.displays ? { displays: body.displays } : {},
1487
+ ...body?.options ? { options: body.options } : {},
1488
+ result: null,
1489
+ createdAt: now,
1490
+ updatedAt: now
1491
+ };
1492
+ this.calibrationJobs.set(id, j);
1493
+ return json(202, j, { location: `/api/v1/venues/${p.venueId}/calibration/jobs/${id}` });
1494
+ }
1495
+ case "getCalibrationJob": {
1496
+ const j = this.calibrationJobs.get(p.jobId);
1497
+ return j ? json(200, j) : problem(404, "not-found", "calibration job");
1498
+ }
1499
+ case "cancelCalibrationJob": {
1500
+ const j = this.calibrationJobs.get(p.jobId);
1501
+ if (!j) return problem(404, "not-found", "calibration job");
1502
+ if (!["succeeded", "failed", "cancelled"].includes(j.status)) {
1503
+ j.status = "cancelled";
1504
+ this.publish(`venues/${p.venueId}/calibration/jobs/${j.id}`, "calibrationJob.state", {
1505
+ resource: j
1506
+ });
1507
+ }
1508
+ return json(200, j);
1509
+ }
1510
+ case "applyCalibrationJob": {
1511
+ const j = this.calibrationJobs.get(p.jobId);
1512
+ if (!j) return problem(404, "not-found", "calibration job");
1513
+ if (j.status !== "succeeded" || !j.result)
1514
+ return problem(409, "conflict", `job ${j.id} has nothing to apply`);
1515
+ return json(200, j.result);
1516
+ }
1517
+ case "listShows":
1518
+ return json(200, {
1519
+ items: [...this.shows.entries()].map(([id, s]) => ({
1520
+ id,
1521
+ revision: s.revision,
1522
+ meta: s.body.meta
1523
+ })),
1524
+ nextCursor: null
1525
+ });
1526
+ case "getShow": {
1527
+ const s = this.shows.get(p.showId);
1528
+ if (!s) return problem(404, "not-found", "show");
1529
+ return json(
1530
+ 200,
1531
+ { id: p.showId, revision: s.revision, status: "ready", ...s.body },
1532
+ this.etag(s.revision)
1533
+ );
1534
+ }
1535
+ case "putShow": {
1536
+ const id = p.showId;
1537
+ const s = this.shows.get(id);
1538
+ if (!s) {
1539
+ if (r.headers["if-none-match"] !== "*")
1540
+ return problem(428, "precondition-required", "create needs If-None-Match: *");
1541
+ this.shows.set(id, { body, revision: 1 });
1542
+ return json(201, { id, revision: 1, status: "ready", ...body }, this.etag(1));
1543
+ }
1544
+ if (r.headers["if-none-match"] === "*")
1545
+ return problem(412, "precondition-failed", `show ${id} exists`);
1546
+ if (r.headers["if-match"] !== `"r${s.revision}"`)
1547
+ return problem(412, "precondition-failed", `revision is ${s.revision}`);
1548
+ s.body = body;
1549
+ s.revision++;
1550
+ this.publish(`shows/${id}`, "show.updated", {
1551
+ resource: { id, revision: s.revision, ...body },
1552
+ revision: s.revision
1553
+ });
1554
+ return json(
1555
+ 200,
1556
+ { id, revision: s.revision, status: "ready", ...body },
1557
+ this.etag(s.revision)
1558
+ );
1559
+ }
1560
+ case "createUpload": {
1561
+ const id = uuidV7();
1562
+ const meta = {};
1563
+ for (const kv of (r.headers["upload-metadata"] ?? "").split(",").filter(Boolean)) {
1564
+ const [k, v] = kv.trim().split(" ");
1565
+ meta[k] = v ? new TextDecoder().decode(Uint8Array.from(atob(v), (c) => c.charCodeAt(0))) : "";
1566
+ }
1567
+ this.uploads.set(id, {
1568
+ length: Number(r.headers["upload-length"]),
1569
+ data: [],
1570
+ offset: 0,
1571
+ meta,
1572
+ status: "uploading"
1573
+ });
1574
+ return new FreedomeResponse(201, {
1575
+ location: `/api/v1/uploads/${id}`,
1576
+ "upload-offset": "0",
1577
+ "tus-resumable": "1.0.0"
1578
+ });
1579
+ }
1580
+ case "getUploadOffset": {
1581
+ const u = this.uploads.get(p.uploadId);
1582
+ if (!u) return problem(404, "not-found", "upload");
1583
+ return new FreedomeResponse(200, {
1584
+ "upload-offset": String(u.offset),
1585
+ "upload-length": String(u.length),
1586
+ "tus-resumable": "1.0.0"
1587
+ });
1588
+ }
1589
+ case "appendUpload": {
1590
+ const u = this.uploads.get(p.uploadId);
1591
+ if (!u) return problem(404, "not-found", "upload");
1592
+ if (Number(r.headers["upload-offset"]) !== u.offset)
1593
+ return problem(409, "conflict", `offset is ${u.offset}`);
1594
+ const chunk = r.body ?? new Uint8Array(0);
1595
+ u.data.push(chunk.slice());
1596
+ u.offset += chunk.length;
1597
+ if (u.offset >= u.length) u.status = "complete";
1598
+ return new FreedomeResponse(204, {
1599
+ "upload-offset": String(u.offset),
1600
+ "tus-resumable": "1.0.0"
1601
+ });
1602
+ }
1603
+ case "deleteUpload":
1604
+ this.uploads.delete(p.uploadId);
1605
+ return new FreedomeResponse(204, { "tus-resumable": "1.0.0" });
1606
+ case "createAsset": {
1607
+ const u = this.uploads.get(body?.uploadId);
1608
+ if (!u || u.status !== "complete")
1609
+ return problem(422, "validation-failed", "/uploadId: no completed upload", {
1610
+ errors: [{ pointer: "/uploadId", detail: "no completed upload" }]
1611
+ });
1612
+ const bytes = new Uint8Array(u.length);
1613
+ let o = 0;
1614
+ for (const c of u.data) {
1615
+ bytes.set(c, o);
1616
+ o += c.length;
1617
+ }
1618
+ const sha = sha256Hex(bytes);
1619
+ if (u.meta.sha256 && u.meta.sha256 !== sha)
1620
+ return problem(422, "upload-checksum-mismatch", "sha256 differs");
1621
+ const id = body.id ?? uuidV7();
1622
+ const a = {
1623
+ id,
1624
+ revision: 1,
1625
+ name: body.name ?? u.meta.filename,
1626
+ type: body.type ?? "other",
1627
+ status: "ready",
1628
+ size: bytes.length,
1629
+ sha256: sha,
1630
+ tags: body.tags ?? [],
1631
+ createdAt: (0, import_protocol3.rfc3339Millis)()
1632
+ };
1633
+ this.assets.set(id, a);
1634
+ this.assetBytes.set(id, bytes);
1635
+ this.publish(`assets/${id}`, "asset.ready", { resource: a });
1636
+ return json(201, a);
1637
+ }
1638
+ case "getAsset": {
1639
+ const a = this.assets.get(p.assetId);
1640
+ return a ? json(200, a, this.etag(a.revision)) : problem(404, "not-found", "asset");
1641
+ }
1642
+ case "listAssets":
1643
+ return json(200, { items: [...this.assets.values()], nextCursor: null });
1644
+ case "getJob": {
1645
+ const j = this.jobs.get(p.jobId);
1646
+ return j ? json(200, j) : problem(404, "not-found", "job");
1647
+ }
1648
+ default: {
1649
+ const a = op.tags.includes("audio") ? this.audio.handle(op.id, p, body, r.headers, r.query ?? {}) : void 0;
1650
+ if (a) return a;
1651
+ const reactive = this.audioReactive.handle(op.id, p, body, r.headers);
1652
+ if (reactive) return reactive;
1653
+ return problem(
1654
+ 501,
1655
+ "internal",
1656
+ `${op.id} is not implemented by the in-memory fake \u2014 use the freedome/fake-dome image`
1657
+ );
1658
+ }
1659
+ }
1660
+ }
1661
+ };
1662
+ var FakeTransport = class {
1663
+ constructor(s) {
1664
+ this.s = s;
1665
+ }
1666
+ s;
1667
+ closed = false;
1668
+ async send(r) {
1669
+ if (this.closed) throw new NetworkError("transport closed");
1670
+ return this.s.handle(r);
1671
+ }
1672
+ async close() {
1673
+ this.closed = true;
1674
+ }
1675
+ };
1676
+ var FakeSocketSession = class {
1677
+ constructor(server) {
1678
+ this.server = server;
1679
+ this.client = {
1680
+ protocol: "freedome.v1",
1681
+ send: (t) => queueMicrotask(() => void this.receive(t)),
1682
+ listen: (m, c) => {
1683
+ this.onMessage = m;
1684
+ this.onClose = c;
1685
+ },
1686
+ close: (code, reason) => this.serverClose(code ?? 1e3, reason)
1687
+ };
1688
+ }
1689
+ server;
1690
+ onMessage;
1691
+ onClose;
1692
+ filters = [];
1693
+ token;
1694
+ open = true;
1695
+ client;
1696
+ out(m) {
1697
+ if (!this.open) return;
1698
+ const t = JSON.stringify(m);
1699
+ queueMicrotask(() => this.onMessage?.(t));
1700
+ }
1701
+ serverClose(code, reason) {
1702
+ if (!this.open) return;
1703
+ this.open = false;
1704
+ this.server.forget(this);
1705
+ queueMicrotask(() => this.onClose?.(code, reason));
1706
+ }
1707
+ deliver(e) {
1708
+ if (this.filters.some((f) => matches(f, e.topic))) this.out(e);
1709
+ }
1710
+ reply(m, type, data) {
1711
+ this.out({ type, id: uuidV7(), ts: (0, import_protocol3.rfc3339Millis)(), replyTo: m.id, data });
1712
+ }
1713
+ async receive(text) {
1714
+ if (!this.open) return;
1715
+ const m = JSON.parse(text);
1716
+ switch (m.type) {
1717
+ case "hello": {
1718
+ this.token = m.data?.token;
1719
+ if (this.token && !this.server.principal(`Bearer ${this.token}`)) {
1720
+ this.out({
1721
+ type: "bye",
1722
+ id: uuidV7(),
1723
+ ts: (0, import_protocol3.rfc3339Millis)(),
1724
+ data: { reason: "unauthenticated", code: 4401 }
1725
+ });
1726
+ this.serverClose(4401, "unauthenticated");
1727
+ return;
1728
+ }
1729
+ this.reply(m, "welcome", {
1730
+ server: { instanceId: this.server.instanceId, version: "1.0.0-rc.1" },
1731
+ heartbeatSec: 20,
1732
+ maxMessageBytes: 1048576
1733
+ });
1734
+ const since = m.data?.resume?.sinceSeq;
1735
+ if (typeof since === "number") this.pendingResume = since;
1736
+ return;
1737
+ }
1738
+ case "subscribe": {
1739
+ const topics = m.data?.topics ?? [];
1740
+ this.filters.push(...topics);
1741
+ this.reply(m, "result", { status: 200, body: { topics } });
1742
+ const since = m.data?.sinceSeq ?? this.pendingResume;
1743
+ if (typeof since === "number") {
1744
+ for (const e of this.server.replay(since))
1745
+ if (topics.some((f) => matches(f, e.topic))) this.out(e);
1746
+ }
1747
+ return;
1748
+ }
1749
+ case "unsubscribe":
1750
+ this.filters = this.filters.filter((f) => !(m.data?.topics ?? []).includes(f));
1751
+ this.reply(m, "result", { status: 200 });
1752
+ return;
1753
+ case "ping":
1754
+ this.reply(m, "pong", {});
1755
+ return;
1756
+ case "call": {
1757
+ const op = import_protocol3.Operations[m.data?.op];
1758
+ if (!op) {
1759
+ this.reply(m, "error", {
1760
+ type: "about:blank",
1761
+ title: "not-found",
1762
+ status: 404,
1763
+ code: "not-found",
1764
+ detail: `unknown op ${m.data?.op}`
1765
+ });
1766
+ return;
1767
+ }
1768
+ const path = op.path.replace(
1769
+ /\{([^}]+)\}/g,
1770
+ (_, n) => encodeURIComponent(m.data.params?.[n] ?? "")
1771
+ );
1772
+ const res = await this.server.handle({
1773
+ method: op.method,
1774
+ path,
1775
+ headers: {
1776
+ ...this.token ? { authorization: `Bearer ${this.token}` } : {},
1777
+ ...m.data.ifMatch ? { "if-match": m.data.ifMatch } : {},
1778
+ "content-type": "application/json"
1779
+ },
1780
+ ...m.data.body !== void 0 ? { body: new TextEncoder().encode(JSON.stringify(m.data.body)) } : {},
1781
+ operationId: op.id
1782
+ });
1783
+ if (res.ok)
1784
+ this.reply(m, "result", {
1785
+ status: res.status,
1786
+ ...res.body.length ? { body: res.json } : {},
1787
+ ...res.headers.etag ? { etag: res.headers.etag } : {}
1788
+ });
1789
+ else this.reply(m, "error", res.json);
1790
+ return;
1791
+ }
1792
+ }
1793
+ }
1794
+ pendingResume;
1795
+ };
1796
+ function matches(filter, topic) {
1797
+ if (filter === "#") return true;
1798
+ const f = filter.split("/");
1799
+ const t = topic.split("/");
1800
+ for (let i = 0; i < f.length; i++) {
1801
+ if (f[i] === "#") return true;
1802
+ if (i >= t.length || f[i] !== "+" && f[i] !== t[i]) return false;
1803
+ }
1804
+ return f.length === t.length;
1805
+ }
1806
+ function createFakeTransport() {
1807
+ return new FakeDomeServer();
1808
+ }
1809
+ // Annotate the CommonJS export names for ESM import in node:
1810
+ 0 && (module.exports = {
1811
+ FakeDomeServer,
1812
+ createFakeTransport
1813
+ });