@freedome/client 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -13,15 +13,24 @@ import {
13
13
  } from "./chunk-CAEBM4AN.js";
14
14
 
15
15
  // src/testing.ts
16
- import { Operations, matchOperation, rfc3339Millis as rfc3339Millis3 } from "@freedome/protocol";
16
+ import {
17
+ Operations,
18
+ ProtocolVersions,
19
+ SemVer,
20
+ matchOperation,
21
+ rfc3339Millis as rfc3339Millis3
22
+ } from "@freedome/protocol";
17
23
 
18
24
  // src/testing/fake-audio.ts
19
25
  import { rfc3339Millis } from "@freedome/protocol";
20
26
  var ENDED = /* @__PURE__ */ new Set(["finished", "stopped", "failed"]);
27
+ var JOB_ENDED = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
21
28
  var FakeAudio = class {
22
- constructor(publish, problem2) {
29
+ constructor(publish, problem2, jobs = /* @__PURE__ */ new Map(), audioControl = () => true) {
23
30
  this.publish = publish;
24
31
  this.problem = problem2;
32
+ this.jobs = jobs;
33
+ this.audioControl = audioControl;
25
34
  this.zones.set("front", {
26
35
  id: "front",
27
36
  name: "Front",
@@ -61,6 +70,8 @@ var FakeAudio = class {
61
70
  }
62
71
  publish;
63
72
  problem;
73
+ jobs;
74
+ audioControl;
64
75
  state = {
65
76
  venueId: "default",
66
77
  mode: "combined",
@@ -88,6 +99,12 @@ var FakeAudio = class {
88
99
  generator = { running: false };
89
100
  /** Last position per source id. */
90
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;
91
108
  /** Test hook: publishes `audio.levels` (`{meter id: dBFS}`) on `venues/{v}/audio/levels`. */
92
109
  emitLevels(levels) {
93
110
  this.publish("audio/levels", "audio.levels", { resource: { levels } });
@@ -114,6 +131,143 @@ var FakeAudio = class {
114
131
  publishSession(s) {
115
132
  this.publish(`audio/sessions/${s.id}`, "audioSession.state", { resource: s });
116
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
+ }
117
271
  publishGenerator() {
118
272
  this.publish("audio/generator", "generator.state", { resource: this.generator });
119
273
  }
@@ -262,6 +416,8 @@ var FakeAudio = class {
262
416
  case "startAudioSession": {
263
417
  if (!this.presets.has(body?.presetId))
264
418
  return this.problem(404, "not-found", `preset ${body?.presetId}`);
419
+ const bad = this.checkRoleZones(body);
420
+ if (bad) return bad;
265
421
  const s = {
266
422
  id: uuidV7(),
267
423
  venueId: p.venueId,
@@ -271,6 +427,7 @@ var FakeAudio = class {
271
427
  position: 0,
272
428
  itemIndex: 0,
273
429
  ...body.targets ? { targets: body.targets } : {},
430
+ ...body.roleZones ? { roleZones: body.roleZones } : {},
274
431
  startedAt: body.at ?? rfc3339Millis()
275
432
  };
276
433
  this.sessions.set(s.id, s);
@@ -291,10 +448,18 @@ var FakeAudio = class {
291
448
  }
292
449
  return noContent();
293
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);
294
457
  case "getGenerator":
295
458
  return json(200, this.generator);
296
- case "setGenerator":
459
+ case "setGenerator": {
297
460
  if (!body?.signal) return this.problem(422, "validation", "signal is required");
461
+ const bad = this.checkGeneratorMulti(body);
462
+ if (bad) return bad;
298
463
  this.generator = {
299
464
  running: true,
300
465
  settings: body,
@@ -302,6 +467,7 @@ var FakeAudio = class {
302
467
  };
303
468
  this.publishGenerator();
304
469
  return json(200, this.generator);
470
+ }
305
471
  case "stopGenerator":
306
472
  this.generator = { running: false };
307
473
  this.publishGenerator();
@@ -580,6 +746,11 @@ var FakeDomeServer = class {
580
746
  pairings = /* @__PURE__ */ new Map();
581
747
  /** Approve every pairing request at once (role = requested role or operator). */
582
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";
583
754
  /** Calibration jobs by id. */
584
755
  calibrationJobs = /* @__PURE__ */ new Map();
585
756
  /** Audio model + hooks (`emitLevels`, `advanceSession`). */
@@ -588,7 +759,12 @@ var FakeDomeServer = class {
588
759
  for (const v of /* @__PURE__ */ new Set(["default", this.activeVenue]))
589
760
  this.publish(`venues/${v}/${t}`, kind, data);
590
761
  },
591
- (status, code, detail) => problem(status, code, detail)
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
+ }
592
768
  );
593
769
  /** Live analysis, AudioReactive scenes, texture sources and gateways (`seed`, `publishFrame`). */
594
770
  audioReactive = new FakeAudioReactive(
@@ -767,6 +943,7 @@ var FakeDomeServer = class {
767
943
  instanceId: this.instanceId,
768
944
  apiVersions: ["v1"],
769
945
  version: "1.0.0-rc.1",
946
+ contractVersion: this.contractVersion,
770
947
  capabilities: { realtime: ["ws"], audio: true },
771
948
  transports: { ws: true, graphql: false, socketIo: false }
772
949
  });
@@ -931,6 +1108,8 @@ var FakeDomeServer = class {
931
1108
  return json(200, x);
932
1109
  }
933
1110
  case "startCalibrationJob": {
1111
+ if (body?.kind === "audio-device-sweep")
1112
+ return problem(422, "validation-failed", "a sweep starts with startAudioDeviceSweep");
934
1113
  const id = uuidV7();
935
1114
  const now = rfc3339Millis3();
936
1115
  const j = {
@@ -953,6 +1132,24 @@ var FakeDomeServer = class {
953
1132
  const j = this.calibrationJobs.get(p.jobId);
954
1133
  return j ? json(200, j) : problem(404, "not-found", "calibration job");
955
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
+ }
956
1153
  case "listShows":
957
1154
  return json(200, {
958
1155
  items: [...this.shows.entries()].map(([id, s]) => ({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@freedome/client",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Isomorphic Freedome client: REST, WebSocket freedome.v1, graphql-ws, socket.io; connection state machine; repositories; offline cache / outbox; codecs (/codecs), Node helpers (/node), in-memory fake (/testing).",
5
5
  "license": "NativeMindNONC",
6
6
  "homepage": "https://freedome.nativemind.us",
@@ -47,7 +47,7 @@
47
47
  "dependencies": {
48
48
  "fflate": "^0.8.3",
49
49
  "socket.io-client": "^4.8.4",
50
- "@freedome/protocol": "1.0.0"
50
+ "@freedome/protocol": "1.1.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^22.20.5",