@arttecs/murmur 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +325 -2
- package/dist/channel.d.ts +22 -0
- package/dist/chunk-QZPDZV62.js +1086 -0
- package/dist/client.d.ts +206 -0
- package/dist/echo.d.ts +119 -0
- package/dist/echo.js +346 -0
- package/dist/envelope.d.ts +9 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +6 -0
- package/dist/invoke-listener.d.ts +2 -0
- package/dist/stream.d.ts +34 -0
- package/dist/transport.d.ts +84 -0
- package/package.json +56 -4
|
@@ -0,0 +1,1086 @@
|
|
|
1
|
+
// src/invoke-listener.ts
|
|
2
|
+
function invokeListener(listener, ...args) {
|
|
3
|
+
try {
|
|
4
|
+
listener(...args);
|
|
5
|
+
} catch (error) {
|
|
6
|
+
queueMicrotask(() => {
|
|
7
|
+
throw error;
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// src/channel.ts
|
|
13
|
+
var Channel = class {
|
|
14
|
+
/**
|
|
15
|
+
* Creates a channel that reports changes to its event names.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
constructor(name, namespace, listeners, listenersChanged) {
|
|
20
|
+
this.namespace = namespace;
|
|
21
|
+
this.listeners = listeners;
|
|
22
|
+
this.listenersChanged = listenersChanged;
|
|
23
|
+
this.name = name;
|
|
24
|
+
}
|
|
25
|
+
namespace;
|
|
26
|
+
listeners;
|
|
27
|
+
listenersChanged;
|
|
28
|
+
/** Callbacks registered for this channel's authorization failures. */
|
|
29
|
+
errors = /* @__PURE__ */ new Set();
|
|
30
|
+
/** Callbacks registered for the server's attachment acknowledgment. */
|
|
31
|
+
attachments = /* @__PURE__ */ new Set();
|
|
32
|
+
/** The subscribed topic, including its prefix for private channels. */
|
|
33
|
+
name;
|
|
34
|
+
/** Registers a callback for an event on this channel. */
|
|
35
|
+
listen(event, callback) {
|
|
36
|
+
const name = this.eventName(event);
|
|
37
|
+
const callbacks = this.listeners.get(name);
|
|
38
|
+
if (callbacks) {
|
|
39
|
+
callbacks.add(callback);
|
|
40
|
+
} else {
|
|
41
|
+
this.listeners.set(name, /* @__PURE__ */ new Set([callback]));
|
|
42
|
+
this.listenersChanged();
|
|
43
|
+
}
|
|
44
|
+
return this;
|
|
45
|
+
}
|
|
46
|
+
/** Removes the callbacks for an event on this channel. */
|
|
47
|
+
stopListening(event) {
|
|
48
|
+
if (this.listeners.delete(this.eventName(event))) {
|
|
49
|
+
this.listenersChanged();
|
|
50
|
+
}
|
|
51
|
+
return this;
|
|
52
|
+
}
|
|
53
|
+
/** Registers a callback for a denied authorization request on this channel. */
|
|
54
|
+
error(callback) {
|
|
55
|
+
this.errors.add(callback);
|
|
56
|
+
return this;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Delivers a denied authorization status to this channel's listeners.
|
|
60
|
+
*
|
|
61
|
+
* @internal
|
|
62
|
+
*/
|
|
63
|
+
authorizationDenied(status) {
|
|
64
|
+
for (const callback of this.errors) {
|
|
65
|
+
invokeListener(callback, status);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Registers a callback for attachment on a connection that included this channel.
|
|
70
|
+
*
|
|
71
|
+
* @internal
|
|
72
|
+
*/
|
|
73
|
+
onAttached(callback) {
|
|
74
|
+
this.attachments.add(callback);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Notifies listeners that the server finished attaching this subscription.
|
|
78
|
+
*
|
|
79
|
+
* @internal
|
|
80
|
+
*/
|
|
81
|
+
attachmentConfirmed() {
|
|
82
|
+
for (const callback of this.attachments) {
|
|
83
|
+
invokeListener(callback);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Clears callbacks when the owning client leaves this subscription.
|
|
88
|
+
*
|
|
89
|
+
* @internal
|
|
90
|
+
*/
|
|
91
|
+
detach() {
|
|
92
|
+
this.listeners.clear();
|
|
93
|
+
this.errors.clear();
|
|
94
|
+
this.attachments.clear();
|
|
95
|
+
}
|
|
96
|
+
/** Resolves an event to the name used in the stream. */
|
|
97
|
+
eventName(event) {
|
|
98
|
+
if (event.startsWith(".")) {
|
|
99
|
+
return event.slice(1);
|
|
100
|
+
}
|
|
101
|
+
return this.namespace ? this.namespace.replaceAll(".", "\\") + "\\" + event : event;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/envelope.ts
|
|
106
|
+
function parseEnvelope(raw) {
|
|
107
|
+
let envelope;
|
|
108
|
+
try {
|
|
109
|
+
envelope = JSON.parse(raw);
|
|
110
|
+
} catch {
|
|
111
|
+
return void 0;
|
|
112
|
+
}
|
|
113
|
+
if (envelope === null || typeof envelope !== "object" || !("topic" in envelope) || typeof envelope.topic !== "string" || !("data" in envelope)) {
|
|
114
|
+
return void 0;
|
|
115
|
+
}
|
|
116
|
+
return { topic: envelope.topic, data: envelope.data };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/transport.ts
|
|
120
|
+
function validateRetryOptions({ retryMs, maxRetryMs, retryJitter }) {
|
|
121
|
+
if (!Number.isFinite(retryMs) || retryMs <= 0) {
|
|
122
|
+
throw new RangeError("retryMs must be finite and greater than zero");
|
|
123
|
+
}
|
|
124
|
+
if (!Number.isFinite(maxRetryMs) || maxRetryMs < retryMs) {
|
|
125
|
+
throw new RangeError("maxRetryMs must be finite and greater than or equal to retryMs");
|
|
126
|
+
}
|
|
127
|
+
if (!Number.isFinite(retryJitter) || retryJitter < 0 || retryJitter > 1) {
|
|
128
|
+
throw new RangeError("retryJitter must be finite and between 0 and 1");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
var RetryAfterError = class extends Error {
|
|
132
|
+
/** Records the retry delay and the original failure. */
|
|
133
|
+
constructor(delayMs, cause) {
|
|
134
|
+
super("Murmur connection attempt must wait before retrying", { cause });
|
|
135
|
+
this.delayMs = delayMs;
|
|
136
|
+
}
|
|
137
|
+
delayMs;
|
|
138
|
+
};
|
|
139
|
+
function isMessage(event) {
|
|
140
|
+
return typeof event === "object" && event !== null && "data" in event && typeof event.data === "string";
|
|
141
|
+
}
|
|
142
|
+
var eventIdPattern = /^[0-9]{1,18}-[0-9]{1,18}(?![\s\S])/;
|
|
143
|
+
function readRequestedCursor(url) {
|
|
144
|
+
const fragment = url.indexOf("#");
|
|
145
|
+
const address = fragment === -1 ? url : url.slice(0, fragment);
|
|
146
|
+
const query = address.indexOf("?");
|
|
147
|
+
const cursor = query === -1 ? void 0 : new URLSearchParams(address.slice(query)).getAll("lastEventId").at(-1);
|
|
148
|
+
return cursor !== void 0 && eventIdPattern.test(cursor) ? cursor : void 0;
|
|
149
|
+
}
|
|
150
|
+
function isLaterEventId(candidate, cursor) {
|
|
151
|
+
const candidateSeparator = candidate.indexOf("-");
|
|
152
|
+
const cursorSeparator = cursor.indexOf("-");
|
|
153
|
+
const candidateTime = BigInt(candidate.slice(0, candidateSeparator));
|
|
154
|
+
const cursorTime = BigInt(cursor.slice(0, cursorSeparator));
|
|
155
|
+
if (candidateTime !== cursorTime) {
|
|
156
|
+
return candidateTime > cursorTime;
|
|
157
|
+
}
|
|
158
|
+
return BigInt(candidate.slice(candidateSeparator + 1)) > BigInt(cursor.slice(cursorSeparator + 1));
|
|
159
|
+
}
|
|
160
|
+
var Transport = class {
|
|
161
|
+
/** Creates a transport that prepares a fresh URL for every attempt. */
|
|
162
|
+
constructor(eventSource, withCredentials, retryOptions, connectionUrl, onMessage, onStatus, onPreOpenError, initialCursor) {
|
|
163
|
+
this.eventSource = eventSource;
|
|
164
|
+
this.withCredentials = withCredentials;
|
|
165
|
+
this.retryOptions = retryOptions;
|
|
166
|
+
this.connectionUrl = connectionUrl;
|
|
167
|
+
this.onMessage = onMessage;
|
|
168
|
+
this.onStatus = onStatus;
|
|
169
|
+
this.onPreOpenError = onPreOpenError;
|
|
170
|
+
this.initialCursor = initialCursor;
|
|
171
|
+
}
|
|
172
|
+
eventSource;
|
|
173
|
+
withCredentials;
|
|
174
|
+
retryOptions;
|
|
175
|
+
connectionUrl;
|
|
176
|
+
onMessage;
|
|
177
|
+
onStatus;
|
|
178
|
+
onPreOpenError;
|
|
179
|
+
initialCursor;
|
|
180
|
+
/** The current connection and its registered listeners. */
|
|
181
|
+
connection;
|
|
182
|
+
/** The controller for URL preparation on the current attempt. */
|
|
183
|
+
pending;
|
|
184
|
+
/** The time scheduled for the next attempt. */
|
|
185
|
+
retryTimer;
|
|
186
|
+
/** The number of failures since the last attach marker. */
|
|
187
|
+
failures = 0;
|
|
188
|
+
/** The latest replay position acknowledged by the server or an application event. */
|
|
189
|
+
lastEventId;
|
|
190
|
+
/** The wire events that the connection should listen for. */
|
|
191
|
+
events = /* @__PURE__ */ new Set(["murmur.gap", "murmur.connected", "murmur.attached", "murmur.heartbeat"]);
|
|
192
|
+
/** Reports whether the active source has opened. */
|
|
193
|
+
get connected() {
|
|
194
|
+
return this.connection?.opened ?? false;
|
|
195
|
+
}
|
|
196
|
+
/** Returns the cursor used when opening the next source. */
|
|
197
|
+
get replayCursor() {
|
|
198
|
+
return this.lastEventId ?? this.initialCursor;
|
|
199
|
+
}
|
|
200
|
+
/** Replaces the active connection with a new attempt. */
|
|
201
|
+
connect() {
|
|
202
|
+
this.close();
|
|
203
|
+
void this.open();
|
|
204
|
+
}
|
|
205
|
+
/** Updates named listeners on the active connection and future attempts. */
|
|
206
|
+
setEvents(events) {
|
|
207
|
+
events.add("murmur.gap");
|
|
208
|
+
events.add("murmur.connected");
|
|
209
|
+
events.add("murmur.attached");
|
|
210
|
+
events.add("murmur.heartbeat");
|
|
211
|
+
const connection = this.connection;
|
|
212
|
+
if (connection) {
|
|
213
|
+
const { source, message } = connection;
|
|
214
|
+
for (const event of this.events) {
|
|
215
|
+
if (!events.has(event)) {
|
|
216
|
+
source.removeEventListener(event, message);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
for (const event of events) {
|
|
220
|
+
if (!this.events.has(event)) {
|
|
221
|
+
source.addEventListener(event, message);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
this.events = events;
|
|
226
|
+
}
|
|
227
|
+
/** Cancels work that could open a connection for obsolete subscriptions. */
|
|
228
|
+
cancelPending() {
|
|
229
|
+
this.pending?.abort();
|
|
230
|
+
this.pending = void 0;
|
|
231
|
+
if (this.retryTimer !== void 0) {
|
|
232
|
+
clearTimeout(this.retryTimer);
|
|
233
|
+
this.retryTimer = void 0;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** Stops the active connection and removes its listeners. */
|
|
237
|
+
close() {
|
|
238
|
+
this.cancelPending();
|
|
239
|
+
const connection = this.connection;
|
|
240
|
+
if (!connection) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
this.connection = void 0;
|
|
244
|
+
const { source, open, error, message } = connection;
|
|
245
|
+
source.removeEventListener("open", open);
|
|
246
|
+
source.removeEventListener("error", error);
|
|
247
|
+
for (const event of this.events) {
|
|
248
|
+
source.removeEventListener(event, message);
|
|
249
|
+
}
|
|
250
|
+
source.close();
|
|
251
|
+
}
|
|
252
|
+
/** Prepares the connection and binds its named events. */
|
|
253
|
+
async open() {
|
|
254
|
+
const attempt = new AbortController();
|
|
255
|
+
this.pending = attempt;
|
|
256
|
+
try {
|
|
257
|
+
const url = await this.connectionUrl(attempt.signal, this.lastEventId);
|
|
258
|
+
if (attempt.signal.aborted || url === void 0) {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const EventSource = this.eventSource ?? globalThis.EventSource;
|
|
262
|
+
const source = this.withCredentials ? new EventSource(url, { withCredentials: true }) : new EventSource(url);
|
|
263
|
+
this.attach(source, url);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (!attempt.signal.aborted) {
|
|
266
|
+
this.handleFailure(error instanceof RetryAfterError ? error.delayMs : void 0);
|
|
267
|
+
}
|
|
268
|
+
} finally {
|
|
269
|
+
if (this.pending === attempt) {
|
|
270
|
+
this.pending = void 0;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** Binds listeners to the active source, including polyfills without currentTarget. */
|
|
275
|
+
attach(source, url) {
|
|
276
|
+
const connection = {
|
|
277
|
+
source,
|
|
278
|
+
opened: false,
|
|
279
|
+
attached: false,
|
|
280
|
+
replayed: false,
|
|
281
|
+
open: (event) => {
|
|
282
|
+
if (this.connection === connection && !isMessage(event)) {
|
|
283
|
+
connection.opened = true;
|
|
284
|
+
this.onStatus("connected", connection.attached || connection.replayed);
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
error: (event) => {
|
|
288
|
+
if (this.connection === connection && !isMessage(event)) {
|
|
289
|
+
if (!connection.opened && !connection.attached) {
|
|
290
|
+
const status = "status" in event && typeof event.status === "number" ? event.status : "code" in event && typeof event.code === "number" ? event.code : void 0;
|
|
291
|
+
this.onPreOpenError?.(url, status);
|
|
292
|
+
}
|
|
293
|
+
this.handleFailure();
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
message: (event) => {
|
|
297
|
+
if (this.connection === connection && isMessage(event)) {
|
|
298
|
+
this.receive(connection, event.type, event.data, event.lastEventId);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
this.connection = connection;
|
|
303
|
+
source.addEventListener("open", connection.open);
|
|
304
|
+
source.addEventListener("error", connection.error);
|
|
305
|
+
for (const event of this.events) {
|
|
306
|
+
source.addEventListener(event, connection.message);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/** Schedules a replacement connection with capped exponential backoff and jitter. */
|
|
310
|
+
retry(minimumDelay = 0) {
|
|
311
|
+
const { retryMs, maxRetryMs, retryJitter } = this.retryOptions;
|
|
312
|
+
let delay = Math.min(retryMs * 2 ** (this.failures - 1), maxRetryMs);
|
|
313
|
+
if (retryJitter !== 0) {
|
|
314
|
+
delay += delay * retryJitter * Math.random();
|
|
315
|
+
}
|
|
316
|
+
this.retryTimer = setTimeout(() => {
|
|
317
|
+
this.retryTimer = void 0;
|
|
318
|
+
void this.open();
|
|
319
|
+
}, Math.max(delay, Math.min(minimumDelay, maxRetryMs)));
|
|
320
|
+
}
|
|
321
|
+
/** Closes the failed connection, schedules a retry, and reports the failure. */
|
|
322
|
+
handleFailure(minimumDelay) {
|
|
323
|
+
const connection = this.connection;
|
|
324
|
+
const madeProgress = connection !== void 0 && (connection.attached || connection.replayed);
|
|
325
|
+
this.close();
|
|
326
|
+
this.failures++;
|
|
327
|
+
this.retry(minimumDelay);
|
|
328
|
+
this.onStatus("disconnected", madeProgress);
|
|
329
|
+
}
|
|
330
|
+
/** Captures the resume cursor and dispatches named stream data. */
|
|
331
|
+
receive(connection, event, data, lastEventId) {
|
|
332
|
+
const id = typeof lastEventId === "string" && eventIdPattern.test(lastEventId) ? lastEventId : void 0;
|
|
333
|
+
if (event === "murmur.heartbeat") {
|
|
334
|
+
if (connection.attached && id !== void 0) {
|
|
335
|
+
this.lastEventId = id;
|
|
336
|
+
}
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (event === "murmur.attached") {
|
|
340
|
+
connection.attached = true;
|
|
341
|
+
this.failures = 0;
|
|
342
|
+
}
|
|
343
|
+
if (id !== void 0 && event !== "murmur.gap" && event !== "murmur.connected") {
|
|
344
|
+
if (!connection.attached && !connection.replayed) {
|
|
345
|
+
const cursor = this.replayCursor;
|
|
346
|
+
connection.replayed = cursor === void 0 || isLaterEventId(id, cursor);
|
|
347
|
+
}
|
|
348
|
+
this.lastEventId = id;
|
|
349
|
+
}
|
|
350
|
+
this.onMessage(event, data);
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
// src/stream.ts
|
|
355
|
+
var MurmurStream = class {
|
|
356
|
+
/**
|
|
357
|
+
* Opens a stream and notifies its owning client when it closes.
|
|
358
|
+
*
|
|
359
|
+
* @internal
|
|
360
|
+
*/
|
|
361
|
+
constructor(url, eventSource, withCredentials, retryOptions, maxFailures, onClose) {
|
|
362
|
+
this.url = url;
|
|
363
|
+
this.onClose = onClose;
|
|
364
|
+
let stalledAttempts = 0;
|
|
365
|
+
this.transport = new Transport(
|
|
366
|
+
eventSource,
|
|
367
|
+
withCredentials,
|
|
368
|
+
retryOptions,
|
|
369
|
+
(_signal, lastEventId) => this.connectionUrl(lastEventId),
|
|
370
|
+
(event, data) => this.receive(event, data),
|
|
371
|
+
(status, madeProgress) => {
|
|
372
|
+
if (status === "disconnected") {
|
|
373
|
+
stalledAttempts = madeProgress ? 0 : stalledAttempts + 1;
|
|
374
|
+
if (stalledAttempts === maxFailures) {
|
|
375
|
+
this.finish("expired");
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
},
|
|
379
|
+
void 0,
|
|
380
|
+
readRequestedCursor(url)
|
|
381
|
+
);
|
|
382
|
+
this.transport.setEvents(/* @__PURE__ */ new Set(["murmur.end"]));
|
|
383
|
+
this.transport.connect();
|
|
384
|
+
}
|
|
385
|
+
url;
|
|
386
|
+
/** The transport that opens and retries the subscription. */
|
|
387
|
+
transport;
|
|
388
|
+
/** The callbacks registered for data and control events. */
|
|
389
|
+
listeners = /* @__PURE__ */ new Map();
|
|
390
|
+
/** Whether the stream has stopped permanently. */
|
|
391
|
+
closed = false;
|
|
392
|
+
/** Releases the owning client's reference to this stream. */
|
|
393
|
+
onClose;
|
|
394
|
+
/** Returns the current replay cursor, including after the stream expires. */
|
|
395
|
+
get lastEventId() {
|
|
396
|
+
return this.transport.replayCursor;
|
|
397
|
+
}
|
|
398
|
+
/** Registers a callback for a data or control event. */
|
|
399
|
+
on(event, callback) {
|
|
400
|
+
if (!this.closed) {
|
|
401
|
+
const callbacks = this.listeners.get(event);
|
|
402
|
+
if (callbacks) {
|
|
403
|
+
callbacks.add(callback);
|
|
404
|
+
} else {
|
|
405
|
+
this.listeners.set(event, /* @__PURE__ */ new Set([callback]));
|
|
406
|
+
const events = new Set(this.listeners.keys());
|
|
407
|
+
events.delete("end");
|
|
408
|
+
events.delete("gap");
|
|
409
|
+
events.delete("expired");
|
|
410
|
+
events.add("murmur.end");
|
|
411
|
+
this.transport.setEvents(events);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return this;
|
|
415
|
+
}
|
|
416
|
+
/** Stops the subscription, cancels retries, and releases its callbacks. */
|
|
417
|
+
close() {
|
|
418
|
+
if (this.closed) {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
this.closed = true;
|
|
422
|
+
this.transport.close();
|
|
423
|
+
for (const callbacks of this.listeners.values()) {
|
|
424
|
+
callbacks.clear();
|
|
425
|
+
}
|
|
426
|
+
this.listeners.clear();
|
|
427
|
+
const onClose = this.onClose;
|
|
428
|
+
this.onClose = void 0;
|
|
429
|
+
onClose?.(this);
|
|
430
|
+
}
|
|
431
|
+
/** Keeps the supplied URL until an event ID is received, then changes only the replay cursor. */
|
|
432
|
+
connectionUrl(lastEventId) {
|
|
433
|
+
if (lastEventId === void 0) {
|
|
434
|
+
return this.url;
|
|
435
|
+
}
|
|
436
|
+
const fragmentIndex = this.url.indexOf("#");
|
|
437
|
+
const address = fragmentIndex === -1 ? this.url : this.url.slice(0, fragmentIndex);
|
|
438
|
+
const fragment = fragmentIndex === -1 ? "" : this.url.slice(fragmentIndex);
|
|
439
|
+
const queryIndex = address.indexOf("?");
|
|
440
|
+
const path = queryIndex === -1 ? address : address.slice(0, queryIndex);
|
|
441
|
+
const query = queryIndex === -1 ? "" : address.slice(queryIndex + 1);
|
|
442
|
+
const parameters = query === "" ? [] : query.split("&");
|
|
443
|
+
const cursor = ["lastEventId=" + encodeURIComponent(lastEventId)];
|
|
444
|
+
let found = false;
|
|
445
|
+
const updated = parameters.flatMap((parameter) => {
|
|
446
|
+
if (!new URLSearchParams("?" + parameter).has("lastEventId")) {
|
|
447
|
+
return [parameter];
|
|
448
|
+
}
|
|
449
|
+
const replacement = found ? [] : cursor;
|
|
450
|
+
found = true;
|
|
451
|
+
return replacement;
|
|
452
|
+
});
|
|
453
|
+
if (!found) {
|
|
454
|
+
updated.push(...cursor);
|
|
455
|
+
}
|
|
456
|
+
return path + (updated.length ? "?" + updated.join("&") : "") + fragment;
|
|
457
|
+
}
|
|
458
|
+
/** Delivers control events or unwrapped data. */
|
|
459
|
+
receive(event, data) {
|
|
460
|
+
if (event === "murmur.connected" || event === "murmur.attached") {
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
if (event === "murmur.end") {
|
|
464
|
+
this.finish("end");
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
if (event === "murmur.gap") {
|
|
468
|
+
this.emit("gap");
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const envelope = parseEnvelope(data);
|
|
472
|
+
if (envelope === void 0) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
this.emit(event, envelope.data);
|
|
476
|
+
}
|
|
477
|
+
/** Delivers a data payload or gap notification to its listeners. */
|
|
478
|
+
emit(event, ...args) {
|
|
479
|
+
for (const listener of this.listeners.get(event) ?? []) {
|
|
480
|
+
invokeListener(listener, ...args);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
/** Closes the connection before notifying listeners of terminal events. */
|
|
484
|
+
finish(event) {
|
|
485
|
+
const listeners = [...this.listeners.get(event) ?? []];
|
|
486
|
+
this.close();
|
|
487
|
+
for (const listener of listeners) {
|
|
488
|
+
invokeListener(listener);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
// src/client.ts
|
|
494
|
+
var privatePrefix = "private-";
|
|
495
|
+
var authorizationConcurrency = 4;
|
|
496
|
+
var requestTargetBudget = 6 * 1024;
|
|
497
|
+
var reservedConnectionId = "0".repeat(32);
|
|
498
|
+
var reservedCursor = "0".repeat(18) + "-" + "0".repeat(18);
|
|
499
|
+
function isAuthorizationToken(value) {
|
|
500
|
+
return value !== null && typeof value === "object" && "token" in value && typeof value.token === "string" && value.token !== "" && !value.token.includes(",") && "expires_at" in value && typeof value.expires_at === "number" && Number.isFinite(value.expires_at) && (!("channels" in value) || value.channels === void 0 || Array.isArray(value.channels) && [...value.channels].every((channel) => typeof channel === "string"));
|
|
501
|
+
}
|
|
502
|
+
function validateFailureLimit(value, option) {
|
|
503
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
504
|
+
throw new RangeError(option + " must be an integer greater than or equal to 1");
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
var AuthorizationResponseError = class extends Error {
|
|
508
|
+
/** Records the status and retry header of the response. */
|
|
509
|
+
constructor(status, retryAfter) {
|
|
510
|
+
super("Murmur authorization failed");
|
|
511
|
+
this.status = status;
|
|
512
|
+
this.retryAfter = retryAfter;
|
|
513
|
+
}
|
|
514
|
+
status;
|
|
515
|
+
retryAfter;
|
|
516
|
+
};
|
|
517
|
+
var imfFixdate = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), [0-9]{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT(?![\s\S])/;
|
|
518
|
+
function retryAfterDelay(header) {
|
|
519
|
+
const value = header?.trim() ?? "";
|
|
520
|
+
if (/^\d+$/.test(value)) {
|
|
521
|
+
return Number(value) * 1e3;
|
|
522
|
+
}
|
|
523
|
+
if (!imfFixdate.test(value)) {
|
|
524
|
+
return 0;
|
|
525
|
+
}
|
|
526
|
+
const utc = value.replace("23:59:60 GMT", "23:59:59 GMT");
|
|
527
|
+
const time = Date.parse(utc);
|
|
528
|
+
if (new Date(time).toUTCString() !== utc) {
|
|
529
|
+
return 0;
|
|
530
|
+
}
|
|
531
|
+
return Math.max(0, time + (utc === value ? 0 : 1e3) - Date.now());
|
|
532
|
+
}
|
|
533
|
+
var Murmur = class {
|
|
534
|
+
/** Creates a client for the given streaming endpoint. */
|
|
535
|
+
constructor(options) {
|
|
536
|
+
this.options = options;
|
|
537
|
+
const retryMs = options.retryMs ?? 3e3;
|
|
538
|
+
this.retryOptions = {
|
|
539
|
+
retryMs,
|
|
540
|
+
maxRetryMs: options.maxRetryMs ?? Math.max(3e4, retryMs),
|
|
541
|
+
retryJitter: options.retryJitter ?? 0.25
|
|
542
|
+
};
|
|
543
|
+
validateRetryOptions(this.retryOptions);
|
|
544
|
+
this.tokenRefreshMarginSeconds = options.tokenRefreshMarginSeconds ?? 30;
|
|
545
|
+
if (!Number.isFinite(this.tokenRefreshMarginSeconds) || this.tokenRefreshMarginSeconds < 0) {
|
|
546
|
+
throw new RangeError("tokenRefreshMarginSeconds must be finite and greater than or equal to zero");
|
|
547
|
+
}
|
|
548
|
+
this.streamMaxFailures = options.streamMaxFailures ?? 8;
|
|
549
|
+
validateFailureLimit(this.streamMaxFailures, "streamMaxFailures");
|
|
550
|
+
this.transport = new Transport(
|
|
551
|
+
options.EventSource,
|
|
552
|
+
options.withCredentials ?? false,
|
|
553
|
+
this.retryOptions,
|
|
554
|
+
(signal, lastEventId) => this.connectionUrl(signal, lastEventId),
|
|
555
|
+
(event, data) => this.receive(event, data),
|
|
556
|
+
(event) => {
|
|
557
|
+
if (event === "connected") {
|
|
558
|
+
this.counts.connections++;
|
|
559
|
+
} else {
|
|
560
|
+
this.attemptSubscriptions = [];
|
|
561
|
+
this.counts.disconnections++;
|
|
562
|
+
}
|
|
563
|
+
this.emit(event);
|
|
564
|
+
},
|
|
565
|
+
(url, status) => this.refreshAfterPreOpenError(url, status)
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
options;
|
|
569
|
+
/** The joined channels and their callbacks, indexed by subscription name and kind. */
|
|
570
|
+
channels = /* @__PURE__ */ new Map();
|
|
571
|
+
/** The wire topics with at least one joined channel. */
|
|
572
|
+
topics = /* @__PURE__ */ new Map();
|
|
573
|
+
/** The callbacks registered for client events. */
|
|
574
|
+
listeners = {
|
|
575
|
+
gap: /* @__PURE__ */ new Set(),
|
|
576
|
+
connected: /* @__PURE__ */ new Set(),
|
|
577
|
+
attached: /* @__PURE__ */ new Set(),
|
|
578
|
+
disconnected: /* @__PURE__ */ new Set(),
|
|
579
|
+
unauthorized: /* @__PURE__ */ new Set(),
|
|
580
|
+
error: /* @__PURE__ */ new Set()
|
|
581
|
+
};
|
|
582
|
+
/** Observers of shared connection preparation. */
|
|
583
|
+
preparationListeners = /* @__PURE__ */ new Set();
|
|
584
|
+
/** The transport for the shared event stream. */
|
|
585
|
+
transport;
|
|
586
|
+
/** The active streams created by this client. */
|
|
587
|
+
streams = /* @__PURE__ */ new Set();
|
|
588
|
+
/** The cumulative counters reported by stats(). */
|
|
589
|
+
counts = {
|
|
590
|
+
connections: 0,
|
|
591
|
+
disconnections: 0,
|
|
592
|
+
events: 0,
|
|
593
|
+
gaps: 0,
|
|
594
|
+
tokenRequests: 0,
|
|
595
|
+
tokenFailures: 0
|
|
596
|
+
};
|
|
597
|
+
/** The time the last valid shared data event was received. */
|
|
598
|
+
lastEventAt;
|
|
599
|
+
/** The ID most recently announced by the shared connection. */
|
|
600
|
+
connectionId;
|
|
601
|
+
/** Whether a protocol mismatch has already been reported. */
|
|
602
|
+
protocolMismatchReported = false;
|
|
603
|
+
/** The client's retry settings, also used as the defaults for streams. */
|
|
604
|
+
retryOptions;
|
|
605
|
+
/** The time that must remain on a cached token for it to be reused, in seconds. */
|
|
606
|
+
tokenRefreshMarginSeconds;
|
|
607
|
+
/** The default limit on consecutive independent stream attempts without attachment or replay progress. */
|
|
608
|
+
streamMaxFailures;
|
|
609
|
+
/** The reusable tokens associated with each authorized private topic. */
|
|
610
|
+
cachedTokens = /* @__PURE__ */ new Map();
|
|
611
|
+
/** The number of pre-open failures that could indicate credential rejection since attachment. */
|
|
612
|
+
preOpenCredentialFailures = 0;
|
|
613
|
+
/** The next credential-bearing failure that triggers an automatic refresh. */
|
|
614
|
+
nextCredentialRefresh = 2;
|
|
615
|
+
/** The private topics waiting for explicit authorization or a new join. */
|
|
616
|
+
deniedTopics = /* @__PURE__ */ new Set();
|
|
617
|
+
/** The subscriptions sent on the attempt waiting for its attach marker. */
|
|
618
|
+
attemptSubscriptions = [];
|
|
619
|
+
/** Whether a channel change has queued a connection update. */
|
|
620
|
+
connectionQueued = false;
|
|
621
|
+
/** Whether the client has been permanently closed. */
|
|
622
|
+
closed = false;
|
|
623
|
+
/** Joins a public channel. */
|
|
624
|
+
channel(name) {
|
|
625
|
+
return this.join("public:" + name, name);
|
|
626
|
+
}
|
|
627
|
+
/** Joins a private channel and authorizes its topic before connecting. */
|
|
628
|
+
private(name) {
|
|
629
|
+
return this.join("private:" + name, privatePrefix + name);
|
|
630
|
+
}
|
|
631
|
+
/** Opens an independent stream using a server-issued subscription URL. */
|
|
632
|
+
stream(url, options = {}) {
|
|
633
|
+
const retryMs = options.retryMs ?? this.retryOptions.retryMs;
|
|
634
|
+
const retryOptions = {
|
|
635
|
+
retryMs,
|
|
636
|
+
maxRetryMs: options.maxRetryMs ?? Math.max(this.retryOptions.maxRetryMs, retryMs),
|
|
637
|
+
retryJitter: options.retryJitter ?? this.retryOptions.retryJitter
|
|
638
|
+
};
|
|
639
|
+
const maxFailures = options.maxFailures ?? this.streamMaxFailures;
|
|
640
|
+
validateRetryOptions(retryOptions);
|
|
641
|
+
validateFailureLimit(maxFailures, "maxFailures");
|
|
642
|
+
const stream = new MurmurStream(
|
|
643
|
+
url,
|
|
644
|
+
this.options.EventSource,
|
|
645
|
+
this.options.withCredentials ?? false,
|
|
646
|
+
retryOptions,
|
|
647
|
+
maxFailures,
|
|
648
|
+
(closed) => {
|
|
649
|
+
this.streams.delete(closed);
|
|
650
|
+
}
|
|
651
|
+
);
|
|
652
|
+
if (this.closed) {
|
|
653
|
+
stream.close();
|
|
654
|
+
} else {
|
|
655
|
+
this.streams.add(stream);
|
|
656
|
+
}
|
|
657
|
+
return stream;
|
|
658
|
+
}
|
|
659
|
+
/** Leaves the subscriptions joined with the given name. */
|
|
660
|
+
leave(name) {
|
|
661
|
+
this.leaveSubscription(name, false);
|
|
662
|
+
this.leaveSubscription(name, true);
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Leaves exactly one subscription by its name and kind.
|
|
666
|
+
*
|
|
667
|
+
* @internal
|
|
668
|
+
*/
|
|
669
|
+
leaveSubscription(name, isPrivate) {
|
|
670
|
+
const key = (isPrivate ? "private:" : "public:") + name;
|
|
671
|
+
const subscription = this.channels.get(key);
|
|
672
|
+
if (!subscription) {
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
subscription.channel.detach();
|
|
676
|
+
this.channels.delete(key);
|
|
677
|
+
const topic = subscription.channel.name;
|
|
678
|
+
if (![...this.channels.values()].some(({ channel }) => channel.name === topic)) {
|
|
679
|
+
this.topics.delete(topic);
|
|
680
|
+
this.deniedTopics.delete(topic);
|
|
681
|
+
const group = this.cachedTokens.get(topic);
|
|
682
|
+
this.cachedTokens.delete(topic);
|
|
683
|
+
if (group && group.length > 1) {
|
|
684
|
+
for (const [other, tokens] of this.cachedTokens) {
|
|
685
|
+
if (tokens === group) {
|
|
686
|
+
this.cachedTokens.delete(other);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
this.updateEvents();
|
|
692
|
+
this.scheduleConnection();
|
|
693
|
+
}
|
|
694
|
+
/** Retries authorization for one denied private channel or all denied private channels. */
|
|
695
|
+
reauthorize(name) {
|
|
696
|
+
if (name !== void 0) {
|
|
697
|
+
if (!this.deniedTopics.delete(privatePrefix + name)) {
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
} else if (this.deniedTopics.size > 0) {
|
|
701
|
+
this.deniedTopics.clear();
|
|
702
|
+
} else {
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
this.scheduleConnection();
|
|
706
|
+
}
|
|
707
|
+
/** Registers a client event listener and returns a function that removes it. */
|
|
708
|
+
on(event, listener) {
|
|
709
|
+
const listeners = this.listeners[event];
|
|
710
|
+
if (!this.closed) {
|
|
711
|
+
listeners.add(listener);
|
|
712
|
+
}
|
|
713
|
+
return () => {
|
|
714
|
+
listeners.delete(listener);
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Registers a connector observer for deliberate connection changes and terminal preparation states.
|
|
719
|
+
*
|
|
720
|
+
* @internal
|
|
721
|
+
*/
|
|
722
|
+
onConnectionPreparation(listener) {
|
|
723
|
+
if (!this.closed) {
|
|
724
|
+
this.preparationListeners.add(listener);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/** Returns the server-issued ID used for Laravel sender exclusion. */
|
|
728
|
+
socketId() {
|
|
729
|
+
return this.connectionId;
|
|
730
|
+
}
|
|
731
|
+
/** Returns a fresh snapshot of shared connection activity and active subscriptions. */
|
|
732
|
+
stats() {
|
|
733
|
+
return {
|
|
734
|
+
...this.counts,
|
|
735
|
+
connected: this.transport.connected,
|
|
736
|
+
channels: this.channels.size,
|
|
737
|
+
streams: this.streams.size,
|
|
738
|
+
lastEventId: this.transport.replayCursor,
|
|
739
|
+
connectionId: this.connectionId,
|
|
740
|
+
lastEventAt: this.lastEventAt
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
/** Closes channels and streams and cancels outstanding connection attempts. */
|
|
744
|
+
close() {
|
|
745
|
+
this.closed = true;
|
|
746
|
+
this.transport.close();
|
|
747
|
+
for (const stream of this.streams) {
|
|
748
|
+
stream.close();
|
|
749
|
+
}
|
|
750
|
+
for (const { channel } of this.channels.values()) {
|
|
751
|
+
channel.detach();
|
|
752
|
+
}
|
|
753
|
+
this.channels.clear();
|
|
754
|
+
this.topics.clear();
|
|
755
|
+
this.attemptSubscriptions = [];
|
|
756
|
+
for (const listeners of Object.values(this.listeners)) {
|
|
757
|
+
listeners.clear();
|
|
758
|
+
}
|
|
759
|
+
this.cachedTokens.clear();
|
|
760
|
+
this.deniedTopics.clear();
|
|
761
|
+
this.updateEvents();
|
|
762
|
+
this.reportPreparation("disconnected");
|
|
763
|
+
this.preparationListeners.clear();
|
|
764
|
+
}
|
|
765
|
+
/** Creates a subscription or returns the existing channel for the same name and kind. */
|
|
766
|
+
join(key, topic) {
|
|
767
|
+
const existing = this.channels.get(key);
|
|
768
|
+
if (existing) {
|
|
769
|
+
return existing.channel;
|
|
770
|
+
}
|
|
771
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
772
|
+
const channel = new Channel(topic, this.options.namespace ?? "App.Events", listeners, () => this.updateEvents());
|
|
773
|
+
if (!this.closed) {
|
|
774
|
+
const joinedTopic = this.topics.get(topic) ?? { pending: true };
|
|
775
|
+
this.topics.set(topic, joinedTopic);
|
|
776
|
+
this.channels.set(key, { channel, listeners, topic: joinedTopic });
|
|
777
|
+
this.scheduleConnection();
|
|
778
|
+
}
|
|
779
|
+
return channel;
|
|
780
|
+
}
|
|
781
|
+
/** Applies channel changes together when the current tick ends. */
|
|
782
|
+
scheduleConnection() {
|
|
783
|
+
this.transport.cancelPending();
|
|
784
|
+
if (this.channels.size === 0) {
|
|
785
|
+
this.attemptSubscriptions = [];
|
|
786
|
+
this.transport.close();
|
|
787
|
+
this.reportPreparation("disconnected");
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
if (this.connectionQueued) {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
this.connectionQueued = true;
|
|
794
|
+
queueMicrotask(() => {
|
|
795
|
+
this.connectionQueued = false;
|
|
796
|
+
if (!this.closed && this.channels.size > 0) {
|
|
797
|
+
this.transport.connect();
|
|
798
|
+
this.reportPreparation("connecting");
|
|
799
|
+
}
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
/** Synchronizes the stream's named events with the active channel listeners. */
|
|
803
|
+
updateEvents() {
|
|
804
|
+
const events = /* @__PURE__ */ new Set();
|
|
805
|
+
for (const { listeners } of this.channels.values()) {
|
|
806
|
+
for (const event of listeners.keys()) {
|
|
807
|
+
events.add(event);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
this.transport.setEvents(events);
|
|
811
|
+
}
|
|
812
|
+
/** Builds the stream URL for the current subscriptions. */
|
|
813
|
+
async connectionUrl(signal, lastEventId) {
|
|
814
|
+
const requested = [...this.topics.keys()];
|
|
815
|
+
const privateTopics = requested.filter((topic) => topic.startsWith(privatePrefix));
|
|
816
|
+
await this.authorize(privateTopics.filter((topic) => !this.deniedTopics.has(topic)), signal);
|
|
817
|
+
signal.throwIfAborted();
|
|
818
|
+
const topics = requested.filter((topic) => !this.deniedTopics.has(topic));
|
|
819
|
+
if (topics.length === 0) {
|
|
820
|
+
this.reportPreparation("disconnected");
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
const url = new URL(this.options.url, globalThis.location?.href);
|
|
824
|
+
url.searchParams.set("topics", topics.join(","));
|
|
825
|
+
url.searchParams.delete("token");
|
|
826
|
+
const tokens = /* @__PURE__ */ new Set();
|
|
827
|
+
for (const topic of topics) {
|
|
828
|
+
for (const { token } of this.cachedTokens.get(topic) ?? []) {
|
|
829
|
+
tokens.add(token);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (tokens.size > 0) {
|
|
833
|
+
url.searchParams.set("token", [...tokens].join(","));
|
|
834
|
+
}
|
|
835
|
+
const largestAttempt = new URL(url);
|
|
836
|
+
largestAttempt.searchParams.set("connection", reservedConnectionId);
|
|
837
|
+
largestAttempt.searchParams.set("lastEventId", reservedCursor);
|
|
838
|
+
largestAttempt.searchParams.set("fresh", topics.join(","));
|
|
839
|
+
if (new TextEncoder().encode(largestAttempt.pathname + largestAttempt.search).length > requestTargetBudget) {
|
|
840
|
+
this.reportPreparation("failed");
|
|
841
|
+
this.emit("error", new Error(
|
|
842
|
+
`Murmur subscription URL exceeds the request budget with ${privateTopics.length} private channels requested. Use a multi-topic token for large private subscriptions or reduce the topic list.`
|
|
843
|
+
));
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
url.searchParams.delete("lastEventId");
|
|
847
|
+
if (lastEventId !== void 0) {
|
|
848
|
+
url.searchParams.set("lastEventId", lastEventId);
|
|
849
|
+
}
|
|
850
|
+
url.searchParams.delete("connection");
|
|
851
|
+
if (this.connectionId !== void 0) {
|
|
852
|
+
url.searchParams.set("connection", this.connectionId);
|
|
853
|
+
}
|
|
854
|
+
const subscriptions = [...this.channels.values()].filter(({ channel }) => !this.deniedTopics.has(channel.name));
|
|
855
|
+
url.searchParams.delete("fresh");
|
|
856
|
+
if (lastEventId !== void 0) {
|
|
857
|
+
const fresh = topics.filter((topic) => this.topics.get(topic)?.pending);
|
|
858
|
+
if (fresh.length > 0) {
|
|
859
|
+
url.searchParams.set("fresh", fresh.join(","));
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
this.attemptSubscriptions = subscriptions;
|
|
863
|
+
return url.href;
|
|
864
|
+
}
|
|
865
|
+
/** Reports a shared connection preparation state to the connector. */
|
|
866
|
+
reportPreparation(state) {
|
|
867
|
+
for (const listener of this.preparationListeners) {
|
|
868
|
+
invokeListener(listener, state);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
/** Reuses valid credentials and authorizes missing private topics. */
|
|
872
|
+
async authorize(topics, signal) {
|
|
873
|
+
const minimumExpiry = Date.now() / 1e3 + this.tokenRefreshMarginSeconds;
|
|
874
|
+
const missing = topics.filter(
|
|
875
|
+
(topic) => !this.cachedTokens.get(topic)?.every(({ expires_at }) => expires_at > minimumExpiry)
|
|
876
|
+
);
|
|
877
|
+
if (missing.length === 0) {
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
const { authorizer } = this.options;
|
|
881
|
+
if (authorizer) {
|
|
882
|
+
await this.authorizeTopics(topics, signal, () => authorizer([...topics], signal), true);
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const remaining = missing.values();
|
|
886
|
+
await Promise.all(Array.from({ length: Math.min(authorizationConcurrency, missing.length) }, async () => {
|
|
887
|
+
for (const topic of remaining) {
|
|
888
|
+
signal.throwIfAborted();
|
|
889
|
+
await this.authorizeTopics([topic], signal, () => this.requestToken(topic, signal), false);
|
|
890
|
+
}
|
|
891
|
+
}));
|
|
892
|
+
}
|
|
893
|
+
/** Records valid tokens or marks only the requested private topics denied. */
|
|
894
|
+
async authorizeTopics(topics, signal, request, acceptsArray) {
|
|
895
|
+
this.counts.tokenRequests++;
|
|
896
|
+
const startedAt = Date.now() / 1e3;
|
|
897
|
+
let tokens;
|
|
898
|
+
try {
|
|
899
|
+
const body = await request();
|
|
900
|
+
signal.throwIfAborted();
|
|
901
|
+
const result = acceptsArray && Array.isArray(body) ? [...body] : [body];
|
|
902
|
+
if (!result.every(isAuthorizationToken)) {
|
|
903
|
+
throw new Error("Invalid Murmur authorization response");
|
|
904
|
+
}
|
|
905
|
+
tokens = result;
|
|
906
|
+
} catch (error) {
|
|
907
|
+
signal.throwIfAborted();
|
|
908
|
+
this.counts.tokenFailures++;
|
|
909
|
+
if (!acceptsArray && !(error instanceof AuthorizationResponseError) || error === null || typeof error !== "object" || !("status" in error) || typeof error.status !== "number") {
|
|
910
|
+
throw error;
|
|
911
|
+
}
|
|
912
|
+
if (!(error.status >= 400 && error.status < 500) || [408, 425, 429].includes(error.status)) {
|
|
913
|
+
const header = error instanceof AuthorizationResponseError ? error.retryAfter : error instanceof Response ? error.headers.get("Retry-After") : null;
|
|
914
|
+
const delay = retryAfterDelay(header);
|
|
915
|
+
throw delay > 0 ? new RetryAfterError(delay, error) : error;
|
|
916
|
+
}
|
|
917
|
+
const minimumExpiry = Math.max(startedAt, Date.now() / 1e3);
|
|
918
|
+
const denied = acceptsArray ? topics.filter(
|
|
919
|
+
(topic) => !this.cachedTokens.get(topic)?.every(({ expires_at }) => expires_at > minimumExpiry)
|
|
920
|
+
) : topics;
|
|
921
|
+
this.deny(denied, error.status);
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
const explicitCoverage = acceptsArray && tokens.some(({ channels }) => channels !== void 0);
|
|
925
|
+
const uncovered = [];
|
|
926
|
+
for (const topic of topics) {
|
|
927
|
+
const covering = explicitCoverage ? tokens.filter(({ channels }) => channels === void 0 || channels.includes(topic)) : tokens;
|
|
928
|
+
if (covering.length > 0) {
|
|
929
|
+
this.cachedTokens.set(topic, covering);
|
|
930
|
+
} else {
|
|
931
|
+
uncovered.push(topic);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
this.deny(uncovered, 403);
|
|
935
|
+
}
|
|
936
|
+
/** Removes uncovered topics from the connection and notifies their listeners. */
|
|
937
|
+
deny(topics, status) {
|
|
938
|
+
const denied = new Set(topics);
|
|
939
|
+
for (const topic of denied) {
|
|
940
|
+
this.deniedTopics.add(topic);
|
|
941
|
+
this.cachedTokens.delete(topic);
|
|
942
|
+
}
|
|
943
|
+
const subscriptions = [...this.channels.values()].filter(({ channel }) => denied.has(channel.name));
|
|
944
|
+
for (const { channel } of subscriptions) {
|
|
945
|
+
channel.authorizationDenied(status);
|
|
946
|
+
}
|
|
947
|
+
for (const topic of denied) {
|
|
948
|
+
this.emit("unauthorized", status, topic.slice(privatePrefix.length));
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
/** Refreshes credentials on exponentially spaced pre-open failures that could indicate rejection. */
|
|
952
|
+
refreshAfterPreOpenError(url, status) {
|
|
953
|
+
if (status !== void 0 && status !== 401 && status !== 403) {
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
const sent = new URL(url).searchParams.get("token");
|
|
957
|
+
if (sent === null) {
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
this.preOpenCredentialFailures++;
|
|
961
|
+
const firstKnownRejection = this.preOpenCredentialFailures === 1 && status !== void 0;
|
|
962
|
+
if (!firstKnownRejection && this.preOpenCredentialFailures !== this.nextCredentialRefresh) {
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
this.nextCredentialRefresh *= 2;
|
|
966
|
+
const rejected = new Set(sent.split(","));
|
|
967
|
+
for (const [topic, tokens] of this.cachedTokens) {
|
|
968
|
+
if (tokens.some(({ token }) => rejected.has(token))) {
|
|
969
|
+
this.cachedTokens.delete(topic);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/** Requests an authorization response from the built-in endpoint. */
|
|
974
|
+
async requestToken(topic, signal) {
|
|
975
|
+
const { auth, authEndpoint } = this.options;
|
|
976
|
+
const supplied = typeof auth?.headers === "function" ? await auth.headers() : auth?.headers;
|
|
977
|
+
signal.throwIfAborted();
|
|
978
|
+
const headers = supplied === void 0 ? void 0 : new Headers(supplied);
|
|
979
|
+
const defaults = {
|
|
980
|
+
Accept: "application/json",
|
|
981
|
+
"Content-Type": "application/json"
|
|
982
|
+
};
|
|
983
|
+
if (auth?.credentials !== "omit" && !headers?.has("X-XSRF-TOKEN") && typeof document !== "undefined") {
|
|
984
|
+
const xsrf = document.cookie.split(";").map((cookie) => cookie.trim()).find((cookie) => cookie.startsWith("XSRF-TOKEN="));
|
|
985
|
+
if (xsrf !== void 0) {
|
|
986
|
+
defaults["X-XSRF-TOKEN"] = decodeURIComponent(xsrf.slice("XSRF-TOKEN=".length));
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
if (headers) {
|
|
990
|
+
for (const [name, value] of Object.entries(defaults)) {
|
|
991
|
+
if (!headers.has(name)) {
|
|
992
|
+
headers.set(name, value);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const fetch = this.options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
997
|
+
const response = await fetch(authEndpoint ?? "/broadcasting/auth", {
|
|
998
|
+
method: "POST",
|
|
999
|
+
credentials: auth?.credentials ?? "include",
|
|
1000
|
+
headers: headers ?? defaults,
|
|
1001
|
+
body: JSON.stringify({ channel_name: topic, socket_id: this.connectionId }),
|
|
1002
|
+
signal
|
|
1003
|
+
});
|
|
1004
|
+
if (!response.ok) {
|
|
1005
|
+
throw new AuthorizationResponseError(response.status, response.headers.get("Retry-After"));
|
|
1006
|
+
}
|
|
1007
|
+
return response.json();
|
|
1008
|
+
}
|
|
1009
|
+
/** Dispatches a stream event to its channel or emits a gap notification. */
|
|
1010
|
+
receive(event, data) {
|
|
1011
|
+
if (event === "murmur.connected") {
|
|
1012
|
+
this.receiveConnection(data);
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
if (event === "murmur.attached") {
|
|
1016
|
+
this.receiveAttachment();
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (event === "murmur.gap") {
|
|
1020
|
+
this.counts.gaps++;
|
|
1021
|
+
this.emit("gap");
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
const envelope = parseEnvelope(data);
|
|
1025
|
+
if (envelope === void 0) {
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
this.counts.events++;
|
|
1029
|
+
this.lastEventAt = Date.now();
|
|
1030
|
+
const { topic, data: payload } = envelope;
|
|
1031
|
+
const subscriptions = [this.channels.get("public:" + topic)];
|
|
1032
|
+
if (topic.startsWith(privatePrefix)) {
|
|
1033
|
+
subscriptions.push(this.channels.get("private:" + topic.slice(privatePrefix.length)));
|
|
1034
|
+
}
|
|
1035
|
+
for (const subscription of subscriptions) {
|
|
1036
|
+
for (const callback of subscription?.listeners.get(event) ?? []) {
|
|
1037
|
+
invokeListener(callback, payload);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/** Acknowledges only the joins included on the connection that attached. */
|
|
1042
|
+
receiveAttachment() {
|
|
1043
|
+
this.preOpenCredentialFailures = 0;
|
|
1044
|
+
this.nextCredentialRefresh = 2;
|
|
1045
|
+
const attached = this.attemptSubscriptions;
|
|
1046
|
+
this.attemptSubscriptions = [];
|
|
1047
|
+
for (const { topic } of attached) {
|
|
1048
|
+
topic.pending = false;
|
|
1049
|
+
}
|
|
1050
|
+
for (const { channel } of attached) {
|
|
1051
|
+
channel.attachmentConfirmed();
|
|
1052
|
+
}
|
|
1053
|
+
this.emit("attached");
|
|
1054
|
+
}
|
|
1055
|
+
/** Stores a valid server-issued connection ID and reports an unexpected protocol. */
|
|
1056
|
+
receiveConnection(data) {
|
|
1057
|
+
let announcement;
|
|
1058
|
+
try {
|
|
1059
|
+
announcement = JSON.parse(data);
|
|
1060
|
+
} catch {
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (announcement === null || typeof announcement !== "object") {
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
if (!("connection_id" in announcement) || typeof announcement.connection_id !== "string" || announcement.connection_id.length !== 32 || /[^a-f0-9]/.test(announcement.connection_id) || !("protocol" in announcement) || typeof announcement.protocol !== "string" && !Number.isFinite(announcement.protocol)) {
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
this.connectionId = announcement.connection_id;
|
|
1070
|
+
if (announcement.protocol !== 1 && !this.protocolMismatchReported) {
|
|
1071
|
+
this.protocolMismatchReported = true;
|
|
1072
|
+
this.emit("error", new Error(`Murmur server announced protocol ${JSON.stringify(announcement.protocol)}; expected 1.`));
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
/** Notifies listeners of a client event. */
|
|
1076
|
+
emit(event, ...args) {
|
|
1077
|
+
for (const listener of this.listeners[event]) {
|
|
1078
|
+
invokeListener(listener, ...args);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
export {
|
|
1084
|
+
invokeListener,
|
|
1085
|
+
Murmur
|
|
1086
|
+
};
|