@qikdev/sdk 0.1.164 → 0.1.166

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,4 +1,4 @@
1
- import { EventDispatcher } from './qik.utils.js';
1
+ import { EventDispatcher } from "./qik.utils.js";
2
2
 
3
3
  ///////////////////////////////////////////////////
4
4
 
@@ -11,338 +11,348 @@ import { EventDispatcher } from './qik.utils.js';
11
11
  * @param {QikAPI} qik A reference to the parent instance of the QikCore module. This module is usually created by a QikCore instance that passes itself in as the first argument.
12
12
  */
13
13
 
14
- const QikSocket = function(qik, mode) {
15
-
16
- mode = mode || 'production';
17
-
18
- if (!qik.auth) {
19
- throw new Error(`Can't Instantiate QikSocket before QikAuth exists`);
14
+ const QikSocket = function (qik, mode) {
15
+ mode = mode || "production";
16
+
17
+ if (!qik.auth) {
18
+ throw new Error(`Can't Instantiate QikSocket before QikAuth exists`);
19
+ }
20
+
21
+ const windowID = qik.utils.guid();
22
+
23
+ ///////////////////////////////////////////////////
24
+
25
+ let service = {
26
+ debug: false,
27
+ url: `wss://iqtm6zjz3l.execute-api.ap-southeast-2.amazonaws.com/${mode}`,
28
+ connected: false,
29
+ windowID,
30
+ autoreconnect: true,
31
+ };
32
+
33
+ let socket;
34
+ let timer;
35
+ let buckets = {};
36
+ const channels = {};
37
+
38
+ //Create a new dispatcher
39
+ const dispatcher = new EventDispatcher();
40
+ dispatcher.bootstrap(service);
41
+
42
+ ///////////////////////////////////////////////////
43
+
44
+ function getSubscriptions() {
45
+ return Object.keys(buckets);
46
+ }
47
+
48
+ ///////////////////////////////////////////////////
49
+
50
+ /**
51
+ * @description Create an event dispatcher instance and subscribe to a new socket channel.
52
+ * This can then be used to receive socket events for this channel
53
+ * @alias socket.channel
54
+ * @param {String} key The key or name of the channel to subscribe to
55
+ * @example
56
+ * const socketChannel = await sdk.socket.channel('awesome:notifications')
57
+ * socketChannel.addEventListener('message', function(message) {
58
+ * console.log('Received a new message from the socket')
59
+ * })
60
+ *
61
+ * // Disconnect from this channel and remove all listeners
62
+ * socketChannel.destroy();
63
+ *
64
+ */
65
+ service.channel = async function (key) {
66
+ if (!buckets[key]) {
67
+ // Create a new channel instance
68
+ const bucket = new EventDispatcher();
69
+ buckets[key] = bucket;
70
+
71
+ // If the user isn't online
72
+ if (!service.connected) {
73
+ // Connect them now
74
+ await service.connect();
75
+ }
76
+
77
+ // Subscribe to this key
78
+ service.subscribe(key);
79
+
80
+ // Listen for all relevant events
81
+ service.addEventListener(key, dispatchMessage);
82
+
83
+ function dispatchMessage(message) {
84
+ bucket.dispatch("message", message);
85
+ }
86
+
87
+ // Destroy the service
88
+ bucket.destroy = function () {
89
+ service.unsubscribe(key);
90
+ buckets[key].removeAllListeners();
91
+ buckets[key] = null;
92
+ };
20
93
  }
21
94
 
95
+ // Return the channel instance
96
+ return buckets[key];
97
+ };
22
98
 
23
- const windowID = qik.utils.guid();
99
+ ///////////////////////////////////////////////////
24
100
 
25
- ///////////////////////////////////////////////////
101
+ function ping() {
102
+ broadcast({
103
+ action: "ping",
104
+ });
105
+ }
26
106
 
27
- let service = {
28
- debug: false,
29
- url: `wss://iqtm6zjz3l.execute-api.ap-southeast-2.amazonaws.com/${mode}`,
30
- connected: false,
31
- windowID,
32
- autoreconnect:true,
107
+ function startHeartbeat() {
108
+ if (timer) {
109
+ return;
33
110
  }
111
+ timer = setInterval(ping, 10000);
112
+ }
34
113
 
35
- let socket;
36
- let timer;
37
- let buckets = {};
38
- const channels = {};
39
-
40
-
41
-
42
- //Create a new dispatcher
43
- const dispatcher = new EventDispatcher();
44
- dispatcher.bootstrap(service);
45
-
46
- ///////////////////////////////////////////////////
47
-
48
- function getSubscriptions() {
49
- return Object.keys(buckets);
114
+ function stopHeartbeat() {
115
+ if (!timer) {
116
+ return;
50
117
  }
51
118
 
52
- ///////////////////////////////////////////////////
53
-
54
-
55
- /**
56
- * @description Create an event dispatcher instance and subscribe to a new socket channel.
57
- * This can then be used to receive socket events for this channel
58
- * @alias socket.channel
59
- * @param {String} key The key or name of the channel to subscribe to
60
- * @example
61
- * const socketChannel = await sdk.socket.channel('awesome:notifications')
62
- * socketChannel.addEventListener('message', function(message) {
63
- * console.log('Received a new message from the socket')
64
- * })
65
- *
66
- * // Disconnect from this channel and remove all listeners
67
- * socketChannel.destroy();
68
- *
69
- */
70
- service.channel = async function(key) {
71
- if (buckets[key]) {
72
- return buckets[key];
73
- }
74
-
75
- const bucket = new EventDispatcher();
76
- buckets[key] = bucket;
77
-
78
- if (!service.connected) {
79
- // Return the socket
80
- await service.connect();
81
- }
82
-
83
- // Subscribe to this channel
84
- service.subscribe(key);
85
-
86
- // Listen for all relevant events
87
- service.addEventListener(key, dispatchMessage);
88
-
89
- function dispatchMessage(message) {
90
- bucket.dispatch('message', message);
91
- }
92
-
93
- // Destroy the service
94
- bucket.destroy = function() {
95
- service.removeAllListeners();
96
- buckets[key] = null;
97
- }
98
-
99
- return buckets[key];
100
- }
101
-
102
- ///////////////////////////////////////////////////
103
-
104
- function ping() {
105
- broadcast({
106
- action: 'ping',
107
- })
108
- }
109
-
110
- function startHeartbeat() {
111
- if (timer) {
112
- return;
113
- }
114
- timer = setInterval(ping, 10000);
119
+ clearInterval(timer);
120
+ timer = null;
121
+ }
122
+
123
+ ///////////////////////////////////////////////////
124
+
125
+ function socketOpened(event) {
126
+ service.debug ? console.log("[socket] Connection open", event) : null;
127
+ service.connected = true;
128
+
129
+ dispatcher.dispatch("connected", event);
130
+
131
+ // startHeartbeat();
132
+ }
133
+
134
+ async function socketClosed(event) {
135
+ if (event.wasClean) {
136
+ service.debug
137
+ ? console.log(
138
+ `[socket] Connection closed cleanly, code=${event.code} reason=${event.reason}`,
139
+ )
140
+ : null;
141
+ } else {
142
+ // e.g. server process killed or network down
143
+ // event.code is usually 1006 in this case
144
+ service.debug
145
+ ? console.log("[socket] - connection closed due to error", event)
146
+ : null;
115
147
  }
116
148
 
117
- function stopHeartbeat() {
118
- if (!timer) {
119
- return;
120
- }
149
+ service.connected = false;
150
+ dispatcher.dispatch("disconnected", event);
151
+ socket = null;
121
152
 
122
- clearInterval(timer)
123
- timer = null;
153
+ if (service.autoreconnect) {
154
+ service.reconnect();
124
155
  }
156
+ }
125
157
 
126
- ///////////////////////////////////////////////////
158
+ function socketError(error) {
159
+ console.log("[event] socketError", event);
160
+ service.debug ? console.log("[socket] Error", error) : null;
161
+ dispatcher.dispatch("error", error);
162
+ }
127
163
 
128
- function socketOpened(event) {
129
- service.debug ? console.log("[socket] Connection open", event) : null;
130
- service.connected = true;
164
+ function socketMessageReceived(event) {
165
+ const eventData = JSON.parse(event.data);
166
+ service.debug ? console.log("[socket] message received", eventData) : null;
131
167
 
132
- dispatcher.dispatch('connected', event);
168
+ // Dispatch a generic message
169
+ dispatcher.dispatch("message", eventData);
133
170
 
134
- // startHeartbeat();
171
+ if (eventData.channel) {
172
+ dispatcher.dispatch(eventData.channel, eventData);
135
173
  }
174
+ }
136
175
 
137
- async function socketClosed(event) {
138
- if (event.wasClean) {
139
- service.debug ? console.log(`[socket] Connection closed cleanly, code=${event.code} reason=${event.reason}`) : null;
140
- } else {
141
- // e.g. server process killed or network down
142
- // event.code is usually 1006 in this case
143
- service.debug ? console.log('[socket] - connection closed due to error', event) : null
144
- }
176
+ async function broadcast(data) {
177
+ socket.send(JSON.stringify(data));
178
+ }
145
179
 
146
- service.connected = false;
147
- dispatcher.dispatch('disconnected', event);
148
- socket = null;
180
+ ///////////////////////////////////////////////////
149
181
 
150
- if(service.autoreconnect) {
151
- service.reconnect();
182
+ function wait() {
183
+ return new Promise(function (resolve) {
184
+ function check() {
185
+ if (service.connected) {
186
+ return resolve(socket);
152
187
  }
153
- }
154
-
155
- function socketError(error) {
156
- console.log('[event] socketError', event);
157
- service.debug ? console.log("[socket] Error", error) : null;
158
- dispatcher.dispatch('error', error);
159
- }
160
188
 
161
- function socketMessageReceived(event) {
162
- const eventData = JSON.parse(event.data);
163
- service.debug ? console.log("[socket] message received", eventData) : null;
164
-
165
- // Dispatch a generic message
166
- dispatcher.dispatch('message', eventData);
167
-
168
- if (eventData.channel) {
169
- dispatcher.dispatch(eventData.channel, eventData);
170
- }
171
- }
189
+ setTimeout(check, 1000);
190
+ }
191
+
192
+ check();
193
+ });
194
+ }
195
+
196
+ ///////////////////////////////////////////////////
197
+
198
+ /**
199
+ * @description Connect to the socket service
200
+ * @alias socket.connect
201
+ * @example
202
+ * const connected = await sdk.socket.connect()
203
+ *
204
+ */
205
+ service.connect = async function () {
206
+ if (socket) {
207
+ if (!socket.connected) {
208
+ return wait();
209
+ }
172
210
 
173
- async function broadcast(data) {
174
- socket.send(JSON.stringify(data));
211
+ console.log("[socket] - Socket is already connected");
212
+ return socket;
175
213
  }
176
214
 
177
- ///////////////////////////////////////////////////
178
-
179
- function wait() {
180
- return new Promise(function(resolve) {
181
- function check() {
182
- if (service.connected) {
183
- return resolve(socket);
184
- }
215
+ const accessToken = qik.auth.getCurrentToken();
185
216
 
186
- setTimeout(check, 1000);
187
- }
188
-
189
- check();
190
- })
217
+ if (!accessToken) {
218
+ service.debug
219
+ ? console.log("[socket] - Must be authenticated to connect to socket")
220
+ : null;
221
+ return;
191
222
  }
192
223
 
193
- ///////////////////////////////////////////////////
194
-
195
- /**
196
- * @description Connect to the socket service
197
- * @alias socket.connect
198
- * @example
199
- * const connected = await sdk.socket.connect()
200
- *
201
- */
202
- service.connect = async function() {
203
- if (socket) {
204
-
205
- if (!socket.connected) {
206
- return wait();
207
- }
208
-
209
- console.log('[socket] - Socket is already connected');
210
- return socket;
211
- }
212
-
213
- const accessToken = qik.auth.getCurrentToken();
214
-
215
- if (!accessToken) {
216
- service.debug ? console.log('[socket] - Must be authenticated to connect to socket') : null;
217
- return;
218
- }
219
-
220
- socket = new WebSocket(`${service.url}?access_token=${accessToken}&windowid=${windowID}`);
221
- socket.addEventListener('close', socketClosed);
222
- socket.addEventListener('error', socketError);
223
- socket.addEventListener('open', socketOpened);
224
- socket.addEventListener('message', socketMessageReceived);
225
- service.debug ? console.log('[socket] - Connected with event listeners') : null;
226
-
227
- return wait();
224
+ socket = new WebSocket(
225
+ `${service.url}?access_token=${accessToken}&windowid=${windowID}`,
226
+ );
227
+ socket.addEventListener("close", socketClosed);
228
+ socket.addEventListener("error", socketError);
229
+ socket.addEventListener("open", socketOpened);
230
+ socket.addEventListener("message", socketMessageReceived);
231
+ service.debug
232
+ ? console.log("[socket] - Connected with event listeners")
233
+ : null;
234
+
235
+ return wait();
236
+ };
237
+
238
+ /**
239
+ * @description Reconnect to the socket service
240
+ * @alias socket.reconnect
241
+ * @example
242
+ * const connected = await sdk.socket.reconnect()
243
+ *
244
+ */
245
+ service.reconnect = async function () {
246
+ if (service.connected) {
247
+ return;
228
248
  }
229
249
 
230
-
231
- /**
232
- * @description Reconnect to the socket service
233
- * @alias socket.reconnect
234
- * @example
235
- * const connected = await sdk.socket.reconnect()
236
- *
237
- */
238
- service.reconnect = async function() {
239
- if(service.connected) {
240
- return;
241
- }
242
-
243
- service.debug ? console.log(`[socket] reconnecting...`) : null;
244
-
245
- // Reconnect all listeners
246
- const result = await service.connect();
247
-
248
- // Resubscribe to all previously connected channels
249
- const subscribedChannels = Object.keys(channels);
250
- subscribedChannels.forEach(function(channel) {
251
- service.subscribe(channel);
252
- })
253
-
254
- return result;
250
+ service.debug ? console.log(`[socket] reconnecting...`) : null;
251
+
252
+ // Reconnect all listeners
253
+ const result = await service.connect();
254
+
255
+ // Resubscribe to all previously connected channels
256
+ const subscribedChannels = Object.keys(channels);
257
+ subscribedChannels.forEach(function (channel) {
258
+ service.subscribe(channel);
259
+ });
260
+
261
+ return result;
262
+ };
263
+
264
+ ///////////////////////////////////////////////////
265
+
266
+ /**
267
+ * @description Close the connection to the socket service
268
+ * @alias socket.close
269
+ * @example
270
+ * const closed = await sdk.socket.close()
271
+ *
272
+ */
273
+ service.close = async function () {
274
+ if (!socket) {
275
+ console.log("[socket] - Socket is not connected");
276
+ return;
255
277
  }
256
-
257
-
258
- ///////////////////////////////////////////////////
259
-
260
- /**
261
- * @description Close the connection to the socket service
262
- * @alias socket.close
263
- * @example
264
- * const closed = await sdk.socket.close()
265
- *
266
- */
267
- service.close = async function() {
268
- if (!socket) {
269
- console.log('[socket] - Socket is not connected');
270
- return;
271
- }
272
278
 
273
- const previousSetting = service.autoreconnect;
274
- service.autoreconnect = false;
275
- socket.close();
276
- socket.removeEventListener('close', socketClosed);
277
- socket.removeEventListener('error', socketError);
278
- socket.removeEventListener('open', socketOpened);
279
- socket.removeEventListener('message', socketMessageReceived);
280
- socket = null;
281
- socketClosed({ wasClean: true });
282
- service.autoreconnect = previousSetting;
279
+ const previousSetting = service.autoreconnect;
280
+ service.autoreconnect = false;
281
+ socket.close();
282
+ socket.removeEventListener("close", socketClosed);
283
+ socket.removeEventListener("error", socketError);
284
+ socket.removeEventListener("open", socketOpened);
285
+ socket.removeEventListener("message", socketMessageReceived);
286
+ socket = null;
287
+ socketClosed({ wasClean: true });
288
+ service.autoreconnect = previousSetting;
289
+ };
290
+
291
+ service.disconnect = service.close;
292
+
293
+ ///////////////////////////////////////////////////
294
+
295
+ /**
296
+ * @description Subscribe to a socket channel
297
+ * @alias socket.subscribe
298
+ * @param {String} key The name of the channel to subscribe to
299
+ * @example
300
+ * const subscribed = await sdk.socket.subscribe('some:cool:alert')
301
+ *
302
+ */
303
+ service.subscribe = async function (channel) {
304
+ if (!socket) {
305
+ console.log(
306
+ `[socket] - Can't subscribe to channel as socket is not connected`,
307
+ );
308
+ return;
283
309
  }
284
310
 
285
- service.disconnect = service.close;
286
-
287
- ///////////////////////////////////////////////////
288
-
289
- /**
290
- * @description Subscribe to a socket channel
291
- * @alias socket.subscribe
292
- * @param {String} key The name of the channel to subscribe to
293
- * @example
294
- * const subscribed = await sdk.socket.subscribe('some:cool:alert')
295
- *
296
- */
297
- service.subscribe = async function(channel) {
298
- if (!socket) {
299
- console.log(`[socket] - Can't subscribe to channel as socket is not connected`);
300
- return;
301
- }
302
-
303
- broadcast({
304
- action: 'subscribe',
305
- channel,
306
- })
307
-
308
- channels[channel] = true;
309
-
310
- dispatcher.dispatch('subscribe', channel)
311
- service.debug ? console.log(`[socket] - subscribed to ${channel}`) : null;
311
+ broadcast({
312
+ action: "subscribe",
313
+ channel,
314
+ });
315
+
316
+ channels[channel] = true;
317
+
318
+ dispatcher.dispatch("subscribe", channel);
319
+ service.debug ? console.log(`[socket] - subscribed to ${channel}`) : null;
320
+ };
321
+
322
+ ///////////////////////////////////////////////////
323
+
324
+ /**
325
+ * @description Unsubscribe from a socket channel
326
+ * @alias socket.unsubscribe
327
+ * @param {String} key The name of the channel to unsubscribe from
328
+ * @example
329
+ * const unsubscribed = await sdk.socket.unsubscribe('some:cool:alert')
330
+ *
331
+ */
332
+ service.unsubscribe = async function (channel) {
333
+ if (!socket) {
334
+ console.log(
335
+ `[socket] - Can't unsubscribe from channel as socket is not connected`,
336
+ );
337
+ return;
312
338
  }
313
339
 
314
- ///////////////////////////////////////////////////
315
-
316
- /**
317
- * @description Unsubscribe from a socket channel
318
- * @alias socket.unsubscribe
319
- * @param {String} key The name of the channel to unsubscribe from
320
- * @example
321
- * const unsubscribed = await sdk.socket.unsubscribe('some:cool:alert')
322
- *
323
- */
324
- service.unsubscribe = async function(channel) {
325
- if (!socket) {
326
- console.log(`[socket] - Can't unsubscribe from channel as socket is not connected`);
327
- return;
328
- }
329
-
330
- broadcast({
331
- action: 'unsubscribe',
332
- channel,
333
- })
334
-
335
- delete channels[channel];
336
-
337
- dispatcher.dispatch('unsubscribe', channel)
338
- service.debug ? console.log(`[socket] - unsubscribed from ${channel}`) : null;
339
- }
340
+ broadcast({
341
+ action: "unsubscribe",
342
+ channel,
343
+ });
340
344
 
341
- ///////////////////////////////////////////////////
345
+ delete channels[channel];
342
346
 
343
- return service;
347
+ dispatcher.dispatch("unsubscribe", channel);
348
+ service.debug
349
+ ? console.log(`[socket] - unsubscribed from ${channel}`)
350
+ : null;
351
+ };
344
352
 
345
- }
353
+ ///////////////////////////////////////////////////
346
354
 
355
+ return service;
356
+ };
347
357
 
348
- export default QikSocket;
358
+ export default QikSocket;
package/src/version.js CHANGED
@@ -1 +1 @@
1
- export const version = "0.1.164";
1
+ export const version = "0.1.166";
package/.eslintcache DELETED
@@ -1 +0,0 @@
1
- [{"/Users/cadeembery/Code/qik/sdk/dist/main.js":"1","/Users/cadeembery/Code/qik/sdk/eslint.config.js":"2","/Users/cadeembery/Code/qik/sdk/src/version.js":"3"},{"size":154130,"mtime":1717379141890,"results":"4","hashOfConfig":"5"},{"size":103,"mtime":1717379186115,"results":"6","hashOfConfig":"5"},{"size":34,"mtime":1717379141891,"results":"7","hashOfConfig":"5"},{"filePath":"8","messages":"9","suppressedMessages":"10","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1wo9pgp",{"filePath":"11","messages":"12","suppressedMessages":"13","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"14","messages":"15","suppressedMessages":"16","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/cadeembery/Code/qik/sdk/dist/main.js",[],[],"/Users/cadeembery/Code/qik/sdk/eslint.config.js",[],[],"/Users/cadeembery/Code/qik/sdk/src/version.js",[],[]]