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