@doitian/dsh-music 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/lib/client.js CHANGED
@@ -23,7 +23,16 @@
23
23
  * on the plugin's own lifetime in the shell document, which keeps running no
24
24
  * matter which panel is on screen. The page becomes a remote control over the
25
25
  * host's shared state, and `window.__dshMusicEngine.sync()` lets it apply a
26
- * command without waiting for the next poll.
26
+ * command at once.
27
+ *
28
+ * ## How the engine hears about changes
29
+ *
30
+ * The host pushes its state over `/music/api/events` (an event stream; see
31
+ * lib/feed.js) whenever something the engine acts on changes. The engine
32
+ * re-reads `/state` itself only while that stream is down. A short local clock
33
+ * still runs regardless, because two things never reach the host as a change:
34
+ * a play the browser refused, which must be retried until it is allowed, and
35
+ * the position reports the engine owes the host.
27
36
  *
28
37
  * @module @doitian/dsh-music/client
29
38
  */
@@ -72,8 +81,13 @@ window.__ModuleLoader__.load({
72
81
  /** Bound in apply() once the dictionary is registered; English until then. */
73
82
  let t = (key) => DICTIONARY.en[key] ?? key;
74
83
 
75
- /** How often the engine re-reads the host state; bounds control latency. */
76
- const POLL_MS = 500;
84
+ /**
85
+ * The engine's own clock: it retries a refused play, sends a report when one
86
+ * is due, and re-reads the host while the event stream is down.
87
+ */
88
+ const TICK_MS = 500;
89
+ /** A stream the browser gave up on (an error answer) is opened again after this. */
90
+ const RELISTEN_MS = 10_000;
77
91
  /** Position report cadence while playing, and while idle. */
78
92
  const REPORT_MS = 1000;
79
93
  const IDLE_REPORT_MS = 5000;
@@ -88,6 +102,23 @@ window.__ModuleLoader__.load({
88
102
  : '';
89
103
  }
90
104
 
105
+ /**
106
+ * Origin that serves audio bytes.
107
+ *
108
+ * The desktop shell runs on the `dsh-app://` custom scheme, whose responses
109
+ * Chromium cannot byte-range (electron/electron#38749): audio plays, but a
110
+ * seek collapses to zero and restarts the track. The shell publishes its
111
+ * real HTTP origin as `__DSH_TRANSPORT__.streamBaseUrl` for exactly this;
112
+ * in a browser it is absent and the document origin serves.
113
+ */
114
+ function streamOrigin() {
115
+ try {
116
+ const base = window.__DSH_TRANSPORT__?.streamBaseUrl;
117
+ if (typeof base === 'string' && base) return new URL(base).origin;
118
+ } catch { /* a malformed base falls back to the document origin */ }
119
+ return origin();
120
+ }
121
+
91
122
  /** Player page URL, shown in errors and used as the iframe source. */
92
123
  function panelUrl() {
93
124
  return `${origin()}${BASE}/panel`;
@@ -97,14 +128,15 @@ window.__ModuleLoader__.load({
97
128
 
98
129
  /**
99
130
  * The page/engine boundary this bundle expects, mirrored from the host's
100
- * `/health`. See {@link createEngine} for why it is checked at all.
131
+ * `/health`. It covers the host's playback core too: see
132
+ * {@link loadPlayback}, and {@link createEngine} for why it is checked at all.
101
133
  */
102
134
  const PANEL_CONTRACT = 2;
103
135
 
104
136
  /** An engine that does nothing, for a host that predates the contract. */
105
137
  function inertEngine() {
106
138
  // `playback: false` is the page's cue to own the audio element itself.
107
- return { playback: false, inert: true, sync() {}, playNow() {}, state: () => null, dispose() {} };
139
+ return { playback: false, inert: true, sync() {}, playNow() {}, state: () => null, position: () => 0, dispose() {} };
108
140
  }
109
141
 
110
142
  /**
@@ -135,6 +167,33 @@ window.__ModuleLoader__.load({
135
167
  }
136
168
  }
137
169
 
170
+ /**
171
+ * Load the playback core the host serves beside the page.
172
+ *
173
+ * The page's fallback transport runs the same file, which is the point:
174
+ * the fades, the seek hold and the autoplay retry exist once. It comes
175
+ * from the host rather than this bundle because the host and the page are
176
+ * one generation and this bundle may be another; the handshake has already
177
+ * established that the host's generation is the one this engine expects.
178
+ * A host from before the core was split out does not serve it, and that
179
+ * leaves the engine inert like any other mismatch.
180
+ *
181
+ * @returns {Promise<{createPlayback: Function} | null>}
182
+ */
183
+ function loadPlayback() {
184
+ return new Promise((resolve) => {
185
+ const script = document.createElement('script');
186
+ const settle = (core) => {
187
+ script.remove();
188
+ resolve(typeof core?.createPlayback === 'function' ? core : null);
189
+ };
190
+ script.addEventListener('load', () => settle(window.__dshMusicPlayback));
191
+ script.addEventListener('error', () => settle(null));
192
+ script.src = `${BASE}/playback.js`;
193
+ (document.head ?? document.documentElement).appendChild(script);
194
+ });
195
+ }
196
+
138
197
  /**
139
198
  * Start the persistent audio engine, after a contract handshake.
140
199
  *
@@ -143,7 +202,7 @@ window.__ModuleLoader__.load({
143
202
  * this engine as well would play every track twice — so the engine stays
144
203
  * inert and the old behaviour applies until the two are refreshed together.
145
204
  *
146
- * @returns {Promise<{sync: () => void, state: () => object | null, dispose: () => void}>}
205
+ * @returns {Promise<{sync: () => void, state: () => object | null, position: () => number, dispose: () => void}>}
147
206
  */
148
207
  async function createEngine() {
149
208
  if (!(await pageAcceptsEngine())) {
@@ -153,27 +212,32 @@ window.__ModuleLoader__.load({
153
212
  );
154
213
  return inertEngine();
155
214
  }
215
+ const core = await loadPlayback();
216
+ if (!core) {
217
+ console.warn('[music] the host serves no playback core; leaving playback to the page until the harness restarts.');
218
+ return inertEngine();
219
+ }
156
220
 
157
221
  // A hot re-materialization must not leave a second element playing.
158
222
  try {
159
223
  window.__dshMusicEngine?.dispose?.();
160
224
  } catch { /* ignore a stale engine */ }
161
225
 
162
- const audio = document.createElement('audio');
163
- audio.preload = 'auto';
164
- audio.setAttribute('aria-hidden', 'true');
165
- audio.style.display = 'none';
166
- (document.body ?? document.documentElement).appendChild(audio);
167
-
168
226
  let state = null;
169
- let appliedTransport = -1;
170
227
  // Start the clock now so the first tick reconciles without also posting a
171
228
  // redundant position report.
172
229
  let lastReportAt = Date.now();
173
230
  let disposed = false;
174
231
  let inflight = false;
175
- /** Guards against stacking overlapping `play()` attempts. */
176
- let playing = false;
232
+ /** The host's event stream, and whether it is open. */
233
+ let events = null;
234
+ let streaming = false;
235
+ let relisten = null;
236
+ /** The newest snapshot version adopted; see {@link take}. */
237
+ let versionFloor = 0;
238
+
239
+ const playback = core.createPlayback({ base: BASE, streamOrigin, call, report });
240
+ const { audio, reconcile, applySource, enforce } = playback;
177
241
 
178
242
  /** One JSON round-trip to the host. */
179
243
  async function call(path, init) {
@@ -186,162 +250,107 @@ window.__ModuleLoader__.load({
186
250
  return text ? JSON.parse(text) : {};
187
251
  }
188
252
 
189
- /** Push the audio element back in line with the host's desired state. */
190
- function reconcile(next) {
191
- if (next.transportRev === appliedTransport) return;
192
- appliedTransport = next.transportRev;
193
-
194
- if (next.pendingSeek !== null && next.pendingSeek !== undefined) {
195
- try {
196
- audio.currentTime = next.pendingSeek / 1000;
197
- } catch { /* not seekable until metadata arrives */ }
198
- // One-shot: drop it so the next poll cannot re-apply the seek.
199
- void call('/seek-consumed', { method: 'POST', body: {} }).catch(() => {});
200
- }
253
+ /** Tell the host where playback actually is. */
254
+ async function report(extra) {
255
+ if (!state?.current) return;
256
+ lastReportAt = Date.now();
257
+ try {
258
+ const next = await call('/report', {
259
+ method: 'POST',
260
+ body: { trackId: state.current.id, ...playback.progress(), ...extra },
261
+ });
262
+ // Taken, not acted on: acting here would retry a refused play from
263
+ // the answer to its own refusal, as fast as the host can reply.
264
+ if (next?.rev !== undefined) take(next);
265
+ } catch { /* the next update carries the host's view */ }
201
266
  }
202
267
 
203
268
  /**
204
- * Decide which resource the element should be playing.
269
+ * Adopt one host state, unless it is older than the one held.
205
270
  *
206
- * Runs on every tick rather than behind the `transportRev` gate, because
207
- * the resource identity includes the streaming quality: quality is not a
208
- * one-shot transport change, and gating it meant a switch did nothing
209
- * until something else moved the revision.
271
+ * A report's answer and a pushed frame travel on different connections,
272
+ * so one read earlier can land later; adopting it would undo the newer
273
+ * one — resume a pause, or load the quality just left — with no frame
274
+ * coming to repair it. While the stream is open, a state whose `version`
275
+ * is older than the newest one adopted is dropped. A reconnect drops the
276
+ * floor, since a restarted host counts its versions from zero again.
277
+ * A host without versions is taken as it comes.
210
278
  *
211
- * The level is part of the URL, not implicit host state: the same track at
212
- * two levels is two different files, so a change must load a new one
213
- * instead of range-requesting offsets into the other encoding. The track
214
- * id stays in the key so a switch resumes in place.
279
+ * @returns {boolean} whether it was adopted.
215
280
  */
216
- function applySource(next) {
217
- const track = next.current;
218
- if (!track) {
219
- if (audio.dataset.trackKey !== undefined) {
220
- delete audio.dataset.trackKey;
221
- delete audio.dataset.trackId;
222
- audio.pause();
223
- audio.removeAttribute('src');
224
- audio.load();
225
- }
226
- return;
227
- }
228
-
229
- const level = next.audio?.preferred ?? 'exhigh';
230
- const key = `${track.id}:${level}`;
231
- if (audio.dataset.trackKey === key) return;
232
-
233
- const sameTrack = audio.dataset.trackId === String(track.id);
234
- const resumeAt = sameTrack ? audio.currentTime : 0;
235
- audio.dataset.trackKey = key;
236
- audio.dataset.trackId = String(track.id);
237
- if (resumeAt > 0.5) {
238
- audio.addEventListener(
239
- 'loadedmetadata',
240
- () => {
241
- try {
242
- audio.currentTime = resumeAt;
243
- } catch { /* not seekable */ }
244
- },
245
- { once: true },
246
- );
281
+ function take(next) {
282
+ if (disposed || !next) return false;
283
+ const version = Number(next.version);
284
+ if (Number.isFinite(version)) {
285
+ if (streaming && version < versionFloor) return false;
286
+ versionFloor = version;
247
287
  }
248
- audio.src = `${origin()}${BASE}/stream/${track.id}?level=${encodeURIComponent(level)}`;
249
- audio.load();
288
+ state = next;
289
+ reconcile(next);
290
+ return true;
250
291
  }
251
292
 
252
- /**
253
- * Start playback, tolerating a refusal.
254
- *
255
- * Chromium blocks audio until the page has been activated by a gesture,
256
- * so an attempt can legitimately fail and has to be repeatable. Both
257
- * outcomes are reported at once, so the host — and the panel's hint —
258
- * learns the real state instead of waiting for the next scheduled report.
259
- * `blocked` says which: only the autoplay policy's `NotAllowedError` is a
260
- * reason to ask for a click, not an attempt still under way or one
261
- * interrupted by a new source.
262
- */
263
- function attemptPlay() {
264
- if (playing || disposed) return;
265
- playing = true;
266
- audio.play().then(
267
- () => {
268
- playing = false;
269
- void report({ blocked: false });
270
- },
271
- (error) => {
272
- playing = false;
273
- void report(error?.name === 'NotAllowedError' ? { blocked: true } : {});
274
- },
275
- );
293
+ /** Adopt one host state and bring the element in line with it. */
294
+ function receive(next) {
295
+ if (!take(next)) return;
296
+ applySource(next);
297
+ enforce(next);
276
298
  }
277
299
 
278
- /**
279
- * Keep the element in line with the desired transport, on every tick.
280
- *
281
- * Deliberately outside the `transportRev` gate: a refused `play()` does
282
- * not change the revision, so gating this would leave the music stopped
283
- * for good after the first refusal — the panel would show the autoplay
284
- * hint and pressing it would fix nothing.
285
- */
286
- function enforce(next) {
287
- audio.volume = next.muted ? 0 : next.volume;
288
- if (!next.current) return;
289
- if (next.playing && audio.paused) {
290
- attemptPlay();
291
- } else if (!next.playing && !audio.paused) {
292
- audio.pause();
293
- void report({});
300
+ /** Read the host's state over a plain request. */
301
+ async function poll() {
302
+ if (disposed || inflight) return;
303
+ inflight = true;
304
+ try {
305
+ receive(await call('/state'));
306
+ } catch { /* host not reachable yet; the next tick tries again */ } finally {
307
+ inflight = false;
294
308
  }
295
309
  }
296
310
 
297
- /** Tell the host where playback actually is. */
298
- async function report(extra) {
299
- if (!state?.current) return;
300
- lastReportAt = Date.now();
301
- try {
302
- const next = await call('/report', {
303
- method: 'POST',
304
- body: {
305
- trackId: state.current.id,
306
- position: Math.round((audio.currentTime || 0) * 1000),
307
- duration: Number.isFinite(audio.duration) ? Math.round(audio.duration * 1000) : undefined,
308
- playing: !audio.paused,
309
- ...extra,
310
- },
311
- });
312
- if (next?.rev !== undefined) {
313
- state = next;
314
- reconcile(next);
311
+ /** Subscribe to the host's pushed state, where the browser can. */
312
+ function listen() {
313
+ relisten = null;
314
+ const Source = window.EventSource;
315
+ if (disposed || typeof Source !== 'function') return;
316
+ events = new Source(`${API}/events`);
317
+ events.onopen = () => {
318
+ streaming = true;
319
+ versionFloor = 0;
320
+ };
321
+ events.onerror = () => {
322
+ streaming = false;
323
+ // A dropped connection is retried by the browser; an error status
324
+ // (a host that predates the route) closes the stream for good.
325
+ if (events?.readyState === Source.CLOSED) {
326
+ events = null;
327
+ if (!disposed) relisten = setTimeout(listen, RELISTEN_MS);
315
328
  }
316
- } catch { /* the host will be re-read on the next tick */ }
329
+ };
330
+ events.addEventListener('state', (event) => {
331
+ try {
332
+ receive(JSON.parse(event.data));
333
+ } catch { /* a garbled frame; the next one carries the whole state */ }
334
+ });
317
335
  }
318
336
 
319
- audio.addEventListener('ended', () => void report({ ended: true }));
320
- audio.addEventListener('error', () => {
321
- // Fires for an unavailable track and for a dropped connection alike;
322
- // the host skips to the next track on either.
323
- if (audio.dataset.trackId) void report({ error: 'audio element error (track unavailable or network)' });
324
- });
325
-
326
- /** One poll: read state, reconcile, and report when due. */
327
- async function tick() {
328
- if (disposed || inflight) return;
329
- inflight = true;
330
- try {
331
- const next = await call('/state');
332
- state = next;
333
- reconcile(next);
334
- applySource(next);
335
- enforce(next);
336
- const due = next.playing && !audio.paused ? REPORT_MS : IDLE_REPORT_MS;
337
- if (audio.dataset.trackId && Date.now() - lastReportAt >= due) void report({});
338
- } catch { /* host not reachable yet; keep polling */ } finally {
339
- inflight = false;
337
+ function tick() {
338
+ if (disposed) return;
339
+ if (!streaming) void poll();
340
+ else if (state) {
341
+ // The host has nothing new to say about a refused play, so it is
342
+ // retried here, against the state already held — which a report's
343
+ // answer may have moved to the next track without loading it.
344
+ applySource(state);
345
+ enforce(state);
340
346
  }
347
+ const due = state?.playing && !audio.paused ? REPORT_MS : IDLE_REPORT_MS;
348
+ if (audio.dataset.trackId && Date.now() - lastReportAt >= due) void report({});
341
349
  }
342
350
 
343
- const timer = setInterval(() => void tick(), POLL_MS);
344
- void tick();
351
+ const timer = setInterval(tick, TICK_MS);
352
+ void poll();
353
+ listen();
345
354
 
346
355
  return {
347
356
  /**
@@ -350,30 +359,38 @@ window.__ModuleLoader__.load({
350
359
  * engine never leaves playback unowned.
351
360
  */
352
361
  playback: true,
353
- /** Apply a pending command immediately instead of waiting for a poll. */
362
+ /** Re-read the host now: the page just sent a command and wants it applied. */
354
363
  sync() {
355
- if (!disposed) void tick();
364
+ void poll();
356
365
  },
357
366
  /**
358
367
  * Retry playback synchronously, for a click on the autoplay hint.
359
368
  *
360
369
  * Called from inside the gesture so the attempt lands while the page is
361
- * being activated, rather than on the next 500 ms poll.
370
+ * being activated, rather than on the next tick.
362
371
  */
363
372
  playNow() {
364
- attemptPlay();
373
+ playback.playNow();
365
374
  },
366
375
  state() {
367
376
  return state;
368
377
  },
378
+ /**
379
+ * Where playback is, in milliseconds, read off the element itself, so
380
+ * the page's bar moves smoothly without a report per frame. A held seek
381
+ * counts as already there.
382
+ */
383
+ position() {
384
+ return playback.position();
385
+ },
369
386
  dispose() {
370
387
  disposed = true;
371
388
  clearInterval(timer);
372
- try {
373
- audio.pause();
374
- audio.removeAttribute('src');
375
- audio.remove();
376
- } catch { /* the document may already be gone */ }
389
+ clearTimeout(relisten);
390
+ events?.close();
391
+ events = null;
392
+ streaming = false;
393
+ playback.dispose();
377
394
  },
378
395
  };
379
396
  }
package/lib/feed.js ADDED
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Server-sent player state, for the player page and the audio engine.
3
+ *
4
+ * `GET /music/api/events` holds the response open as an event stream and
5
+ * writes the full snapshot whenever something either of them would show or
6
+ * act on changes. Both used to re-read `/state` on a timer — the page every
7
+ * 1.5 s, the engine every 500 ms — and the page rebuilt its lists on every
8
+ * read whether or not anything had moved.
9
+ *
10
+ * A change is found by comparing snapshots rather than by trusting every
11
+ * mutation to announce itself: the snapshot draws on the player, the session
12
+ * store, the like cache, the scrobbler and the stream resolver, and several of
13
+ * those change without passing through the player. Announcements only decide
14
+ * *when* to compare: on a player bump, after any API write, and on a slow
15
+ * sweep that catches what announces nothing (a boost running out, a like
16
+ * resolved in the background, a sign-in from an agent tool). The position
17
+ * report the engine posts every second bumps the player, but moves nothing
18
+ * the comparison sees, so a playing track sends no frames.
19
+ *
20
+ * @module dsh-music/feed
21
+ */
22
+
23
+ /** Keeps idle connections, and the desktop shell's forwarding fetch, alive. */
24
+ const HEARTBEAT_MS = 25_000;
25
+
26
+ /** How soon a dropped browser connection reconnects. */
27
+ const RETRY_MS = 2_000;
28
+
29
+ /** Compare this often even when nothing announced a change. */
30
+ const SWEEP_MS = 5_000;
31
+
32
+ /**
33
+ * The snapshot as the page and engine see it, minus what moves while a track
34
+ * plays: the position, its timestamp, and the revision a position report bumps.
35
+ * The last stream request's time goes too: every seek is a new range request,
36
+ * and the time is all that changes about it.
37
+ */
38
+ export function visibleKey(snapshot) {
39
+ const { rev, version, reported, audio, ...rest } = snapshot ?? {};
40
+ const { position, at, ...steady } = reported ?? {};
41
+ const { at: requestedAt, ...last } = audio?.last ?? {};
42
+ return JSON.stringify({ ...rest, reported: steady, audio: { ...audio, last } });
43
+ }
44
+
45
+ /**
46
+ * Numbers snapshots by what they show, for the clients' ordering guard.
47
+ *
48
+ * The player's `rev` cannot order them: a streaming quality, a setting or a
49
+ * resolved like changes the snapshot without bumping it, so a report's late
50
+ * answer and a newer pushed frame could share a `rev` and the stale one win.
51
+ * `version` moves whenever {@link visibleKey} does, whatever moved it, and
52
+ * never for a position report.
53
+ */
54
+ export class SnapshotVersions {
55
+ constructor() {
56
+ this.key = undefined;
57
+ this.version = 0;
58
+ }
59
+
60
+ /** `snapshot` with its `version`. */
61
+ stamp(snapshot) {
62
+ const key = visibleKey(snapshot);
63
+ if (key !== this.key) {
64
+ this.key = key;
65
+ this.version += 1;
66
+ }
67
+ return { ...snapshot, version: this.version };
68
+ }
69
+ }
70
+
71
+ function frame(snapshot) {
72
+ return `event: state\ndata: ${JSON.stringify(snapshot)}\n\n`;
73
+ }
74
+
75
+ export class StateFeed {
76
+ /**
77
+ * @param {object} options
78
+ * @param {() => Promise<object>} options.snapshot the state document to send.
79
+ * @param {{warn: Function}} [options.logger]
80
+ * @param {number} [options.sweepMs]
81
+ * @param {number} [options.heartbeatMs]
82
+ */
83
+ constructor({ snapshot, logger, sweepMs = SWEEP_MS, heartbeatMs = HEARTBEAT_MS }) {
84
+ this.snapshot = snapshot;
85
+ this.logger = logger;
86
+ this.sweepMs = sweepMs;
87
+ this.heartbeatMs = heartbeatMs;
88
+ /** @type {Set<import('node:http').ServerResponse>} */
89
+ this.clients = new Set();
90
+ /** Clients that have not been sent a state yet. */
91
+ this.newcomers = new Set();
92
+ /** What the clients were last sent, as {@link visibleKey}. */
93
+ this.lastKey = undefined;
94
+ /** The comparison under way, and whether another was asked for meanwhile. */
95
+ this.pending = null;
96
+ this.dirty = false;
97
+ this.sweep = undefined;
98
+ this.heartbeat = undefined;
99
+ }
100
+
101
+ /** Take over one `GET /events` response for as long as the client stays. */
102
+ attach(req, res) {
103
+ res.writeHead(200, {
104
+ 'Content-Type': 'text/event-stream; charset=utf-8',
105
+ 'Cache-Control': 'no-store',
106
+ 'X-Accel-Buffering': 'no',
107
+ });
108
+ res.write(`retry: ${RETRY_MS}\n\n`);
109
+ this.clients.add(res);
110
+ this.newcomers.add(res);
111
+ this.#start();
112
+ const leave = () => {
113
+ this.newcomers.delete(res);
114
+ if (!this.clients.delete(res)) return;
115
+ if (this.clients.size === 0) this.#stop();
116
+ };
117
+ req.on('close', leave);
118
+ res.on('close', leave);
119
+ res.on('error', leave);
120
+ // Through the same queue as every other frame, so a newcomer's first state
121
+ // can never land after a newer one.
122
+ this.changed();
123
+ }
124
+
125
+ /** Something may have changed; compare once the current burst has settled. */
126
+ changed() {
127
+ if (this.clients.size === 0) return;
128
+ if (this.pending) {
129
+ this.dirty = true;
130
+ return;
131
+ }
132
+ this.pending = this.#flush().finally(() => {
133
+ this.pending = null;
134
+ if (this.dirty) {
135
+ this.dirty = false;
136
+ this.changed();
137
+ }
138
+ });
139
+ }
140
+
141
+ /** End every stream and stop the timers; the route is going away. */
142
+ close() {
143
+ for (const res of this.clients) {
144
+ try {
145
+ res.end();
146
+ } catch { /* the socket is already gone */ }
147
+ }
148
+ this.clients.clear();
149
+ this.newcomers.clear();
150
+ this.#stop();
151
+ }
152
+
153
+ async #flush() {
154
+ // One comparison for a burst of synchronous mutations, not one each.
155
+ await new Promise((resolve) => setImmediate(resolve));
156
+ let snapshot;
157
+ try {
158
+ snapshot = await this.snapshot();
159
+ } catch (error) {
160
+ this.logger?.warn?.(`[music] event stream could not read the state: ${error.message}`);
161
+ return;
162
+ }
163
+ const key = visibleKey(snapshot);
164
+ // Everyone when it moved; otherwise only those who have nothing yet.
165
+ const targets = key === this.lastKey ? [...this.newcomers] : [...this.clients];
166
+ this.lastKey = key;
167
+ this.newcomers.clear();
168
+ if (targets.length === 0) return;
169
+ const text = frame(snapshot);
170
+ for (const res of targets) res.write(text);
171
+ }
172
+
173
+ #start() {
174
+ if (this.sweep !== undefined) return;
175
+ this.sweep = setInterval(() => this.changed(), this.sweepMs);
176
+ this.sweep.unref?.();
177
+ this.heartbeat = setInterval(() => {
178
+ for (const res of this.clients) res.write(': ping\n\n');
179
+ }, this.heartbeatMs);
180
+ this.heartbeat.unref?.();
181
+ }
182
+
183
+ #stop() {
184
+ clearInterval(this.sweep);
185
+ clearInterval(this.heartbeat);
186
+ this.sweep = undefined;
187
+ this.heartbeat = undefined;
188
+ // Nobody holds the last frame any more; the next client starts afresh.
189
+ this.lastKey = undefined;
190
+ }
191
+ }