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