@opensea/sdk 11.8.0 → 11.9.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.
Files changed (51) hide show
  1. package/README.md +45 -13
  2. package/lib/api/api.d.ts +9 -0
  3. package/lib/api/api.js +15 -2
  4. package/lib/api/api.js.map +1 -1
  5. package/lib/api/collections.d.ts +7 -0
  6. package/lib/api/collections.js +10 -1
  7. package/lib/api/collections.js.map +1 -1
  8. package/lib/api/fetcher.d.ts +5 -2
  9. package/lib/index.d.ts +1 -1
  10. package/lib/orders/privateListings.js +8 -0
  11. package/lib/orders/privateListings.js.map +1 -1
  12. package/lib/stream/client.d.ts +67 -0
  13. package/lib/stream/client.js +174 -0
  14. package/lib/stream/client.js.map +1 -0
  15. package/lib/stream/constants.d.ts +3 -0
  16. package/lib/stream/constants.js +8 -0
  17. package/lib/stream/constants.js.map +1 -0
  18. package/lib/stream/helpers.d.ts +1 -0
  19. package/lib/stream/helpers.js +8 -0
  20. package/lib/stream/helpers.js.map +1 -0
  21. package/lib/stream/index.d.ts +17 -0
  22. package/lib/stream/index.js +34 -0
  23. package/lib/stream/index.js.map +1 -0
  24. package/lib/stream/transport/phoenix.d.ts +121 -0
  25. package/lib/stream/transport/phoenix.js +642 -0
  26. package/lib/stream/transport/phoenix.js.map +1 -0
  27. package/lib/stream/transport/types.d.ts +85 -0
  28. package/lib/stream/transport/types.js +24 -0
  29. package/lib/stream/transport/types.js.map +1 -0
  30. package/lib/stream/types.d.ts +269 -0
  31. package/lib/stream/types.js +29 -0
  32. package/lib/stream/types.js.map +1 -0
  33. package/lib/types.d.ts +14 -0
  34. package/lib/utils/units.d.ts +5 -0
  35. package/lib/utils/units.js +48 -9
  36. package/lib/utils/units.js.map +1 -1
  37. package/package.json +9 -8
  38. package/src/api/api.ts +19 -2
  39. package/src/api/collections.ts +14 -1
  40. package/src/api/fetcher.ts +5 -2
  41. package/src/index.ts +1 -1
  42. package/src/orders/privateListings.ts +15 -0
  43. package/src/stream/client.ts +277 -0
  44. package/src/stream/constants.ts +5 -0
  45. package/src/stream/helpers.ts +3 -0
  46. package/src/stream/index.ts +18 -0
  47. package/src/stream/transport/phoenix.ts +815 -0
  48. package/src/stream/transport/types.ts +91 -0
  49. package/src/stream/types.ts +314 -0
  50. package/src/types.ts +14 -0
  51. package/src/utils/units.ts +54 -9
@@ -0,0 +1,815 @@
1
+ import type {
2
+ StreamMessageHandler,
3
+ StreamSubscription,
4
+ StreamTransport,
5
+ StreamWebSocket,
6
+ StreamWebSocketConstructor,
7
+ SubscribeCallbacks,
8
+ SubscribeOptions,
9
+ } from "./types"
10
+
11
+ /**
12
+ * Phoenix Channels v2 transport.
13
+ *
14
+ * Implements the subset of the protocol that `wss://stream-api.opensea.io/socket`
15
+ * requires. The stream is receive-only: apart from join, leave, and heartbeat
16
+ * control frames, the client never pushes to the server, so none of the
17
+ * general Phoenix client's push, presence, binary serializer, or longpoll
18
+ * machinery is included.
19
+ *
20
+ * Wire format is a JSON array: `[join_ref, ref, topic, event, payload]`.
21
+ * Control events are `phx_join`, `phx_leave`, `phx_reply`, `phx_error`, and
22
+ * `phx_close`. Heartbeats go to the `phoenix` topic and must be answered
23
+ * before the next interval elapses or the connection is considered dead.
24
+ */
25
+
26
+ const VSN = "2.0.0"
27
+ const DEFAULT_TIMEOUT_MS = 10_000
28
+ const DEFAULT_HEARTBEAT_INTERVAL_MS = 30_000
29
+ const WS_CLOSE_NORMAL = 1000
30
+ const WS_OPEN = 1
31
+
32
+ const PHX_JOIN = "phx_join"
33
+ const PHX_LEAVE = "phx_leave"
34
+ const PHX_REPLY = "phx_reply"
35
+ const PHX_ERROR = "phx_error"
36
+ const PHX_CLOSE = "phx_close"
37
+ const HEARTBEAT_TOPIC = "phoenix"
38
+ const HEARTBEAT_EVENT = "heartbeat"
39
+
40
+ /** Backoff schedule in ms, indexed by attempt number. Tail is reused. */
41
+ const DEFAULT_RECONNECT_BACKOFF_MS = [
42
+ 10, 50, 100, 150, 200, 250, 500, 1000, 2000,
43
+ ]
44
+ const MAX_RECONNECT_BACKOFF_MS = 5000
45
+
46
+ const defaultReconnectAfterMs = (tries: number): number =>
47
+ DEFAULT_RECONNECT_BACKOFF_MS[tries - 1] ?? MAX_RECONNECT_BACKOFF_MS
48
+
49
+ /** A decoded Phoenix frame. */
50
+ type Frame = {
51
+ joinRef: string | null
52
+ ref: string | null
53
+ topic: string
54
+ event: string
55
+ payload: unknown
56
+ }
57
+
58
+ export interface PhoenixTransportOptions {
59
+ /** Base socket URL, e.g. `wss://stream-api.opensea.io/socket`. */
60
+ endpoint: string
61
+ /** Query parameters appended to the socket URL, e.g. the API key. */
62
+ params?: Record<string, string>
63
+ /** WebSocket implementation. Defaults to the global `WebSocket`. */
64
+ transport?: StreamWebSocketConstructor
65
+ /** Milliseconds to wait for a subscribe acknowledgement. Default 10000. */
66
+ timeout?: number
67
+ /** Milliseconds between heartbeats. Default 30000. */
68
+ heartbeatIntervalMs?: number
69
+ /** Backoff for reconnect attempt `tries` (1-indexed). */
70
+ reconnectAfterMs?: (tries: number) => number
71
+ /** Optional debug logger. */
72
+ logger?: (message: string) => void
73
+ }
74
+
75
+ type ReplyHandler = (payload: unknown, status: string) => void
76
+
77
+ class PhoenixSubscription implements StreamSubscription {
78
+ public readonly topic: string
79
+ /** Handlers by event name. */
80
+ public readonly handlers = new Map<string, Set<StreamMessageHandler>>()
81
+ /**
82
+ * Server-side event filter sent in the join payload. Widened in place when a
83
+ * later subscriber to the same topic needs events outside the current filter.
84
+ */
85
+ public eventTypes?: string[]
86
+ /** Ref of the in-flight or completed join, used to correlate replies. */
87
+ public joinRef: string | null = null
88
+ public joined = false
89
+ /**
90
+ * Callbacks from every caller that subscribed to this topic. A topic is
91
+ * joined once and shared, so a second subscriber must still be told whether
92
+ * the join succeeded, and every subscriber is notified again after a rejoin.
93
+ */
94
+ public readonly callbackList: SubscribeCallbacks[] = []
95
+ /** Backoff state for rejoining after a server-side channel error. */
96
+ public rejoinTries = 0
97
+ public rejoinTimer: ReturnType<typeof setTimeout> | null = null
98
+
99
+ constructor(
100
+ topic: string,
101
+ eventTypes: string[] | undefined,
102
+ private readonly transport: PhoenixChannelsTransport,
103
+ ) {
104
+ this.topic = topic
105
+ this.eventTypes = eventTypes
106
+ }
107
+
108
+ on(event: string, handler: StreamMessageHandler): () => void {
109
+ let handlers = this.handlers.get(event)
110
+ if (!handlers) {
111
+ handlers = new Set()
112
+ this.handlers.set(event, handlers)
113
+ }
114
+ handlers.add(handler)
115
+ return () => this.transport.removeHandler(this.topic, event, handler)
116
+ }
117
+
118
+ /**
119
+ * Remove one handler, reporting whether the topic has gone quiet. Unlike
120
+ * the original stream-js client, removing a handler does not tear down the
121
+ * whole topic while sibling handlers are still listening; the transport
122
+ * unsubscribes only once the last handler is gone.
123
+ */
124
+ off(event: string, handler: StreamMessageHandler): boolean {
125
+ const handlers = this.handlers.get(event)
126
+ if (!handlers) {
127
+ return this.handlers.size === 0
128
+ }
129
+ handlers.delete(handler)
130
+ if (handlers.size === 0) {
131
+ this.handlers.delete(event)
132
+ }
133
+ return this.handlers.size === 0
134
+ }
135
+
136
+ unsubscribe(onUnsubscribed?: () => void): void {
137
+ this.transport.unsubscribeTopic(this.topic, onUnsubscribed)
138
+ }
139
+
140
+ dispatch(event: string, message: unknown): void {
141
+ const handlers = this.handlers.get(event)
142
+ if (!handlers) {
143
+ return
144
+ }
145
+ for (const handler of handlers) {
146
+ try {
147
+ handler(message)
148
+ } catch (error) {
149
+ // A consumer callback that throws must not take down the socket. This
150
+ // runs inside `WebSocket.onmessage`, so an escaping error becomes an
151
+ // unhandled exception and skips every sibling handler for this event.
152
+ this.transport.reportError(error)
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ export class PhoenixChannelsTransport implements StreamTransport {
159
+ private readonly endpoint: string
160
+ private readonly params: Record<string, string>
161
+ private readonly webSocketCtor: StreamWebSocketConstructor
162
+ private readonly timeout: number
163
+ private readonly heartbeatIntervalMs: number
164
+ private readonly reconnectAfterMs: (tries: number) => number
165
+ private readonly logger?: (message: string) => void
166
+
167
+ private socket: StreamWebSocket | null = null
168
+ private readonly subscriptions = new Map<string, PhoenixSubscription>()
169
+ private readonly pendingReplies = new Map<
170
+ string,
171
+ { handler: ReplyHandler; timer: ReturnType<typeof setTimeout> }
172
+ >()
173
+ private errorHandlers: ((error: unknown) => void)[] = []
174
+ /**
175
+ * Unsubscribe callbacks still waiting for a `phx_leave` reply. `disconnect()`
176
+ * closes the socket without a round trip, so these are drained there instead;
177
+ * otherwise a caller awaiting unsubscribe confirmation waits forever.
178
+ */
179
+ private readonly pendingUnsubscribes = new Set<() => void>()
180
+
181
+ private refCounter = 0
182
+ private reconnectTries = 0
183
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null
184
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null
185
+ private pendingHeartbeatRef: string | null = null
186
+ private disconnectedIntentionally = false
187
+ /**
188
+ * Whether the current socket has ever answered us. An open socket is not
189
+ * proof of a working connection: a server that accepts the TCP/WS handshake
190
+ * but never replies would otherwise reset the backoff on every attempt and
191
+ * be hammered at the shortest delay forever.
192
+ */
193
+ private connectionProven = false
194
+
195
+ constructor(options: PhoenixTransportOptions) {
196
+ this.endpoint = options.endpoint.replace(/\/+$/, "")
197
+ this.params = options.params ?? {}
198
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS
199
+ this.heartbeatIntervalMs =
200
+ options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS
201
+ this.reconnectAfterMs = options.reconnectAfterMs ?? defaultReconnectAfterMs
202
+ this.logger = options.logger
203
+
204
+ // The global `WebSocket` is structurally compatible but its DOM handler
205
+ // signatures do not assign cleanly to our narrower shape, so resolve it
206
+ // through a single explicit cast rather than widening the interface.
207
+ const resolved =
208
+ options.transport ??
209
+ (globalThis as { WebSocket?: unknown }).WebSocket ??
210
+ undefined
211
+ if (!resolved) {
212
+ throw new Error(
213
+ "No WebSocket implementation found. Node 22+ and all browsers provide one globally; " +
214
+ "on older runtimes pass `connectOptions.transport` (for example the `ws` package).",
215
+ )
216
+ }
217
+ this.webSocketCtor = resolved as StreamWebSocketConstructor
218
+ }
219
+
220
+ // ── URL ────────────────────────────────────────────────────────────
221
+
222
+ endpointUrl(): string {
223
+ const query = new URLSearchParams({ ...this.params, vsn: VSN })
224
+ return `${this.endpoint}/websocket?${query.toString()}`
225
+ }
226
+
227
+ protocol(): string {
228
+ return this.endpoint.startsWith("wss:") ||
229
+ this.endpoint.startsWith("https:")
230
+ ? "wss"
231
+ : "ws"
232
+ }
233
+
234
+ // ── Connection lifecycle ───────────────────────────────────────────
235
+
236
+ connect(): void {
237
+ if (this.socket) {
238
+ return
239
+ }
240
+ this.disconnectedIntentionally = false
241
+ this.connectionProven = false
242
+ this.log(`connecting to ${this.endpoint}`)
243
+
244
+ const socket = new this.webSocketCtor(this.endpointUrl())
245
+ this.socket = socket
246
+
247
+ socket.onopen = () => this.handleOpen()
248
+ socket.onmessage = event => this.handleMessage(event.data)
249
+ socket.onerror = error => this.emitError(error)
250
+ socket.onclose = event => this.handleClose(event)
251
+ }
252
+
253
+ isConnected(): boolean {
254
+ return this.socket?.readyState === WS_OPEN
255
+ }
256
+
257
+ disconnect(onDisconnect?: () => void): void {
258
+ this.disconnectedIntentionally = true
259
+ this.clearReconnectTimer()
260
+ this.stopHeartbeat()
261
+ // clearPendingReplies also settles pending unsubscribe acknowledgements.
262
+ this.clearPendingReplies()
263
+ for (const subscription of this.subscriptions.values()) {
264
+ this.clearRejoinTimer(subscription)
265
+ }
266
+ this.subscriptions.clear()
267
+
268
+ const socket = this.socket
269
+ this.socket = null
270
+ if (socket) {
271
+ socket.onclose = null
272
+ socket.onerror = null
273
+ socket.onmessage = null
274
+ socket.onopen = null
275
+ socket.close(WS_CLOSE_NORMAL, "client disconnect")
276
+ }
277
+ onDisconnect?.()
278
+ }
279
+
280
+ onError(handler: (error: unknown) => void): void {
281
+ this.errorHandlers.push(handler)
282
+ }
283
+
284
+ /** Surface an error raised by consumer code, used by subscriptions. */
285
+ reportError(error: unknown): void {
286
+ this.emitError(error)
287
+ }
288
+
289
+ /**
290
+ * Run a consumer callback without letting it escape into our state machine.
291
+ *
292
+ * These fire from inside teardown and reply handling, where an escaping
293
+ * exception would skip the work that follows: a throwing unsubscribe
294
+ * callback would abort `handleClose` before `scheduleReconnect`, leaving the
295
+ * client permanently disconnected, and a throwing subscribe callback would
296
+ * starve every later subscriber to the same topic.
297
+ */
298
+ private safeInvoke(callback: () => void): void {
299
+ try {
300
+ callback()
301
+ } catch (error) {
302
+ this.reportError(error)
303
+ }
304
+ }
305
+
306
+ private handleOpen(): void {
307
+ this.log("socket open")
308
+ // Deliberately not resetting `reconnectTries` here. The backoff resets in
309
+ // `handleReply`, once the server has actually answered something.
310
+ this.startHeartbeat()
311
+ // A fresh socket re-joins everything below, so any per-channel rejoin
312
+ // timer left over from the previous connection is redundant.
313
+ for (const subscription of this.subscriptions.values()) {
314
+ this.clearRejoinTimer(subscription)
315
+ }
316
+ // Establish every topic: the ones subscribed to before the socket opened,
317
+ // and the ones that were live before a drop. Joins are never sent while
318
+ // disconnected, so this is the single place they get written.
319
+ for (const subscription of this.subscriptions.values()) {
320
+ subscription.joined = false
321
+ this.sendJoin(subscription)
322
+ }
323
+ }
324
+
325
+ private handleClose(event: { code?: number; reason?: string }): void {
326
+ this.log(`socket closed (code ${event?.code ?? "unknown"})`)
327
+ this.connectionProven = false
328
+ this.stopHeartbeat()
329
+ this.clearPendingReplies()
330
+ this.socket = null
331
+ if (!this.disconnectedIntentionally) {
332
+ this.scheduleReconnect()
333
+ }
334
+ }
335
+
336
+ private scheduleReconnect(): void {
337
+ this.clearReconnectTimer()
338
+ this.reconnectTries += 1
339
+ const delay = this.reconnectAfterMs(this.reconnectTries)
340
+ this.log(`reconnecting in ${delay}ms (attempt ${this.reconnectTries})`)
341
+ this.reconnectTimer = setTimeout(() => {
342
+ this.reconnectTimer = null
343
+ this.connect()
344
+ }, delay)
345
+ }
346
+
347
+ private clearReconnectTimer(): void {
348
+ if (this.reconnectTimer) {
349
+ clearTimeout(this.reconnectTimer)
350
+ this.reconnectTimer = null
351
+ }
352
+ }
353
+
354
+ // ── Heartbeat ──────────────────────────────────────────────────────
355
+
356
+ private startHeartbeat(): void {
357
+ this.stopHeartbeat()
358
+ this.pendingHeartbeatRef = null
359
+ this.heartbeatTimer = setInterval(
360
+ () => this.sendHeartbeat(),
361
+ this.heartbeatIntervalMs,
362
+ )
363
+ }
364
+
365
+ private stopHeartbeat(): void {
366
+ if (this.heartbeatTimer) {
367
+ clearInterval(this.heartbeatTimer)
368
+ this.heartbeatTimer = null
369
+ }
370
+ this.pendingHeartbeatRef = null
371
+ }
372
+
373
+ private sendHeartbeat(): void {
374
+ if (!this.isConnected()) {
375
+ return
376
+ }
377
+ // The previous heartbeat was never answered, so the connection is dead
378
+ // even though the socket still looks open. Tear it down and reconnect.
379
+ if (this.pendingHeartbeatRef !== null) {
380
+ this.log("heartbeat timeout, tearing down connection")
381
+ this.pendingHeartbeatRef = null
382
+ this.emitError(new Error("Heartbeat timeout"))
383
+ this.teardownForReconnect()
384
+ return
385
+ }
386
+ const ref = this.nextRef()
387
+ this.pendingHeartbeatRef = ref
388
+ this.push(null, ref, HEARTBEAT_TOPIC, HEARTBEAT_EVENT, {})
389
+ }
390
+
391
+ /** Close the socket without marking the disconnect intentional. */
392
+ private teardownForReconnect(): void {
393
+ const socket = this.socket
394
+ this.stopHeartbeat()
395
+ this.socket = null
396
+ if (socket) {
397
+ socket.onclose = null
398
+ socket.onerror = null
399
+ socket.onmessage = null
400
+ socket.onopen = null
401
+ socket.close(WS_CLOSE_NORMAL, "heartbeat timeout")
402
+ }
403
+ this.clearPendingReplies()
404
+ this.scheduleReconnect()
405
+ }
406
+
407
+ // ── Subscriptions ──────────────────────────────────────────────────
408
+
409
+ subscribe(
410
+ topic: string,
411
+ options?: SubscribeOptions,
412
+ callbacks?: SubscribeCallbacks,
413
+ ): StreamSubscription {
414
+ this.connect()
415
+
416
+ const existing = this.subscriptions.get(topic)
417
+ if (existing) {
418
+ // The topic is already joined or joining. Register this caller's
419
+ // callbacks too, otherwise a second subscriber never learns the outcome.
420
+ if (callbacks) {
421
+ existing.callbackList.push(callbacks)
422
+ // A settled subscription has no reply left to fire, so report now.
423
+ if (existing.joined) {
424
+ callbacks.onSubscribed?.()
425
+ }
426
+ }
427
+ this.widenFilterIfNeeded(existing, options?.eventTypes)
428
+ return existing
429
+ }
430
+
431
+ const subscription = new PhoenixSubscription(
432
+ topic,
433
+ options?.eventTypes,
434
+ this,
435
+ )
436
+ if (callbacks) {
437
+ subscription.callbackList.push(callbacks)
438
+ }
439
+ this.subscriptions.set(topic, subscription)
440
+ // If the socket is not open yet, `handleOpen` sends the join. Writing it
441
+ // here as well would join the topic twice.
442
+ if (this.isConnected()) {
443
+ this.sendJoin(subscription)
444
+ }
445
+ return subscription
446
+ }
447
+
448
+ private sendJoin(subscription: PhoenixSubscription): void {
449
+ const ref = this.nextRef()
450
+ subscription.joinRef = ref
451
+ const payload = subscription.eventTypes
452
+ ? { event_types: subscription.eventTypes }
453
+ : {}
454
+
455
+ this.awaitReply(
456
+ ref,
457
+ (_response, status) => {
458
+ if (status === "ok") {
459
+ subscription.joined = true
460
+ subscription.rejoinTries = 0
461
+ this.log(`subscribed to "${subscription.topic}"`)
462
+ for (const callbacks of subscription.callbackList) {
463
+ this.safeInvoke(() => callbacks.onSubscribed?.())
464
+ }
465
+ } else {
466
+ this.log(`failed to subscribe to "${subscription.topic}"`)
467
+ const error = new Error(
468
+ `Subscribe to "${subscription.topic}" failed: ${status}`,
469
+ )
470
+ for (const callbacks of subscription.callbackList) {
471
+ this.safeInvoke(() => callbacks.onSubscribeError?.(error))
472
+ }
473
+ }
474
+ },
475
+ reason => {
476
+ for (const callbacks of subscription.callbackList) {
477
+ this.safeInvoke(() => callbacks.onSubscribeError?.(reason))
478
+ }
479
+ },
480
+ )
481
+
482
+ this.push(ref, ref, subscription.topic, PHX_JOIN, payload)
483
+ }
484
+
485
+ /**
486
+ * Rejoin a topic whose channel died while the socket stayed open. Uses the
487
+ * same backoff schedule as reconnects, so a channel that keeps crashing does
488
+ * not turn into a join loop.
489
+ */
490
+ private scheduleRejoin(subscription: PhoenixSubscription): void {
491
+ this.clearRejoinTimer(subscription)
492
+ subscription.rejoinTries += 1
493
+ const delay = this.reconnectAfterMs(subscription.rejoinTries)
494
+ this.log(
495
+ `rejoining "${subscription.topic}" in ${delay}ms (attempt ${subscription.rejoinTries})`,
496
+ )
497
+ subscription.rejoinTimer = setTimeout(() => {
498
+ subscription.rejoinTimer = null
499
+ // The caller may have unsubscribed, or the socket may have dropped, in
500
+ // which case `handleOpen` owns the rejoin instead.
501
+ if (!this.subscriptions.has(subscription.topic) || !this.isConnected()) {
502
+ return
503
+ }
504
+ this.sendJoin(subscription)
505
+ }, delay)
506
+ }
507
+
508
+ private clearRejoinTimer(subscription: PhoenixSubscription): void {
509
+ if (subscription.rejoinTimer) {
510
+ clearTimeout(subscription.rejoinTimer)
511
+ subscription.rejoinTimer = null
512
+ }
513
+ }
514
+
515
+ /**
516
+ * A topic is joined once and shared, and the join payload carries the
517
+ * server-side `event_types` filter. A later subscriber asking for an event
518
+ * outside that filter would otherwise register a handler the server never
519
+ * feeds, which fails silently. Widen the filter and re-join instead.
520
+ *
521
+ * `undefined` means no filter, so it is the widest value rather than the
522
+ * narrowest: an individual `on*` call subscribes to everything.
523
+ */
524
+ private widenFilterIfNeeded(
525
+ subscription: PhoenixSubscription,
526
+ requested: string[] | undefined,
527
+ ): void {
528
+ const current = subscription.eventTypes
529
+ // Already unfiltered, so every event already arrives.
530
+ if (current === undefined) {
531
+ return
532
+ }
533
+
534
+ let widened: string[] | undefined
535
+ if (requested === undefined) {
536
+ // The new subscriber wants everything, so drop the filter entirely.
537
+ widened = undefined
538
+ } else {
539
+ const missing = requested.filter(type => !current.includes(type))
540
+ if (missing.length === 0) {
541
+ return
542
+ }
543
+ widened = [...current, ...missing]
544
+ }
545
+
546
+ subscription.eventTypes = widened
547
+ this.log(
548
+ `widening the filter on "${subscription.topic}" to ${widened ? widened.join(", ") : "all events"}`,
549
+ )
550
+
551
+ // While disconnected there is nothing to re-issue: `handleOpen` sends the
552
+ // join, and it will use the widened filter.
553
+ if (!this.isConnected()) {
554
+ return
555
+ }
556
+
557
+ // Re-establish the channel so the server applies the new filter. Frames
558
+ // still in flight for the old join ref are dropped by the guard in
559
+ // `handleMessage`, so no stale events reach the widened subscription.
560
+ if (subscription.joinRef !== null) {
561
+ this.push(
562
+ subscription.joinRef,
563
+ this.nextRef(),
564
+ subscription.topic,
565
+ PHX_LEAVE,
566
+ {},
567
+ )
568
+ }
569
+ subscription.joined = false
570
+ this.sendJoin(subscription)
571
+ }
572
+
573
+ private drainPendingUnsubscribes(): void {
574
+ const pending = Array.from(this.pendingUnsubscribes)
575
+ this.pendingUnsubscribes.clear()
576
+ for (const callback of pending) {
577
+ this.safeInvoke(callback)
578
+ }
579
+ }
580
+
581
+ /** Called by a subscription, and directly by the client. */
582
+ unsubscribeTopic(topic: string, onUnsubscribed?: () => void): void {
583
+ const subscription = this.subscriptions.get(topic)
584
+ if (!subscription) {
585
+ onUnsubscribed?.()
586
+ return
587
+ }
588
+ this.clearRejoinTimer(subscription)
589
+ this.subscriptions.delete(topic)
590
+
591
+ if (!this.isConnected()) {
592
+ onUnsubscribed?.()
593
+ return
594
+ }
595
+
596
+ // `joinRef` is assigned synchronously by `sendJoin`, and `sendJoin` runs
597
+ // for every subscription either at subscribe time (when connected) or in
598
+ // `handleOpen`. Reaching here with a null ref would mean that invariant
599
+ // broke, and a leave frame with a null join_ref cannot be correlated by
600
+ // the server, so drop it rather than send a malformed frame.
601
+ if (subscription.joinRef === null) {
602
+ onUnsubscribed?.()
603
+ return
604
+ }
605
+
606
+ // Fire at most once, whichever of reply, timeout, or disconnect wins.
607
+ let settled = false
608
+ const settle = () => {
609
+ if (settled) {
610
+ return
611
+ }
612
+ settled = true
613
+ this.pendingUnsubscribes.delete(settle)
614
+ onUnsubscribed?.()
615
+ }
616
+ this.pendingUnsubscribes.add(settle)
617
+
618
+ const ref = this.nextRef()
619
+ this.awaitReply(
620
+ ref,
621
+ () => {
622
+ this.log(`unsubscribed from "${topic}"`)
623
+ settle()
624
+ },
625
+ // A leave that is never acknowledged still means we have stopped
626
+ // dispatching locally, so treat a timeout as done rather than an error.
627
+ settle,
628
+ )
629
+ this.push(subscription.joinRef, ref, topic, PHX_LEAVE, {})
630
+ }
631
+
632
+ /** Remove a single handler, unsubscribing only when the topic goes quiet. */
633
+ removeHandler(
634
+ topic: string,
635
+ event: string,
636
+ handler: StreamMessageHandler,
637
+ onUnsubscribed?: () => void,
638
+ ): void {
639
+ const subscription = this.subscriptions.get(topic)
640
+ if (!subscription) {
641
+ return
642
+ }
643
+ const isEmpty = subscription.off(event, handler)
644
+ if (isEmpty) {
645
+ this.unsubscribeTopic(topic, onUnsubscribed)
646
+ }
647
+ }
648
+
649
+ // ── Messaging ──────────────────────────────────────────────────────
650
+
651
+ private handleMessage(data: unknown): void {
652
+ const frame = this.decode(data)
653
+ if (!frame) {
654
+ return
655
+ }
656
+
657
+ if (frame.event === PHX_REPLY) {
658
+ this.handleReply(frame)
659
+ return
660
+ }
661
+
662
+ const subscription = this.subscriptions.get(frame.topic)
663
+
664
+ // Drop frames from a previous instance of this channel. Leaving a topic
665
+ // and re-subscribing to it produces a new join ref, and the server's
666
+ // in-flight frames for the old one are still arriving. Without this, a
667
+ // late `phx_close` for the channel we already left tears down the new
668
+ // subscription, and stale events leak to the new handlers.
669
+ if (
670
+ subscription &&
671
+ frame.joinRef !== null &&
672
+ subscription.joinRef !== null &&
673
+ frame.joinRef !== subscription.joinRef
674
+ ) {
675
+ this.log(`dropping stale frame for "${frame.topic}"`)
676
+ return
677
+ }
678
+
679
+ if (frame.event === PHX_ERROR || frame.event === PHX_CLOSE) {
680
+ // No subscription means we already left this topic, and the server is
681
+ // acknowledging that. Not an error worth reporting.
682
+ if (!subscription) {
683
+ return
684
+ }
685
+ // The channel died server-side while the socket stayed up, so a
686
+ // reconnect will never fire. Without an explicit rejoin the topic is
687
+ // silently dead for the rest of the process's life.
688
+ subscription.joined = false
689
+ this.emitError(
690
+ new Error(`Channel "${frame.topic}" received ${frame.event}`),
691
+ )
692
+ this.scheduleRejoin(subscription)
693
+ return
694
+ }
695
+
696
+ subscription?.dispatch(frame.event, frame.payload)
697
+ }
698
+
699
+ private handleReply(frame: Frame): void {
700
+ if (frame.ref === null) {
701
+ return
702
+ }
703
+ // The server answered, so this connection works. Anything before this is
704
+ // an unproven connection and must not clear the reconnect backoff.
705
+ if (!this.connectionProven) {
706
+ this.connectionProven = true
707
+ this.reconnectTries = 0
708
+ }
709
+ if (frame.ref === this.pendingHeartbeatRef) {
710
+ this.pendingHeartbeatRef = null
711
+ return
712
+ }
713
+ const pending = this.pendingReplies.get(frame.ref)
714
+ if (!pending) {
715
+ return
716
+ }
717
+ this.pendingReplies.delete(frame.ref)
718
+ clearTimeout(pending.timer)
719
+
720
+ const payload = frame.payload as
721
+ | { status?: string; response?: unknown }
722
+ | undefined
723
+ pending.handler(payload?.response, payload?.status ?? "error")
724
+ }
725
+
726
+ private awaitReply(
727
+ ref: string,
728
+ handler: ReplyHandler,
729
+ onTimeout: (reason: unknown) => void,
730
+ ): void {
731
+ const timer = setTimeout(() => {
732
+ this.pendingReplies.delete(ref)
733
+ onTimeout(
734
+ new Error(`Timed out after ${this.timeout}ms waiting for reply`),
735
+ )
736
+ }, this.timeout)
737
+ this.pendingReplies.set(ref, { handler, timer })
738
+ }
739
+
740
+ /**
741
+ * Drop every in-flight reply without invoking its handler. The socket going
742
+ * away is not a rejection: a join whose ack never arrives is re-sent by
743
+ * `handleOpen` after the reconnect, so reporting it as a subscribe failure
744
+ * here would be both wrong and noisy.
745
+ *
746
+ * Unsubscribes are the exception and are settled rather than dropped. A left
747
+ * topic stays left across a reconnect, so its acknowledgement is never coming
748
+ * and a caller waiting on one would hang. Draining here covers every teardown
749
+ * path: `disconnect`, `handleClose`, and `teardownForReconnect`.
750
+ */
751
+ private clearPendingReplies(): void {
752
+ for (const [, pending] of this.pendingReplies) {
753
+ clearTimeout(pending.timer)
754
+ }
755
+ this.pendingReplies.clear()
756
+ this.drainPendingUnsubscribes()
757
+ }
758
+
759
+ private push(
760
+ joinRef: string | null,
761
+ ref: string | null,
762
+ topic: string,
763
+ event: string,
764
+ payload: unknown,
765
+ ): void {
766
+ // Every caller either checks `isConnected()` first or runs from
767
+ // `handleOpen`, so there is nothing to buffer: a frame written while the
768
+ // socket is down would be a bug, not a queued write.
769
+ if (!this.isConnected()) {
770
+ return
771
+ }
772
+ this.socket?.send(JSON.stringify([joinRef, ref, topic, event, payload]))
773
+ }
774
+
775
+ private decode(data: unknown): Frame | null {
776
+ if (typeof data !== "string") {
777
+ this.emitError(new Error("Received non-text frame from stream"))
778
+ return null
779
+ }
780
+ let parsed: unknown
781
+ try {
782
+ parsed = JSON.parse(data)
783
+ } catch {
784
+ this.emitError(new Error("Received malformed JSON frame from stream"))
785
+ return null
786
+ }
787
+ if (!Array.isArray(parsed) || parsed.length < 5) {
788
+ this.emitError(new Error("Received unexpected frame shape from stream"))
789
+ return null
790
+ }
791
+ const [joinRef, ref, topic, event, payload] = parsed as [
792
+ string | null,
793
+ string | null,
794
+ string,
795
+ string,
796
+ unknown,
797
+ ]
798
+ return { joinRef, ref, topic, event, payload }
799
+ }
800
+
801
+ private nextRef(): string {
802
+ this.refCounter += 1
803
+ return String(this.refCounter)
804
+ }
805
+
806
+ private emitError(error: unknown): void {
807
+ for (const handler of this.errorHandlers) {
808
+ handler(error)
809
+ }
810
+ }
811
+
812
+ private log(message: string): void {
813
+ this.logger?.(message)
814
+ }
815
+ }