laravel-echo-api-gateway 0.5.8 → 0.5.9

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.
@@ -1,870 +1,511 @@
1
- function _classCallCheck(instance, Constructor) {
2
- if (!(instance instanceof Constructor)) {
3
- throw new TypeError("Cannot call a class as a function");
4
- }
5
- }
6
-
7
- function _defineProperties(target, props) {
8
- for (var i = 0; i < props.length; i++) {
9
- var descriptor = props[i];
10
- descriptor.enumerable = descriptor.enumerable || false;
11
- descriptor.configurable = true;
12
- if ("value" in descriptor) descriptor.writable = true;
13
- Object.defineProperty(target, descriptor.key, descriptor);
14
- }
15
- }
16
-
17
- function _createClass(Constructor, protoProps, staticProps) {
18
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
19
- if (staticProps) _defineProperties(Constructor, staticProps);
20
- Object.defineProperty(Constructor, "prototype", {
21
- writable: false
22
- });
23
- return Constructor;
24
- }
25
-
26
- function _extends() {
27
- _extends = Object.assign || function (target) {
28
- for (var i = 1; i < arguments.length; i++) {
29
- var source = arguments[i];
30
-
31
- for (var key in source) {
32
- if (Object.prototype.hasOwnProperty.call(source, key)) {
33
- target[key] = source[key];
34
- }
35
- }
36
- }
37
-
38
- return target;
39
- };
40
-
41
- return _extends.apply(this, arguments);
42
- }
43
-
44
- function _inherits(subClass, superClass) {
45
- if (typeof superClass !== "function" && superClass !== null) {
46
- throw new TypeError("Super expression must either be null or a function");
47
- }
48
-
49
- Object.defineProperty(subClass, "prototype", {
50
- value: Object.create(superClass && superClass.prototype, {
51
- constructor: {
52
- value: subClass,
53
- writable: true,
54
- configurable: true
55
- }
56
- }),
57
- writable: false
58
- });
59
- if (superClass) _setPrototypeOf(subClass, superClass);
60
- }
61
-
62
- function _getPrototypeOf(o) {
63
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
64
- return o.__proto__ || Object.getPrototypeOf(o);
65
- };
66
- return _getPrototypeOf(o);
67
- }
68
-
69
- function _setPrototypeOf(o, p) {
70
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
71
- o.__proto__ = p;
72
- return o;
73
- };
74
-
75
- return _setPrototypeOf(o, p);
76
- }
77
-
78
- function _isNativeReflectConstruct() {
79
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
80
- if (Reflect.construct.sham) return false;
81
- if (typeof Proxy === "function") return true;
82
-
83
- try {
84
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
85
- return true;
86
- } catch (e) {
87
- return false;
88
- }
89
- }
90
-
91
- function _assertThisInitialized(self) {
92
- if (self === void 0) {
93
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
94
- }
95
-
96
- return self;
97
- }
98
-
99
- function _possibleConstructorReturn(self, call) {
100
- if (call && (typeof call === "object" || typeof call === "function")) {
101
- return call;
102
- } else if (call !== void 0) {
103
- throw new TypeError("Derived constructors may only return object or undefined");
104
- }
105
-
106
- return _assertThisInitialized(self);
107
- }
108
-
109
- function _createSuper(Derived) {
110
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
111
-
112
- return function _createSuperInternal() {
113
- var Super = _getPrototypeOf(Derived),
114
- result;
115
-
116
- if (hasNativeReflectConstruct) {
117
- var NewTarget = _getPrototypeOf(this).constructor;
118
-
119
- result = Reflect.construct(Super, arguments, NewTarget);
120
- } else {
121
- result = Super.apply(this, arguments);
122
- }
123
-
124
- return _possibleConstructorReturn(this, result);
125
- };
126
- }
127
-
128
- function _unsupportedIterableToArray(o, minLen) {
129
- if (!o) return;
130
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
131
- var n = Object.prototype.toString.call(o).slice(8, -1);
132
- if (n === "Object" && o.constructor) n = o.constructor.name;
133
- if (n === "Map" || n === "Set") return Array.from(o);
134
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
135
- }
136
-
137
- function _arrayLikeToArray(arr, len) {
138
- if (len == null || len > arr.length) len = arr.length;
139
-
140
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
141
-
142
- return arr2;
143
- }
144
-
145
- function _createForOfIteratorHelper(o, allowArrayLike) {
146
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
147
-
148
- if (!it) {
149
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
150
- if (it) o = it;
151
- var i = 0;
152
-
153
- var F = function () {};
154
-
155
- return {
156
- s: F,
157
- n: function () {
158
- if (i >= o.length) return {
159
- done: true
160
- };
161
- return {
162
- done: false,
163
- value: o[i++]
164
- };
165
- },
166
- e: function (e) {
167
- throw e;
168
- },
169
- f: F
170
- };
171
- }
172
-
173
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
174
- }
175
-
176
- var normalCompletion = true,
177
- didErr = false,
178
- err;
179
- return {
180
- s: function () {
181
- it = it.call(o);
182
- },
183
- n: function () {
184
- var step = it.next();
185
- normalCompletion = step.done;
186
- return step;
187
- },
188
- e: function (e) {
189
- didErr = true;
190
- err = e;
191
- },
192
- f: function () {
193
- try {
194
- if (!normalCompletion && it.return != null) it.return();
195
- } finally {
196
- if (didErr) throw err;
197
- }
198
- }
199
- };
200
- }
201
-
202
- class Connector {
203
- /**
204
- * Create a new class instance.
205
- */
1
+ const LOG_PREFIX$2 = '[LE-AG-Websocket]';
2
+ const OPEN = 1;
3
+ class Websocket {
206
4
  constructor(options) {
5
+ this.buffer = [];
207
6
  /**
208
- * Default connector options.
7
+ * Every channel that should be subscribed, re-subscribed each time a new connection is identified.
209
8
  */
210
- this._defaultOptions = {
211
- auth: {
212
- headers: {},
213
- },
214
- authEndpoint: '/broadcasting/auth',
215
- broadcaster: 'pusher',
216
- csrfToken: null,
217
- host: null,
218
- key: null,
219
- namespace: 'App.Events',
9
+ this.channels = new Map();
10
+ this.listeners = {};
11
+ this.closing = false;
12
+ this.reconnectAttempts = 0;
13
+ this.options = options;
14
+ if (this.options.host) {
15
+ this.connect();
16
+ }
17
+ }
18
+ connect() {
19
+ const host = this.options.host;
20
+ this.debug(`Trying to connect to ${host}...`);
21
+ const websocket = new WebSocket(host);
22
+ this.websocket = websocket;
23
+ websocket.onopen = () => {
24
+ this.debug('Connected !');
25
+ this.reconnectAttempts = 0;
26
+ this.send({ event: 'whoami' });
27
+ while (this.buffer.length) {
28
+ this.send(this.buffer.shift());
29
+ }
30
+ this.startPing();
31
+ };
32
+ websocket.onmessage = (messageEvent) => {
33
+ this.handleMessage(messageEvent.data);
34
+ };
35
+ websocket.onerror = () => {
36
+ // A close event always follows an error, so reconnecting is handled in onclose.
37
+ this.debug('Connection error.');
38
+ };
39
+ websocket.onclose = () => {
40
+ if (this.websocket !== websocket) {
41
+ return;
42
+ }
43
+ this.debug('Connection closed.');
44
+ this.stopPing();
45
+ this.socketId = undefined;
46
+ if (!this.closing) {
47
+ this.scheduleReconnect();
48
+ }
220
49
  };
221
- this.setOptions(options);
222
- this.connect();
223
50
  }
224
- /**
225
- * Merge the custom options with the defaults.
226
- */
227
- setOptions(options) {
228
- this.options = Object.assign(this._defaultOptions, options);
229
- if (this.csrfToken()) {
230
- this.options.auth.headers['X-CSRF-TOKEN'] = this.csrfToken();
231
- }
232
- return options;
51
+ scheduleReconnect() {
52
+ var _a, _b;
53
+ const baseDelay = (_a = this.options.reconnectDelay) !== null && _a !== void 0 ? _a : 1000;
54
+ const maxDelay = (_b = this.options.maxReconnectDelay) !== null && _b !== void 0 ? _b : 30000;
55
+ const delay = Math.min(baseDelay * 2 ** this.reconnectAttempts, maxDelay);
56
+ this.reconnectAttempts++;
57
+ this.debug(`Connection lost, reconnecting in ${delay}ms...`);
58
+ clearTimeout(this.reconnectTimer);
59
+ this.reconnectTimer = setTimeout(() => this.connect(), delay);
60
+ }
61
+ startPing() {
62
+ var _a;
63
+ this.stopPing();
64
+ this.pingTimer = setInterval(() => {
65
+ if (this.socketIsReady()) {
66
+ this.debug('Sending ping');
67
+ this.send({ event: 'ping' });
68
+ }
69
+ }, (_a = this.options.pingInterval) !== null && _a !== void 0 ? _a : 60 * 1000);
233
70
  }
234
- /**
235
- * Extract the CSRF token from the page.
236
- */
237
- csrfToken() {
238
- let selector;
239
- if (typeof window !== 'undefined' && window['Laravel'] && window['Laravel'].csrfToken) {
240
- return window['Laravel'].csrfToken;
71
+ stopPing() {
72
+ clearInterval(this.pingTimer);
73
+ this.pingTimer = undefined;
74
+ }
75
+ handleMessage(body) {
76
+ var _a;
77
+ const message = this.parseMessage(body);
78
+ if (!message) {
79
+ return;
241
80
  }
242
- else if (this.options.csrfToken) {
243
- return this.options.csrfToken;
81
+ this.debug('onmessage', body);
82
+ if (message.channel) {
83
+ this.dispatch(message.channel, message.event, message.data);
84
+ return;
244
85
  }
245
- else if (typeof document !== 'undefined' &&
246
- typeof document.querySelector === 'function' &&
247
- (selector = document.querySelector('meta[name="csrf-token"]'))) {
248
- return selector.getAttribute('content');
86
+ if (message.event === 'whoami') {
87
+ this.socketId = (_a = message.data) === null || _a === void 0 ? void 0 : _a.socket_id;
88
+ this.debug(`Just set socketId to ${this.socketId}`);
89
+ this.channels.forEach((channel) => this.actuallySubscribe(channel));
249
90
  }
250
- return null;
251
91
  }
252
- }
253
-
254
- var LOG_PREFIX = '[LE-AG-Websocket]';
255
- var Websocket = /*#__PURE__*/function () {
256
- function Websocket(options) {
257
- _classCallCheck(this, Websocket);
258
-
259
- this.buffer = [];
260
- this.listeners = {};
261
- this.internalListeners = {};
262
- this.channelBacklog = [];
263
- this.closing = false;
264
- this.hasConnected = false;
265
- this.options = options;
266
- this.connect(this.options.host);
267
- return this;
268
- }
269
-
270
- _createClass(Websocket, [{
271
- key: "connect",
272
- value: function connect(host) {
273
- var _this = this;
274
-
275
- if (!host) {
276
- this.options.debug && console.error(LOG_PREFIX + "Cannont connect without host !");
277
- return;
278
- }
279
-
280
- this.options.debug && console.log(LOG_PREFIX + "Trying to connect to ".concat(host, "..."));
281
- this.websocket = new WebSocket(host);
282
-
283
- this.websocket.onerror = function () {
284
- if (!_this.hasConnected) {
285
- setTimeout(function () {
286
- _this.socketId = undefined;
287
-
288
- _this.connect(host);
289
- }, 3000);
92
+ dispatch(channelName, event, data) {
93
+ var _a, _b;
94
+ const callbacks = (_b = (_a = this.listeners[channelName]) === null || _a === void 0 ? void 0 : _a[event]) !== null && _b !== void 0 ? _b : [];
95
+ callbacks.slice().forEach((callback) => callback(data));
96
+ }
97
+ parseMessage(body) {
98
+ try {
99
+ return JSON.parse(body);
290
100
  }
291
- };
292
-
293
- this.websocket.onopen = function () {
294
- _this.options.debug && console.log(LOG_PREFIX + ' Connected !');
295
- _this.hasConnected = true;
296
-
297
- _this.send({
298
- event: 'whoami'
299
- });
300
-
301
- while (_this.buffer.length) {
302
- var message = _this.buffer[0];
303
-
304
- _this.send(message);
305
-
306
- _this.buffer.splice(0, 1);
307
- } // Register events only once connected, or they won't be registered if connection failed/lost
308
-
309
-
310
- _this.websocket.onmessage = function (messageEvent) {
311
- var message = _this.parseMessage(messageEvent.data);
312
-
313
- _this.options.debug && console.log(LOG_PREFIX + ' onmessage', messageEvent.data);
314
-
315
- if (!message) {
316
- return;
317
- }
318
-
319
- if (message.channel) {
320
- _this.options.debug && console.log("".concat(LOG_PREFIX, " Received event ").concat(message.event, " on channel ").concat(message.channel));
321
-
322
- if (_this.listeners[message.channel] && _this.listeners[message.channel][message.event]) {
323
- _this.listeners[message.channel][message.event](message.data);
324
- }
325
-
101
+ catch (error) {
102
+ this.options.debug && console.error(error);
103
+ return undefined;
104
+ }
105
+ }
106
+ getSocketId() {
107
+ return this.socketId;
108
+ }
109
+ socketIsReady() {
110
+ var _a;
111
+ return ((_a = this.websocket) === null || _a === void 0 ? void 0 : _a.readyState) === OPEN;
112
+ }
113
+ send(message) {
114
+ if (this.socketIsReady()) {
115
+ this.websocket.send(JSON.stringify(message));
326
116
  return;
327
- }
328
-
329
- if (_this.internalListeners[message.event]) {
330
- _this.internalListeners[message.event](message.data);
331
- }
332
- }; // send ping every 60 seconds to keep connection alive
333
-
334
-
335
- _this.pingInterval = setInterval(function () {
336
- if (_this.websocket.readyState === _this.websocket.OPEN) {
337
- _this.options.debug && console.log(LOG_PREFIX + ' Sending ping');
338
-
339
- _this.send({
340
- event: 'ping'
341
- });
342
- }
343
- }, 60 * 1000);
344
- };
345
-
346
- this.websocket.onclose = function () {
347
- _this.options.debug && console.info('Connection closed.');
348
-
349
- if (_this.closing) {
350
- return;
351
117
  }
352
-
353
- _this.hasConnected = false;
354
- _this.options.debug && console.info('Connection lost, reconnecting...');
355
- setTimeout(function () {
356
- _this.socketId = undefined;
357
-
358
- _this.connect(host);
359
- }, 1000);
360
- };
361
-
362
- this.on('whoami', function (_ref) {
363
- var socketId = _ref.socket_id;
364
- _this.socketId = socketId;
365
- _this.options.debug && console.log("".concat(LOG_PREFIX, " Just set socketId to ").concat(socketId)); // Handle the backlog and don't empty it, we'll need it if we lose connection
366
-
367
- var channel;
368
-
369
- var _iterator = _createForOfIteratorHelper(_this.channelBacklog),
370
- _step;
371
-
372
- try {
373
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
374
- channel = _step.value;
375
-
376
- _this.actuallySubscribe(channel);
377
- }
378
- } catch (err) {
379
- _iterator.e(err);
380
- } finally {
381
- _iterator.f();
118
+ this.buffer.push(message);
119
+ }
120
+ close() {
121
+ var _a;
122
+ this.closing = true;
123
+ clearTimeout(this.reconnectTimer);
124
+ this.stopPing();
125
+ (_a = this.websocket) === null || _a === void 0 ? void 0 : _a.close();
126
+ }
127
+ subscribe(channel) {
128
+ this.channels.set(channel.name, channel);
129
+ if (this.socketId && this.socketIsReady()) {
130
+ this.actuallySubscribe(channel);
382
131
  }
383
- });
384
- }
385
- }, {
386
- key: "parseMessage",
387
- value: function parseMessage(body) {
388
- try {
389
- return JSON.parse(body);
390
- } catch (error) {
391
- this.options.debug && console.error(error);
392
- return undefined;
393
- }
394
- }
395
- }, {
396
- key: "getSocketId",
397
- value: function getSocketId() {
398
- return this.socketId;
399
- }
400
- }, {
401
- key: "socketIsReady",
402
- value: function socketIsReady() {
403
- return this.websocket.readyState === this.websocket.OPEN;
404
- }
405
- }, {
406
- key: "send",
407
- value: function send(message) {
408
- if (this.socketIsReady()) {
409
- this.websocket.send(JSON.stringify(message));
410
- return;
411
- }
412
-
413
- this.buffer.push(message);
414
- }
415
- }, {
416
- key: "close",
417
- value: function close() {
418
- this.closing = true;
419
- this.internalListeners = {};
420
- clearInterval(this.pingInterval);
421
- this.pingInterval = undefined;
422
- this.websocket.close();
423
- }
424
- }, {
425
- key: "subscribe",
426
- value: function subscribe(channel) {
427
- if (this.getSocketId()) {
428
- this.actuallySubscribe(channel);
429
- } else {
430
- this.options.debug && console.log("".concat(LOG_PREFIX, " subscribe - push channel backlog for channel ").concat(channel.name));
431
- this.channelBacklog.push(channel);
432
- }
433
- }
434
- }, {
435
- key: "actuallySubscribe",
436
- value: function actuallySubscribe(channel) {
437
- var _this2 = this;
438
-
439
- if (channel.name.startsWith('private-') || channel.name.startsWith('presence-')) {
440
- this.options.debug && console.log("".concat(LOG_PREFIX, " Sending auth request for channel ").concat(channel.name));
441
-
442
- if (this.options.bearerToken) {
443
- this.options.auth.headers['Authorization'] = 'Bearer ' + this.options.bearerToken;
132
+ else {
133
+ this.debug(`Channel ${channel.name} will be subscribed once connected`);
444
134
  }
445
-
446
- fetch(this.options.authEndpoint, {
447
- method: 'POST',
448
- headers: _extends({
449
- 'Content-Type': 'application/json'
450
- }, this.options.auth.headers),
451
- body: JSON.stringify({
452
- socket_id: this.getSocketId(),
453
- channel_name: channel.name
454
- })
455
- }).then(function (response) {
456
- if (!response.ok) {
457
- throw new Error("Auth request failed: ".concat(response.status));
458
- }
459
-
460
- return response.json();
461
- }).then(function (data) {
462
- _this2.options.debug && console.log("".concat(LOG_PREFIX, " Subscribing to private channel ").concat(channel.name));
463
-
464
- _this2.send({
465
- event: 'subscribe',
466
- data: _extends({
467
- channel: channel.name
468
- }, data)
469
- });
470
- })["catch"](function (error) {
471
- _this2.options.debug && console.log("".concat(LOG_PREFIX, " Auth request for channel ").concat(channel.name, " failed"));
472
- _this2.options.debug && console.error(error);
135
+ }
136
+ actuallySubscribe(channel) {
137
+ if (!channel.name.startsWith('private-') && !channel.name.startsWith('presence-')) {
138
+ this.debug(`Subscribing to channel ${channel.name}`);
139
+ this.send({ event: 'subscribe', data: { channel: channel.name } });
140
+ return;
141
+ }
142
+ const socketId = this.socketId;
143
+ this.debug(`Sending auth request for channel ${channel.name}`);
144
+ this.authorize(channel.name, socketId).then((data) => {
145
+ // Skip outdated authorizations: the connection changed or the channel was left meanwhile.
146
+ if (socketId !== this.socketId || this.channels.get(channel.name) !== channel) {
147
+ return;
148
+ }
149
+ this.debug(`Subscribing to private channel ${channel.name}`);
150
+ this.send({ event: 'subscribe', data: Object.assign({ channel: channel.name }, data) });
151
+ }).catch((error) => {
152
+ this.debug(`Auth request for channel ${channel.name} failed`, error);
153
+ this.dispatch(channel.name, 'error', error);
473
154
  });
474
- } else {
475
- this.options.debug && console.log("".concat(LOG_PREFIX, " Subscribing to channel ").concat(channel.name));
476
- this.send({
477
- event: 'subscribe',
478
- data: {
479
- channel: channel.name
480
- }
155
+ }
156
+ authorize(channelName, socketId) {
157
+ var _a, _b, _c;
158
+ const channelAuthorization = (_a = this.options.channelAuthorization) !== null && _a !== void 0 ? _a : {};
159
+ if (typeof channelAuthorization.customHandler === 'function') {
160
+ return new Promise((resolve, reject) => {
161
+ channelAuthorization.customHandler({ socketId, channelName }, (error, data) => {
162
+ var _a;
163
+ if (error) {
164
+ reject(this.authorizationError(error, (_a = error === null || error === void 0 ? void 0 : error.status) !== null && _a !== void 0 ? _a : null));
165
+ }
166
+ else {
167
+ resolve(data);
168
+ }
169
+ });
170
+ });
171
+ }
172
+ return fetch((_b = channelAuthorization.endpoint) !== null && _b !== void 0 ? _b : this.options.authEndpoint, {
173
+ method: 'POST',
174
+ headers: Object.assign(Object.assign({ 'Content-Type': 'application/json', 'Accept': 'application/json' }, (_c = this.options.auth) === null || _c === void 0 ? void 0 : _c.headers), channelAuthorization.headers),
175
+ body: JSON.stringify({
176
+ socket_id: socketId,
177
+ channel_name: channelName,
178
+ }),
179
+ }).then((response) => {
180
+ if (!response.ok) {
181
+ throw this.authorizationError(new Error(`Auth request failed: ${response.status}`), response.status);
182
+ }
183
+ return response.json();
184
+ }, (error) => {
185
+ throw this.authorizationError(error, null);
481
186
  });
482
- }
483
- }
484
- }, {
485
- key: "unsubscribe",
486
- value: function unsubscribe(channel) {
487
- this.options.debug && console.log("".concat(LOG_PREFIX, " unsubscribe for channel ").concat(channel.name));
488
- this.send({
489
- event: 'unsubscribe',
490
- data: {
491
- channel: channel.name
187
+ }
188
+ authorizationError(error, status) {
189
+ return { type: 'AuthError', status, error };
190
+ }
191
+ unsubscribe(channel) {
192
+ this.debug(`unsubscribe for channel ${channel.name}`);
193
+ if (this.channels.get(channel.name) === channel) {
194
+ this.channels.delete(channel.name);
195
+ delete this.listeners[channel.name];
196
+ }
197
+ if (this.socketId && this.socketIsReady()) {
198
+ this.send({ event: 'unsubscribe', data: { channel: channel.name } });
492
199
  }
493
- });
494
-
495
- if (this.listeners[channel.name]) {
496
- delete this.listeners[channel.name];
497
- }
498
- }
499
- }, {
500
- key: "on",
501
- value: function on(event) {
502
- var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
503
- this.options.debug && console.log("".concat(LOG_PREFIX, " on event ").concat(event, " ..."));
504
- this.internalListeners[event] = callback;
505
- }
506
- }, {
507
- key: "bind",
508
- value: function bind(channel, event, callback) {
509
- this.options.debug && console.log("".concat(LOG_PREFIX, " bind event ").concat(event, " for channel ").concat(channel.name, " ..."));
510
-
511
- if (!this.listeners[channel.name]) {
512
- this.listeners[channel.name] = {};
513
- }
514
-
515
- this.listeners[channel.name][event] = callback;
516
200
  }
517
- }, {
518
- key: "unbindEvent",
519
- value: function unbindEvent(channel, event) {
520
- var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
521
- this.options.debug && console.log("".concat(LOG_PREFIX, " unbind event ").concat(event, " for channel ").concat(channel.name, " ..."));
522
-
523
- if (this.internalListeners[event] && (callback === null || this.internalListeners[event] === callback)) {
524
- delete this.internalListeners[event];
525
- }
201
+ bind(channel, event, callback) {
202
+ var _a, _b;
203
+ var _c, _d, _e;
204
+ this.debug(`bind event ${event} for channel ${channel.name} ...`);
205
+ (_a = (_c = this.listeners)[_d = channel.name]) !== null && _a !== void 0 ? _a : (_c[_d] = {});
206
+ (_b = (_e = this.listeners[channel.name])[event]) !== null && _b !== void 0 ? _b : (_e[event] = []);
207
+ this.listeners[channel.name][event].push(callback);
208
+ }
209
+ unbind(channel, event, callback) {
210
+ var _a;
211
+ this.debug(`unbind event ${event} for channel ${channel.name} ...`);
212
+ const callbacks = (_a = this.listeners[channel.name]) === null || _a === void 0 ? void 0 : _a[event];
213
+ if (!callbacks) {
214
+ return;
215
+ }
216
+ if (callback) {
217
+ this.listeners[channel.name][event] = callbacks.filter((existing) => existing !== callback);
218
+ }
219
+ else {
220
+ delete this.listeners[channel.name][event];
221
+ }
526
222
  }
527
- }]);
528
-
529
- return Websocket;
530
- }();
223
+ debug(...messages) {
224
+ this.options.debug && console.log(LOG_PREFIX$2, ...messages);
225
+ }
226
+ }
531
227
 
532
228
  /**
533
- * Event name formatter
229
+ * Formats event names the same way laravel-echo does, so `listen('OrderCreated')` matches
230
+ * `App\Events\OrderCreated` and `listen('.custom-name')` matches `custom-name`.
534
231
  */
535
232
  class EventFormatter {
536
- /**
537
- * Create a new class instance.
538
- */
539
233
  constructor(namespace) {
540
- this.setNamespace(namespace);
234
+ this.namespace = namespace;
541
235
  }
542
- /**
543
- * Format the given event name.
544
- */
545
236
  format(event) {
546
- if (event.charAt(0) === '.' || event.charAt(0) === '\\') {
547
- return event.substr(1);
237
+ if (['.', '\\'].includes(event.charAt(0))) {
238
+ return event.substring(1);
548
239
  }
549
- else if (this.namespace) {
240
+ if (this.namespace) {
550
241
  event = this.namespace + '.' + event;
551
242
  }
552
243
  return event.replace(/\./g, '\\');
553
244
  }
554
- /**
555
- * Set the event namespace.
556
- */
557
- setNamespace(value) {
558
- this.namespace = value;
245
+ setNamespace(namespace) {
246
+ this.namespace = namespace;
559
247
  }
560
248
  }
561
249
 
250
+ const LOG_PREFIX$1 = '[LE-AG-Channel]';
251
+ const NOTIFICATION_EVENT = '.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated';
562
252
  /**
563
- * This class represents a basic channel.
253
+ * A channel on the API Gateway websocket. It implements the public, private and presence channel
254
+ * interfaces of laravel-echo (v1 and v2) without extending its internal classes.
564
255
  */
565
256
  class Channel {
257
+ /**
258
+ * Create a new class instance.
259
+ */
260
+ constructor(socket, name, options) {
261
+ this.name = name;
262
+ this.socket = socket;
263
+ this.options = options;
264
+ this.eventFormatter = new EventFormatter(this.options.namespace);
265
+ this.subscribe();
266
+ }
267
+ /**
268
+ * Subscribe to the channel.
269
+ */
270
+ subscribe() {
271
+ this.options.debug && console.log(`${LOG_PREFIX$1} subscribe for channel ${this.name} ...`);
272
+ this.socket.subscribe(this);
273
+ }
274
+ /**
275
+ * Unsubscribe from the channel.
276
+ */
277
+ unsubscribe() {
278
+ this.options.debug && console.log(`${LOG_PREFIX$1} unsubscribe for channel ${this.name} ...`);
279
+ this.socket.unsubscribe(this);
280
+ }
281
+ /**
282
+ * Listen for an event on the channel instance.
283
+ */
284
+ listen(event, callback) {
285
+ this.options.debug && console.log(`${LOG_PREFIX$1} listen to ${event} for channel ${this.name} ...`);
286
+ return this.on(this.eventFormatter.format(event), callback);
287
+ }
288
+ /**
289
+ * Stop listening for an event on the channel instance. Without a callback, every listener of the event is removed.
290
+ */
291
+ stopListening(event, callback) {
292
+ this.options.debug && console.log(`${LOG_PREFIX$1} stop listening to ${event} for channel ${this.name} ...`);
293
+ this.socket.unbind(this, this.eventFormatter.format(event), callback);
294
+ return this;
295
+ }
566
296
  /**
567
297
  * Listen for a whisper event on the channel instance.
568
298
  */
569
299
  listenForWhisper(event, callback) {
570
300
  return this.listen('.client-' + event, callback);
571
301
  }
302
+ /**
303
+ * Stop listening for a whisper event on the channel instance.
304
+ */
305
+ stopListeningForWhisper(event, callback) {
306
+ return this.stopListening('.client-' + event, callback);
307
+ }
572
308
  /**
573
309
  * Listen for an event on the channel instance.
574
310
  */
575
311
  notification(callback) {
576
- return this.listen('.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated', callback);
312
+ return this.listen(NOTIFICATION_EVENT, callback);
577
313
  }
578
314
  /**
579
- * Stop listening for a whisper event on the channel instance.
315
+ * Stop listening for notification events on the channel instance.
580
316
  */
581
- stopListeningForWhisper(event, callback) {
582
- return this.stopListening('.client-' + event, callback);
317
+ stopListeningForNotification(callback) {
318
+ return this.stopListening(NOTIFICATION_EVENT, callback);
583
319
  }
584
- }
585
-
586
- var LOG_PREFIX$1 = '[LE-AG-Channel]';
587
- /**
588
- * This class represents a Pusher channel.
589
- */
590
-
591
- var Channel$1 = /*#__PURE__*/function (_BaseChannel) {
592
- _inherits(Channel, _BaseChannel);
593
-
594
- var _super = _createSuper(Channel);
595
-
596
- /**
597
- * Create a new class instance.
598
- */
599
- function Channel(socket, name, options) {
600
- var _this;
601
-
602
- _classCallCheck(this, Channel);
603
-
604
- _this = _super.call(this);
605
- _this.name = name;
606
- _this.socket = socket;
607
- _this.options = options;
608
- _this.eventFormatter = new EventFormatter(_this.options["namespace"]);
609
-
610
- _this.subscribe();
611
-
612
- return _this;
613
- }
614
- /**
615
- * Subscribe to a Pusher channel.
616
- */
617
-
618
-
619
- _createClass(Channel, [{
620
- key: "subscribe",
621
- value: function subscribe() {
622
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " subscribe for channel ").concat(this.name, " ..."));
623
- this.socket.subscribe(this);
320
+ /**
321
+ * Register a callback to be called anytime a subscription succeeds.
322
+ */
323
+ subscribed(callback) {
324
+ return this.on('subscription_succeeded', () => {
325
+ callback();
326
+ });
624
327
  }
625
328
  /**
626
- * Unsubscribe from a Pusher channel.
329
+ * Register a callback to be called anytime a subscription or authorization error occurs.
627
330
  */
628
-
629
- }, {
630
- key: "unsubscribe",
631
- value: function unsubscribe() {
632
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " unsubscribe for channel ").concat(this.name, " ..."));
633
- this.socket.unsubscribe(this);
331
+ error(callback) {
332
+ return this.on('error', callback);
634
333
  }
635
334
  /**
636
- * Listen for an event on the channel instance.
335
+ * Bind a channel to an event.
637
336
  */
638
-
639
- }, {
640
- key: "listen",
641
- value: function listen(event, callback) {
642
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " listen to ").concat(event, " for channel ").concat(this.name, " ..."));
643
- this.on(this.eventFormatter.format(event), callback);
644
- return this;
337
+ on(event, callback) {
338
+ this.options.debug && console.log(`${LOG_PREFIX$1} on ${event} for channel ${this.name} ...`);
339
+ this.socket.bind(this, event, callback);
340
+ return this;
645
341
  }
646
342
  /**
647
- * Stop listening for an event on the channel instance.
343
+ * Send a client event to the other members of the channel.
648
344
  */
649
-
650
- }, {
651
- key: "stopListening",
652
- value: function stopListening(event, callback) {
653
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " stop listening to ").concat(event, " for channel ").concat(this.name, " ..."));
654
- this.socket.unbindEvent(this, event, callback);
655
- return this;
345
+ whisper(event, data) {
346
+ this.socket.send({
347
+ event: 'client-' + event,
348
+ channel: this.name,
349
+ data,
350
+ });
351
+ return this;
656
352
  }
657
353
  /**
658
- * Register a callback to be called anytime a subscription succeeds.
354
+ * Presence channels are not supported yet: member tracking is not implemented on the server.
659
355
  */
660
-
661
- }, {
662
- key: "subscribed",
663
- value: function subscribed(callback) {
664
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " subscribed for channel ").concat(this.name, " ..."));
665
- this.on('subscription_succeeded', function () {
666
- callback();
667
- });
668
- return this;
356
+ here(_callback) {
357
+ return this;
669
358
  }
670
359
  /**
671
- * Register a callback to be called anytime a subscription error occurs.
360
+ * Presence channels are not supported yet: member tracking is not implemented on the server.
672
361
  */
673
-
674
- }, {
675
- key: "error",
676
- value: function error(callback) {
677
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " error for channel ").concat(this.name, " ..."));
678
- this.on('error', function (status) {
679
- callback(status);
680
- });
681
- return this;
362
+ joining(_callback) {
363
+ return this;
682
364
  }
683
365
  /**
684
- * Bind a channel to an event.
366
+ * Presence channels are not supported yet: member tracking is not implemented on the server.
685
367
  */
368
+ leaving(_callback) {
369
+ return this;
370
+ }
371
+ }
686
372
 
687
- }, {
688
- key: "on",
689
- value: function on(event, callback) {
690
- this.options["debug"] && console.log("".concat(LOG_PREFIX$1, " on ").concat(event, " for channel ").concat(this.name, " ..."));
691
- this.socket.bind(this, event, callback);
692
- return this;
693
- }
694
- }, {
695
- key: "whisper",
696
- value: function whisper(event, data) {
697
- var channel = this.name;
698
- var formattedEvent = "client-" + event;
699
- this.socket.send({
700
- "event": formattedEvent,
701
- data: data,
702
- channel: channel
703
- });
704
- return this;
705
- }
706
- }, {
707
- key: "here",
708
- value: function here(callback) {
709
- // TODO: implement
710
- return this;
373
+ const LOG_PREFIX = '[LE-AG-Connector]';
374
+ /**
375
+ * Laravel Echo connector for API Gateway websockets.
376
+ *
377
+ * It does not extend laravel-echo's internal classes, so it works with laravel-echo v1 and v2:
378
+ * both create custom connectors with `new options.broadcaster(options)`.
379
+ */
380
+ class Connector {
381
+ /**
382
+ * Create a new class instance. Without a host no connection is opened, which keeps
383
+ * laravel-echo v2's `new broadcaster()` capability check free of side effects.
384
+ */
385
+ constructor(options = {}) {
386
+ /**
387
+ * All of the subscribed channel names.
388
+ */
389
+ this.channels = {};
390
+ this.setOptions(options);
391
+ this.connect();
711
392
  }
712
393
  /**
713
- * Listen for someone joining the channel.
394
+ * Merge the custom options with the defaults and add the CSRF and bearer token headers.
714
395
  */
715
-
716
- }, {
717
- key: "joining",
718
- value: function joining(callback) {
719
- // TODO: implement
720
- return this;
396
+ setOptions(options) {
397
+ var _a, _b;
398
+ this.options = Object.assign(Object.assign(Object.assign({}, Connector._defaultOptions), options), { auth: {
399
+ headers: Object.assign({}, ((_b = (_a = options.auth) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : {})),
400
+ } });
401
+ const csrfToken = this.csrfToken();
402
+ if (csrfToken) {
403
+ this.options.auth.headers['X-CSRF-TOKEN'] = csrfToken;
404
+ }
405
+ if (this.options.bearerToken) {
406
+ this.options.auth.headers['Authorization'] = 'Bearer ' + this.options.bearerToken;
407
+ }
721
408
  }
722
409
  /**
723
- * Listen for someone leaving the channel.
410
+ * Extract the CSRF token from the page.
724
411
  */
725
-
726
- }, {
727
- key: "leaving",
728
- value: function leaving(callback) {
729
- // TODO: implement
730
- return this;
412
+ csrfToken() {
413
+ var _a, _b, _c;
414
+ if (typeof window !== 'undefined' && ((_a = window.Laravel) === null || _a === void 0 ? void 0 : _a.csrfToken)) {
415
+ return window.Laravel.csrfToken;
416
+ }
417
+ if (this.options.csrfToken) {
418
+ return this.options.csrfToken;
419
+ }
420
+ if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
421
+ return (_c = (_b = document.querySelector('meta[name="csrf-token"]')) === null || _b === void 0 ? void 0 : _b.getAttribute('content')) !== null && _c !== void 0 ? _c : null;
422
+ }
423
+ return null;
731
424
  }
732
- }]);
733
-
734
- return Channel;
735
- }(Channel);
736
-
737
- var broadcaster = function broadcaster(options) {
738
- return new Connector$1(options);
739
- };
740
- var LOG_PREFIX$2 = '[LE-AG-Connector]';
741
- var Connector$1 = /*#__PURE__*/function (_BaseConnector) {
742
- _inherits(Connector, _BaseConnector);
743
-
744
- var _super = _createSuper(Connector);
745
-
746
- /**
747
- * Create a new class instance.
748
- */
749
- function Connector(options) {
750
- var _this;
751
-
752
- _classCallCheck(this, Connector);
753
-
754
- _this = _super.call(this, options);
755
425
  /**
756
- * All of the subscribed channel names.
426
+ * Create a fresh websocket connection.
757
427
  */
758
-
759
- _this.channels = {};
760
- return _this;
761
- }
762
- /**
763
- * Create a fresh Socket.io connection.
764
- */
765
-
766
-
767
- _createClass(Connector, [{
768
- key: "connect",
769
- value: function connect() {
770
- this.options.debug && console.log(LOG_PREFIX$2 + 'Connect ...');
771
- this.socket = new Websocket(this.options);
772
- return; //
773
- // this.socket.on('reconnect', () => {
774
- // Object.values(this.channels).forEach((channel) => {
775
- // channel.subscribe();
776
- // });
777
- // });
778
- //
779
- // return this.socket;
428
+ connect() {
429
+ this.options.debug && console.log(LOG_PREFIX + ' Connect ...');
430
+ this.socket = new Websocket(this.options);
431
+ }
432
+ /**
433
+ * Listen for an event on a channel instance.
434
+ */
435
+ listen(name, event, callback) {
436
+ return this.channel(name).listen(event, callback);
780
437
  }
781
438
  /**
782
439
  * Get a channel instance by name.
783
440
  */
784
-
785
- }, {
786
- key: "channel",
787
- value: function channel(name) {
788
- if (!this.channels[name]) {
789
- this.channels[name] = new Channel$1(this.socket, name, this.options);
790
- }
791
-
792
- return this.channels[name];
441
+ channel(name) {
442
+ if (!this.channels[name]) {
443
+ this.channels[name] = new Channel(this.socket, name, this.options);
444
+ }
445
+ return this.channels[name];
793
446
  }
794
447
  /**
795
448
  * Get a private channel instance by name.
796
449
  */
797
-
798
- }, {
799
- key: "privateChannel",
800
- value: function privateChannel(name) {
801
- if (!this.channels['private-' + name]) {
802
- this.channels['private-' + name] = new Channel$1(this.socket, 'private-' + name, this.options);
803
- }
804
-
805
- return this.channels['private-' + name];
450
+ privateChannel(name) {
451
+ return this.channel('private-' + name);
806
452
  }
807
453
  /**
808
454
  * Get a presence channel instance by name.
809
455
  */
810
-
811
- }, {
812
- key: "presenceChannel",
813
- value: function presenceChannel(name) {
814
- if (!this.channels['presence-' + name]) {
815
- this.channels['presence-' + name] = new Channel$1(this.socket, 'presence-' + name, this.options);
816
- }
817
-
818
- return this.channels['presence-' + name];
456
+ presenceChannel(name) {
457
+ return this.channel('presence-' + name);
819
458
  }
820
459
  /**
821
460
  * Leave the given channel, as well as its private and presence variants.
822
461
  */
823
-
824
- }, {
825
- key: "leave",
826
- value: function leave(name) {
827
- var _this2 = this;
828
-
829
- var channels = [name, 'private-' + name, 'presence-' + name];
830
- channels.forEach(function (name) {
831
- _this2.leaveChannel(name);
832
- });
462
+ leave(name) {
463
+ [name, 'private-' + name, 'presence-' + name].forEach((channelName) => {
464
+ this.leaveChannel(channelName);
465
+ });
833
466
  }
834
467
  /**
835
468
  * Leave the given channel.
836
469
  */
837
-
838
- }, {
839
- key: "leaveChannel",
840
- value: function leaveChannel(name) {
841
- if (this.channels[name]) {
842
- this.channels[name].unsubscribe();
843
- delete this.channels[name];
844
- }
470
+ leaveChannel(name) {
471
+ if (this.channels[name]) {
472
+ this.channels[name].unsubscribe();
473
+ delete this.channels[name];
474
+ }
845
475
  }
846
476
  /**
847
477
  * Get the socket ID for the connection.
848
478
  */
849
-
850
- }, {
851
- key: "socketId",
852
- value: function socketId() {
853
- return this.socket.getSocketId();
479
+ socketId() {
480
+ return this.socket.getSocketId();
854
481
  }
855
482
  /**
856
483
  * Disconnect socket connection.
857
484
  */
858
-
859
- }, {
860
- key: "disconnect",
861
- value: function disconnect() {
862
- this.options.debug && console.log(LOG_PREFIX$2 + 'Disconnect ...');
863
- this.socket.close();
485
+ disconnect() {
486
+ this.options.debug && console.log(LOG_PREFIX + ' Disconnect ...');
487
+ this.socket.close();
864
488
  }
865
- }]);
866
-
867
- return Connector;
868
- }(Connector);
489
+ }
490
+ /**
491
+ * Default connector options, matching laravel-echo's defaults.
492
+ */
493
+ Connector._defaultOptions = {
494
+ auth: {
495
+ headers: {},
496
+ },
497
+ authEndpoint: '/broadcasting/auth',
498
+ csrfToken: null,
499
+ bearerToken: null,
500
+ host: null,
501
+ namespace: 'App.Events',
502
+ };
503
+ /**
504
+ * Kept for backwards compatibility: `new Echo({ broadcaster })`. A function declaration (not an arrow
505
+ * function) so laravel-echo can call it with `new`.
506
+ */
507
+ function broadcaster(options) {
508
+ return new Connector(options);
509
+ }
869
510
 
870
- export { Connector$1 as Connector, broadcaster };
511
+ export { Channel, Connector, EventFormatter, broadcaster };