madeonsol 2.28.0 → 2.29.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/stream.js CHANGED
@@ -63,6 +63,9 @@ async function resolveWebSocket(override) {
63
63
  }
64
64
  const OPEN = 1;
65
65
  const HELD_LIVE_CAP = 10000;
66
+ const DEFAULT_SUB_ID = "default";
67
+ const SUB_ID_RE = /^[A-Za-z0-9_.-]{1,64}$/;
68
+ const subIdOf = (f) => (typeof f.sub_id === "string" && f.sub_id ? f.sub_id : DEFAULT_SUB_ID);
66
69
  function isThenable(v) {
67
70
  return !!v && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
68
71
  }
@@ -103,6 +106,12 @@ export class MadeOnSolStream {
103
106
  this.ws = null;
104
107
  this.listeners = new Map();
105
108
  this.desired = { channels: new Set(), filters: {} };
109
+ /** Named subscriptions (Phase 2), in creation order; the default one is `desired`. */
110
+ this.named = new Map();
111
+ /** sub_ids of the subscribes sent on this connection whose `subscribed` ack is still due (acks arrive in order). */
112
+ this.ackExpect = [];
113
+ this.namedUnsupportedWarned = false;
114
+ this.listWaiters = [];
106
115
  this.closedByUser = false;
107
116
  this.stopped = false;
108
117
  this.attempt = 0;
@@ -218,27 +227,123 @@ export class MadeOnSolStream {
218
227
  }
219
228
  }
220
229
  }
221
- /** Subscribe to one or more channels (connects on first call). Optional server-side filters. */
222
- subscribe(channels, filters) {
223
- for (const c of channels)
224
- this.desired.channels.add(c);
225
- if (filters)
226
- this.desired.filters = { ...this.desired.filters, ...filters };
230
+ subscribe(arg, filters) {
231
+ if (Array.isArray(arg)) {
232
+ for (const c of arg)
233
+ this.desired.channels.add(c);
234
+ if (filters)
235
+ this.desired.filters = { ...this.desired.filters, ...filters };
236
+ if (this.ws && this.ws.readyState === OPEN)
237
+ this.sendSubscribe({ only: [DEFAULT_SUB_ID] });
238
+ else
239
+ void this.connect();
240
+ return this;
241
+ }
242
+ const subId = arg.subId;
243
+ if (typeof subId !== "string" || !SUB_ID_RE.test(subId))
244
+ throw new Error("subId must be 1-64 characters of A-Z a-z 0-9 _ . -");
245
+ if (subId === DEFAULT_SUB_ID)
246
+ return this.subscribe(arg.channels, arg.filters);
247
+ const entry = this.named.get(subId) ?? { channels: new Set(), filters: {} };
248
+ for (const c of arg.channels)
249
+ entry.channels.add(c);
250
+ // A named subscription's filters are REPLACED when given (the server does the same).
251
+ if (arg.filters)
252
+ entry.filters = { ...arg.filters };
253
+ this.named.set(subId, entry);
227
254
  if (this.ws && this.ws.readyState === OPEN)
228
- this.sendSubscribe();
255
+ this.sendSubscribe({ only: [subId] });
229
256
  else
230
257
  void this.connect();
231
258
  return this;
232
259
  }
233
- /** Stop receiving the given channels. */
234
- unsubscribe(channels) {
235
- for (const c of channels)
260
+ /**
261
+ * Replace the filters of a subscription (`"default"` for the plain one).
262
+ * The server acks with an `updated` frame; a refused update (for example a
263
+ * `token:prices` subscription without valid `mints`) arrives as a `warning`
264
+ * with code `invalid_filters` and the previous filters stay.
265
+ */
266
+ updateSubscription(subId, filters) {
267
+ if (subId === DEFAULT_SUB_ID)
268
+ this.desired.filters = { ...filters };
269
+ else {
270
+ const entry = this.named.get(subId);
271
+ if (!entry)
272
+ throw new Error(`unknown subscription ${subId}`);
273
+ entry.filters = { ...filters };
274
+ }
275
+ if (this.ws && this.ws.readyState === OPEN) {
276
+ this.ws.send(JSON.stringify({ type: "update", ...(subId === DEFAULT_SUB_ID ? {} : { sub_id: subId }), filters }));
277
+ }
278
+ return this;
279
+ }
280
+ unsubscribe(arg) {
281
+ if (typeof arg === "string") {
282
+ if (arg === DEFAULT_SUB_ID)
283
+ return this.unsubscribe(Array.from(this.desired.channels));
284
+ this.named.delete(arg);
285
+ this.forgetPending(arg);
286
+ if (this.ws && this.ws.readyState === OPEN)
287
+ this.ws.send(JSON.stringify({ type: "unsubscribe", sub_id: arg }));
288
+ return this;
289
+ }
290
+ for (const c of arg)
236
291
  this.desired.channels.delete(c);
237
292
  if (this.ws && this.ws.readyState === OPEN) {
238
- this.ws.send(JSON.stringify({ type: "unsubscribe", channels }));
293
+ this.ws.send(JSON.stringify({ type: "unsubscribe", channels: arg }));
239
294
  }
240
295
  return this;
241
296
  }
297
+ /** Every subscription this client asks for (local view, no round trip). */
298
+ getSubscriptions() {
299
+ const out = [];
300
+ if (this.desired.channels.size > 0)
301
+ out.push({ subId: DEFAULT_SUB_ID, channels: Array.from(this.desired.channels), filters: { ...this.desired.filters } });
302
+ for (const [subId, e] of this.named)
303
+ out.push({ subId, channels: Array.from(e.channels), filters: { ...e.filters } });
304
+ return out;
305
+ }
306
+ /**
307
+ * Ask the server what this connection holds (`list` → `subscriptions`).
308
+ * Resolves with the local view when not connected or when the server does
309
+ * not answer within `timeoutMs`.
310
+ */
311
+ listSubscriptions(timeoutMs = 5000) {
312
+ if (!this.ws || this.ws.readyState !== OPEN)
313
+ return Promise.resolve(this.getSubscriptions());
314
+ return new Promise((resolve) => {
315
+ const w = { resolve, timer: setTimeout(() => { this.listWaiters = this.listWaiters.filter((x) => x !== w); resolve(this.getSubscriptions()); }, timeoutMs) };
316
+ this.listWaiters.push(w);
317
+ try {
318
+ this.ws.send(JSON.stringify({ type: "list" }));
319
+ }
320
+ catch { /* closing: the timer answers */ }
321
+ });
322
+ }
323
+ /**
324
+ * A pre-Phase-2 server (ignores sub_id) answers every resume with ONE
325
+ * replay for the whole connection, reported without sub_id: only "default"
326
+ * can still be awaited. Finishes the recovery at once when that one has
327
+ * already ended.
328
+ */
329
+ collapsePending(r) {
330
+ if (r.pending.size === 1 && r.pending.has(DEFAULT_SUB_ID))
331
+ return;
332
+ r.pending.clear();
333
+ if (!r.ends.has(DEFAULT_SUB_ID))
334
+ r.pending.add(DEFAULT_SUB_ID);
335
+ if (r.pending.size === 0 && r.protocol !== "detect")
336
+ this.finishRecovery(r.ends.get(DEFAULT_SUB_ID) ?? null);
337
+ }
338
+ /** A subscription removed while its replay was still awaited: stop waiting for it. */
339
+ forgetPending(subId) {
340
+ const r = this.recovery;
341
+ if (!r || !r.pending.has(subId))
342
+ return;
343
+ r.pending.delete(subId);
344
+ if (r.pending.size === 0 && r.protocol !== "detect")
345
+ this.finishRecovery(r.ends.size ? [...r.ends.values()].pop() : null);
346
+ }
242
347
  /** Open the connection (also called implicitly by subscribe). Restarts a stream that went `"fatal"`. */
243
348
  async connect() {
244
349
  if (this.connecting || (this.ws && this.ws.readyState === OPEN))
@@ -270,7 +375,8 @@ export class MadeOnSolStream {
270
375
  // The backoff attempt is NOT reset here — only a `subscribed` ack proves
271
376
  // the connection is usable (an auth/limit close follows a successful open).
272
377
  this.resetHeartbeat();
273
- if (this.desired.channels.size > 0)
378
+ this.ackExpect = [];
379
+ if (this.desired.channels.size > 0 || this.named.size > 0)
274
380
  this.sendSubscribe();
275
381
  this.emit("open", undefined);
276
382
  };
@@ -388,29 +494,64 @@ export class MadeOnSolStream {
388
494
  }
389
495
  this.emit("fatal", { code, reason });
390
496
  }
391
- sendSubscribe(resumeOverride) {
392
- const channels = Array.from(this.desired.channels);
393
- if (channels.length === 0 || !this.ws)
497
+ /** The subscribe frames for the given subscriptions (default first, then named in creation order). */
498
+ subscribeFrames(only) {
499
+ const out = [];
500
+ const want = (id) => !only || only.includes(id);
501
+ if (want(DEFAULT_SUB_ID) && this.desired.channels.size > 0) {
502
+ const msg = { type: "subscribe", channels: Array.from(this.desired.channels) };
503
+ if (Object.keys(this.desired.filters).length > 0)
504
+ msg.filters = this.desired.filters;
505
+ out.push({ subId: DEFAULT_SUB_ID, msg });
506
+ }
507
+ for (const [subId, e] of this.named) {
508
+ if (!want(subId) || e.channels.size === 0)
509
+ continue;
510
+ out.push({ subId, msg: { type: "subscribe", sub_id: subId, channels: Array.from(e.channels), filters: e.filters } });
511
+ }
512
+ return out;
513
+ }
514
+ /**
515
+ * Send the subscribe(s). On a connection's FIRST subscribe (or an explicit
516
+ * retry after a retryable gap) every subscription is sent with the SAME
517
+ * resume cursor: the server serves one replay per subscription, one after
518
+ * another, and holds live frames until the last replay_end. A later
519
+ * subscribe adds channels live (no resume).
520
+ */
521
+ sendSubscribe({ resumeOverride, only } = {}) {
522
+ if (!this.ws)
523
+ return;
524
+ const frames = this.subscribeFrames(only);
525
+ if (frames.length === 0)
394
526
  return;
395
- const msg = { type: "subscribe", channels };
396
- if (Object.keys(this.desired.filters).length > 0)
397
- msg.filters = this.desired.filters;
398
- // Only the FIRST subscribe of a connection resumes (or an explicit retry
399
- // after a retryable gap); a later subscribe adds channels live, and the
400
- // server replays only the channels named in a subscribe.
401
527
  if ((!this.firstSubscribeSent || resumeOverride) && this.cursor && !this.recovery) {
402
528
  const from = resumeOverride ?? { ...this.cursor };
403
- msg.resume = from;
529
+ const pending = new Set();
530
+ const channels = new Set();
531
+ for (const f of frames) {
532
+ f.msg.resume = from;
533
+ pending.add(f.subId);
534
+ for (const c of f.msg.channels)
535
+ channels.add(c);
536
+ }
404
537
  this.recovery = {
405
- protocol: "detect", from, channels, request: { resume: from }, acked: false, suppressAck: false,
538
+ protocol: "detect", from, channels: Array.from(channels), request: { resume: from }, acked: false, suppressAck: false,
406
539
  instanceChanged: false, start: null, received: 0, delivered: 0, duplicates: 0, held: [], timer: null,
407
- maxSeq: null, maxTs: null,
540
+ maxSeq: null, maxTs: null, pending, starts: new Map(), ends: new Map(),
408
541
  };
409
542
  }
410
543
  this.firstSubscribeSent = true;
411
- this.ws.send(JSON.stringify(msg));
544
+ for (const f of frames) {
545
+ this.ackExpect.push(f.subId);
546
+ this.ws.send(JSON.stringify(f.msg));
547
+ }
412
548
  }
413
- /** The server did not answer `resume` (older deployment): retry with the legacy fields. */
549
+ /**
550
+ * The server did not answer `resume` (older deployment): retry with the
551
+ * legacy fields. Such a server has no named subscriptions either, so the
552
+ * one legacy replay covers the union of channels and resolves every pending
553
+ * subscription at once.
554
+ */
414
555
  fallbackToLegacy() {
415
556
  const r = this.recovery;
416
557
  if (!r || r.protocol !== "detect" || !r.from || !this.ws)
@@ -420,6 +561,7 @@ export class MadeOnSolStream {
420
561
  r.timer = null;
421
562
  }
422
563
  r.protocol = "legacy";
564
+ r.pending = new Set([DEFAULT_SUB_ID]);
423
565
  r.instanceChanged = !this.serverInstance || this.serverInstance !== r.from.instance;
424
566
  // Same process → its ring still indexes our seq. Restarted → seq restarted, use time.
425
567
  const legacy = r.instanceChanged ? { replay_since_ts: r.from.ts } : { replay_since_seq: r.from.seq };
@@ -442,13 +584,22 @@ export class MadeOnSolStream {
442
584
  clearTimeout(this.retryTimer);
443
585
  this.retryTimer = null;
444
586
  }
587
+ // A `list` still awaiting its answer resolves with the local view; the
588
+ // ack order of the dead connection means nothing on the next one.
589
+ this.ackExpect = [];
590
+ const waiters = this.listWaiters;
591
+ this.listWaiters = [];
592
+ for (const w of waiters) {
593
+ clearTimeout(w.timer);
594
+ w.resolve(this.getSubscriptions());
595
+ }
445
596
  }
446
597
  /**
447
598
  * A retryable gap: ask the server again on this connection after its
448
599
  * retry_after_ms (row_cap resumes from resume_ts_hint). Bounded — the next
449
600
  * reconnect resumes anyway.
450
601
  */
451
- scheduleResumeRetry(retryAfterMs, hintTs) {
602
+ scheduleResumeRetry(retryAfterMs, hintTs, only) {
452
603
  if (this.retryTimer || !this.cursor)
453
604
  return;
454
605
  if (this.resumeRetries >= this.opts.maxResumeRetries)
@@ -458,11 +609,90 @@ export class MadeOnSolStream {
458
609
  const from = hintTs !== null && hintTs > this.cursor.ts ? { ...this.cursor, ts: hintTs } : { ...this.cursor };
459
610
  this.retryTimer = setTimeout(() => {
460
611
  this.retryTimer = null;
612
+ // Only the subscriptions whose replay was incomplete are asked again.
461
613
  if (this.ws && this.ws.readyState === OPEN && !this.recovery)
462
- this.sendSubscribe(from);
614
+ this.sendSubscribe({ resumeOverride: from, only });
463
615
  }, delay);
464
616
  }
465
- finishRecovery(end) {
617
+ /**
618
+ * One `replay_end` per subscription → one aggregate the single-replay logic
619
+ * can run on unchanged: complete only when every subscription is; the
620
+ * commit position is the SMALLEST last_seq / last_ts across them (a later
621
+ * subscription's replay covered more, but the earlier one's live frames
622
+ * from that point on are still only in the live flush); channel entries
623
+ * keyed `"<sub_id>/<channel>"` for named subscriptions; `retryable` when
624
+ * any subscription says so.
625
+ */
626
+ aggregateEnds(r, lastEnd) {
627
+ const ends = [...r.ends.entries()];
628
+ if (ends.length === 0)
629
+ return lastEnd;
630
+ if (ends.length === 1 && ends[0][0] === DEFAULT_SUB_ID)
631
+ return ends[0][1];
632
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
633
+ const agg = { ...(lastEnd ?? ends[ends.length - 1][1]) };
634
+ const channels = {};
635
+ let complete = true, retryableKnown = true, retryable = false, truncated = false;
636
+ let lastSeq = null, lastTs = null, liveFrom = null, retryAfter = null, hint = null;
637
+ let count = 0, sent = 0, matched = 0, reason = null, limits = null;
638
+ const min = (a, b) => (a === null ? b : b === null ? a : Math.min(a, b));
639
+ for (const [subId, e] of ends) {
640
+ if (e.complete === false) {
641
+ complete = false;
642
+ if (!reason && typeof e.reason === "string")
643
+ reason = e.reason;
644
+ }
645
+ if (typeof e.retryable !== "boolean")
646
+ retryableKnown = false;
647
+ else if (e.retryable)
648
+ retryable = true;
649
+ if (e.replay_truncated === true)
650
+ truncated = true;
651
+ const chs = e.channels;
652
+ if (chs && typeof chs === "object")
653
+ for (const [ch, raw] of Object.entries(chs))
654
+ channels[subId === DEFAULT_SUB_ID ? ch : `${subId}/${ch}`] = raw;
655
+ lastSeq = min(lastSeq, num(e.last_seq));
656
+ lastTs = min(lastTs, num(e.last_ts));
657
+ liveFrom = min(liveFrom, num(e.live_from_seq));
658
+ const ra = num(e.retry_after_ms);
659
+ if (ra !== null)
660
+ retryAfter = retryAfter === null ? ra : Math.max(retryAfter, ra);
661
+ hint = min(hint, num(e.resume_ts_hint));
662
+ count += num(e.count) ?? 0;
663
+ sent += num(e.sent) ?? 0;
664
+ matched += num(e.matched) ?? 0;
665
+ if (!limits && e.limits && typeof e.limits === "object")
666
+ limits = e.limits;
667
+ }
668
+ agg.complete = complete;
669
+ agg.reason = complete ? null : reason ?? "incomplete";
670
+ agg.channels = channels;
671
+ if (retryableKnown)
672
+ agg.retryable = retryable;
673
+ else
674
+ delete agg.retryable;
675
+ if (truncated)
676
+ agg.replay_truncated = true;
677
+ agg.last_seq = lastSeq;
678
+ agg.last_ts = lastTs;
679
+ agg.live_from_seq = liveFrom;
680
+ if (retryAfter !== null)
681
+ agg.retry_after_ms = retryAfter;
682
+ else
683
+ delete agg.retry_after_ms;
684
+ if (hint !== null)
685
+ agg.resume_ts_hint = hint;
686
+ else
687
+ delete agg.resume_ts_hint;
688
+ agg.count = count;
689
+ agg.sent = sent;
690
+ agg.matched = matched;
691
+ if (limits)
692
+ agg.limits = limits;
693
+ return agg;
694
+ }
695
+ finishRecovery(lastEnd) {
466
696
  const r = this.recovery;
467
697
  if (!r)
468
698
  return;
@@ -471,6 +701,10 @@ export class MadeOnSolStream {
471
701
  r.timer = null;
472
702
  }
473
703
  this.recovery = null;
704
+ const end = this.aggregateEnds(r, lastEnd);
705
+ // Subscriptions whose own replay_end was incomplete and retryable (or, on a
706
+ // server that does not say, incomplete): the automatic retry asks only for them.
707
+ const retrySubs = [...r.ends.entries()].filter(([, e]) => e.complete === false && e.retryable !== false).map(([id]) => id);
474
708
  const reasons = [];
475
709
  /** Reasons of the channels the server reported incomplete, with their retryability. */
476
710
  const channelReasons = [];
@@ -480,7 +714,7 @@ export class MadeOnSolStream {
480
714
  const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
481
715
  // A v1 server answers with complete/sent/matched; an older one with count only.
482
716
  const v1 = !!end && ("complete" in end || "sent" in end || "matched" in end);
483
- if (r.start?.replay_truncated === true || end?.replay_truncated === true)
717
+ if ([...r.starts.values()].some((s) => s.replay_truncated === true) || r.start?.replay_truncated === true || end?.replay_truncated === true)
484
718
  reasons.push("ring_truncated");
485
719
  if (!end)
486
720
  reasons.push("replay_timeout");
@@ -529,6 +763,8 @@ export class MadeOnSolStream {
529
763
  resumeReason: typeof end?.resume_reason === "string" ? end.resume_reason : null,
530
764
  start: r.start,
531
765
  end,
766
+ subscriptions: r.ends.size ? [...r.ends.keys()] : r.pending.size ? [...r.pending] : [DEFAULT_SUB_ID],
767
+ ends: Object.fromEntries(r.ends),
532
768
  };
533
769
  // Final vs retryable. The server says which (`retryable`): true only when an
534
770
  // incomplete channel's reason is transient (backpressure, closed,
@@ -607,7 +843,7 @@ export class MadeOnSolStream {
607
843
  else if (retryable) {
608
844
  this.unsafe = true;
609
845
  if (serverSays)
610
- this.scheduleResumeRetry(num(end?.retry_after_ms), capOnly ? num(end?.resume_ts_hint) : null);
846
+ this.scheduleResumeRetry(num(end?.retry_after_ms), capOnly ? num(end?.resume_ts_hint) : null, retrySubs.length ? retrySubs : undefined);
611
847
  }
612
848
  else {
613
849
  // strict: stop instead of skipping what cannot be recovered.
@@ -637,7 +873,7 @@ export class MadeOnSolStream {
637
873
  if (typeof msg.instance === "string")
638
874
  this.serverInstance = msg.instance;
639
875
  // Nothing to subscribe to → this frame is as far as a healthy connection gets.
640
- if (this.desired.channels.size === 0) {
876
+ if (this.desired.channels.size === 0 && this.named.size === 0) {
641
877
  this.attempt = 0;
642
878
  this.authFailures = 0;
643
879
  }
@@ -652,23 +888,47 @@ export class MadeOnSolStream {
652
888
  r.suppressAck = false;
653
889
  return;
654
890
  } // ack of our own fallback subscribe
655
- this.emit("subscribed", msg.channels);
891
+ // Acks arrive in the order the subscribes were sent: a named subscribe
892
+ // answered WITHOUT sub_id means the server ignores sub_id (older
893
+ // deployment) — every subscription then collapsed into one on the
894
+ // server. Said once, never silently.
895
+ const expected = this.ackExpect.shift() ?? DEFAULT_SUB_ID;
896
+ // The subscription this ack is about: the server's sub_id, else the
897
+ // one we sent in this position (an older server echoes none).
898
+ const ackedId = typeof msg.sub_id === "string" && msg.sub_id ? msg.sub_id : expected;
899
+ if (expected !== DEFAULT_SUB_ID && typeof msg.sub_id !== "string") {
900
+ if (!this.namedUnsupportedWarned) {
901
+ this.namedUnsupportedWarned = true;
902
+ this.emit("warning", { code: "named_subscriptions_unsupported", sub_id: expected, message: "The server ignored sub_id: it predates named subscriptions, so every subscription on this connection shares one channel set and one filter object." });
903
+ }
904
+ // Such a server runs ONE replay for the whole connection and reports
905
+ // it without sub_id ("default"): every named id must leave `pending`
906
+ // or the recovery would never finish and the cursor would freeze.
907
+ if (r)
908
+ this.collapsePending(r);
909
+ }
910
+ this.emit("subscribed", msg.channels, msg);
656
911
  if (r && r.protocol === "detect" && !r.acked) {
657
912
  r.acked = true;
658
- const echo = msg.resume;
659
- if (echo && typeof echo === "object" && echo.accepted === false) {
660
- // Refused (e.g. replay_in_progress): no replay follows, and this is
661
- // a v1 server — no waiting, no legacy fallback. The server's own
662
- // warning frame explains why. Nothing was recovered, so the
663
- // committed cursor must not move until a later recovery completes.
664
- this.dropRecovery();
665
- this.unsafe = true;
666
- }
667
- else if ("resume" in msg)
913
+ if ("resume" in msg)
668
914
  r.protocol = "resume"; // server echoed resume: it understood
669
915
  else
670
916
  r.timer = setTimeout(() => this.fallbackToLegacy(), this.opts.resumeDetectMs);
671
917
  }
918
+ const echo = msg.resume;
919
+ if (r && echo && typeof echo === "object" && echo.accepted === false) {
920
+ // Refused for THIS subscription (replay_in_progress: it already has a
921
+ // replay running or queued): no replay_end will come for it. When
922
+ // nothing at all was accepted, nothing was recovered, so the
923
+ // committed cursor must not move until a later recovery completes.
924
+ r.pending.delete(ackedId);
925
+ if (r.pending.size === 0 && r.ends.size === 0) {
926
+ this.dropRecovery();
927
+ this.unsafe = true;
928
+ }
929
+ else if (r.pending.size === 0 && r.protocol !== "detect")
930
+ this.finishRecovery([...r.ends.values()].pop() ?? null);
931
+ }
672
932
  return;
673
933
  }
674
934
  case "replay_start": {
@@ -678,7 +938,7 @@ export class MadeOnSolStream {
678
938
  r = this.recovery = {
679
939
  protocol: "resume", from: null, channels: [], request: {}, acked: true, suppressAck: false,
680
940
  instanceChanged: false, start: null, received: 0, delivered: 0, duplicates: 0, held: [], timer: null,
681
- maxSeq: null, maxTs: null,
941
+ maxSeq: null, maxTs: null, pending: new Set([subIdOf(msg)]), starts: new Map(), ends: new Map(),
682
942
  };
683
943
  }
684
944
  if (r.protocol === "detect") {
@@ -688,13 +948,48 @@ export class MadeOnSolStream {
688
948
  r.timer = null;
689
949
  }
690
950
  }
691
- r.start = msg;
951
+ r.starts.set(subIdOf(msg), msg);
952
+ if (!r.start)
953
+ r.start = msg;
954
+ return;
955
+ }
956
+ case "replay_end": {
957
+ const r = this.recovery;
958
+ if (!r)
959
+ return;
960
+ const sid = subIdOf(msg);
961
+ r.ends.set(sid, msg);
962
+ r.pending.delete(sid);
963
+ // Every subscription's replay has ended (a legacy server answers once,
964
+ // for the whole connection) → aggregate and commit.
965
+ if (r.pending.size === 0 || r.protocol === "legacy")
966
+ this.finishRecovery(msg);
692
967
  return;
693
968
  }
694
- case "replay_end":
695
- this.finishRecovery(msg);
969
+ case "updated":
970
+ this.emit("updated", msg);
971
+ return;
972
+ case "unsubscribed":
973
+ this.emit("unsubscribed", msg);
974
+ return;
975
+ case "subscriptions": {
976
+ const list = Array.isArray(msg.list)
977
+ ? msg.list.map((s) => ({
978
+ subId: typeof s.sub_id === "string" ? s.sub_id : DEFAULT_SUB_ID,
979
+ channels: (Array.isArray(s.channels) ? s.channels : []),
980
+ filters: (s.filters && typeof s.filters === "object" ? s.filters : {}),
981
+ }))
982
+ : [];
983
+ const waiters = this.listWaiters;
984
+ this.listWaiters = [];
985
+ for (const w of waiters) {
986
+ clearTimeout(w.timer);
987
+ w.resolve(list);
988
+ }
696
989
  return;
697
- case "warning":
990
+ }
991
+ case "warning": {
992
+ const sid = typeof msg.sub_id === "string" ? msg.sub_id : null;
698
993
  if (msg.code === "channels_revoked") {
699
994
  // The server dropped these (e.g. plan downgrade): stop re-subscribing them.
700
995
  const names = new Set();
@@ -710,12 +1005,22 @@ export class MadeOnSolStream {
710
1005
  names.add(x.channel);
711
1006
  }
712
1007
  }
713
- for (const c of names)
714
- this.desired.channels.delete(c);
1008
+ const target = sid && sid !== DEFAULT_SUB_ID ? this.named.get(sid)?.channels : this.desired.channels;
1009
+ if (target)
1010
+ for (const c of names)
1011
+ target.delete(c);
1012
+ if (sid && sid !== DEFAULT_SUB_ID && this.named.get(sid)?.channels.size === 0)
1013
+ this.named.delete(sid);
1014
+ }
1015
+ else if ((msg.code === "too_many_subscriptions" || msg.code === "invalid_sub_id") && sid && sid !== DEFAULT_SUB_ID) {
1016
+ // The server will refuse it on every reconnect too: forget it, and do not wait for its replay.
1017
+ this.named.delete(sid);
1018
+ this.forgetPending(sid);
715
1019
  }
716
1020
  // Never swallow a server warning: a rejected/revoked channel is silent.
717
1021
  this.emit("warning", msg);
718
1022
  return;
1023
+ }
719
1024
  default:
720
1025
  break;
721
1026
  }
@@ -755,7 +1060,9 @@ export class MadeOnSolStream {
755
1060
  }
756
1061
  const id = typeof msg.id === "string" || typeof msg.id === "number" ? String(msg.id) : null;
757
1062
  if (id !== null && this.opts.dedupeSize > 0) {
758
- const key = `${String(msg.channel)}\u0000${id}`;
1063
+ // Dedupe is per (sub_id, channel, id): the same event delivered under two
1064
+ // named subscriptions is two legitimate deliveries.
1065
+ const key = `${subIdOf(msg)}\u0000${String(msg.channel)}\u0000${id}`;
759
1066
  if (this.seen.has(key)) {
760
1067
  this.seen.delete(key);
761
1068
  this.seen.set(key, true);