@supabase/phoenix 0.1.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 (49) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +122 -0
  3. package/assets/js/phoenix/ajax.js +116 -0
  4. package/assets/js/phoenix/channel.js +331 -0
  5. package/assets/js/phoenix/constants.js +35 -0
  6. package/assets/js/phoenix/index.js +212 -0
  7. package/assets/js/phoenix/longpoll.js +192 -0
  8. package/assets/js/phoenix/presence.js +208 -0
  9. package/assets/js/phoenix/push.js +134 -0
  10. package/assets/js/phoenix/serializer.js +133 -0
  11. package/assets/js/phoenix/socket.js +747 -0
  12. package/assets/js/phoenix/timer.js +48 -0
  13. package/assets/js/phoenix/types.js +184 -0
  14. package/assets/js/phoenix/utils.js +16 -0
  15. package/package.json +58 -0
  16. package/priv/static/favicon.ico +0 -0
  17. package/priv/static/phoenix-orange.png +0 -0
  18. package/priv/static/phoenix.cjs.js +1812 -0
  19. package/priv/static/phoenix.cjs.js.map +7 -0
  20. package/priv/static/phoenix.js +1834 -0
  21. package/priv/static/phoenix.min.js +2 -0
  22. package/priv/static/phoenix.mjs +1789 -0
  23. package/priv/static/phoenix.mjs.map +7 -0
  24. package/priv/static/phoenix.png +0 -0
  25. package/priv/static/types/ajax.d.ts +10 -0
  26. package/priv/static/types/ajax.d.ts.map +1 -0
  27. package/priv/static/types/channel.d.ts +167 -0
  28. package/priv/static/types/channel.d.ts.map +1 -0
  29. package/priv/static/types/constants.d.ts +36 -0
  30. package/priv/static/types/constants.d.ts.map +1 -0
  31. package/priv/static/types/index.d.ts +10 -0
  32. package/priv/static/types/index.d.ts.map +1 -0
  33. package/priv/static/types/longpoll.d.ts +29 -0
  34. package/priv/static/types/longpoll.d.ts.map +1 -0
  35. package/priv/static/types/presence.d.ts +107 -0
  36. package/priv/static/types/presence.d.ts.map +1 -0
  37. package/priv/static/types/push.d.ts +70 -0
  38. package/priv/static/types/push.d.ts.map +1 -0
  39. package/priv/static/types/serializer.d.ts +74 -0
  40. package/priv/static/types/serializer.d.ts.map +1 -0
  41. package/priv/static/types/socket.d.ts +284 -0
  42. package/priv/static/types/socket.d.ts.map +1 -0
  43. package/priv/static/types/timer.d.ts +36 -0
  44. package/priv/static/types/timer.d.ts.map +1 -0
  45. package/priv/static/types/types.d.ts +280 -0
  46. package/priv/static/types/types.d.ts.map +1 -0
  47. package/priv/static/types/utils.d.ts +2 -0
  48. package/priv/static/types/utils.d.ts.map +1 -0
  49. package/tsconfig.json +20 -0
@@ -0,0 +1,1789 @@
1
+ // js/phoenix/utils.js
2
+ var closure = (value) => {
3
+ if (typeof value === "function") {
4
+ return (
5
+ /** @type {() => T} */
6
+ value
7
+ );
8
+ } else {
9
+ let closure2 = function() {
10
+ return value;
11
+ };
12
+ return closure2;
13
+ }
14
+ };
15
+
16
+ // js/phoenix/constants.js
17
+ var globalSelf = typeof self !== "undefined" ? self : null;
18
+ var phxWindow = typeof window !== "undefined" ? window : null;
19
+ var global = globalSelf || phxWindow || globalThis;
20
+ var DEFAULT_VSN = "2.0.0";
21
+ var DEFAULT_TIMEOUT = 1e4;
22
+ var WS_CLOSE_NORMAL = 1e3;
23
+ var SOCKET_STATES = (
24
+ /** @type {const} */
25
+ { connecting: 0, open: 1, closing: 2, closed: 3 }
26
+ );
27
+ var CHANNEL_STATES = (
28
+ /** @type {const} */
29
+ {
30
+ closed: "closed",
31
+ errored: "errored",
32
+ joined: "joined",
33
+ joining: "joining",
34
+ leaving: "leaving"
35
+ }
36
+ );
37
+ var CHANNEL_EVENTS = (
38
+ /** @type {const} */
39
+ {
40
+ close: "phx_close",
41
+ error: "phx_error",
42
+ join: "phx_join",
43
+ reply: "phx_reply",
44
+ leave: "phx_leave"
45
+ }
46
+ );
47
+ var TRANSPORTS = (
48
+ /** @type {const} */
49
+ {
50
+ longpoll: "longpoll",
51
+ websocket: "websocket"
52
+ }
53
+ );
54
+ var XHR_STATES = (
55
+ /** @type {const} */
56
+ {
57
+ complete: 4
58
+ }
59
+ );
60
+ var AUTH_TOKEN_PREFIX = "base64url.bearer.phx.";
61
+
62
+ // js/phoenix/push.js
63
+ var Push = class {
64
+ /**
65
+ * Initializes the Push
66
+ * @param {Channel} channel - The Channel
67
+ * @param {ChannelEvent} event - The event, for example `"phx_join"`
68
+ * @param {() => Record<string, unknown>} payload - The payload, for example `{user_id: 123}`
69
+ * @param {number} timeout - The push timeout in milliseconds
70
+ */
71
+ constructor(channel, event, payload, timeout) {
72
+ this.channel = channel;
73
+ this.event = event;
74
+ this.payload = payload || function() {
75
+ return {};
76
+ };
77
+ this.receivedResp = null;
78
+ this.timeout = timeout;
79
+ this.timeoutTimer = null;
80
+ this.recHooks = [];
81
+ this.sent = false;
82
+ this.ref = void 0;
83
+ }
84
+ /**
85
+ *
86
+ * @param {number} timeout
87
+ */
88
+ resend(timeout) {
89
+ this.timeout = timeout;
90
+ this.reset();
91
+ this.send();
92
+ }
93
+ /**
94
+ *
95
+ */
96
+ send() {
97
+ if (this.hasReceived("timeout")) {
98
+ return;
99
+ }
100
+ this.startTimeout();
101
+ this.sent = true;
102
+ this.channel.socket.push({
103
+ topic: this.channel.topic,
104
+ event: this.event,
105
+ payload: this.payload(),
106
+ ref: this.ref,
107
+ join_ref: this.channel.joinRef()
108
+ });
109
+ }
110
+ /**
111
+ *
112
+ * @param {string} status
113
+ * @param {(response: any) => void} callback
114
+ */
115
+ receive(status, callback) {
116
+ if (this.hasReceived(status)) {
117
+ callback(this.receivedResp.response);
118
+ }
119
+ this.recHooks.push({ status, callback });
120
+ return this;
121
+ }
122
+ reset() {
123
+ this.cancelRefEvent();
124
+ this.ref = null;
125
+ this.refEvent = null;
126
+ this.receivedResp = null;
127
+ this.sent = false;
128
+ }
129
+ destroy() {
130
+ this.cancelRefEvent();
131
+ this.cancelTimeout();
132
+ }
133
+ /**
134
+ * @private
135
+ */
136
+ matchReceive({ status, response, _ref }) {
137
+ this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response));
138
+ }
139
+ /**
140
+ * @private
141
+ */
142
+ cancelRefEvent() {
143
+ if (!this.refEvent) {
144
+ return;
145
+ }
146
+ this.channel.off(this.refEvent);
147
+ }
148
+ cancelTimeout() {
149
+ clearTimeout(this.timeoutTimer);
150
+ this.timeoutTimer = null;
151
+ }
152
+ startTimeout() {
153
+ if (this.timeoutTimer) {
154
+ this.cancelTimeout();
155
+ }
156
+ this.ref = this.channel.socket.makeRef();
157
+ this.refEvent = this.channel.replyEventName(this.ref);
158
+ this.channel.on(this.refEvent, (payload) => {
159
+ this.cancelRefEvent();
160
+ this.cancelTimeout();
161
+ this.receivedResp = payload;
162
+ this.matchReceive(payload);
163
+ });
164
+ this.timeoutTimer = setTimeout(() => {
165
+ this.trigger("timeout", {});
166
+ }, this.timeout);
167
+ }
168
+ /**
169
+ * @private
170
+ */
171
+ hasReceived(status) {
172
+ return this.receivedResp && this.receivedResp.status === status;
173
+ }
174
+ trigger(status, response) {
175
+ this.channel.trigger(this.refEvent, { status, response });
176
+ }
177
+ };
178
+
179
+ // js/phoenix/timer.js
180
+ var Timer = class {
181
+ /**
182
+ * @param {() => void} callback
183
+ * @param {(tries: number) => number} timerCalc
184
+ */
185
+ constructor(callback, timerCalc) {
186
+ this.callback = callback;
187
+ this.timerCalc = timerCalc;
188
+ this.timer = void 0;
189
+ this.tries = 0;
190
+ }
191
+ reset() {
192
+ this.tries = 0;
193
+ clearTimeout(this.timer);
194
+ }
195
+ /**
196
+ * Cancels any previous scheduleTimeout and schedules callback
197
+ */
198
+ scheduleTimeout() {
199
+ clearTimeout(this.timer);
200
+ this.timer = setTimeout(() => {
201
+ this.tries = this.tries + 1;
202
+ this.callback();
203
+ }, this.timerCalc(this.tries + 1));
204
+ }
205
+ };
206
+
207
+ // js/phoenix/channel.js
208
+ var Channel = class {
209
+ /**
210
+ * @param {string} topic
211
+ * @param {Params | (() => Params)} params
212
+ * @param {Socket} socket
213
+ */
214
+ constructor(topic, params, socket) {
215
+ this.state = CHANNEL_STATES.closed;
216
+ this.topic = topic;
217
+ this.params = closure(params || {});
218
+ this.socket = socket;
219
+ this.bindings = [];
220
+ this.bindingRef = 0;
221
+ this.timeout = this.socket.timeout;
222
+ this.joinedOnce = false;
223
+ this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
224
+ this.pushBuffer = [];
225
+ this.stateChangeRefs = [];
226
+ this.rejoinTimer = new Timer(() => {
227
+ if (this.socket.isConnected()) {
228
+ this.rejoin();
229
+ }
230
+ }, this.socket.rejoinAfterMs);
231
+ this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset()));
232
+ this.stateChangeRefs.push(
233
+ this.socket.onOpen(() => {
234
+ this.rejoinTimer.reset();
235
+ if (this.isErrored()) {
236
+ this.rejoin();
237
+ }
238
+ })
239
+ );
240
+ this.joinPush.receive("ok", () => {
241
+ this.state = CHANNEL_STATES.joined;
242
+ this.rejoinTimer.reset();
243
+ this.pushBuffer.forEach((pushEvent) => pushEvent.send());
244
+ this.pushBuffer = [];
245
+ });
246
+ this.joinPush.receive("error", (reason) => {
247
+ this.state = CHANNEL_STATES.errored;
248
+ if (this.socket.hasLogger()) this.socket.log("channel", `error ${this.topic}`, reason);
249
+ if (this.socket.isConnected()) {
250
+ this.rejoinTimer.scheduleTimeout();
251
+ }
252
+ });
253
+ this.onClose(() => {
254
+ this.rejoinTimer.reset();
255
+ if (this.socket.hasLogger()) this.socket.log("channel", `close ${this.topic}`);
256
+ this.state = CHANNEL_STATES.closed;
257
+ this.socket.remove(this);
258
+ });
259
+ this.onError((reason) => {
260
+ if (this.socket.hasLogger()) this.socket.log("channel", `error ${this.topic}`, reason);
261
+ if (this.isJoining()) {
262
+ this.joinPush.reset();
263
+ }
264
+ this.state = CHANNEL_STATES.errored;
265
+ if (this.socket.isConnected()) {
266
+ this.rejoinTimer.scheduleTimeout();
267
+ }
268
+ });
269
+ this.joinPush.receive("timeout", () => {
270
+ if (this.socket.hasLogger()) this.socket.log("channel", `timeout ${this.topic}`, this.joinPush.timeout);
271
+ let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout);
272
+ leavePush.send();
273
+ this.state = CHANNEL_STATES.errored;
274
+ this.joinPush.reset();
275
+ if (this.socket.isConnected()) {
276
+ this.rejoinTimer.scheduleTimeout();
277
+ }
278
+ });
279
+ this.on(CHANNEL_EVENTS.reply, (payload, ref) => {
280
+ this.trigger(this.replyEventName(ref), payload);
281
+ });
282
+ }
283
+ /**
284
+ * Join the channel
285
+ * @param {number} timeout
286
+ * @returns {Push}
287
+ */
288
+ join(timeout = this.timeout) {
289
+ if (this.joinedOnce) {
290
+ throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");
291
+ } else {
292
+ this.timeout = timeout;
293
+ this.joinedOnce = true;
294
+ this.rejoin();
295
+ return this.joinPush;
296
+ }
297
+ }
298
+ /**
299
+ * Teardown the channel.
300
+ *
301
+ * Destroys and stops related timers.
302
+ */
303
+ teardown() {
304
+ this.pushBuffer.forEach((push) => push.destroy());
305
+ this.pushBuffer = [];
306
+ this.rejoinTimer.reset();
307
+ this.joinPush.destroy();
308
+ this.state = CHANNEL_STATES.closed;
309
+ this.bindings = {};
310
+ }
311
+ /**
312
+ * Hook into channel close
313
+ * @param {ChannelBindingCallback} callback
314
+ */
315
+ onClose(callback) {
316
+ this.on(CHANNEL_EVENTS.close, callback);
317
+ }
318
+ /**
319
+ * Hook into channel errors
320
+ * @param {ChannelOnErrorCallback} callback
321
+ * @return {number}
322
+ */
323
+ onError(callback) {
324
+ return this.on(CHANNEL_EVENTS.error, (reason) => callback(reason));
325
+ }
326
+ /**
327
+ * Subscribes on channel events
328
+ *
329
+ * Subscription returns a ref counter, which can be used later to
330
+ * unsubscribe the exact event listener
331
+ *
332
+ * @example
333
+ * const ref1 = channel.on("event", do_stuff)
334
+ * const ref2 = channel.on("event", do_other_stuff)
335
+ * channel.off("event", ref1)
336
+ * // Since unsubscription, do_stuff won't fire,
337
+ * // while do_other_stuff will keep firing on the "event"
338
+ *
339
+ * @param {string} event
340
+ * @param {ChannelBindingCallback} callback
341
+ * @returns {number} ref
342
+ */
343
+ on(event, callback) {
344
+ let ref = this.bindingRef++;
345
+ this.bindings.push({ event, ref, callback });
346
+ return ref;
347
+ }
348
+ /**
349
+ * Unsubscribes off of channel events
350
+ *
351
+ * Use the ref returned from a channel.on() to unsubscribe one
352
+ * handler, or pass nothing for the ref to unsubscribe all
353
+ * handlers for the given event.
354
+ *
355
+ * @example
356
+ * // Unsubscribe the do_stuff handler
357
+ * const ref1 = channel.on("event", do_stuff)
358
+ * channel.off("event", ref1)
359
+ *
360
+ * // Unsubscribe all handlers from event
361
+ * channel.off("event")
362
+ *
363
+ * @param {string} event
364
+ * @param {number} [ref]
365
+ */
366
+ off(event, ref) {
367
+ this.bindings = this.bindings.filter((bind) => {
368
+ return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref));
369
+ });
370
+ }
371
+ /**
372
+ * @private
373
+ */
374
+ canPush() {
375
+ return this.socket.isConnected() && this.isJoined();
376
+ }
377
+ /**
378
+ * Sends a message `event` to phoenix with the payload `payload`.
379
+ * Phoenix receives this in the `handle_in(event, payload, socket)`
380
+ * function. if phoenix replies or it times out (default 10000ms),
381
+ * then optionally the reply can be received.
382
+ *
383
+ * @example
384
+ * channel.push("event")
385
+ * .receive("ok", payload => console.log("phoenix replied:", payload))
386
+ * .receive("error", err => console.log("phoenix errored", err))
387
+ * .receive("timeout", () => console.log("timed out pushing"))
388
+ * @param {string} event
389
+ * @param {Object} payload
390
+ * @param {number} [timeout]
391
+ * @returns {Push}
392
+ */
393
+ push(event, payload, timeout = this.timeout) {
394
+ payload = payload || {};
395
+ if (!this.joinedOnce) {
396
+ throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`);
397
+ }
398
+ let pushEvent = new Push(this, event, function() {
399
+ return payload;
400
+ }, timeout);
401
+ if (this.canPush()) {
402
+ pushEvent.send();
403
+ } else {
404
+ pushEvent.startTimeout();
405
+ this.pushBuffer.push(pushEvent);
406
+ }
407
+ return pushEvent;
408
+ }
409
+ /** Leaves the channel
410
+ *
411
+ * Unsubscribes from server events, and
412
+ * instructs channel to terminate on server
413
+ *
414
+ * Triggers onClose() hooks
415
+ *
416
+ * To receive leave acknowledgements, use the `receive`
417
+ * hook to bind to the server ack, ie:
418
+ *
419
+ * @example
420
+ * channel.leave().receive("ok", () => alert("left!") )
421
+ *
422
+ * @param {number} timeout
423
+ * @returns {Push}
424
+ */
425
+ leave(timeout = this.timeout) {
426
+ this.rejoinTimer.reset();
427
+ this.joinPush.cancelTimeout();
428
+ this.state = CHANNEL_STATES.leaving;
429
+ let onClose = () => {
430
+ if (this.socket.hasLogger()) this.socket.log("channel", `leave ${this.topic}`);
431
+ this.trigger(CHANNEL_EVENTS.close, "leave");
432
+ };
433
+ let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout);
434
+ leavePush.receive("ok", () => onClose()).receive("timeout", () => onClose());
435
+ leavePush.send();
436
+ if (!this.canPush()) {
437
+ leavePush.trigger("ok", {});
438
+ }
439
+ return leavePush;
440
+ }
441
+ /**
442
+ * Overridable message hook
443
+ *
444
+ * Receives all events for specialized message handling
445
+ * before dispatching to the channel callbacks.
446
+ *
447
+ * Must return the payload, modified or unmodified
448
+ * @type{ChannelOnMessage}
449
+ */
450
+ onMessage(_event, payload, _ref) {
451
+ return payload;
452
+ }
453
+ /**
454
+ * Overridable filter hook
455
+ *
456
+ * If this function returns `true`, `binding`'s callback will be called.
457
+ *
458
+ * @type{ChannelFilterBindings}
459
+ */
460
+ filterBindings(_binding, _payload, _ref) {
461
+ return true;
462
+ }
463
+ isMember(topic, event, payload, joinRef) {
464
+ if (this.topic !== topic) {
465
+ return false;
466
+ }
467
+ if (joinRef && joinRef !== this.joinRef()) {
468
+ if (this.socket.hasLogger()) this.socket.log("channel", "dropping outdated message", { topic, event, payload, joinRef });
469
+ return false;
470
+ } else {
471
+ return true;
472
+ }
473
+ }
474
+ joinRef() {
475
+ return this.joinPush.ref;
476
+ }
477
+ /**
478
+ * @private
479
+ */
480
+ rejoin(timeout = this.timeout) {
481
+ if (this.isLeaving()) {
482
+ return;
483
+ }
484
+ this.socket.leaveOpenTopic(this.topic);
485
+ this.state = CHANNEL_STATES.joining;
486
+ this.joinPush.resend(timeout);
487
+ }
488
+ /**
489
+ * @param {string} event
490
+ * @param {unknown} [payload]
491
+ * @param {?string} [ref]
492
+ * @param {?string} [joinRef]
493
+ */
494
+ trigger(event, payload, ref, joinRef) {
495
+ let handledPayload = this.onMessage(event, payload, ref, joinRef);
496
+ if (payload && !handledPayload) {
497
+ throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");
498
+ }
499
+ let eventBindings = this.bindings.filter((bind) => bind.event === event && this.filterBindings(bind, payload, ref));
500
+ for (let i = 0; i < eventBindings.length; i++) {
501
+ let bind = eventBindings[i];
502
+ bind.callback(handledPayload, ref, joinRef || this.joinRef());
503
+ }
504
+ }
505
+ /**
506
+ * @param {string} ref
507
+ */
508
+ replyEventName(ref) {
509
+ return `chan_reply_${ref}`;
510
+ }
511
+ isClosed() {
512
+ return this.state === CHANNEL_STATES.closed;
513
+ }
514
+ isErrored() {
515
+ return this.state === CHANNEL_STATES.errored;
516
+ }
517
+ isJoined() {
518
+ return this.state === CHANNEL_STATES.joined;
519
+ }
520
+ isJoining() {
521
+ return this.state === CHANNEL_STATES.joining;
522
+ }
523
+ isLeaving() {
524
+ return this.state === CHANNEL_STATES.leaving;
525
+ }
526
+ };
527
+
528
+ // js/phoenix/ajax.js
529
+ var Ajax = class {
530
+ static request(method, endPoint, headers, body, timeout, ontimeout, callback) {
531
+ if (global.XDomainRequest) {
532
+ let req = new global.XDomainRequest();
533
+ return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);
534
+ } else if (global.XMLHttpRequest) {
535
+ let req = new global.XMLHttpRequest();
536
+ return this.xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback);
537
+ } else if (global.fetch && global.AbortController) {
538
+ return this.fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback);
539
+ } else {
540
+ throw new Error("No suitable XMLHttpRequest implementation found");
541
+ }
542
+ }
543
+ static fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback) {
544
+ let options = {
545
+ method,
546
+ headers,
547
+ body
548
+ };
549
+ let controller = null;
550
+ if (timeout) {
551
+ controller = new AbortController();
552
+ const _timeoutId = setTimeout(() => controller.abort(), timeout);
553
+ options.signal = controller.signal;
554
+ }
555
+ global.fetch(endPoint, options).then((response) => response.text()).then((data) => this.parseJSON(data)).then((data) => callback && callback(data)).catch((err) => {
556
+ if (err.name === "AbortError" && ontimeout) {
557
+ ontimeout();
558
+ } else {
559
+ callback && callback(null);
560
+ }
561
+ });
562
+ return controller;
563
+ }
564
+ static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {
565
+ req.timeout = timeout;
566
+ req.open(method, endPoint);
567
+ req.onload = () => {
568
+ let response = this.parseJSON(req.responseText);
569
+ callback && callback(response);
570
+ };
571
+ if (ontimeout) {
572
+ req.ontimeout = ontimeout;
573
+ }
574
+ req.onprogress = () => {
575
+ };
576
+ req.send(body);
577
+ return req;
578
+ }
579
+ static xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback) {
580
+ req.open(method, endPoint, true);
581
+ req.timeout = timeout;
582
+ for (let [key, value] of Object.entries(headers)) {
583
+ req.setRequestHeader(key, value);
584
+ }
585
+ req.onerror = () => callback && callback(null);
586
+ req.onreadystatechange = () => {
587
+ if (req.readyState === XHR_STATES.complete && callback) {
588
+ let response = this.parseJSON(req.responseText);
589
+ callback(response);
590
+ }
591
+ };
592
+ if (ontimeout) {
593
+ req.ontimeout = ontimeout;
594
+ }
595
+ req.send(body);
596
+ return req;
597
+ }
598
+ static parseJSON(resp) {
599
+ if (!resp || resp === "") {
600
+ return null;
601
+ }
602
+ try {
603
+ return JSON.parse(resp);
604
+ } catch {
605
+ console && console.log("failed to parse JSON response", resp);
606
+ return null;
607
+ }
608
+ }
609
+ static serialize(obj, parentKey) {
610
+ let queryStr = [];
611
+ for (var key in obj) {
612
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) {
613
+ continue;
614
+ }
615
+ let paramKey = parentKey ? `${parentKey}[${key}]` : key;
616
+ let paramVal = obj[key];
617
+ if (typeof paramVal === "object") {
618
+ queryStr.push(this.serialize(paramVal, paramKey));
619
+ } else {
620
+ queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal));
621
+ }
622
+ }
623
+ return queryStr.join("&");
624
+ }
625
+ static appendParams(url, params) {
626
+ if (Object.keys(params).length === 0) {
627
+ return url;
628
+ }
629
+ let prefix = url.match(/\?/) ? "&" : "?";
630
+ return `${url}${prefix}${this.serialize(params)}`;
631
+ }
632
+ };
633
+
634
+ // js/phoenix/longpoll.js
635
+ var arrayBufferToBase64 = (buffer) => {
636
+ let binary = "";
637
+ let bytes = new Uint8Array(buffer);
638
+ let len = bytes.byteLength;
639
+ for (let i = 0; i < len; i++) {
640
+ binary += String.fromCharCode(bytes[i]);
641
+ }
642
+ return btoa(binary);
643
+ };
644
+ var LongPoll = class {
645
+ constructor(endPoint, protocols) {
646
+ if (protocols && protocols.length === 2 && protocols[1].startsWith(AUTH_TOKEN_PREFIX)) {
647
+ this.authToken = atob(protocols[1].slice(AUTH_TOKEN_PREFIX.length));
648
+ }
649
+ this.endPoint = null;
650
+ this.token = null;
651
+ this.skipHeartbeat = true;
652
+ this.reqs = /* @__PURE__ */ new Set();
653
+ this.awaitingBatchAck = false;
654
+ this.currentBatch = null;
655
+ this.currentBatchTimer = null;
656
+ this.batchBuffer = [];
657
+ this.onopen = function() {
658
+ };
659
+ this.onerror = function() {
660
+ };
661
+ this.onmessage = function() {
662
+ };
663
+ this.onclose = function() {
664
+ };
665
+ this.pollEndpoint = this.normalizeEndpoint(endPoint);
666
+ this.readyState = SOCKET_STATES.connecting;
667
+ setTimeout(() => this.poll(), 0);
668
+ }
669
+ normalizeEndpoint(endPoint) {
670
+ return endPoint.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll);
671
+ }
672
+ endpointURL() {
673
+ return Ajax.appendParams(this.pollEndpoint, { token: this.token });
674
+ }
675
+ closeAndRetry(code, reason, wasClean) {
676
+ this.close(code, reason, wasClean);
677
+ this.readyState = SOCKET_STATES.connecting;
678
+ }
679
+ ontimeout() {
680
+ this.onerror("timeout");
681
+ this.closeAndRetry(1005, "timeout", false);
682
+ }
683
+ isActive() {
684
+ return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting;
685
+ }
686
+ poll() {
687
+ const headers = { "Accept": "application/json" };
688
+ if (this.authToken) {
689
+ headers["X-Phoenix-AuthToken"] = this.authToken;
690
+ }
691
+ this.ajax("GET", headers, null, () => this.ontimeout(), (resp) => {
692
+ if (resp) {
693
+ var { status, token, messages } = resp;
694
+ if (status === 410 && this.token !== null) {
695
+ this.onerror(410);
696
+ this.closeAndRetry(3410, "session_gone", false);
697
+ return;
698
+ }
699
+ this.token = token;
700
+ } else {
701
+ status = 0;
702
+ }
703
+ switch (status) {
704
+ case 200:
705
+ messages.forEach((msg) => {
706
+ setTimeout(() => this.onmessage({ data: msg }), 0);
707
+ });
708
+ this.poll();
709
+ break;
710
+ case 204:
711
+ this.poll();
712
+ break;
713
+ case 410:
714
+ this.readyState = SOCKET_STATES.open;
715
+ this.onopen({});
716
+ this.poll();
717
+ break;
718
+ case 403:
719
+ this.onerror(403);
720
+ this.close(1008, "forbidden", false);
721
+ break;
722
+ case 0:
723
+ case 500:
724
+ this.onerror(500);
725
+ this.closeAndRetry(1011, "internal server error", 500);
726
+ break;
727
+ default:
728
+ throw new Error(`unhandled poll status ${status}`);
729
+ }
730
+ });
731
+ }
732
+ // we collect all pushes within the current event loop by
733
+ // setTimeout 0, which optimizes back-to-back procedural
734
+ // pushes against an empty buffer
735
+ send(body) {
736
+ if (typeof body !== "string") {
737
+ body = arrayBufferToBase64(body);
738
+ }
739
+ if (this.currentBatch) {
740
+ this.currentBatch.push(body);
741
+ } else if (this.awaitingBatchAck) {
742
+ this.batchBuffer.push(body);
743
+ } else {
744
+ this.currentBatch = [body];
745
+ this.currentBatchTimer = setTimeout(() => {
746
+ this.batchSend(this.currentBatch);
747
+ this.currentBatch = null;
748
+ }, 0);
749
+ }
750
+ }
751
+ batchSend(messages) {
752
+ this.awaitingBatchAck = true;
753
+ this.ajax("POST", { "Content-Type": "application/x-ndjson" }, messages.join("\n"), () => this.onerror("timeout"), (resp) => {
754
+ this.awaitingBatchAck = false;
755
+ if (!resp || resp.status !== 200) {
756
+ this.onerror(resp && resp.status);
757
+ this.closeAndRetry(1011, "internal server error", false);
758
+ } else if (this.batchBuffer.length > 0) {
759
+ this.batchSend(this.batchBuffer);
760
+ this.batchBuffer = [];
761
+ }
762
+ });
763
+ }
764
+ close(code, reason, wasClean) {
765
+ for (let req of this.reqs) {
766
+ req.abort();
767
+ }
768
+ this.readyState = SOCKET_STATES.closed;
769
+ let opts = Object.assign({ code: 1e3, reason: void 0, wasClean: true }, { code, reason, wasClean });
770
+ this.batchBuffer = [];
771
+ clearTimeout(this.currentBatchTimer);
772
+ this.currentBatchTimer = null;
773
+ if (typeof CloseEvent !== "undefined") {
774
+ this.onclose(new CloseEvent("close", opts));
775
+ } else {
776
+ this.onclose(opts);
777
+ }
778
+ }
779
+ ajax(method, headers, body, onCallerTimeout, callback) {
780
+ let req;
781
+ let ontimeout = () => {
782
+ this.reqs.delete(req);
783
+ onCallerTimeout();
784
+ };
785
+ req = Ajax.request(method, this.endpointURL(), headers, body, this.timeout, ontimeout, (resp) => {
786
+ this.reqs.delete(req);
787
+ if (this.isActive()) {
788
+ callback(resp);
789
+ }
790
+ });
791
+ this.reqs.add(req);
792
+ }
793
+ };
794
+
795
+ // js/phoenix/presence.js
796
+ var Presence = class _Presence {
797
+ /**
798
+ * Initializes the Presence
799
+ * @param {Channel} channel - The Channel
800
+ * @param {PresenceOptions} [opts] - The options, for example `{events: {state: "state", diff: "diff"}}`
801
+ */
802
+ constructor(channel, opts = {}) {
803
+ let events = opts.events || /** @type {PresenceEvents} */
804
+ { state: "presence_state", diff: "presence_diff" };
805
+ this.state = {};
806
+ this.pendingDiffs = [];
807
+ this.channel = channel;
808
+ this.joinRef = null;
809
+ this.caller = {
810
+ onJoin: function() {
811
+ },
812
+ onLeave: function() {
813
+ },
814
+ onSync: function() {
815
+ }
816
+ };
817
+ this.channel.on(events.state, (newState) => {
818
+ let { onJoin, onLeave, onSync } = this.caller;
819
+ this.joinRef = this.channel.joinRef();
820
+ this.state = _Presence.syncState(this.state, newState, onJoin, onLeave);
821
+ this.pendingDiffs.forEach((diff) => {
822
+ this.state = _Presence.syncDiff(this.state, diff, onJoin, onLeave);
823
+ });
824
+ this.pendingDiffs = [];
825
+ onSync();
826
+ });
827
+ this.channel.on(events.diff, (diff) => {
828
+ let { onJoin, onLeave, onSync } = this.caller;
829
+ if (this.inPendingSyncState()) {
830
+ this.pendingDiffs.push(diff);
831
+ } else {
832
+ this.state = _Presence.syncDiff(this.state, diff, onJoin, onLeave);
833
+ onSync();
834
+ }
835
+ });
836
+ }
837
+ /**
838
+ * @param {PresenceOnJoin} callback
839
+ */
840
+ onJoin(callback) {
841
+ this.caller.onJoin = callback;
842
+ }
843
+ /**
844
+ * @param {PresenceOnLeave} callback
845
+ */
846
+ onLeave(callback) {
847
+ this.caller.onLeave = callback;
848
+ }
849
+ /**
850
+ * @param {PresenceOnSync} callback
851
+ */
852
+ onSync(callback) {
853
+ this.caller.onSync = callback;
854
+ }
855
+ /**
856
+ * Returns the array of presences, with selected metadata.
857
+ *
858
+ * @template [T=PresenceState]
859
+ * @param {((key: string, obj: PresenceState) => T)} [by]
860
+ *
861
+ * @returns {T[]}
862
+ */
863
+ list(by) {
864
+ return _Presence.list(this.state, by);
865
+ }
866
+ inPendingSyncState() {
867
+ return !this.joinRef || this.joinRef !== this.channel.joinRef();
868
+ }
869
+ // lower-level public static API
870
+ /**
871
+ * Used to sync the list of presences on the server
872
+ * with the client's state. An optional `onJoin` and `onLeave` callback can
873
+ * be provided to react to changes in the client's local presences across
874
+ * disconnects and reconnects with the server.
875
+ *
876
+ * @param {Record<string, PresenceState>} currentState
877
+ * @param {Record<string, PresenceState>} newState
878
+ * @param {PresenceOnJoin} onJoin
879
+ * @param {PresenceOnLeave} onLeave
880
+ *
881
+ * @returns {Record<string, PresenceState>}
882
+ */
883
+ static syncState(currentState, newState, onJoin, onLeave) {
884
+ let state = this.clone(currentState);
885
+ let joins = {};
886
+ let leaves = {};
887
+ this.map(state, (key, presence) => {
888
+ if (!newState[key]) {
889
+ leaves[key] = presence;
890
+ }
891
+ });
892
+ this.map(newState, (key, newPresence) => {
893
+ let currentPresence = state[key];
894
+ if (currentPresence) {
895
+ let newRefs = newPresence.metas.map((m) => m.phx_ref);
896
+ let curRefs = currentPresence.metas.map((m) => m.phx_ref);
897
+ let joinedMetas = newPresence.metas.filter((m) => curRefs.indexOf(m.phx_ref) < 0);
898
+ let leftMetas = currentPresence.metas.filter((m) => newRefs.indexOf(m.phx_ref) < 0);
899
+ if (joinedMetas.length > 0) {
900
+ joins[key] = newPresence;
901
+ joins[key].metas = joinedMetas;
902
+ }
903
+ if (leftMetas.length > 0) {
904
+ leaves[key] = this.clone(currentPresence);
905
+ leaves[key].metas = leftMetas;
906
+ }
907
+ } else {
908
+ joins[key] = newPresence;
909
+ }
910
+ });
911
+ return this.syncDiff(state, { joins, leaves }, onJoin, onLeave);
912
+ }
913
+ /**
914
+ *
915
+ * Used to sync a diff of presence join and leave
916
+ * events from the server, as they happen. Like `syncState`, `syncDiff`
917
+ * accepts optional `onJoin` and `onLeave` callbacks to react to a user
918
+ * joining or leaving from a device.
919
+ *
920
+ * @param {Record<string, PresenceState>} state
921
+ * @param {PresenceDiff} diff
922
+ * @param {PresenceOnJoin} onJoin
923
+ * @param {PresenceOnLeave} onLeave
924
+ *
925
+ * @returns {Record<string, PresenceState>}
926
+ */
927
+ static syncDiff(state, diff, onJoin, onLeave) {
928
+ let { joins, leaves } = this.clone(diff);
929
+ if (!onJoin) {
930
+ onJoin = function() {
931
+ };
932
+ }
933
+ if (!onLeave) {
934
+ onLeave = function() {
935
+ };
936
+ }
937
+ this.map(joins, (key, newPresence) => {
938
+ let currentPresence = state[key];
939
+ state[key] = this.clone(newPresence);
940
+ if (currentPresence) {
941
+ let joinedRefs = state[key].metas.map((m) => m.phx_ref);
942
+ let curMetas = currentPresence.metas.filter((m) => joinedRefs.indexOf(m.phx_ref) < 0);
943
+ state[key].metas.unshift(...curMetas);
944
+ }
945
+ onJoin(key, currentPresence, newPresence);
946
+ });
947
+ this.map(leaves, (key, leftPresence) => {
948
+ let currentPresence = state[key];
949
+ if (!currentPresence) {
950
+ return;
951
+ }
952
+ let refsToRemove = leftPresence.metas.map((m) => m.phx_ref);
953
+ currentPresence.metas = currentPresence.metas.filter((p) => {
954
+ return refsToRemove.indexOf(p.phx_ref) < 0;
955
+ });
956
+ onLeave(key, currentPresence, leftPresence);
957
+ if (currentPresence.metas.length === 0) {
958
+ delete state[key];
959
+ }
960
+ });
961
+ return state;
962
+ }
963
+ /**
964
+ * Returns the array of presences, with selected metadata.
965
+ *
966
+ * @template [T=PresenceState]
967
+ * @param {Record<string, PresenceState>} presences
968
+ * @param {((key: string, obj: PresenceState) => T)} [chooser]
969
+ *
970
+ * @returns {T[]}
971
+ */
972
+ static list(presences, chooser) {
973
+ if (!chooser) {
974
+ chooser = function(key, pres) {
975
+ return pres;
976
+ };
977
+ }
978
+ return this.map(presences, (key, presence) => {
979
+ return chooser(key, presence);
980
+ });
981
+ }
982
+ // private
983
+ /**
984
+ * @template T
985
+ * @param {Record<string, PresenceState>} obj
986
+ * @param {(key: string, obj: PresenceState) => T} func
987
+ */
988
+ static map(obj, func) {
989
+ return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key]));
990
+ }
991
+ /**
992
+ * @template T
993
+ * @param {T} obj
994
+ * @returns {T}
995
+ */
996
+ static clone(obj) {
997
+ return JSON.parse(JSON.stringify(obj));
998
+ }
999
+ };
1000
+
1001
+ // js/phoenix/serializer.js
1002
+ var serializer_default = {
1003
+ HEADER_LENGTH: 1,
1004
+ META_LENGTH: 4,
1005
+ KINDS: { push: 0, reply: 1, broadcast: 2 },
1006
+ /**
1007
+ * @template T
1008
+ * @param {Message<Record<string, any>>} msg
1009
+ * @param {(msg: ArrayBuffer | string) => T} callback
1010
+ * @returns {T}
1011
+ */
1012
+ encode(msg, callback) {
1013
+ if (msg.payload.constructor === ArrayBuffer) {
1014
+ return callback(this.binaryEncode(msg));
1015
+ } else {
1016
+ let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];
1017
+ return callback(JSON.stringify(payload));
1018
+ }
1019
+ },
1020
+ /**
1021
+ * @template T
1022
+ * @param {ArrayBuffer | string} rawPayload
1023
+ * @param {(msg: Message<unknown>) => T} callback
1024
+ * @returns {T}
1025
+ */
1026
+ decode(rawPayload, callback) {
1027
+ if (rawPayload.constructor === ArrayBuffer) {
1028
+ return callback(this.binaryDecode(rawPayload));
1029
+ } else {
1030
+ let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload);
1031
+ return callback({ join_ref, ref, topic, event, payload });
1032
+ }
1033
+ },
1034
+ /** @private */
1035
+ binaryEncode(message) {
1036
+ let { join_ref, ref, event, topic, payload } = message;
1037
+ let metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length;
1038
+ let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
1039
+ let view = new DataView(header);
1040
+ let offset = 0;
1041
+ view.setUint8(offset++, this.KINDS.push);
1042
+ view.setUint8(offset++, join_ref.length);
1043
+ view.setUint8(offset++, ref.length);
1044
+ view.setUint8(offset++, topic.length);
1045
+ view.setUint8(offset++, event.length);
1046
+ Array.from(join_ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1047
+ Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1048
+ Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1049
+ Array.from(event, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1050
+ var combined = new Uint8Array(header.byteLength + payload.byteLength);
1051
+ combined.set(new Uint8Array(header), 0);
1052
+ combined.set(new Uint8Array(payload), header.byteLength);
1053
+ return combined.buffer;
1054
+ },
1055
+ /**
1056
+ * @private
1057
+ */
1058
+ binaryDecode(buffer) {
1059
+ let view = new DataView(buffer);
1060
+ let kind = view.getUint8(0);
1061
+ let decoder = new TextDecoder();
1062
+ switch (kind) {
1063
+ case this.KINDS.push:
1064
+ return this.decodePush(buffer, view, decoder);
1065
+ case this.KINDS.reply:
1066
+ return this.decodeReply(buffer, view, decoder);
1067
+ case this.KINDS.broadcast:
1068
+ return this.decodeBroadcast(buffer, view, decoder);
1069
+ }
1070
+ },
1071
+ /** @private */
1072
+ decodePush(buffer, view, decoder) {
1073
+ let joinRefSize = view.getUint8(1);
1074
+ let topicSize = view.getUint8(2);
1075
+ let eventSize = view.getUint8(3);
1076
+ let offset = this.HEADER_LENGTH + this.META_LENGTH - 1;
1077
+ let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
1078
+ offset = offset + joinRefSize;
1079
+ let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
1080
+ offset = offset + topicSize;
1081
+ let event = decoder.decode(buffer.slice(offset, offset + eventSize));
1082
+ offset = offset + eventSize;
1083
+ let data = buffer.slice(offset, buffer.byteLength);
1084
+ return { join_ref: joinRef, ref: null, topic, event, payload: data };
1085
+ },
1086
+ /** @private */
1087
+ decodeReply(buffer, view, decoder) {
1088
+ let joinRefSize = view.getUint8(1);
1089
+ let refSize = view.getUint8(2);
1090
+ let topicSize = view.getUint8(3);
1091
+ let eventSize = view.getUint8(4);
1092
+ let offset = this.HEADER_LENGTH + this.META_LENGTH;
1093
+ let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
1094
+ offset = offset + joinRefSize;
1095
+ let ref = decoder.decode(buffer.slice(offset, offset + refSize));
1096
+ offset = offset + refSize;
1097
+ let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
1098
+ offset = offset + topicSize;
1099
+ let event = decoder.decode(buffer.slice(offset, offset + eventSize));
1100
+ offset = offset + eventSize;
1101
+ let data = buffer.slice(offset, buffer.byteLength);
1102
+ let payload = { status: event, response: data };
1103
+ return { join_ref: joinRef, ref, topic, event: CHANNEL_EVENTS.reply, payload };
1104
+ },
1105
+ /** @private */
1106
+ decodeBroadcast(buffer, view, decoder) {
1107
+ let topicSize = view.getUint8(1);
1108
+ let eventSize = view.getUint8(2);
1109
+ let offset = this.HEADER_LENGTH + 2;
1110
+ let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
1111
+ offset = offset + topicSize;
1112
+ let event = decoder.decode(buffer.slice(offset, offset + eventSize));
1113
+ offset = offset + eventSize;
1114
+ let data = buffer.slice(offset, buffer.byteLength);
1115
+ return { join_ref: null, ref: null, topic, event, payload: data };
1116
+ }
1117
+ };
1118
+
1119
+ // js/phoenix/socket.js
1120
+ var Socket = class {
1121
+ /** Initializes the Socket *
1122
+ *
1123
+ * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)
1124
+ *
1125
+ * @constructor
1126
+ * @param {string} endPoint - The string WebSocket endpoint, ie, `"ws://example.com/socket"`,
1127
+ * `"wss://example.com"`
1128
+ * `"/socket"` (inherited host & protocol)
1129
+ * @param {SocketOptions} [opts] - Optional configuration
1130
+ */
1131
+ constructor(endPoint, opts = {}) {
1132
+ this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] };
1133
+ this.channels = [];
1134
+ this.sendBuffer = [];
1135
+ this.ref = 0;
1136
+ this.fallbackRef = null;
1137
+ this.timeout = opts.timeout || DEFAULT_TIMEOUT;
1138
+ this.transport = opts.transport || global.WebSocket || LongPoll;
1139
+ this.conn = void 0;
1140
+ this.primaryPassedHealthCheck = false;
1141
+ this.longPollFallbackMs = opts.longPollFallbackMs;
1142
+ this.fallbackTimer = null;
1143
+ this.sessionStore = opts.sessionStorage || global && global.sessionStorage;
1144
+ this.establishedConnections = 0;
1145
+ this.defaultEncoder = serializer_default.encode.bind(serializer_default);
1146
+ this.defaultDecoder = serializer_default.decode.bind(serializer_default);
1147
+ this.closeWasClean = false;
1148
+ this.disconnecting = false;
1149
+ this.binaryType = opts.binaryType || "arraybuffer";
1150
+ this.connectClock = 1;
1151
+ this.pageHidden = false;
1152
+ this.encode = void 0;
1153
+ this.decode = void 0;
1154
+ if (this.transport !== LongPoll) {
1155
+ this.encode = opts.encode || this.defaultEncoder;
1156
+ this.decode = opts.decode || this.defaultDecoder;
1157
+ } else {
1158
+ this.encode = this.defaultEncoder;
1159
+ this.decode = this.defaultDecoder;
1160
+ }
1161
+ let awaitingConnectionOnPageShow = null;
1162
+ if (phxWindow && phxWindow.addEventListener) {
1163
+ phxWindow.addEventListener("pagehide", (_e) => {
1164
+ if (this.conn) {
1165
+ this.disconnect();
1166
+ awaitingConnectionOnPageShow = this.connectClock;
1167
+ }
1168
+ });
1169
+ phxWindow.addEventListener("pageshow", (_e) => {
1170
+ if (awaitingConnectionOnPageShow === this.connectClock) {
1171
+ awaitingConnectionOnPageShow = null;
1172
+ this.connect();
1173
+ }
1174
+ });
1175
+ phxWindow.addEventListener("visibilitychange", () => {
1176
+ if (document.visibilityState === "hidden") {
1177
+ this.pageHidden = true;
1178
+ } else {
1179
+ this.pageHidden = false;
1180
+ if (!this.isConnected()) {
1181
+ this.teardown(() => this.connect());
1182
+ }
1183
+ }
1184
+ });
1185
+ }
1186
+ this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 3e4;
1187
+ this.autoSendHeartbeat = opts.autoSendHeartbeat ?? true;
1188
+ this.heartbeatCallback = opts.heartbeatCallback ?? (() => {
1189
+ });
1190
+ this.rejoinAfterMs = (tries) => {
1191
+ if (opts.rejoinAfterMs) {
1192
+ return opts.rejoinAfterMs(tries);
1193
+ } else {
1194
+ return [1e3, 2e3, 5e3][tries - 1] || 1e4;
1195
+ }
1196
+ };
1197
+ this.reconnectAfterMs = (tries) => {
1198
+ if (opts.reconnectAfterMs) {
1199
+ return opts.reconnectAfterMs(tries);
1200
+ } else {
1201
+ return [10, 50, 100, 150, 200, 250, 500, 1e3, 2e3][tries - 1] || 5e3;
1202
+ }
1203
+ };
1204
+ this.logger = opts.logger || null;
1205
+ if (!this.logger && opts.debug) {
1206
+ this.logger = (kind, msg, data) => {
1207
+ console.log(`${kind}: ${msg}`, data);
1208
+ };
1209
+ }
1210
+ this.longpollerTimeout = opts.longpollerTimeout || 2e4;
1211
+ this.params = closure(opts.params || {});
1212
+ this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;
1213
+ this.vsn = opts.vsn || DEFAULT_VSN;
1214
+ this.heartbeatTimeoutTimer = null;
1215
+ this.heartbeatTimer = null;
1216
+ this.heartbeatSentAt = null;
1217
+ this.pendingHeartbeatRef = null;
1218
+ this.reconnectTimer = new Timer(() => {
1219
+ if (this.pageHidden) {
1220
+ this.log("Not reconnecting as page is hidden!");
1221
+ this.teardown();
1222
+ return;
1223
+ }
1224
+ this.teardown(async () => {
1225
+ if (opts.beforeReconnect) await opts.beforeReconnect();
1226
+ this.connect();
1227
+ });
1228
+ }, this.reconnectAfterMs);
1229
+ this.authToken = opts.authToken;
1230
+ }
1231
+ /**
1232
+ * Returns the LongPoll transport reference
1233
+ */
1234
+ getLongPollTransport() {
1235
+ return LongPoll;
1236
+ }
1237
+ /**
1238
+ * Disconnects and replaces the active transport
1239
+ *
1240
+ * @param {SocketTransport} newTransport - The new transport class to instantiate
1241
+ *
1242
+ */
1243
+ replaceTransport(newTransport) {
1244
+ this.connectClock++;
1245
+ this.closeWasClean = true;
1246
+ clearTimeout(this.fallbackTimer);
1247
+ this.reconnectTimer.reset();
1248
+ if (this.conn) {
1249
+ this.conn.close();
1250
+ this.conn = null;
1251
+ }
1252
+ this.transport = newTransport;
1253
+ }
1254
+ /**
1255
+ * Returns the socket protocol
1256
+ *
1257
+ * @returns {"wss" | "ws"}
1258
+ */
1259
+ protocol() {
1260
+ return location.protocol.match(/^https/) ? "wss" : "ws";
1261
+ }
1262
+ /**
1263
+ * The fully qualified socket url
1264
+ *
1265
+ * @returns {string}
1266
+ */
1267
+ endPointURL() {
1268
+ let uri = Ajax.appendParams(
1269
+ Ajax.appendParams(this.endPoint, this.params()),
1270
+ { vsn: this.vsn }
1271
+ );
1272
+ if (uri.charAt(0) !== "/") {
1273
+ return uri;
1274
+ }
1275
+ if (uri.charAt(1) === "/") {
1276
+ return `${this.protocol()}:${uri}`;
1277
+ }
1278
+ return `${this.protocol()}://${location.host}${uri}`;
1279
+ }
1280
+ /**
1281
+ * Disconnects the socket
1282
+ *
1283
+ * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes.
1284
+ *
1285
+ * @param {() => void} [callback] - Optional callback which is called after socket is disconnected.
1286
+ * @param {number} [code] - A status code for disconnection (Optional).
1287
+ * @param {string} [reason] - A textual description of the reason to disconnect. (Optional)
1288
+ */
1289
+ disconnect(callback, code, reason) {
1290
+ this.connectClock++;
1291
+ this.disconnecting = true;
1292
+ this.closeWasClean = true;
1293
+ clearTimeout(this.fallbackTimer);
1294
+ this.reconnectTimer.reset();
1295
+ this.teardown(() => {
1296
+ this.disconnecting = false;
1297
+ callback && callback();
1298
+ }, code, reason);
1299
+ }
1300
+ /**
1301
+ * @param {Params} [params] - [DEPRECATED] The params to send when connecting, for example `{user_id: userToken}`
1302
+ *
1303
+ * Passing params to connect is deprecated; pass them in the Socket constructor instead:
1304
+ * `new Socket("/socket", {params: {user_id: userToken}})`.
1305
+ */
1306
+ connect(params) {
1307
+ if (params) {
1308
+ console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor");
1309
+ this.params = closure(params);
1310
+ }
1311
+ if (this.conn && !this.disconnecting) {
1312
+ return;
1313
+ }
1314
+ if (this.longPollFallbackMs && this.transport !== LongPoll) {
1315
+ this.connectWithFallback(LongPoll, this.longPollFallbackMs);
1316
+ } else {
1317
+ this.transportConnect();
1318
+ }
1319
+ }
1320
+ /**
1321
+ * Logs the message. Override `this.logger` for specialized logging. noops by default
1322
+ * @param {string} kind
1323
+ * @param {string} msg
1324
+ * @param {Object} data
1325
+ */
1326
+ log(kind, msg, data) {
1327
+ this.logger && this.logger(kind, msg, data);
1328
+ }
1329
+ /**
1330
+ * Returns true if a logger has been set on this socket.
1331
+ */
1332
+ hasLogger() {
1333
+ return this.logger !== null;
1334
+ }
1335
+ /**
1336
+ * Registers callbacks for connection open events
1337
+ *
1338
+ * @example socket.onOpen(function(){ console.info("the socket was opened") })
1339
+ *
1340
+ * @param {SocketOnOpen} callback
1341
+ */
1342
+ onOpen(callback) {
1343
+ let ref = this.makeRef();
1344
+ this.stateChangeCallbacks.open.push([ref, callback]);
1345
+ return ref;
1346
+ }
1347
+ /**
1348
+ * Registers callbacks for connection close events
1349
+ * @param {SocketOnClose} callback
1350
+ * @returns {string}
1351
+ */
1352
+ onClose(callback) {
1353
+ let ref = this.makeRef();
1354
+ this.stateChangeCallbacks.close.push([ref, callback]);
1355
+ return ref;
1356
+ }
1357
+ /**
1358
+ * Registers callbacks for connection error events
1359
+ *
1360
+ * @example socket.onError(function(error){ alert("An error occurred") })
1361
+ *
1362
+ * @param {SocketOnError} callback
1363
+ * @returns {string}
1364
+ */
1365
+ onError(callback) {
1366
+ let ref = this.makeRef();
1367
+ this.stateChangeCallbacks.error.push([ref, callback]);
1368
+ return ref;
1369
+ }
1370
+ /**
1371
+ * Registers callbacks for connection message events
1372
+ * @param {SocketOnMessage} callback
1373
+ * @returns {string}
1374
+ */
1375
+ onMessage(callback) {
1376
+ let ref = this.makeRef();
1377
+ this.stateChangeCallbacks.message.push([ref, callback]);
1378
+ return ref;
1379
+ }
1380
+ /**
1381
+ * Sets a callback that receives lifecycle events for internal heartbeat messages.
1382
+ * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected).
1383
+ * @param {HeartbeatCallback} callback
1384
+ */
1385
+ onHeartbeat(callback) {
1386
+ this.heartbeatCallback = callback;
1387
+ }
1388
+ /**
1389
+ * Pings the server and invokes the callback with the RTT in milliseconds
1390
+ * @param {(timeDelta: number) => void} callback
1391
+ *
1392
+ * Returns true if the ping was pushed or false if unable to be pushed.
1393
+ */
1394
+ ping(callback) {
1395
+ if (!this.isConnected()) {
1396
+ return false;
1397
+ }
1398
+ let ref = this.makeRef();
1399
+ let startTime = Date.now();
1400
+ this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref });
1401
+ let onMsgRef = this.onMessage((msg) => {
1402
+ if (msg.ref === ref) {
1403
+ this.off([onMsgRef]);
1404
+ callback(Date.now() - startTime);
1405
+ }
1406
+ });
1407
+ return true;
1408
+ }
1409
+ /**
1410
+ * @private
1411
+ */
1412
+ transportConnect() {
1413
+ this.connectClock++;
1414
+ this.closeWasClean = false;
1415
+ let protocols = void 0;
1416
+ if (this.authToken) {
1417
+ protocols = ["phoenix", `${AUTH_TOKEN_PREFIX}${btoa(this.authToken).replace(/=/g, "")}`];
1418
+ }
1419
+ this.conn = new this.transport(this.endPointURL(), protocols);
1420
+ this.conn.binaryType = this.binaryType;
1421
+ this.conn.timeout = this.longpollerTimeout;
1422
+ this.conn.onopen = () => this.onConnOpen();
1423
+ this.conn.onerror = (error) => this.onConnError(error);
1424
+ this.conn.onmessage = (event) => this.onConnMessage(event);
1425
+ this.conn.onclose = (event) => this.onConnClose(event);
1426
+ }
1427
+ getSession(key) {
1428
+ return this.sessionStore && this.sessionStore.getItem(key);
1429
+ }
1430
+ storeSession(key, val) {
1431
+ this.sessionStore && this.sessionStore.setItem(key, val);
1432
+ }
1433
+ connectWithFallback(fallbackTransport, fallbackThreshold = 2500) {
1434
+ clearTimeout(this.fallbackTimer);
1435
+ let established = false;
1436
+ let primaryTransport = true;
1437
+ let openRef, errorRef;
1438
+ let fallback = (reason) => {
1439
+ this.log("transport", `falling back to ${fallbackTransport.name}...`, reason);
1440
+ this.off([openRef, errorRef]);
1441
+ primaryTransport = false;
1442
+ this.replaceTransport(fallbackTransport);
1443
+ this.transportConnect();
1444
+ };
1445
+ if (this.getSession(`phx:fallback:${fallbackTransport.name}`)) {
1446
+ return fallback("memorized");
1447
+ }
1448
+ this.fallbackTimer = setTimeout(fallback, fallbackThreshold);
1449
+ errorRef = this.onError((reason) => {
1450
+ this.log("transport", "error", reason);
1451
+ if (primaryTransport && !established) {
1452
+ clearTimeout(this.fallbackTimer);
1453
+ fallback(reason);
1454
+ }
1455
+ });
1456
+ if (this.fallbackRef) {
1457
+ this.off([this.fallbackRef]);
1458
+ }
1459
+ this.fallbackRef = this.onOpen(() => {
1460
+ established = true;
1461
+ if (!primaryTransport) {
1462
+ if (!this.primaryPassedHealthCheck) {
1463
+ this.storeSession(`phx:fallback:${fallbackTransport.name}`, "true");
1464
+ }
1465
+ return this.log("transport", `established ${fallbackTransport.name} fallback`);
1466
+ }
1467
+ clearTimeout(this.fallbackTimer);
1468
+ this.fallbackTimer = setTimeout(fallback, fallbackThreshold);
1469
+ this.ping((rtt) => {
1470
+ this.log("transport", "connected to primary after", rtt);
1471
+ this.primaryPassedHealthCheck = true;
1472
+ clearTimeout(this.fallbackTimer);
1473
+ });
1474
+ });
1475
+ this.transportConnect();
1476
+ }
1477
+ clearHeartbeats() {
1478
+ clearTimeout(this.heartbeatTimer);
1479
+ clearTimeout(this.heartbeatTimeoutTimer);
1480
+ }
1481
+ onConnOpen() {
1482
+ if (this.hasLogger()) this.log("transport", `connected to ${this.endPointURL()}`);
1483
+ this.closeWasClean = false;
1484
+ this.disconnecting = false;
1485
+ this.establishedConnections++;
1486
+ this.flushSendBuffer();
1487
+ this.reconnectTimer.reset();
1488
+ if (this.autoSendHeartbeat) {
1489
+ this.resetHeartbeat();
1490
+ }
1491
+ this.triggerStateCallbacks("open");
1492
+ }
1493
+ /**
1494
+ * @private
1495
+ */
1496
+ heartbeatTimeout() {
1497
+ if (this.pendingHeartbeatRef) {
1498
+ this.pendingHeartbeatRef = null;
1499
+ this.heartbeatSentAt = null;
1500
+ if (this.hasLogger()) {
1501
+ this.log("transport", "heartbeat timeout. Attempting to re-establish connection");
1502
+ }
1503
+ try {
1504
+ this.heartbeatCallback("timeout");
1505
+ } catch (e) {
1506
+ this.log("error", "error in heartbeat callback", e);
1507
+ }
1508
+ this.triggerChanError();
1509
+ this.closeWasClean = false;
1510
+ this.teardown(() => this.reconnectTimer.scheduleTimeout(), WS_CLOSE_NORMAL, "heartbeat timeout");
1511
+ }
1512
+ }
1513
+ resetHeartbeat() {
1514
+ if (this.conn && this.conn.skipHeartbeat) {
1515
+ return;
1516
+ }
1517
+ this.pendingHeartbeatRef = null;
1518
+ this.clearHeartbeats();
1519
+ this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
1520
+ }
1521
+ teardown(callback, code, reason) {
1522
+ if (!this.conn) {
1523
+ return callback && callback();
1524
+ }
1525
+ let connectClock = this.connectClock;
1526
+ this.waitForBufferDone(() => {
1527
+ if (connectClock !== this.connectClock) {
1528
+ return;
1529
+ }
1530
+ if (this.conn) {
1531
+ if (code) {
1532
+ this.conn.close(code, reason || "");
1533
+ } else {
1534
+ this.conn.close();
1535
+ }
1536
+ }
1537
+ this.waitForSocketClosed(() => {
1538
+ if (connectClock !== this.connectClock) {
1539
+ return;
1540
+ }
1541
+ if (this.conn) {
1542
+ this.conn.onopen = function() {
1543
+ };
1544
+ this.conn.onerror = function() {
1545
+ };
1546
+ this.conn.onmessage = function() {
1547
+ };
1548
+ this.conn.onclose = function() {
1549
+ };
1550
+ this.conn = null;
1551
+ }
1552
+ callback && callback();
1553
+ });
1554
+ });
1555
+ }
1556
+ waitForBufferDone(callback, tries = 1) {
1557
+ if (tries === 5 || !this.conn || !this.conn.bufferedAmount) {
1558
+ callback();
1559
+ return;
1560
+ }
1561
+ setTimeout(() => {
1562
+ this.waitForBufferDone(callback, tries + 1);
1563
+ }, 150 * tries);
1564
+ }
1565
+ waitForSocketClosed(callback, tries = 1) {
1566
+ if (tries === 5 || !this.conn || this.conn.readyState === SOCKET_STATES.closed) {
1567
+ callback();
1568
+ return;
1569
+ }
1570
+ setTimeout(() => {
1571
+ this.waitForSocketClosed(callback, tries + 1);
1572
+ }, 150 * tries);
1573
+ }
1574
+ /**
1575
+ * @param {CloseEvent} event
1576
+ */
1577
+ onConnClose(event) {
1578
+ if (this.conn) this.conn.onclose = () => {
1579
+ };
1580
+ if (this.hasLogger()) this.log("transport", "close", event);
1581
+ this.triggerChanError();
1582
+ this.clearHeartbeats();
1583
+ if (!this.closeWasClean) {
1584
+ this.reconnectTimer.scheduleTimeout();
1585
+ }
1586
+ this.triggerStateCallbacks("close", event);
1587
+ }
1588
+ /**
1589
+ * @private
1590
+ * @param {Event} error
1591
+ */
1592
+ onConnError(error) {
1593
+ if (this.hasLogger()) this.log("transport", error);
1594
+ let transportBefore = this.transport;
1595
+ let establishedBefore = this.establishedConnections;
1596
+ this.triggerStateCallbacks("error", error, transportBefore, establishedBefore);
1597
+ if (transportBefore === this.transport || establishedBefore > 0) {
1598
+ this.triggerChanError();
1599
+ }
1600
+ }
1601
+ /**
1602
+ * @private
1603
+ */
1604
+ triggerChanError() {
1605
+ this.channels.forEach((channel) => {
1606
+ if (!(channel.isErrored() || channel.isLeaving() || channel.isClosed())) {
1607
+ channel.trigger(CHANNEL_EVENTS.error);
1608
+ }
1609
+ });
1610
+ }
1611
+ /**
1612
+ * @returns {string}
1613
+ */
1614
+ connectionState() {
1615
+ switch (this.conn && this.conn.readyState) {
1616
+ case SOCKET_STATES.connecting:
1617
+ return "connecting";
1618
+ case SOCKET_STATES.open:
1619
+ return "open";
1620
+ case SOCKET_STATES.closing:
1621
+ return "closing";
1622
+ default:
1623
+ return "closed";
1624
+ }
1625
+ }
1626
+ /**
1627
+ * @returns {boolean}
1628
+ */
1629
+ isConnected() {
1630
+ return this.connectionState() === "open";
1631
+ }
1632
+ /**
1633
+ *
1634
+ * @param {Channel} channel
1635
+ */
1636
+ remove(channel) {
1637
+ this.off(channel.stateChangeRefs);
1638
+ this.channels = this.channels.filter((c) => c !== channel);
1639
+ }
1640
+ /**
1641
+ * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations.
1642
+ *
1643
+ * @param {string[]} refs - list of refs returned by calls to
1644
+ * `onOpen`, `onClose`, `onError,` and `onMessage`
1645
+ */
1646
+ off(refs) {
1647
+ for (let key in this.stateChangeCallbacks) {
1648
+ this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => {
1649
+ return refs.indexOf(ref) === -1;
1650
+ });
1651
+ }
1652
+ }
1653
+ /**
1654
+ * Initiates a new channel for the given topic
1655
+ *
1656
+ * @param {string} topic
1657
+ * @param {Params | (() => Params)} [chanParams]- Parameters for the channel
1658
+ * @returns {Channel}
1659
+ */
1660
+ channel(topic, chanParams = {}) {
1661
+ let chan = new Channel(topic, chanParams, this);
1662
+ this.channels.push(chan);
1663
+ return chan;
1664
+ }
1665
+ /**
1666
+ * @param {Message<Record<string, any>>} data
1667
+ */
1668
+ push(data) {
1669
+ if (this.hasLogger()) {
1670
+ let { topic, event, payload, ref, join_ref } = data;
1671
+ this.log("push", `${topic} ${event} (${join_ref}, ${ref})`, payload);
1672
+ }
1673
+ if (this.isConnected()) {
1674
+ this.encode(data, (result) => this.conn.send(result));
1675
+ } else {
1676
+ this.sendBuffer.push(() => this.encode(data, (result) => this.conn.send(result)));
1677
+ }
1678
+ }
1679
+ /**
1680
+ * Return the next message ref, accounting for overflows
1681
+ * @returns {string}
1682
+ */
1683
+ makeRef() {
1684
+ let newRef = this.ref + 1;
1685
+ if (newRef === this.ref) {
1686
+ this.ref = 0;
1687
+ } else {
1688
+ this.ref = newRef;
1689
+ }
1690
+ return this.ref.toString();
1691
+ }
1692
+ sendHeartbeat() {
1693
+ if (!this.isConnected()) {
1694
+ try {
1695
+ this.heartbeatCallback("disconnected");
1696
+ } catch (e) {
1697
+ this.log("error", "error in heartbeat callback", e);
1698
+ }
1699
+ return;
1700
+ }
1701
+ if (this.pendingHeartbeatRef) {
1702
+ this.heartbeatTimeout();
1703
+ return;
1704
+ }
1705
+ this.pendingHeartbeatRef = this.makeRef();
1706
+ this.heartbeatSentAt = Date.now();
1707
+ this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef });
1708
+ try {
1709
+ this.heartbeatCallback("sent");
1710
+ } catch (e) {
1711
+ this.log("error", "error in heartbeat callback", e);
1712
+ }
1713
+ this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs);
1714
+ }
1715
+ flushSendBuffer() {
1716
+ if (this.isConnected() && this.sendBuffer.length > 0) {
1717
+ this.sendBuffer.forEach((callback) => callback());
1718
+ this.sendBuffer = [];
1719
+ }
1720
+ }
1721
+ /**
1722
+ * @param {MessageEvent<any>} rawMessage
1723
+ */
1724
+ onConnMessage(rawMessage) {
1725
+ this.decode(rawMessage.data, (msg) => {
1726
+ let { topic, event, payload, ref, join_ref } = msg;
1727
+ if (ref && ref === this.pendingHeartbeatRef) {
1728
+ const latency = this.heartbeatSentAt ? Date.now() - this.heartbeatSentAt : void 0;
1729
+ this.clearHeartbeats();
1730
+ try {
1731
+ this.heartbeatCallback(payload.status === "ok" ? "ok" : "error", latency);
1732
+ } catch (e) {
1733
+ this.log("error", "error in heartbeat callback", e);
1734
+ }
1735
+ this.pendingHeartbeatRef = null;
1736
+ this.heartbeatSentAt = null;
1737
+ if (this.autoSendHeartbeat) {
1738
+ this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
1739
+ }
1740
+ }
1741
+ if (this.hasLogger()) this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`.trim(), payload);
1742
+ for (let i = 0; i < this.channels.length; i++) {
1743
+ const channel = this.channels[i];
1744
+ if (!channel.isMember(topic, event, payload, join_ref)) {
1745
+ continue;
1746
+ }
1747
+ channel.trigger(event, payload, ref, join_ref);
1748
+ }
1749
+ this.triggerStateCallbacks("message", msg);
1750
+ });
1751
+ }
1752
+ /**
1753
+ * @private
1754
+ * @template {keyof SocketStateChangeCallbacks} K
1755
+ * @param {K} event
1756
+ * @param {...Parameters<SocketStateChangeCallbacks[K][number][1]>} args
1757
+ * @returns {void}
1758
+ */
1759
+ triggerStateCallbacks(event, ...args) {
1760
+ try {
1761
+ this.stateChangeCallbacks[event].forEach(([_, callback]) => {
1762
+ try {
1763
+ callback(...args);
1764
+ } catch (e) {
1765
+ this.log("error", `error in ${event} callback`, e);
1766
+ }
1767
+ });
1768
+ } catch (e) {
1769
+ this.log("error", `error triggering ${event} callbacks`, e);
1770
+ }
1771
+ }
1772
+ leaveOpenTopic(topic) {
1773
+ let dupChannel = this.channels.find((c) => c.topic === topic && (c.isJoined() || c.isJoining()));
1774
+ if (dupChannel) {
1775
+ if (this.hasLogger()) this.log("transport", `leaving duplicate topic "${topic}"`);
1776
+ dupChannel.leave();
1777
+ }
1778
+ }
1779
+ };
1780
+ export {
1781
+ Channel,
1782
+ LongPoll,
1783
+ Presence,
1784
+ Push,
1785
+ serializer_default as Serializer,
1786
+ Socket,
1787
+ Timer
1788
+ };
1789
+ //# sourceMappingURL=phoenix.mjs.map