@freedome/client 1.0.0 → 1.2.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();
@@ -547,6 +713,11 @@ var FakeDomeServer = class {
547
713
  ]);
548
714
  /** Accepted API keys → role. */
549
715
  apiKeys = /* @__PURE__ */ new Map();
716
+ /** Pending physical actions (`listAssistantConfirmations`). */
717
+ confirmations = [];
718
+ linkSessions = [];
719
+ /** The code `approveAssistantLink` accepts. */
720
+ linkCode = "7KQM-2XVB";
550
721
  networkDown = false;
551
722
  realtimeAvailable = true;
552
723
  accessTtlSec = 900;
@@ -580,6 +751,11 @@ var FakeDomeServer = class {
580
751
  pairings = /* @__PURE__ */ new Map();
581
752
  /** Approve every pairing request at once (role = requested role or operator). */
582
753
  autoApprovePairings = false;
754
+ /**
755
+ * Contract version the fake reports in `getInfo` and behaves as: below 1.1.0 the operations of 1.1.0 answer 404 and
756
+ * its members 422, as a 1.0 server does.
757
+ */
758
+ contractVersion = "1.2.0";
583
759
  /** Calibration jobs by id. */
584
760
  calibrationJobs = /* @__PURE__ */ new Map();
585
761
  /** Audio model + hooks (`emitLevels`, `advanceSession`). */
@@ -588,7 +764,12 @@ var FakeDomeServer = class {
588
764
  for (const v of /* @__PURE__ */ new Set(["default", this.activeVenue]))
589
765
  this.publish(`venues/${v}/${t}`, kind, data);
590
766
  },
591
- (status, code, detail) => problem(status, code, detail)
767
+ (status, code, detail) => problem(status, code, detail),
768
+ this.calibrationJobs,
769
+ () => {
770
+ const v = SemVer.tryParse(this.contractVersion);
771
+ return v !== null && v.compareTo(ProtocolVersions.audioControl) >= 0;
772
+ }
592
773
  );
593
774
  /** Live analysis, AudioReactive scenes, texture sources and gateways (`seed`, `publishFrame`). */
594
775
  audioReactive = new FakeAudioReactive(
@@ -767,9 +948,42 @@ var FakeDomeServer = class {
767
948
  instanceId: this.instanceId,
768
949
  apiVersions: ["v1"],
769
950
  version: "1.0.0-rc.1",
951
+ contractVersion: this.contractVersion,
770
952
  capabilities: { realtime: ["ws"], audio: true },
771
953
  transports: { ws: true, graphql: false, socketIo: false }
772
954
  });
955
+ case "listAssistantConfirmations":
956
+ return json(200, { items: this.confirmations, nextCursor: null });
957
+ case "refuseAssistantConfirmation": {
958
+ const c = this.confirmations.find((x) => x.id === p.confirmationId);
959
+ if (!c) return problem(404, "not-found", "no such confirmation");
960
+ c.status = "refused";
961
+ delete c.code;
962
+ return json(200, c);
963
+ }
964
+ case "getAssistantLink":
965
+ return json(200, { enabled: true, state: "online", sessions: this.linkSessions });
966
+ case "approveAssistantLink": {
967
+ if (body?.code !== this.linkCode) return problem(422, "validation-failed", "wrong code");
968
+ const session = {
969
+ id: uuidV7(),
970
+ approver: "user:admin",
971
+ role: "operator",
972
+ scopes: ["playback:control"],
973
+ createdAt: (/* @__PURE__ */ new Date(0)).toISOString(),
974
+ expiresAt: new Date(8 * 36e5).toISOString(),
975
+ status: "active",
976
+ calls: 0
977
+ };
978
+ this.linkSessions.push(session);
979
+ return json(201, session);
980
+ }
981
+ case "endAssistantLink": {
982
+ const x = this.linkSessions.find((v) => v.id === p.sessionId);
983
+ if (!x) return problem(404, "not-found", "no such approval");
984
+ x.status = "ended";
985
+ return new FreedomeResponse(204);
986
+ }
773
987
  case "createSession": {
774
988
  if (this.users.get(body?.username) !== body?.password)
775
989
  return problem(401, "unauthenticated", "wrong username or password");
@@ -931,6 +1145,8 @@ var FakeDomeServer = class {
931
1145
  return json(200, x);
932
1146
  }
933
1147
  case "startCalibrationJob": {
1148
+ if (body?.kind === "audio-device-sweep")
1149
+ return problem(422, "validation-failed", "a sweep starts with startAudioDeviceSweep");
934
1150
  const id = uuidV7();
935
1151
  const now = rfc3339Millis3();
936
1152
  const j = {
@@ -953,6 +1169,24 @@ var FakeDomeServer = class {
953
1169
  const j = this.calibrationJobs.get(p.jobId);
954
1170
  return j ? json(200, j) : problem(404, "not-found", "calibration job");
955
1171
  }
1172
+ case "cancelCalibrationJob": {
1173
+ const j = this.calibrationJobs.get(p.jobId);
1174
+ if (!j) return problem(404, "not-found", "calibration job");
1175
+ if (!["succeeded", "failed", "cancelled"].includes(j.status)) {
1176
+ j.status = "cancelled";
1177
+ this.publish(`venues/${p.venueId}/calibration/jobs/${j.id}`, "calibrationJob.state", {
1178
+ resource: j
1179
+ });
1180
+ }
1181
+ return json(200, j);
1182
+ }
1183
+ case "applyCalibrationJob": {
1184
+ const j = this.calibrationJobs.get(p.jobId);
1185
+ if (!j) return problem(404, "not-found", "calibration job");
1186
+ if (j.status !== "succeeded" || !j.result)
1187
+ return problem(409, "conflict", `job ${j.id} has nothing to apply`);
1188
+ return json(200, j.result);
1189
+ }
956
1190
  case "listShows":
957
1191
  return json(200, {
958
1192
  items: [...this.shows.entries()].map(([id, s]) => ({
@@ -1078,8 +1312,19 @@ var FakeDomeServer = class {
1078
1312
  const a = this.assets.get(p.assetId);
1079
1313
  return a ? json(200, a, this.etag(a.revision)) : problem(404, "not-found", "asset");
1080
1314
  }
1081
- case "listAssets":
1082
- return json(200, { items: [...this.assets.values()], nextCursor: null });
1315
+ case "listAssets": {
1316
+ const f2 = r.query ?? {};
1317
+ const q = f2.q?.toLowerCase();
1318
+ const all = [...this.assets.values()].filter(
1319
+ (a) => (f2.type === void 0 || a.type === f2.type) && (f2.tag === void 0 || (a.tags ?? []).includes(f2.tag)) && (f2.status === void 0 || a.status === f2.status) && (q === void 0 || String(a.name).toLowerCase().includes(q))
1320
+ );
1321
+ const start = Number(f2.cursor ?? 0) || 0;
1322
+ const end = f2.limit === void 0 ? all.length : Math.min(all.length, start + Number(f2.limit));
1323
+ return json(200, {
1324
+ items: all.slice(start, end),
1325
+ nextCursor: end < all.length ? String(end) : null
1326
+ });
1327
+ }
1083
1328
  case "getJob": {
1084
1329
  const j = this.jobs.get(p.jobId);
1085
1330
  return j ? json(200, j) : problem(404, "not-found", "job");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@freedome/client",
3
- "version": "1.0.0",
3
+ "version": "1.2.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.2.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^22.20.5",