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