@metamask-previews/perps-controller 25.0.0-preview-c785ff081 → 26.0.0-preview-203750488

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 (144) hide show
  1. package/CHANGELOG.md +95 -4
  2. package/dist/PerpsController-method-action-types.d.ts +149 -3
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +125 -3
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +746 -28
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +63 -0
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +73 -0
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +15 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +14 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/perpsConfig.d.ts +10 -1
  18. package/dist/constants/perpsConfig.d.ts.map +1 -1
  19. package/dist/constants/perpsConfig.js +11 -1
  20. package/dist/constants/perpsConfig.js.map +1 -1
  21. package/dist/index.d.ts +10 -8
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/internal/accountReturnOnEquity.d.ts +12 -0
  26. package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
  27. package/dist/internal/accountReturnOnEquity.js +18 -0
  28. package/dist/internal/accountReturnOnEquity.js.map +1 -0
  29. package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
  30. package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
  31. package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
  32. package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
  33. package/dist/internal/marketNumericValues.d.ts +10 -0
  34. package/dist/internal/marketNumericValues.d.ts.map +1 -0
  35. package/dist/internal/marketNumericValues.js +9 -0
  36. package/dist/internal/marketNumericValues.js.map +1 -0
  37. package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
  38. package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
  39. package/dist/internal/perpsDisplaySymbol.js +21 -0
  40. package/dist/internal/perpsDisplaySymbol.js.map +1 -0
  41. package/dist/perpsErrorCodes.d.ts +1 -0
  42. package/dist/perpsErrorCodes.d.ts.map +1 -1
  43. package/dist/perpsErrorCodes.js +1 -0
  44. package/dist/perpsErrorCodes.js.map +1 -1
  45. package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
  46. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  47. package/dist/providers/AggregatedPerpsProvider.js +140 -0
  48. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  49. package/dist/providers/HyperLiquidProvider.d.ts +72 -4
  50. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  51. package/dist/providers/HyperLiquidProvider.js +749 -157
  52. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  53. package/dist/providers/LighterProvider.d.ts +2 -1
  54. package/dist/providers/LighterProvider.d.ts.map +1 -1
  55. package/dist/providers/LighterProvider.js +3 -0
  56. package/dist/providers/LighterProvider.js.map +1 -1
  57. package/dist/services/HyperLiquidClientService.d.ts +8 -0
  58. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  59. package/dist/services/HyperLiquidClientService.js +65 -0
  60. package/dist/services/HyperLiquidClientService.js.map +1 -1
  61. package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
  62. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  63. package/dist/services/HyperLiquidSubscriptionService.js +97 -17
  64. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  65. package/dist/services/MarketDataService.d.ts +15 -1
  66. package/dist/services/MarketDataService.d.ts.map +1 -1
  67. package/dist/services/MarketDataService.js +43 -1
  68. package/dist/services/MarketDataService.js.map +1 -1
  69. package/dist/services/StreamChannelManager.d.ts +139 -0
  70. package/dist/services/StreamChannelManager.d.ts.map +1 -0
  71. package/dist/services/StreamChannelManager.js +475 -0
  72. package/dist/services/StreamChannelManager.js.map +1 -0
  73. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  74. package/dist/services/TerminalMarketService.js +7 -0
  75. package/dist/services/TerminalMarketService.js.map +1 -1
  76. package/dist/services/agentSigner.d.ts +8 -0
  77. package/dist/services/agentSigner.d.ts.map +1 -1
  78. package/dist/services/agentSigner.js +13 -0
  79. package/dist/services/agentSigner.js.map +1 -1
  80. package/dist/types/hyperliquid-types.d.ts +9 -1
  81. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  82. package/dist/types/hyperliquid-types.js +10 -0
  83. package/dist/types/hyperliquid-types.js.map +1 -1
  84. package/dist/types/index.d.ts +430 -14
  85. package/dist/types/index.d.ts.map +1 -1
  86. package/dist/types/index.js.map +1 -1
  87. package/dist/utils/accountAggregation.d.ts +17 -0
  88. package/dist/utils/accountAggregation.d.ts.map +1 -1
  89. package/dist/utils/accountAggregation.js +21 -5
  90. package/dist/utils/accountAggregation.js.map +1 -1
  91. package/dist/utils/accountUtils.d.ts +31 -10
  92. package/dist/utils/accountUtils.d.ts.map +1 -1
  93. package/dist/utils/accountUtils.js +68 -28
  94. package/dist/utils/accountUtils.js.map +1 -1
  95. package/dist/utils/closeCalculations.d.ts +17 -4
  96. package/dist/utils/closeCalculations.d.ts.map +1 -1
  97. package/dist/utils/closeCalculations.js +23 -7
  98. package/dist/utils/closeCalculations.js.map +1 -1
  99. package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
  100. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  101. package/dist/utils/hyperLiquidAdapter.js +17 -1
  102. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  103. package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
  104. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  105. package/dist/utils/hyperLiquidPositionPreview.js +264 -29
  106. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  107. package/dist/utils/index.d.ts +4 -2
  108. package/dist/utils/index.d.ts.map +1 -1
  109. package/dist/utils/index.js +1 -0
  110. package/dist/utils/index.js.map +1 -1
  111. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  112. package/dist/utils/lighterAdapter.js +46 -9
  113. package/dist/utils/lighterAdapter.js.map +1 -1
  114. package/dist/utils/marketDataTransform.d.ts.map +1 -1
  115. package/dist/utils/marketDataTransform.js +8 -0
  116. package/dist/utils/marketDataTransform.js.map +1 -1
  117. package/dist/utils/marketUtils.d.ts +1 -2
  118. package/dist/utils/marketUtils.d.ts.map +1 -1
  119. package/dist/utils/marketUtils.js +7 -17
  120. package/dist/utils/marketUtils.js.map +1 -1
  121. package/dist/utils/orderBookGrouping.d.ts +35 -5
  122. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  123. package/dist/utils/orderBookGrouping.js +62 -6
  124. package/dist/utils/orderBookGrouping.js.map +1 -1
  125. package/dist/utils/perpsClientCopy.d.ts.map +1 -1
  126. package/dist/utils/perpsClientCopy.js +4 -0
  127. package/dist/utils/perpsClientCopy.js.map +1 -1
  128. package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
  129. package/dist/utils/perpsDiskPersistence.js +10 -0
  130. package/dist/utils/perpsDiskPersistence.js.map +1 -1
  131. package/dist/utils/perpsFormatters.d.ts +31 -0
  132. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  133. package/dist/utils/perpsFormatters.js +26 -0
  134. package/dist/utils/perpsFormatters.js.map +1 -1
  135. package/dist/utils/sortMarkets.d.ts +13 -5
  136. package/dist/utils/sortMarkets.d.ts.map +1 -1
  137. package/dist/utils/sortMarkets.js +60 -38
  138. package/dist/utils/sortMarkets.js.map +1 -1
  139. package/docs/architecture.md +37 -7
  140. package/docs/client-contract.md +42 -17
  141. package/docs/contracts/events.md +34 -30
  142. package/docs/formatting.md +2 -0
  143. package/docs/venues/lighter/capabilities.md +18 -15
  144. package/package.json +1 -1
@@ -0,0 +1,139 @@
1
+ import { WebSocketConnectionState } from '../types/index.js';
2
+ /**
3
+ * What one shared stream is: the stream name plus everything its source
4
+ * reads. Two subscriptions with equal keys share one venue subscription.
5
+ */
6
+ export type StreamChannelKey = {
7
+ /** Stream name, such as `prices` or `orderBook`. */
8
+ stream: string;
9
+ /** Provider route, or the default route when omitted. */
10
+ providerId?: string;
11
+ /** Account, or the selected account when omitted. */
12
+ accountId?: string;
13
+ /** Market, for market streams. */
14
+ symbol?: string;
15
+ /** Any other option the source reads. Functions are ignored. */
16
+ options?: Record<string, unknown>;
17
+ };
18
+ /**
19
+ * The venue subscription behind a channel. `open` runs once for the first
20
+ * subscriber and its cleanup once the last one leaves.
21
+ */
22
+ export type StreamChannelSource<Args extends unknown[]> = {
23
+ /**
24
+ * Open the live stream.
25
+ *
26
+ * @param emit - Delivers a value to every subscriber.
27
+ * @param fail - Reports a stream failure, with any detail the source adds
28
+ * (such as the failing venue); the last value stays current.
29
+ * @param key - The key the channel opens under, which changes on `rebind`.
30
+ * @returns Cleanup that stops the stream.
31
+ */
32
+ open(emit: (...args: Args) => void, fail: (error: Error, ...detail: unknown[]) => void, key: StreamChannelKey): () => void;
33
+ /**
34
+ * One REST read for while the stream is down: it seeds a channel that opens
35
+ * while the transport is disconnected, and runs once each time the
36
+ * connection drops. It is never repeated on a timer.
37
+ * Resolving `undefined` delivers nothing.
38
+ *
39
+ * @param key - The channel's current key.
40
+ */
41
+ read?(key: StreamChannelKey): Promise<Args | undefined>;
42
+ /**
43
+ * Deliver the last value to a subscriber that joins an open channel.
44
+ * Defaults to true; turn it off for event streams, such as fills, where a
45
+ * replay would repeat an event.
46
+ */
47
+ replay?: boolean;
48
+ /**
49
+ * Stop and reopen the venue subscription when the connection comes back
50
+ * after a drop, for streams the transport does not restore by itself. The
51
+ * channel stays the one owner of that resubscribe, whatever its reader count.
52
+ */
53
+ reopenOnReconnect?: boolean;
54
+ };
55
+ /** One reader of a channel. */
56
+ export type StreamChannelSubscriber<Args extends unknown[]> = {
57
+ /** Receives each value, at most once per `throttleMs` when set. */
58
+ callback: (...args: Args) => void;
59
+ /** Receives stream and seed-read failures. */
60
+ onError?: (error: Error, ...detail: any[]) => void;
61
+ /** Minimum time between two deliveries to this subscriber. */
62
+ throttleMs?: number;
63
+ /**
64
+ * Called when the channel moves to another context (provider or account)
65
+ * and its last value no longer applies. The next delivery is the new
66
+ * context's data.
67
+ */
68
+ onReset?: () => void;
69
+ };
70
+ /** Watches the transport the channels stream on. */
71
+ export type StreamConnectionWatcher = (listener: (state: WebSocketConnectionState) => void) => () => void;
72
+ export type StreamChannelManagerOptions = {
73
+ /** Connection state source; a drop triggers each channel's `read`. */
74
+ subscribeToConnectionState?: StreamConnectionWatcher;
75
+ /** Receives subscriber callback failures, which never reach the venue. */
76
+ onError?: (error: unknown) => void;
77
+ };
78
+ /**
79
+ * The one stream layer every client shares. Each key gets one ref-counted
80
+ * channel over one venue subscription: it opens with the first subscriber,
81
+ * replays its last value to later ones, throttles each subscriber on its own
82
+ * and stops with the last one. Reconnect and resubscribe stay with the
83
+ * channel's source, so N readers cost one resubscribe. REST is read only
84
+ * while the transport is down: to seed a channel and once per drop.
85
+ */
86
+ export declare class StreamChannelManager {
87
+ #private;
88
+ constructor(options?: StreamChannelManagerOptions);
89
+ /**
90
+ * Open channels, for diagnostics and tests.
91
+ *
92
+ * @returns The number of open channels.
93
+ */
94
+ get size(): number;
95
+ /**
96
+ * Join the channel for `key`, opening it when it is the first subscriber.
97
+ *
98
+ * @param key - What the channel streams.
99
+ * @param source - Venue subscription used when the channel opens.
100
+ * @param subscriber - Callbacks and throttle for this reader.
101
+ * @returns Cleanup that leaves the channel.
102
+ */
103
+ subscribe<Args extends unknown[]>(key: StreamChannelKey, source: StreamChannelSource<Args>, subscriber: StreamChannelSubscriber<Args>): () => void;
104
+ /**
105
+ * Move every open channel whose key is no longer current to its next key,
106
+ * such as after the provider or the selected account changed. The source is
107
+ * stopped, the last value dropped and, when there was one, each reader's
108
+ * `onReset` called; the channel then reopens under the new key, or its
109
+ * readers join the channel already open there. Reader cleanups stay valid.
110
+ *
111
+ * @param isCurrent - Whether a key still matches the context.
112
+ * @param nextKey - The key a stale channel moves to.
113
+ */
114
+ rebind(isCurrent: (key: StreamChannelKey) => boolean, nextKey: (key: StreamChannelKey) => StreamChannelKey): void;
115
+ /**
116
+ * Stop delivering one stream while an operation runs. Values keep arriving
117
+ * and the latest is kept; when the last holder releases, pending throttled
118
+ * deliveries are dropped and each reader receives the latest value once.
119
+ *
120
+ * @param stream - Stream name, matched against every channel's `key.stream`.
121
+ * @returns Release; calling it again does nothing.
122
+ */
123
+ pause(stream: string): () => void;
124
+ /**
125
+ * Stop and restart every open channel's source, keeping readers and last
126
+ * values, such as when a socket that looks open has stopped delivering.
127
+ */
128
+ reopenAll(): void;
129
+ /**
130
+ * The last value of an open channel.
131
+ *
132
+ * @param key - What the channel streams.
133
+ * @returns The last delivered arguments, or `undefined`.
134
+ */
135
+ getLast(key: StreamChannelKey): readonly unknown[] | undefined;
136
+ /** Stop every channel; their subscribers receive nothing more. */
137
+ clear(): void;
138
+ }
139
+ //# sourceMappingURL=StreamChannelManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StreamChannelManager.d.ts","sourceRoot":"","sources":["../../src/services/StreamChannelManager.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,475 @@
1
+ import { WebSocketConnectionState } from '../types/index.js';
2
+ /**
3
+ * Serialize a key so equal keys match regardless of property order.
4
+ *
5
+ * @param value - Key or nested option value.
6
+ * @returns A stable string form; functions and `undefined` are dropped.
7
+ */
8
+ function stableKey(value) {
9
+ if (Array.isArray(value)) {
10
+ return `[${value.map(stableKey).join(',')}]`;
11
+ }
12
+ if (value !== null && typeof value === 'object') {
13
+ return `{${Object.keys(value)
14
+ .sort()
15
+ .filter((name) => {
16
+ const entry = value[name];
17
+ return entry !== undefined && typeof entry !== 'function';
18
+ })
19
+ .map((name) => `${JSON.stringify(name)}:${stableKey(value[name])}`)
20
+ .join(',')}}`;
21
+ }
22
+ return JSON.stringify(value) ?? 'null';
23
+ }
24
+ /**
25
+ * The one stream layer every client shares. Each key gets one ref-counted
26
+ * channel over one venue subscription: it opens with the first subscriber,
27
+ * replays its last value to later ones, throttles each subscriber on its own
28
+ * and stops with the last one. Reconnect and resubscribe stay with the
29
+ * channel's source, so N readers cost one resubscribe. REST is read only
30
+ * while the transport is down: to seed a channel and once per drop.
31
+ */
32
+ export class StreamChannelManager {
33
+ #channels = new Map();
34
+ #subscribeToConnectionState;
35
+ #onError;
36
+ #stopConnectionWatch;
37
+ #connectionState;
38
+ /** The connection dropped since it was last connected. */
39
+ #dropped = false;
40
+ /**
41
+ * Failed channels still serving their readers; never reseeded or reopened.
42
+ */
43
+ #detached = new Set();
44
+ /** Pause holders per stream name. */
45
+ #pauses = new Map();
46
+ constructor(options = {}) {
47
+ this.#subscribeToConnectionState = options.subscribeToConnectionState;
48
+ this.#onError = options.onError ?? (() => undefined);
49
+ }
50
+ /**
51
+ * Open channels, for diagnostics and tests.
52
+ *
53
+ * @returns The number of open channels.
54
+ */
55
+ get size() {
56
+ return this.#channels.size;
57
+ }
58
+ /**
59
+ * Join the channel for `key`, opening it when it is the first subscriber.
60
+ *
61
+ * @param key - What the channel streams.
62
+ * @param source - Venue subscription used when the channel opens.
63
+ * @param subscriber - Callbacks and throttle for this reader.
64
+ * @returns Cleanup that leaves the channel.
65
+ */
66
+ subscribe(key, source, subscriber) {
67
+ const id = stableKey(key);
68
+ const open = this.#channels.get(id);
69
+ const channel = open ?? this.#createChannel(id, key, source);
70
+ const reader = {
71
+ subscriber: subscriber,
72
+ channel,
73
+ lastDeliveredAt: 0,
74
+ pending: undefined,
75
+ timer: undefined,
76
+ };
77
+ if (open) {
78
+ this.#join(open, reader);
79
+ }
80
+ else {
81
+ // The reader joins before the source opens, so a value the source
82
+ // delivers while opening reaches it.
83
+ channel.readers.add(reader);
84
+ this.#open(channel);
85
+ }
86
+ return () => this.#leave(reader);
87
+ }
88
+ /**
89
+ * Move every open channel whose key is no longer current to its next key,
90
+ * such as after the provider or the selected account changed. The source is
91
+ * stopped, the last value dropped and, when there was one, each reader's
92
+ * `onReset` called; the channel then reopens under the new key, or its
93
+ * readers join the channel already open there. Reader cleanups stay valid.
94
+ *
95
+ * @param isCurrent - Whether a key still matches the context.
96
+ * @param nextKey - The key a stale channel moves to.
97
+ */
98
+ rebind(isCurrent, nextKey) {
99
+ let moved = false;
100
+ for (const channel of [...this.#channels.values()]) {
101
+ // A source stopped earlier in this pass may have closed this channel.
102
+ if (channel.closed ||
103
+ this.#channels.get(channel.id) !== channel ||
104
+ isCurrent(channel.key)) {
105
+ continue;
106
+ }
107
+ moved = true;
108
+ const key = nextKey(channel.key);
109
+ const id = stableKey(key);
110
+ this.#channels.delete(channel.id);
111
+ this.#stopSource(channel);
112
+ // Readers hold nothing to reset when no value arrived since the last move.
113
+ const hadValue = channel.last !== undefined;
114
+ channel.last = undefined;
115
+ channel.suppressed = false;
116
+ // A seed read still in flight answers for the old key.
117
+ channel.version += 1;
118
+ const readers = [...channel.readers];
119
+ for (const reader of readers) {
120
+ this.#cancelPending(reader);
121
+ try {
122
+ if (hadValue) {
123
+ reader.subscriber.onReset?.();
124
+ }
125
+ }
126
+ catch (error) {
127
+ this.#onError(error);
128
+ }
129
+ }
130
+ const existing = this.#channels.get(id);
131
+ if (existing) {
132
+ channel.closed = true;
133
+ channel.readers.clear();
134
+ for (const reader of readers) {
135
+ reader.channel = existing;
136
+ this.#join(existing, reader);
137
+ }
138
+ continue;
139
+ }
140
+ channel.id = id;
141
+ channel.key = key;
142
+ this.#channels.set(id, channel);
143
+ this.#start(channel);
144
+ }
145
+ if (moved) {
146
+ // The connection watch answered for the old context.
147
+ this.#stopWatch();
148
+ this.#watchConnection();
149
+ }
150
+ }
151
+ /**
152
+ * Stop delivering one stream while an operation runs. Values keep arriving
153
+ * and the latest is kept; when the last holder releases, pending throttled
154
+ * deliveries are dropped and each reader receives the latest value once.
155
+ *
156
+ * @param stream - Stream name, matched against every channel's `key.stream`.
157
+ * @returns Release; calling it again does nothing.
158
+ */
159
+ pause(stream) {
160
+ this.#pauses.set(stream, (this.#pauses.get(stream) ?? 0) + 1);
161
+ let released = false;
162
+ return () => {
163
+ if (released) {
164
+ return;
165
+ }
166
+ released = true;
167
+ const count = (this.#pauses.get(stream) ?? 1) - 1;
168
+ if (count > 0) {
169
+ this.#pauses.set(stream, count);
170
+ return;
171
+ }
172
+ this.#pauses.delete(stream);
173
+ for (const channel of [...this.#channels.values(), ...this.#detached]) {
174
+ if (channel.key.stream !== stream || !channel.suppressed) {
175
+ continue;
176
+ }
177
+ channel.suppressed = false;
178
+ const { last } = channel;
179
+ for (const reader of [...channel.readers]) {
180
+ this.#cancelPending(reader);
181
+ if (last) {
182
+ this.#call(reader, last);
183
+ }
184
+ }
185
+ }
186
+ };
187
+ }
188
+ /**
189
+ * Stop and restart every open channel's source, keeping readers and last
190
+ * values, such as when a socket that looks open has stopped delivering.
191
+ */
192
+ reopenAll() {
193
+ for (const channel of [...this.#channels.values()]) {
194
+ if (!channel.closed) {
195
+ this.#reopen(channel);
196
+ }
197
+ }
198
+ }
199
+ /**
200
+ * The last value of an open channel.
201
+ *
202
+ * @param key - What the channel streams.
203
+ * @returns The last delivered arguments, or `undefined`.
204
+ */
205
+ getLast(key) {
206
+ return this.#channels.get(stableKey(key))?.last;
207
+ }
208
+ /**
209
+ * Add a reader to an open channel and replay its last value.
210
+ *
211
+ * @param channel - The open channel.
212
+ * @param reader - The joining reader.
213
+ */
214
+ #join(channel, reader) {
215
+ channel.readers.add(reader);
216
+ const { last, version } = channel;
217
+ if (last && channel.source.replay !== false) {
218
+ // Replay after `subscribe` returns, so callers hold their cleanup.
219
+ queueMicrotask(() => {
220
+ if (reader.channel === channel &&
221
+ channel.readers.has(reader) &&
222
+ channel.version === version) {
223
+ this.#deliver(reader, last);
224
+ }
225
+ });
226
+ }
227
+ }
228
+ /** Stop every channel; their subscribers receive nothing more. */
229
+ clear() {
230
+ for (const channel of [...this.#channels.values(), ...this.#detached]) {
231
+ for (const reader of channel.readers) {
232
+ clearTimeout(reader.timer);
233
+ }
234
+ channel.readers.clear();
235
+ this.#close(channel.id, channel);
236
+ }
237
+ }
238
+ #createChannel(id, key, source) {
239
+ return {
240
+ id,
241
+ key,
242
+ source,
243
+ readers: new Set(),
244
+ last: undefined,
245
+ version: 0,
246
+ stop: () => undefined,
247
+ closed: false,
248
+ suppressed: false,
249
+ };
250
+ }
251
+ #open(channel) {
252
+ this.#channels.set(channel.id, channel);
253
+ this.#watchConnection();
254
+ this.#start(channel);
255
+ // Seed only a channel that opens while the transport is known to be down;
256
+ // a connected stream delivers its own first value.
257
+ if (this.#connectionState !== undefined &&
258
+ this.#connectionState !== WebSocketConnectionState.Connected) {
259
+ this.#seed(channel);
260
+ }
261
+ }
262
+ #start(channel) {
263
+ try {
264
+ const stop = channel.source.open((...args) => this.#emit(channel, args), (error, ...detail) => this.#fail(channel, error, detail), channel.key);
265
+ if (channel.closed) {
266
+ stop();
267
+ }
268
+ else {
269
+ channel.stop = stop;
270
+ }
271
+ }
272
+ catch (error) {
273
+ queueMicrotask(() => this.#fail(channel, toError(error)));
274
+ }
275
+ }
276
+ #reopen(channel) {
277
+ this.#stopSource(channel);
278
+ this.#start(channel);
279
+ }
280
+ #stopSource(channel) {
281
+ const { stop } = channel;
282
+ channel.stop = () => undefined;
283
+ try {
284
+ stop();
285
+ }
286
+ catch (error) {
287
+ this.#onError(error);
288
+ }
289
+ }
290
+ #cancelPending(reader) {
291
+ clearTimeout(reader.timer);
292
+ reader.timer = undefined;
293
+ reader.pending = undefined;
294
+ }
295
+ #seed(channel) {
296
+ const { source, version } = channel;
297
+ if (!source.read) {
298
+ return;
299
+ }
300
+ source
301
+ .read(channel.key)
302
+ .then((args) => {
303
+ if (args && !channel.closed && channel.version === version) {
304
+ this.#emit(channel, args);
305
+ }
306
+ })
307
+ // A failed REST seed leaves the live stream attached.
308
+ .catch((error) => this.#fail(channel, toError(error), [], false));
309
+ }
310
+ #emit(channel, args) {
311
+ if (channel.closed) {
312
+ return;
313
+ }
314
+ channel.last = args;
315
+ channel.version += 1;
316
+ if (this.#pauses.has(channel.key.stream)) {
317
+ channel.suppressed = true;
318
+ return;
319
+ }
320
+ for (const reader of [...channel.readers]) {
321
+ this.#deliver(reader, args);
322
+ }
323
+ }
324
+ /**
325
+ * Report a failure to the channel's readers. A failed source is detached:
326
+ * it keeps serving the readers it has until they leave, and the next
327
+ * subscribe on its key opens a fresh source instead of rejoining it.
328
+ *
329
+ * @param channel - The failing channel.
330
+ * @param error - The failure.
331
+ * @param detail - Detail the source adds, such as the failing venue.
332
+ * @param detach - Detach the channel from its key.
333
+ */
334
+ #fail(channel, error, detail = [], detach = true) {
335
+ if (channel.closed) {
336
+ return;
337
+ }
338
+ if (detach && this.#channels.get(channel.id) === channel) {
339
+ this.#channels.delete(channel.id);
340
+ this.#detached.add(channel);
341
+ }
342
+ for (const reader of [...channel.readers]) {
343
+ try {
344
+ reader.subscriber.onError?.(error, ...detail);
345
+ }
346
+ catch (callbackError) {
347
+ this.#onError(callbackError);
348
+ }
349
+ }
350
+ }
351
+ #deliver(reader, args) {
352
+ const { throttleMs } = reader.subscriber;
353
+ if (!throttleMs || throttleMs <= 0) {
354
+ this.#call(reader, args);
355
+ return;
356
+ }
357
+ const wait = reader.lastDeliveredAt + throttleMs - Date.now();
358
+ if (wait <= 0 && reader.timer === undefined) {
359
+ this.#call(reader, args);
360
+ return;
361
+ }
362
+ reader.pending = args;
363
+ reader.timer ??= setTimeout(() => {
364
+ reader.timer = undefined;
365
+ // A pause delivers the latest value itself when it ends.
366
+ if (this.#pauses.has(reader.channel.key.stream)) {
367
+ reader.pending = undefined;
368
+ reader.channel.suppressed = true;
369
+ return;
370
+ }
371
+ const { pending } = reader;
372
+ reader.pending = undefined;
373
+ if (pending) {
374
+ this.#call(reader, pending);
375
+ }
376
+ }, Math.max(wait, 0));
377
+ }
378
+ #call(reader, args) {
379
+ reader.lastDeliveredAt = Date.now();
380
+ try {
381
+ reader.subscriber.callback(...args);
382
+ }
383
+ catch (error) {
384
+ this.#onError(error);
385
+ }
386
+ }
387
+ #leave(reader) {
388
+ const { channel } = reader;
389
+ if (!channel.readers.delete(reader)) {
390
+ return;
391
+ }
392
+ this.#cancelPending(reader);
393
+ if (channel.readers.size === 0) {
394
+ this.#close(channel.id, channel);
395
+ }
396
+ }
397
+ #close(id, channel) {
398
+ if (channel.closed) {
399
+ return;
400
+ }
401
+ channel.closed = true;
402
+ this.#detached.delete(channel);
403
+ if (this.#channels.get(id) === channel) {
404
+ this.#channels.delete(id);
405
+ }
406
+ try {
407
+ channel.stop();
408
+ }
409
+ catch (error) {
410
+ this.#onError(error);
411
+ }
412
+ if (this.#channels.size === 0) {
413
+ this.#stopWatch();
414
+ }
415
+ }
416
+ #stopWatch() {
417
+ const stopWatch = this.#stopConnectionWatch;
418
+ this.#stopConnectionWatch = undefined;
419
+ this.#connectionState = undefined;
420
+ this.#dropped = false;
421
+ try {
422
+ stopWatch?.();
423
+ }
424
+ catch (error) {
425
+ this.#onError(error);
426
+ }
427
+ }
428
+ /** Watch the transport while any channel is open. */
429
+ #watchConnection() {
430
+ if (this.#stopConnectionWatch || !this.#subscribeToConnectionState) {
431
+ return;
432
+ }
433
+ this.#stopConnectionWatch = () => undefined;
434
+ try {
435
+ this.#stopConnectionWatch = this.#subscribeToConnectionState((state) => this.#onConnectionState(state));
436
+ }
437
+ catch (error) {
438
+ this.#onError(error);
439
+ }
440
+ }
441
+ /**
442
+ * Read each channel's REST source once when a live connection drops.
443
+ *
444
+ * @param state - The new transport state.
445
+ */
446
+ #onConnectionState(state) {
447
+ const previous = this.#connectionState;
448
+ this.#connectionState = state;
449
+ if (previous === WebSocketConnectionState.Connected &&
450
+ state !== WebSocketConnectionState.Connected) {
451
+ this.#dropped = true;
452
+ for (const channel of [...this.#channels.values()]) {
453
+ this.#seed(channel);
454
+ }
455
+ }
456
+ else if (state === WebSocketConnectionState.Connected && this.#dropped) {
457
+ this.#dropped = false;
458
+ for (const channel of [...this.#channels.values()]) {
459
+ if (channel.source.reopenOnReconnect && !channel.closed) {
460
+ this.#reopen(channel);
461
+ }
462
+ }
463
+ }
464
+ }
465
+ }
466
+ /**
467
+ * Normalize a thrown value.
468
+ *
469
+ * @param error - Thrown value.
470
+ * @returns An `Error`.
471
+ */
472
+ function toError(error) {
473
+ return error instanceof Error ? error : new Error(String(error));
474
+ }
475
+ //# sourceMappingURL=StreamChannelManager.js.map