@folklore/socket 0.4.11 → 0.4.13

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 (3) hide show
  1. package/dist/cjs.js +649 -823
  2. package/dist/es.js +649 -813
  3. package/package.json +6 -6
package/dist/cjs.js CHANGED
@@ -2,22 +2,12 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
6
- var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
7
- var _defineProperty = require('@babel/runtime/helpers/defineProperty');
8
- var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
9
- var _createClass = require('@babel/runtime/helpers/createClass');
10
- var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
11
- var _inherits = require('@babel/runtime/helpers/inherits');
12
- var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
13
- var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
14
5
  var createDebug = require('debug');
15
6
  var EventEmitter = require('wolfy87-eventemitter');
16
7
  var invariant = require('invariant');
17
8
  var isFunction = require('lodash/isFunction');
18
9
  var isArray = require('lodash/isArray');
19
10
  var React = require('react');
20
- var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
21
11
  var PropTypes = require('prop-types');
22
12
  var jsxRuntime = require('react/jsx-runtime');
23
13
  var isString = require('lodash/isString');
@@ -42,827 +32,689 @@ function _interopNamespace(e) {
42
32
  return Object.freeze(n);
43
33
  }
44
34
 
45
- var _objectWithoutProperties__default = /*#__PURE__*/_interopDefaultLegacy(_objectWithoutProperties);
46
- var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
47
- var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
48
- var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
49
- var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
50
- var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
51
- var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
52
- var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
53
- var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
54
35
  var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
55
36
  var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
56
37
  var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
57
38
  var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);
58
39
  var isArray__default = /*#__PURE__*/_interopDefaultLegacy(isArray);
59
40
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
60
- var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
61
41
  var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);
62
42
  var isString__default = /*#__PURE__*/_interopDefaultLegacy(isString);
63
43
 
64
- function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
44
+ const debug$2 = createDebug__default["default"]('folklore:socket:pubnub');
65
45
 
66
- function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
67
-
68
- function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
69
-
70
- function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
71
- var debug$2 = createDebug__default["default"]('folklore:socket:pubnub');
72
-
73
- var PubNubSocket = /*#__PURE__*/function (_EventEmitter) {
74
- _inherits__default["default"](PubNubSocket, _EventEmitter);
75
-
76
- var _super = _createSuper$2(PubNubSocket);
77
-
78
- function PubNubSocket(opts) {
79
- var _this;
80
-
81
- _classCallCheck__default["default"](this, PubNubSocket);
82
-
83
- _this = _super.call(this);
84
- _this.options = _objectSpread$4({
46
+ class PubNubSocket extends EventEmitter__default["default"] {
47
+ constructor(opts) {
48
+ super();
49
+ this.options = {
85
50
  uuid: null,
86
51
  publishKey: null,
87
52
  subscribeKey: null,
88
- secretKey: null
89
- }, opts);
90
- _this.onReady = _this.onReady.bind(_assertThisInitialized__default["default"](_this));
91
- _this.onStatus = _this.onStatus.bind(_assertThisInitialized__default["default"](_this));
92
- _this.onMessage = _this.onMessage.bind(_assertThisInitialized__default["default"](_this));
93
- _this.ready = false;
94
- _this.shouldStart = false;
95
- _this.started = false;
96
- _this.starting = false;
97
- _this.PubNub = null;
98
- _this.pubnub = null;
99
- _this.pubnubListener = null;
100
- _this.channels = [];
101
-
102
- _this.init();
103
-
104
- return _this;
53
+ secretKey: null,
54
+ ...opts
55
+ };
56
+ this.onReady = this.onReady.bind(this);
57
+ this.onStatus = this.onStatus.bind(this);
58
+ this.onMessage = this.onMessage.bind(this);
59
+ this.destroyed = false;
60
+ this.ready = false;
61
+ this.shouldStart = false;
62
+ this.started = false;
63
+ this.starting = false;
64
+ this.PubNub = null;
65
+ this.pubnub = null;
66
+ this.pubnubListener = null;
67
+ this.channels = [];
68
+ this.init();
105
69
  }
106
70
 
107
- _createClass__default["default"](PubNubSocket, [{
108
- key: "onReady",
109
- value: function onReady() {
110
- this.ready = true;
111
- this.emit('ready');
71
+ onReady() {
72
+ if (this.destroyed) {
73
+ return;
112
74
  }
113
- }, {
114
- key: "onStatus",
115
- value: function onStatus(statusEvent) {
116
- if (statusEvent.category === 'PNConnectedCategory' && !this.started) {
117
- this.started = true;
118
- this.starting = false;
119
- this.emit('started');
120
- }
121
- }
122
- }, {
123
- key: "onMessage",
124
- value: function onMessage(_ref) {
125
- var message = _ref.message;
126
- this.emit('message', message);
127
-
128
- if (typeof message.event !== 'undefined') {
129
- this.emit(message.event, message.data || message);
130
- }
131
- }
132
- }, {
133
- key: "updateChannels",
134
- value: function updateChannels(channels) {
135
- debug$2("Updating channels: ".concat(channels.join(', ')));
136
- var shouldStart = this.shouldStart,
137
- started = this.started,
138
- starting = this.starting;
139
-
140
- if (started || starting) {
141
- this.stop();
142
- }
143
75
 
144
- this.channels = channels;
76
+ this.ready = true;
77
+ this.emit('ready');
78
+ }
145
79
 
146
- if (started || starting || shouldStart) {
147
- this.shouldStart = false;
148
- this.start();
149
- }
150
- }
151
- }, {
152
- key: "init",
153
- value: function init() {
154
- var _this2 = this;
155
-
156
- Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('pubnub')); }).then(function (_ref2) {
157
- var PubNub = _ref2.default;
158
- _this2.PubNub = PubNub;
159
- }).then(function () {
160
- return _this2.createPubNub();
161
- }).then(function () {
162
- return _this2.onReady();
163
- });
80
+ onStatus(statusEvent) {
81
+ if (statusEvent.category === 'PNConnectedCategory' && !this.started) {
82
+ this.started = true;
83
+ this.starting = false;
84
+ this.emit('started');
164
85
  }
165
- }, {
166
- key: "createPubNub",
167
- value: function createPubNub() {
168
- var PubNub = this.PubNub;
169
- var pubnubOptions = {
170
- publishKey: this.options.publishKey,
171
- subscribeKey: this.options.subscribeKey
172
- };
173
-
174
- if (this.options.uuid !== null) {
175
- pubnubOptions.uuid = this.options.uuid;
176
- }
86
+ }
177
87
 
178
- if (this.options.secretKey !== null) {
179
- pubnubOptions.secretKey = this.options.secretKey;
180
- }
88
+ onMessage(_ref) {
89
+ let {
90
+ message
91
+ } = _ref;
92
+ this.emit('message', message);
181
93
 
182
- this.pubnub = new PubNub(pubnubOptions);
183
- this.pubnubListener = {
184
- status: this.onStatus,
185
- message: this.onMessage
186
- };
187
- this.pubnub.addListener(this.pubnubListener);
94
+ if (typeof message.event !== 'undefined') {
95
+ this.emit(message.event, message.data || message);
188
96
  }
189
- }, {
190
- key: "destroy",
191
- value: function destroy() {
97
+ }
98
+
99
+ updateChannels(channels) {
100
+ debug$2("Updating channels: ".concat(channels.join(', ')));
101
+ const {
102
+ shouldStart,
103
+ started,
104
+ starting
105
+ } = this;
106
+
107
+ if (started || starting) {
192
108
  this.stop();
109
+ }
193
110
 
194
- if (this.pubnubListener) {
195
- this.pubnub.removeListener(this.pubnubListener);
196
- this.pubnubListener = null;
197
- }
111
+ this.channels = channels;
198
112
 
199
- this.ready = false;
200
- debug$2('Destroyed.');
113
+ if (started || starting || shouldStart) {
114
+ this.shouldStart = false;
115
+ this.start();
201
116
  }
202
- }, {
203
- key: "start",
204
- value: function start() {
205
- if (this.started) {
206
- debug$2('Skipping start: Already started.');
207
- return;
208
- }
117
+ }
209
118
 
210
- if (this.starting) {
211
- debug$2('Skipping start: Already starting.');
212
- return;
213
- }
119
+ init() {
120
+ if (this.pubnub !== null) {
121
+ return;
122
+ }
214
123
 
215
- if (this.channels.length === 0) {
216
- debug$2('Skipping start: No channels.');
217
- this.shouldStart = true;
218
- return;
219
- }
124
+ debug$2('Init');
125
+ this.destroyed = false;
126
+ const loadPubnub = this.PubNub !== null ? Promise.resolve() : this.loadPubNub();
127
+ loadPubnub.then(() => this.createPubNub()).then(() => this.onReady());
128
+ }
220
129
 
221
- this.shouldStart = false;
222
- this.starting = true;
223
- this.pubnub.subscribe({
224
- channels: this.channels
225
- });
226
- this.emit('start');
130
+ loadPubNub() {
131
+ debug$2('Load PubNub');
132
+ return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('pubnub')); }).then(_ref2 => {
133
+ let {
134
+ default: PubNub
135
+ } = _ref2;
136
+ this.PubNub = PubNub;
137
+ });
138
+ }
139
+
140
+ createPubNub() {
141
+ if (this.destroyed) {
142
+ return;
227
143
  }
228
- }, {
229
- key: "stop",
230
- value: function stop() {
231
- if (!this.started && !this.starting) {
232
- return;
233
- }
234
144
 
235
- debug$2('Stopping...');
236
- this.shouldStart = false;
237
- this.started = false;
238
- this.starting = false;
239
- this.pubnub.unsubscribe({
240
- channels: this.channels
241
- });
242
- this.emit('stop');
145
+ const {
146
+ PubNub
147
+ } = this;
148
+ const pubnubOptions = {
149
+ publishKey: this.options.publishKey,
150
+ subscribeKey: this.options.subscribeKey
151
+ };
152
+
153
+ if (this.options.uuid !== null) {
154
+ pubnubOptions.uuid = this.options.uuid;
243
155
  }
244
- }, {
245
- key: "send",
246
- value: function send(data) {
247
- var _this3 = this;
248
-
249
- debug$2('Sending', data);
250
- return new Promise(function (resolve, reject) {
251
- _this3.pubnub.publish(data, function (status, response) {
252
- if (status.error) {
253
- reject(new Error("Error operation:".concat(status.operation, " status:").concat(status.statusCode)));
254
- } else {
255
- resolve({
256
- status: status,
257
- response: response,
258
- data: data
259
- });
260
- }
261
- });
262
- });
156
+
157
+ if (this.options.secretKey !== null) {
158
+ pubnubOptions.secretKey = this.options.secretKey;
263
159
  }
264
- }]);
265
160
 
266
- return PubNubSocket;
267
- }(EventEmitter__default["default"]);
161
+ this.pubnub = new PubNub(pubnubOptions);
162
+ this.pubnubListener = {
163
+ status: this.onStatus,
164
+ message: this.onMessage
165
+ };
166
+ this.pubnub.addListener(this.pubnubListener);
167
+ }
268
168
 
269
- var _excluded$1 = ["host"];
169
+ destroy() {
170
+ this.destroyed = true;
171
+ this.stop();
270
172
 
271
- function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
173
+ if (this.pubnubListener) {
174
+ this.pubnub.removeListener(this.pubnubListener);
175
+ this.pubnubListener = null;
176
+ }
272
177
 
273
- function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
178
+ this.pubnub = null;
179
+ this.ready = false;
180
+ debug$2('Destroyed.');
181
+ }
274
182
 
275
- function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
183
+ start() {
184
+ if (this.started) {
185
+ debug$2('Skipping start: Already started.');
186
+ return;
187
+ }
276
188
 
277
- function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
278
- var debug$1 = createDebug__default["default"]('folklore:socket:socketio');
189
+ if (this.starting) {
190
+ debug$2('Skipping start: Already starting.');
191
+ return;
192
+ }
279
193
 
280
- var SocketIOSocket = /*#__PURE__*/function (_EventEmitter) {
281
- _inherits__default["default"](SocketIOSocket, _EventEmitter);
194
+ if (this.channels.length === 0) {
195
+ debug$2('Skipping start: No channels.');
196
+ this.shouldStart = true;
197
+ return;
198
+ }
282
199
 
283
- var _super = _createSuper$1(SocketIOSocket);
200
+ this.shouldStart = false;
201
+ this.starting = true;
202
+ this.pubnub.subscribe({
203
+ channels: this.channels
204
+ });
205
+ this.emit('start');
206
+ }
284
207
 
285
- function SocketIOSocket(opts) {
286
- var _this;
208
+ stop() {
209
+ if (!this.started && !this.starting) {
210
+ return;
211
+ }
287
212
 
288
- _classCallCheck__default["default"](this, SocketIOSocket);
213
+ debug$2('Stopping...');
214
+ this.shouldStart = false;
215
+ this.started = false;
216
+ this.starting = false;
217
+ this.pubnub.unsubscribe({
218
+ channels: this.channels
219
+ });
220
+ this.emit('stop');
221
+ }
289
222
 
290
- _this = _super.call(this);
291
- _this.options = _objectSpread$3({
223
+ send(data) {
224
+ debug$2('Sending', data);
225
+ return new Promise((resolve, reject) => {
226
+ this.pubnub.publish(data, (status, response) => {
227
+ if (status.error) {
228
+ reject(new Error("Error operation:".concat(status.operation, " status:").concat(status.statusCode)));
229
+ } else {
230
+ resolve({
231
+ status,
232
+ response,
233
+ data
234
+ });
235
+ }
236
+ });
237
+ });
238
+ }
239
+
240
+ }
241
+
242
+ const debug$1 = createDebug__default["default"]('folklore:socket:socketio');
243
+
244
+ class SocketIOSocket extends EventEmitter__default["default"] {
245
+ constructor(opts) {
246
+ super();
247
+ this.options = {
292
248
  uuid: null,
293
249
  host: 'http://127.0.0.1',
294
250
  path: null,
295
- query: null
296
- }, opts);
297
- _this.onReady = _this.onReady.bind(_assertThisInitialized__default["default"](_this));
298
- _this.onConnect = _this.onConnect.bind(_assertThisInitialized__default["default"](_this));
299
- _this.onMessage = _this.onMessage.bind(_assertThisInitialized__default["default"](_this));
300
- _this.ready = false;
301
- _this.shouldStart = false;
302
- _this.started = false;
303
- _this.starting = false;
304
- _this.Manager = null;
305
- _this.io = null;
306
- _this.sockets = {};
307
- _this.channels = [];
308
-
309
- _this.init();
310
-
311
- return _this;
251
+ query: null,
252
+ ...opts
253
+ };
254
+ this.onReady = this.onReady.bind(this);
255
+ this.onConnect = this.onConnect.bind(this);
256
+ this.onMessage = this.onMessage.bind(this);
257
+ this.ready = false;
258
+ this.shouldStart = false;
259
+ this.started = false;
260
+ this.starting = false;
261
+ this.Manager = null;
262
+ this.io = null;
263
+ this.sockets = {};
264
+ this.channels = [];
265
+ this.init();
312
266
  }
313
267
 
314
- _createClass__default["default"](SocketIOSocket, [{
315
- key: "onReady",
316
- value: function onReady() {
317
- this.ready = true;
318
- this.emit('ready');
319
- }
320
- }, {
321
- key: "onConnect",
322
- value: function onConnect(channel) {
323
- debug$1('Socket connected on %s', channel);
324
-
325
- if (!this.started) {
326
- this.started = true;
327
- this.starting = false;
328
- this.emit('started');
329
- }
330
- }
331
- }, {
332
- key: "onMessage",
333
- value: function onMessage(message, channel) {
334
- debug$1('Message received on %s %o', channel, message);
335
- this.emit('message', message, channel);
336
- }
337
- }, {
338
- key: "init",
339
- value: function init() {
340
- var _this2 = this;
341
-
342
- Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('socket.io-client')); }).then(function (_ref) {
343
- var IO = _ref.default;
344
- _this2.Manager = IO.Manager;
345
- }).then(function () {
346
- return _this2.createManager();
347
- }).then(function () {
348
- return _this2.onReady();
349
- }).then(function () {
350
- if (_this2.shouldStart) {
351
- _this2.start();
352
- }
353
- });
354
- }
355
- }, {
356
- key: "createManager",
357
- value: function createManager() {
358
- var Manager = this.Manager;
359
-
360
- var _this$options = this.options,
361
- host = _this$options.host,
362
- opts = _objectWithoutProperties__default["default"](_this$options, _excluded$1);
363
-
364
- this.io = new Manager(host, _objectSpread$3({
365
- autoConnect: false
366
- }, opts));
268
+ onReady() {
269
+ this.ready = true;
270
+ this.emit('ready');
271
+ }
272
+
273
+ onConnect(channel) {
274
+ debug$1('Socket connected on %s', channel);
275
+
276
+ if (!this.started) {
277
+ this.started = true;
278
+ this.starting = false;
279
+ this.emit('started');
367
280
  }
368
- }, {
369
- key: "updateChannels",
370
- value: function updateChannels(channels) {
371
- debug$1("Updating channels: ".concat(channels.join(', ')));
372
- var shouldStart = this.shouldStart,
373
- started = this.started,
374
- starting = this.starting;
375
-
376
- if (started || starting) {
377
- this.stop();
378
- }
281
+ }
379
282
 
380
- this.channels = channels;
283
+ onMessage(message, channel) {
284
+ debug$1('Message received on %s %o', channel, message);
285
+ this.emit('message', message, channel);
286
+ }
381
287
 
382
- if (started || starting || shouldStart) {
288
+ init() {
289
+ Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('socket.io-client')); }).then(_ref => {
290
+ let {
291
+ default: IO
292
+ } = _ref;
293
+ this.Manager = IO.Manager;
294
+ }).then(() => this.createManager()).then(() => this.onReady()).then(() => {
295
+ if (this.shouldStart) {
383
296
  this.start();
384
297
  }
385
- }
386
- }, {
387
- key: "start",
388
- value: function start() {
389
- var _this3 = this;
390
-
391
- if (this.started) {
392
- debug$1('Skipping start: Already started.');
393
- return;
394
- }
298
+ });
299
+ }
395
300
 
396
- if (this.starting) {
397
- debug$1('Skipping start: Already starting.');
398
- return;
399
- }
301
+ createManager() {
302
+ const {
303
+ Manager
304
+ } = this;
305
+ const {
306
+ host,
307
+ ...opts
308
+ } = this.options;
309
+ this.io = new Manager(host, {
310
+ autoConnect: false,
311
+ ...opts
312
+ });
313
+ }
400
314
 
401
- if (this.io === null) {
402
- debug$1('Socket.io not ready.');
403
- this.shouldStart = true;
404
- return;
405
- }
315
+ updateChannels(channels) {
316
+ debug$1("Updating channels: ".concat(channels.join(', ')));
317
+ const {
318
+ shouldStart,
319
+ started,
320
+ starting
321
+ } = this;
406
322
 
407
- if (this.channels.length === 0) {
408
- debug$1('Skipping start: No channels.');
409
- this.shouldStart = true;
410
- return;
411
- }
323
+ if (started || starting) {
324
+ this.stop();
325
+ }
412
326
 
413
- this.shouldStart = false;
414
- this.starting = true;
415
- this.sockets = this.channels.reduce(function (map, channel) {
416
- return _objectSpread$3(_objectSpread$3({}, map), {}, _defineProperty__default["default"]({}, channel, _this3.createSocket(channel)));
417
- }, {});
418
- this.emit('start');
327
+ this.channels = channels;
328
+
329
+ if (started || starting || shouldStart) {
330
+ this.start();
419
331
  }
420
- }, {
421
- key: "stop",
422
- value: function stop() {
423
- var _this4 = this;
332
+ }
424
333
 
425
- if (!this.started && !this.starting) {
426
- return;
427
- }
334
+ start() {
335
+ if (this.started) {
336
+ debug$1('Skipping start: Already started.');
337
+ return;
338
+ }
428
339
 
429
- debug$1('Stopping...');
430
- this.shouldStart = false;
431
- this.started = false;
432
- this.starting = false;
433
- Object.values(this.sockets).forEach(function (socket) {
434
- return _this4.stopSocket(socket);
435
- });
436
- this.emit('stop');
340
+ if (this.starting) {
341
+ debug$1('Skipping start: Already starting.');
342
+ return;
437
343
  }
438
- }, {
439
- key: "createSocket",
440
- value: function createSocket(channel) {
441
- var _this5 = this;
442
-
443
- var socket = this.io.socket("/".concat(channel.replace(/^\//, '')));
444
- socket.on('message', function (message) {
445
- return _this5.onMessage(message, channel);
446
- });
447
- socket.on('connect', function () {
448
- return _this5.onConnect(channel);
449
- });
450
- socket.open();
451
- return socket;
452
- } // eslint-disable-next-line class-methods-use-this
453
-
454
- }, {
455
- key: "stopSocket",
456
- value: function stopSocket(socket) {
457
- socket.off('connect');
458
- socket.off('message');
459
- socket.close();
460
- return socket;
344
+
345
+ if (this.io === null) {
346
+ debug$1('Socket.io not ready.');
347
+ this.shouldStart = true;
348
+ return;
461
349
  }
462
- }, {
463
- key: "destroy",
464
- value: function destroy() {
465
- this.stop();
466
- this.sockets = {};
467
350
 
468
- if (this.io !== null) {
469
- this.io.close();
470
- this.io = null;
471
- }
351
+ if (this.channels.length === 0) {
352
+ debug$1('Skipping start: No channels.');
353
+ this.shouldStart = true;
354
+ return;
472
355
  }
473
- }, {
474
- key: "send",
475
- value: function send(data) {
476
- var _this6 = this;
477
-
478
- var channel = data.channel,
479
- message = data.message;
480
- var channels = !isArray__default["default"](channel) ? [channel] : channel;
481
- channels.forEach(function (ch) {
482
- _this6.sockets[ch].send(message);
483
- });
484
- return Promise.resolve();
356
+
357
+ this.shouldStart = false;
358
+ this.starting = true;
359
+ this.sockets = this.channels.reduce((map, channel) => ({ ...map,
360
+ [channel]: this.createSocket(channel)
361
+ }), {});
362
+ this.emit('start');
363
+ }
364
+
365
+ stop() {
366
+ if (!this.started && !this.starting) {
367
+ return;
485
368
  }
486
- }]);
487
369
 
488
- return SocketIOSocket;
489
- }(EventEmitter__default["default"]);
370
+ debug$1('Stopping...');
371
+ this.shouldStart = false;
372
+ this.started = false;
373
+ this.starting = false;
374
+ Object.values(this.sockets).forEach(socket => this.stopSocket(socket));
375
+ this.emit('stop');
376
+ }
490
377
 
491
- var SocketAdapters = {
492
- PubNub: PubNubSocket,
493
- SocketIO: SocketIOSocket
494
- };
378
+ createSocket(channel) {
379
+ const socket = this.io.socket("/".concat(channel.replace(/^\//, '')));
380
+ socket.on('message', message => this.onMessage(message, channel));
381
+ socket.on('connect', () => this.onConnect(channel));
382
+ socket.open();
383
+ return socket;
384
+ } // eslint-disable-next-line class-methods-use-this
495
385
 
496
- var _excluded = ["adapter", "channels"];
497
386
 
498
- function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
387
+ stopSocket(socket) {
388
+ socket.off('connect');
389
+ socket.off('message');
390
+ socket.close();
391
+ return socket;
392
+ }
499
393
 
500
- function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
394
+ destroy() {
395
+ this.stop();
396
+ this.sockets = {};
501
397
 
502
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
398
+ if (this.io !== null) {
399
+ this.io.close();
400
+ this.io = null;
401
+ }
402
+ }
503
403
 
504
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
404
+ send(data) {
405
+ const {
406
+ channel,
407
+ message
408
+ } = data;
409
+ const channels = !isArray__default["default"](channel) ? [channel] : channel;
410
+ channels.forEach(ch => {
411
+ this.sockets[ch].send(message);
412
+ });
413
+ return Promise.resolve();
414
+ }
505
415
 
506
- var normalize = function normalize(str) {
507
- return str.replace(/[^a-z0-9]+/gi, '').toLowerCase();
416
+ }
417
+
418
+ var SocketAdapters = {
419
+ PubNub: PubNubSocket,
420
+ SocketIO: SocketIOSocket
508
421
  };
509
422
 
510
- var debug = createDebug__default["default"]('folklore:socket');
423
+ const normalize = str => str.replace(/[^a-z0-9]+/gi, '').toLowerCase();
424
+
425
+ const debug = createDebug__default["default"]('folklore:socket');
426
+
427
+ class Socket extends EventEmitter__default["default"] {
428
+ static getAdapters() {
429
+ return Socket.adapters;
430
+ }
431
+
432
+ static getAdapter(adapter) {
433
+ // prettier-ignore
434
+ const adapterKey = Object.keys(Socket.adapters).find(key => normalize(key) === normalize(adapter)) || null;
511
435
 
512
- var Socket = /*#__PURE__*/function (_EventEmitter) {
513
- _inherits__default["default"](Socket, _EventEmitter);
436
+ if (adapterKey === null) {
437
+ throw new Error("Adapter ".concat(adapter, " not found"));
438
+ }
514
439
 
515
- var _super = _createSuper(Socket);
440
+ return Socket.adapters[adapterKey];
441
+ }
516
442
 
517
- function Socket(opts) {
518
- var _this;
443
+ static addAdapter(name, adapter) {
444
+ Socket.adapters = { ...Socket.adapters,
445
+ [name]: adapter
446
+ };
447
+ return Socket;
448
+ }
519
449
 
520
- _classCallCheck__default["default"](this, Socket);
450
+ static setAdapters(adapters) {
451
+ Socket.adapters = adapters;
452
+ return Socket;
453
+ }
521
454
 
522
- _this = _super.call(this);
523
- _this.options = _objectSpread$2({
455
+ constructor(opts) {
456
+ super();
457
+ this.options = {
524
458
  adapter: 'pubnub',
525
459
  namespace: null,
526
460
  uuid: null,
527
461
  publishKey: null,
528
462
  subscribeKey: null,
529
463
  secretKey: null,
530
- channels: []
531
- }, opts);
532
- _this.onAdapterReady = _this.onAdapterReady.bind(_assertThisInitialized__default["default"](_this));
533
- _this.onAdapterStart = _this.onAdapterStart.bind(_assertThisInitialized__default["default"](_this));
534
- _this.onAdapterStarted = _this.onAdapterStarted.bind(_assertThisInitialized__default["default"](_this));
535
- _this.onAdapterMessage = _this.onAdapterMessage.bind(_assertThisInitialized__default["default"](_this));
536
- _this.onAdapterStop = _this.onAdapterStop.bind(_assertThisInitialized__default["default"](_this));
537
- _this.shouldStart = false;
538
- _this.started = false;
539
- _this.starting = false;
540
- _this.ready = false;
541
- _this.adapter = null;
542
- _this.channels = [];
543
-
544
- _this.init();
545
-
546
- if (_this.options.channels.length) {
547
- _this.setChannels(_this.options.channels);
464
+ channels: [],
465
+ ...opts
466
+ };
467
+ this.onAdapterReady = this.onAdapterReady.bind(this);
468
+ this.onAdapterStart = this.onAdapterStart.bind(this);
469
+ this.onAdapterStarted = this.onAdapterStarted.bind(this);
470
+ this.onAdapterMessage = this.onAdapterMessage.bind(this);
471
+ this.onAdapterStop = this.onAdapterStop.bind(this);
472
+ this.shouldStart = false;
473
+ this.started = false;
474
+ this.starting = false;
475
+ this.ready = false;
476
+ this.adapter = null;
477
+ this.channels = [];
478
+ this.init();
479
+
480
+ if (this.options.channels.length) {
481
+ this.setChannels(this.options.channels);
548
482
  }
549
-
550
- return _this;
551
483
  }
552
484
 
553
- _createClass__default["default"](Socket, [{
554
- key: "onAdapterReady",
555
- value: function onAdapterReady() {
556
- debug('Adapter ready');
557
- this.ready = true;
558
- this.emit('ready');
485
+ onAdapterReady() {
486
+ debug('Adapter ready');
487
+ this.ready = true;
488
+ this.emit('ready');
559
489
 
560
- if (this.shouldStart) {
561
- this.shouldStart = false;
562
- this.start();
563
- }
564
- }
565
- }, {
566
- key: "onAdapterStart",
567
- value: function onAdapterStart() {
568
- debug('Adapter starting...');
569
- this.starting = true;
570
- this.started = false;
571
- this.emit('start');
572
- }
573
- }, {
574
- key: "onAdapterStarted",
575
- value: function onAdapterStarted() {
576
- debug('Adapter started');
577
- this.starting = false;
578
- this.started = true;
579
- this.emit('started');
580
- }
581
- }, {
582
- key: "onAdapterStop",
583
- value: function onAdapterStop() {
584
- debug('Adapter stopped');
585
- this.starting = false;
586
- this.started = false;
587
- this.emit('stop');
588
- }
589
- }, {
590
- key: "onAdapterMessage",
591
- value: function onAdapterMessage(message) {
592
- debug('Adapter message', message);
593
- this.emit('message', message);
490
+ if (this.shouldStart) {
491
+ this.shouldStart = false;
492
+ this.start();
594
493
  }
595
- }, {
596
- key: "getChannelWithoutNamespace",
597
- value: function getChannelWithoutNamespace(name) {
598
- if (this.options.namespace === null) {
599
- return name;
600
- }
494
+ }
601
495
 
602
- var regExp = new RegExp("^".concat(this.options.namespace, ":"));
603
- return name.replace(regExp, '');
604
- }
605
- }, {
606
- key: "getChannelWithNamespace",
607
- value: function getChannelWithNamespace(name) {
608
- var parts = [];
496
+ onAdapterStart() {
497
+ debug('Adapter starting...');
498
+ this.starting = true;
499
+ this.started = false;
500
+ this.emit('start');
501
+ }
609
502
 
610
- if (this.options.namespace !== null) {
611
- parts.push(this.options.namespace);
612
- }
503
+ onAdapterStarted() {
504
+ debug('Adapter started');
505
+ this.starting = false;
506
+ this.started = true;
507
+ this.emit('started');
508
+ }
509
+
510
+ onAdapterStop() {
511
+ debug('Adapter stopped');
512
+ this.starting = false;
513
+ this.started = false;
514
+ this.emit('stop');
515
+ }
516
+
517
+ onAdapterMessage(message) {
518
+ debug('Adapter message', message);
519
+ this.emit('message', message);
520
+ }
613
521
 
614
- parts.push(name);
615
- return parts.join(':');
522
+ getChannelWithoutNamespace(name) {
523
+ if (this.options.namespace === null) {
524
+ return name;
616
525
  }
617
- }, {
618
- key: "setChannels",
619
- value: function setChannels(channels) {
620
- var _this2 = this;
621
526
 
622
- var namespacedChannels = channels.map(function (channel) {
623
- return _this2.getChannelWithNamespace(channel);
624
- }).sort();
527
+ const regExp = new RegExp("^".concat(this.options.namespace, ":"));
528
+ return name.replace(regExp, '');
529
+ }
625
530
 
626
- if (this.channels.join(',') === namespacedChannels.join(',')) {
627
- return;
628
- }
531
+ getChannelWithNamespace(name) {
532
+ const parts = [];
629
533
 
630
- debug("Set channels: ".concat(namespacedChannels.join(', ')));
631
- this.updateChannels(namespacedChannels);
534
+ if (this.options.namespace !== null) {
535
+ parts.push(this.options.namespace);
632
536
  }
633
- }, {
634
- key: "addChannel",
635
- value: function addChannel(channel) {
636
- var namespacedChannel = this.getChannelWithNamespace(channel);
637
537
 
638
- if (this.channels.indexOf(namespacedChannel) !== -1) {
639
- return;
640
- }
538
+ parts.push(name);
539
+ return parts.join(':');
540
+ }
641
541
 
642
- debug("Adding channel: ".concat(channel));
643
- this.updateChannels([].concat(_toConsumableArray__default["default"](this.channels), [namespacedChannel]));
644
- }
645
- }, {
646
- key: "addChannels",
647
- value: function addChannels(channels) {
648
- var _this3 = this;
649
-
650
- var namespacedChannels = channels.map(function (channel) {
651
- return _this3.getChannelWithNamespace(channel);
652
- }).sort();
653
- debug("Adding channels: ".concat(channels.join(',')));
654
- this.updateChannels([].concat(_toConsumableArray__default["default"](this.channels), _toConsumableArray__default["default"](namespacedChannels.filter(function (it) {
655
- return _this3.channels.indexOf(it) === -1;
656
- }))));
542
+ setChannels(channels) {
543
+ const namespacedChannels = channels.map(channel => this.getChannelWithNamespace(channel)).sort();
544
+
545
+ if (this.channels.join(',') === namespacedChannels.join(',')) {
546
+ return;
657
547
  }
658
- }, {
659
- key: "removeChannel",
660
- value: function removeChannel(channel) {
661
- var namespacedChannel = this.getChannelWithNamespace(channel);
662
548
 
663
- if (this.channels.indexOf(namespacedChannel) === -1) {
664
- return;
665
- }
549
+ debug("Set channels: ".concat(namespacedChannels.join(', ')));
550
+ this.updateChannels(namespacedChannels);
551
+ }
666
552
 
667
- debug("Removing channel: ".concat(channel));
668
- this.updateChannels(this.channels.filter(function (ch) {
669
- return ch !== namespacedChannel;
670
- }));
671
- }
672
- }, {
673
- key: "removeChannels",
674
- value: function removeChannels(channels) {
675
- var _this4 = this;
676
-
677
- var namespacedChannels = channels.map(function (channel) {
678
- return _this4.getChannelWithNamespace(channel);
679
- }).sort();
680
- debug("Removing channels: ".concat(channels.join(',')));
681
- this.updateChannels(this.channels.filter(function (it) {
682
- return namespacedChannels.indexOf(it) === -1;
683
- }));
684
- }
685
- }, {
686
- key: "updateChannels",
687
- value: function updateChannels(channels) {
688
- var sortedChannels = channels.sort();
689
- debug("Updating channels: ".concat(sortedChannels.join(', ')));
690
- this.channels = _toConsumableArray__default["default"](sortedChannels);
691
-
692
- if (this.adapter !== null) {
693
- this.adapter.updateChannels(sortedChannels);
694
- }
695
- }
696
- }, {
697
- key: "hasChannel",
698
- value: function hasChannel(channel) {
699
- var namespacedChannel = this.getChannelWithNamespace(channel);
700
- return this.channels.reduce(function (found, it) {
701
- return found || it === namespacedChannel;
702
- }, false);
703
- }
704
- }, {
705
- key: "getChannels",
706
- value: function getChannels() {
707
- var _this5 = this;
553
+ addChannel(channel) {
554
+ const namespacedChannel = this.getChannelWithNamespace(channel);
708
555
 
709
- return this.channels.map(function (channel) {
710
- return _this5.getChannelWithoutNamespace(channel);
711
- });
712
- }
713
- }, {
714
- key: "init",
715
- value: function init() {
716
- var _this6 = this;
717
-
718
- var _this$options = this.options,
719
- adapterKey = _this$options.adapter;
720
- _this$options.channels;
721
- var adapterOptions = _objectWithoutProperties__default["default"](_this$options, _excluded);
722
-
723
- var SocketAdapter = Socket.getAdapter(adapterKey);
724
- this.adapter = new SocketAdapter(adapterOptions);
725
- var methods = ['start', 'stop', 'destroy', 'updateChannels', 'send'];
726
- methods.forEach(function (method) {
727
- invariant__default["default"](isFunction__default["default"](_this6.adapter[method] || null), "Socket adapter should implement method ".concat(method));
728
- });
729
- this.adapter.on('ready', this.onAdapterReady);
730
- this.adapter.on('start', this.onAdapterStart);
731
- this.adapter.on('started', this.onAdapterStarted);
732
- this.adapter.on('message', this.onAdapterMessage);
733
- this.adapter.on('stop', this.onAdapterStop);
556
+ if (this.channels.indexOf(namespacedChannel) !== -1) {
557
+ return;
734
558
  }
735
- }, {
736
- key: "destroy",
737
- value: function destroy() {
738
- if (this.adapter !== null) {
739
- this.adapter.removeAllListeners();
740
- this.adapter.destroy();
741
- this.adapter = null;
742
- }
743
559
 
744
- this.started = false;
745
- this.starting = false;
746
- this.ready = false;
747
- debug('Destroyed.');
748
- }
749
- }, {
750
- key: "restart",
751
- value: function restart() {
752
- this.stop();
753
- this.start();
560
+ debug("Adding channel: ".concat(channel));
561
+ this.updateChannels([...this.channels, namespacedChannel]);
562
+ }
563
+
564
+ addChannels(channels) {
565
+ const namespacedChannels = channels.map(channel => this.getChannelWithNamespace(channel)).sort();
566
+ debug("Adding channels: ".concat(channels.join(',')));
567
+ this.updateChannels([...this.channels, ...namespacedChannels.filter(it => this.channels.indexOf(it) === -1)]);
568
+ }
569
+
570
+ removeChannel(channel) {
571
+ const namespacedChannel = this.getChannelWithNamespace(channel);
572
+
573
+ if (this.channels.indexOf(namespacedChannel) === -1) {
574
+ return;
754
575
  }
755
- }, {
756
- key: "start",
757
- value: function start() {
758
- var _this7 = this;
759
-
760
- if (this.started) {
761
- debug('Skipping start: Already started.');
762
- return;
763
- }
764
576
 
765
- if (this.starting) {
766
- debug('Skipping start: Already starting.');
767
- return;
768
- }
577
+ debug("Removing channel: ".concat(channel));
578
+ this.updateChannels(this.channels.filter(ch => ch !== namespacedChannel));
579
+ }
769
580
 
770
- if (!this.ready) {
771
- debug('Skipping start: No ready.');
772
- this.shouldStart = true;
773
- return;
774
- }
581
+ removeChannels(channels) {
582
+ const namespacedChannels = channels.map(channel => this.getChannelWithNamespace(channel)).sort();
583
+ debug("Removing channels: ".concat(channels.join(',')));
584
+ this.updateChannels(this.channels.filter(it => namespacedChannels.indexOf(it) === -1));
585
+ }
775
586
 
776
- this.shouldStart = false;
777
- debug('Starting on channels:');
778
- this.channels.forEach(function (channel) {
779
- debug("- ".concat(_this7.getChannelWithoutNamespace(channel)));
780
- });
781
- this.adapter.start();
587
+ updateChannels(channels) {
588
+ const sortedChannels = channels.sort();
589
+ debug("Updating channels: ".concat(sortedChannels.join(', ')));
590
+ this.channels = [...sortedChannels];
591
+
592
+ if (this.adapter !== null) {
593
+ this.adapter.updateChannels(sortedChannels);
782
594
  }
783
- }, {
784
- key: "stop",
785
- value: function stop() {
786
- this.shouldStart = false;
595
+ }
787
596
 
788
- if (!this.started && !this.starting) {
789
- return;
790
- }
597
+ hasChannel(channel) {
598
+ const namespacedChannel = this.getChannelWithNamespace(channel);
599
+ return this.channels.reduce((found, it) => found || it === namespacedChannel, false);
600
+ }
791
601
 
792
- debug('Stopping...');
602
+ getChannels() {
603
+ return this.channels.map(channel => this.getChannelWithoutNamespace(channel));
604
+ }
793
605
 
794
- if (this.adapter !== null) {
795
- this.adapter.stop();
796
- }
606
+ init() {
607
+ if (this.adapter !== null) {
608
+ debug('Already initialized');
609
+ return;
610
+ }
611
+
612
+ debug('Init');
613
+ const {
614
+ adapter: adapterKey,
615
+ channels,
616
+ ...adapterOptions
617
+ } = this.options;
618
+ const SocketAdapter = Socket.getAdapter(adapterKey);
619
+ this.adapter = new SocketAdapter(adapterOptions);
620
+ const methods = ['start', 'stop', 'destroy', 'updateChannels', 'send'];
621
+ methods.forEach(method => {
622
+ invariant__default["default"](isFunction__default["default"](this.adapter[method] || null), "Socket adapter should implement method ".concat(method));
623
+ });
624
+ this.adapter.on('ready', this.onAdapterReady);
625
+ this.adapter.on('start', this.onAdapterStart);
626
+ this.adapter.on('started', this.onAdapterStarted);
627
+ this.adapter.on('message', this.onAdapterMessage);
628
+ this.adapter.on('stop', this.onAdapterStop);
629
+ }
630
+
631
+ destroy() {
632
+ if (this.adapter !== null) {
633
+ this.adapter.removeAllListeners();
634
+ this.adapter.destroy();
635
+ this.adapter = null;
797
636
  }
798
- }, {
799
- key: "send",
800
- value: function send(data, channel) {
801
- if (!this.started) {
802
- debug('Abort sending data: Not started');
803
- return Promise.reject();
804
- }
805
637
 
806
- var publishData = typeof data.channel !== 'undefined' && typeof data.message !== 'undefined' ? data : {
807
- channel: typeof channel !== 'undefined' ? this.getChannelWithNamespace(channel) : this.channels,
808
- message: data
809
- };
810
- debug('Sending', publishData);
811
- return this.adapter.send(publishData);
638
+ this.started = false;
639
+ this.starting = false;
640
+ this.ready = false;
641
+ debug('Destroyed.');
642
+ }
643
+
644
+ restart() {
645
+ this.stop();
646
+ this.start();
647
+ }
648
+
649
+ start() {
650
+ if (this.started) {
651
+ debug('Skipping start: Already started.');
652
+ return;
812
653
  }
813
- }, {
814
- key: "isStarted",
815
- value: function isStarted() {
816
- return this.started;
654
+
655
+ if (this.starting) {
656
+ debug('Skipping start: Already starting.');
657
+ return;
817
658
  }
818
- }], [{
819
- key: "getAdapters",
820
- value: function getAdapters() {
821
- return Socket.adapters;
659
+
660
+ if (!this.ready) {
661
+ debug('Skipping start: No ready.');
662
+ this.shouldStart = true;
663
+ return;
822
664
  }
823
- }, {
824
- key: "getAdapter",
825
- value: function getAdapter(adapter) {
826
- // prettier-ignore
827
- var adapterKey = Object.keys(Socket.adapters).find(function (key) {
828
- return normalize(key) === normalize(adapter);
829
- }) || null;
830
-
831
- if (adapterKey === null) {
832
- throw new Error("Adapter ".concat(adapter, " not found"));
833
- }
834
665
 
835
- return Socket.adapters[adapterKey];
666
+ this.shouldStart = false;
667
+ debug('Starting on channels:');
668
+ this.channels.forEach(channel => {
669
+ debug("- ".concat(this.getChannelWithoutNamespace(channel)));
670
+ });
671
+ this.adapter.start();
672
+ }
673
+
674
+ stop() {
675
+ this.shouldStart = false;
676
+
677
+ if (!this.started && !this.starting) {
678
+ return;
836
679
  }
837
- }, {
838
- key: "addAdapter",
839
- value: function addAdapter(name, adapter) {
840
- Socket.adapters = _objectSpread$2(_objectSpread$2({}, Socket.adapters), {}, _defineProperty__default["default"]({}, name, adapter));
841
- return Socket;
680
+
681
+ debug('Stopping...');
682
+
683
+ if (this.adapter !== null) {
684
+ this.adapter.stop();
842
685
  }
843
- }, {
844
- key: "setAdapters",
845
- value: function setAdapters(adapters) {
846
- Socket.adapters = adapters;
847
- return Socket;
686
+ }
687
+
688
+ send(data, channel) {
689
+ if (!this.started) {
690
+ debug('Abort sending data: Not started');
691
+ return Promise.reject();
848
692
  }
849
- }]);
850
693
 
851
- return Socket;
852
- }(EventEmitter__default["default"]);
694
+ const publishData = typeof data.channel !== 'undefined' && typeof data.message !== 'undefined' ? data : {
695
+ channel: typeof channel !== 'undefined' ? this.getChannelWithNamespace(channel) : this.channels,
696
+ message: data
697
+ };
698
+ debug('Sending', publishData);
699
+ return this.adapter.send(publishData);
700
+ }
701
+
702
+ isStarted() {
703
+ return this.started;
704
+ }
705
+
706
+ }
853
707
 
854
- Socket.adapters = _objectSpread$2({}, SocketAdapters);
708
+ Socket.adapters = { ...SocketAdapters
709
+ };
855
710
 
856
- var SocketContext = /*#__PURE__*/React__default["default"].createContext({
711
+ const SocketContext = /*#__PURE__*/React__default["default"].createContext({
857
712
  socket: null,
858
- subscribe: function subscribe() {},
859
- unsubscribe: function unsubscribe() {}
713
+ subscribe: () => {},
714
+ unsubscribe: () => {}
860
715
  });
861
716
 
862
- function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
863
-
864
- function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
865
- var propTypes = {
717
+ const propTypes = {
866
718
  socket: PropTypes__default["default"].instanceOf(Socket),
867
719
  adapter: PropTypes__default["default"].string,
868
720
  host: PropTypes__default["default"].string,
@@ -875,7 +727,7 @@ var propTypes = {
875
727
  autoStart: PropTypes__default["default"].bool,
876
728
  children: PropTypes__default["default"].node
877
729
  };
878
- var defaultProps = {
730
+ const defaultProps = {
879
731
  socket: null,
880
732
  adapter: 'pubnub',
881
733
  host: null,
@@ -889,82 +741,73 @@ var defaultProps = {
889
741
  children: null
890
742
  };
891
743
 
892
- var SocketContainer = function SocketContainer(_ref) {
893
- var children = _ref.children,
894
- socket = _ref.socket,
895
- autoStart = _ref.autoStart,
896
- adapter = _ref.adapter,
897
- host = _ref.host,
898
- namespace = _ref.namespace,
899
- uuid = _ref.uuid,
900
- publishKey = _ref.publishKey,
901
- subscribeKey = _ref.subscribeKey,
902
- secretKey = _ref.secretKey,
903
- initialChannels = _ref.channels;
904
- var finalSocket = React.useMemo(function () {
905
- return socket || new Socket({
906
- adapter: adapter,
907
- host: host,
908
- namespace: namespace,
909
- uuid: uuid,
910
- publishKey: publishKey,
911
- subscribeKey: subscribeKey,
912
- secretKey: secretKey
913
- });
914
- }, [socket, host, adapter, namespace, uuid, publishKey, subscribeKey, secretKey]);
915
-
916
- var _useState = React.useState([]),
917
- _useState2 = _slicedToArray__default["default"](_useState, 2),
918
- channels = _useState2[0],
919
- setChannels = _useState2[1];
920
-
921
- var channelsCountRef = React.useRef({});
922
- var updateChannels = React.useCallback(function (newChannels) {
744
+ const SocketContainer = function (_ref) {
745
+ let {
746
+ children,
747
+ socket,
748
+ autoStart,
749
+ adapter,
750
+ host,
751
+ namespace,
752
+ uuid,
753
+ publishKey,
754
+ subscribeKey,
755
+ secretKey,
756
+ channels: initialChannels
757
+ } = _ref;
758
+ const finalSocket = React.useMemo(() => socket || new Socket({
759
+ adapter,
760
+ host,
761
+ namespace,
762
+ uuid,
763
+ publishKey,
764
+ subscribeKey,
765
+ secretKey
766
+ }), [socket, host, adapter, namespace, uuid, publishKey, subscribeKey, secretKey]);
767
+ const [channels, setChannels] = React.useState([]);
768
+ const channelsCountRef = React.useRef({});
769
+ const updateChannels = React.useCallback(newChannels => {
923
770
  finalSocket.setChannels(newChannels);
924
771
  setChannels(newChannels);
925
772
  }, [finalSocket, setChannels]);
926
- var addToChannelsCount = React.useCallback(function (newChannels) {
927
- channelsCountRef.current = newChannels.reduce(function (map, channel) {
928
- return _objectSpread$1(_objectSpread$1({}, map), {}, _defineProperty__default["default"]({}, channel, (map[channel] || 0) + 1));
929
- }, channelsCountRef.current);
773
+ const addToChannelsCount = React.useCallback(newChannels => {
774
+ channelsCountRef.current = newChannels.reduce((map, channel) => ({ ...map,
775
+ [channel]: (map[channel] || 0) + 1
776
+ }), channelsCountRef.current);
930
777
  updateChannels(Object.keys(channelsCountRef.current));
931
778
  }, [updateChannels]);
932
- var removeToChannelsCount = React.useCallback(function (newChannels) {
933
- channelsCountRef.current = newChannels.reduce(function (map, channel) {
934
- var newCount = (map[channel] || 0) - 1;
935
- return newCount > 0 ? _objectSpread$1(_objectSpread$1({}, map), {}, _defineProperty__default["default"]({}, channel, newCount)) : map;
779
+ const removeToChannelsCount = React.useCallback(newChannels => {
780
+ channelsCountRef.current = newChannels.reduce((map, channel) => {
781
+ const newCount = (map[channel] || 0) - 1;
782
+ return newCount > 0 ? { ...map,
783
+ [channel]: newCount
784
+ } : map;
936
785
  }, channelsCountRef.current);
937
786
  updateChannels(Object.keys(channelsCountRef.current));
938
787
  }, [updateChannels]);
939
- var subscribe = React.useCallback(function (channelsToAdd) {
940
- return addToChannelsCount(channelsToAdd);
941
- }, [addToChannelsCount]);
942
- var unsubscribe = React.useCallback(function (channelsToRemove) {
943
- return removeToChannelsCount(channelsToRemove);
944
- }, [removeToChannelsCount]);
945
- React.useEffect(function () {
788
+ const subscribe = React.useCallback(channelsToAdd => addToChannelsCount(channelsToAdd), [addToChannelsCount]);
789
+ const unsubscribe = React.useCallback(channelsToRemove => removeToChannelsCount(channelsToRemove), [removeToChannelsCount]);
790
+ React.useEffect(() => {
946
791
  subscribe(initialChannels);
947
- return function () {
792
+ return () => {
948
793
  unsubscribe(initialChannels);
949
794
  };
950
795
  }, [initialChannels, subscribe, unsubscribe]);
951
- React.useEffect(function () {
796
+ React.useEffect(() => {
952
797
  if (autoStart) {
953
798
  finalSocket.start();
954
799
  }
955
800
 
956
- return function () {
801
+ return () => {
957
802
  finalSocket.destroy();
958
803
  };
959
804
  }, [autoStart, finalSocket]);
960
- var value = React.useMemo(function () {
961
- return {
962
- socket: finalSocket,
963
- subscribe: subscribe,
964
- unsubscribe: unsubscribe,
965
- channels: channels
966
- };
967
- }, [finalSocket, subscribe]);
805
+ const value = React.useMemo(() => ({
806
+ socket: finalSocket,
807
+ subscribe,
808
+ unsubscribe,
809
+ channels
810
+ }), [finalSocket, subscribe]);
968
811
  return /*#__PURE__*/jsxRuntime.jsx(SocketContext.Provider, {
969
812
  value: value,
970
813
  children: children
@@ -974,75 +817,58 @@ var SocketContainer = function SocketContainer(_ref) {
974
817
  SocketContainer.propTypes = propTypes;
975
818
  SocketContainer.defaultProps = defaultProps;
976
819
 
977
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
978
-
979
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
980
-
981
- var getDisplayName = function getDisplayName(WrappedComponent) {
982
- return WrappedComponent.displayName || WrappedComponent.name || 'Component';
983
- };
984
-
985
- var withSocket = function withSocket(WrappedComponent) {
986
- var WithSocketComponent = function WithSocketComponent(props) {
987
- return /*#__PURE__*/jsxRuntime.jsx(SocketContext.Consumer, {
988
- children: function children(_ref) {
989
- var socket = _ref.socket,
990
- subscribe = _ref.subscribe,
991
- unsubscribe = _ref.unsubscribe;
992
- return /*#__PURE__*/jsxRuntime.jsx(WrappedComponent, _objectSpread({
993
- socket: socket,
994
- socketSubscribe: subscribe,
995
- socketUnsubscribe: unsubscribe
996
- }, props));
997
- }
998
- });
999
- };
820
+ const getDisplayName = WrappedComponent => WrappedComponent.displayName || WrappedComponent.name || 'Component';
821
+
822
+ const withSocket = WrappedComponent => {
823
+ const WithSocketComponent = props => /*#__PURE__*/jsxRuntime.jsx(SocketContext.Consumer, {
824
+ children: _ref => {
825
+ let {
826
+ socket,
827
+ subscribe,
828
+ unsubscribe
829
+ } = _ref;
830
+ return /*#__PURE__*/jsxRuntime.jsx(WrappedComponent, {
831
+ socket: socket,
832
+ socketSubscribe: subscribe,
833
+ socketUnsubscribe: unsubscribe,
834
+ ...props
835
+ });
836
+ }
837
+ });
1000
838
 
1001
839
  WithSocketComponent.displayName = "WithSocket(".concat(getDisplayName(WrappedComponent), ")");
1002
840
  return WithSocketComponent;
1003
841
  };
1004
842
 
1005
- var useSocket = function useSocket() {
1006
- var channelNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1007
-
1008
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
1009
- _ref$socket = _ref.socket,
1010
- customSocket = _ref$socket === void 0 ? null : _ref$socket,
1011
- _ref$onMessage = _ref.onMessage,
1012
- customOnMessage = _ref$onMessage === void 0 ? null : _ref$onMessage;
1013
-
1014
- var _useContext = React.useContext(SocketContext),
1015
- contextSocket = _useContext.socket,
1016
- subscribe = _useContext.subscribe,
1017
- unsubscribe = _useContext.unsubscribe;
1018
-
1019
- var socket = customSocket || contextSocket || null;
1020
-
1021
- var _useState = React.useState(socket !== null ? socket.isStarted() : false),
1022
- _useState2 = _slicedToArray__default["default"](_useState, 2),
1023
- started = _useState2[0],
1024
- setStarted = _useState2[1];
1025
-
1026
- var channels = isString__default["default"](channelNames) ? [channelNames] : channelNames;
1027
- var channelsKey = (channels || []).sort().join(',');
1028
- React.useEffect(function () {
843
+ const useSocket = function () {
844
+ let channelNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
845
+ let {
846
+ socket: customSocket = null,
847
+ onMessage: customOnMessage = null
848
+ } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
849
+ const {
850
+ socket: contextSocket,
851
+ subscribe,
852
+ unsubscribe
853
+ } = React.useContext(SocketContext);
854
+ const socket = customSocket || contextSocket || null;
855
+ const [started, setStarted] = React.useState(socket !== null ? socket.isStarted() : false);
856
+ const channels = isString__default["default"](channelNames) ? [channelNames] : channelNames;
857
+ const channelsKey = (channels || []).sort().join(',');
858
+ React.useEffect(() => {
1029
859
  if (socket === null) {
1030
860
  if (process.env.NODE_ENV !== 'production') {
1031
861
  console.warn('Socket context is empty.');
1032
862
  }
1033
863
 
1034
- return function () {};
864
+ return () => {};
1035
865
  }
1036
866
 
1037
- var wasStarted = socket.isStarted();
867
+ const wasStarted = socket.isStarted();
1038
868
 
1039
- var onStarted = function onStarted() {
1040
- return setStarted(true);
1041
- };
869
+ const onStarted = () => setStarted(true);
1042
870
 
1043
- var onStop = function onStop() {
1044
- return setStarted(false);
1045
- };
871
+ const onStop = () => setStarted(false);
1046
872
 
1047
873
  socket.on('stop', onStop);
1048
874
  socket.on('started', onStarted);
@@ -1055,7 +881,7 @@ var useSocket = function useSocket() {
1055
881
  socket.start();
1056
882
  }
1057
883
 
1058
- return function () {
884
+ return () => {
1059
885
  socket.off('stop', onStop);
1060
886
  socket.off('started', onStarted);
1061
887
 
@@ -1068,27 +894,27 @@ var useSocket = function useSocket() {
1068
894
  }
1069
895
  };
1070
896
  }, [channelsKey, customSocket]);
1071
- React.useEffect(function () {
897
+ React.useEffect(() => {
1072
898
  if (socket === null) {
1073
- return function () {};
899
+ return () => {};
1074
900
  }
1075
901
 
1076
- var onMessage = function onMessage() {
902
+ const onMessage = function () {
1077
903
  if (customOnMessage !== null) {
1078
- customOnMessage.apply(void 0, arguments);
904
+ customOnMessage(...arguments);
1079
905
  }
1080
906
  };
1081
907
 
1082
908
  socket.on('message', onMessage);
1083
- return function () {
909
+ return () => {
1084
910
  socket.off('message', onMessage);
1085
911
  };
1086
912
  }, [customOnMessage]);
1087
913
  return {
1088
- socket: socket,
1089
- started: started,
1090
- subscribe: subscribe,
1091
- unsubscribe: unsubscribe
914
+ socket,
915
+ started,
916
+ subscribe,
917
+ unsubscribe
1092
918
  };
1093
919
  };
1094
920