@zerodensity/realityhub-api 1.20.0 → 2.0.1

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.
@@ -3,7 +3,7 @@
3
3
  // This file is part of realityhub-api.
4
4
  //
5
5
  // realityhub-api is free software: you can redistribute it and/or modify
6
- // it under the terms of the GNU General Public License version 2, as published by
6
+ // it under the terms of the GNU General Public License version 2, as published by
7
7
  // the Free Software Foundation.
8
8
  //
9
9
  // realityhub-api is distributed in the hope that it will be useful,
@@ -14,24 +14,17 @@
14
14
  // You should have received a copy of the GNU General Public License
15
15
  // along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
16
16
 
17
- const { v4: uuid } = require('uuid');
18
- const BrokerBase = require('./BrokerBase.js');
19
- const BrokerError = require('./BrokerError.js');
20
- const RawRequest = require('./RawRequest.js');
21
- const consoleLogger = require('./consoleLogger.js');
22
- const onceMultiple = require('./onceMultiple.js');
17
+ import { v4 as uuid } from 'uuid';
18
+ import BrokerBase from './BrokerBase.js';
19
+ import BrokerError from './BrokerError.js';
20
+ import RawRequest from './RawRequest.js';
21
+ import consoleLogger from './consoleLogger.js';
22
+ import onceMultiple from './onceMultiple.js';
23
+ import WebSocket from 'ws';
23
24
 
24
- let ws;
25
+ const WS = typeof window !== 'undefined' ? window.WebSocket : WebSocket;
25
26
 
26
- const runningInBrowser = typeof window !== 'undefined';
27
-
28
- if (runningInBrowser) {
29
- ws = WebSocket;
30
- } else {
31
- ws = require('ws');
32
- }
33
-
34
- module.exports = class BrokerClient extends BrokerBase {
27
+ export default class BrokerClient extends BrokerBase {
35
28
  /**
36
29
  * BrokerClient constructor
37
30
  * @param {object} params Parameters
@@ -47,13 +40,7 @@ module.exports = class BrokerClient extends BrokerBase {
47
40
 
48
41
  this.setMaxListeners(20);
49
42
 
50
- for (const func of [
51
- this.onOpen,
52
- this.onClose,
53
- this.onError,
54
- this.connect,
55
- this.onSocketMessage,
56
- ]) {
43
+ for (const func of [this.onOpen, this.onClose, this.onError, this.connect, this.onSocketMessage]) {
57
44
  const name = func.name;
58
45
  this[name] = func.bind(this);
59
46
  }
@@ -126,7 +113,7 @@ module.exports = class BrokerClient extends BrokerBase {
126
113
  url = { hostname: options.host, port: options.port };
127
114
  }
128
115
 
129
- const scheme = (url.protocol === 'https:' || this.ssl) ? 'wss' : 'ws';
116
+ const scheme = url.protocol === 'https:' || this.ssl ? 'wss' : 'ws';
130
117
 
131
118
  const webSocketURL = url.port
132
119
  ? `${scheme}://${url.hostname}:${url.port}${this.webSocketURL}`
@@ -134,22 +121,22 @@ module.exports = class BrokerClient extends BrokerBase {
134
121
 
135
122
  this.logger.info(`BrokerClient is connecting to ${webSocketURL}`);
136
123
 
137
- if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
124
+ if (typeof process !== 'undefined' && process.versions != null && process.versions.node != null) {
138
125
  const NODE_TLS_REJECT_UNAUTHORIZED = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
139
126
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
140
- this.socket = new ws(`${webSocketURL}?module=true`);
127
+ this.socket = new WS(`${webSocketURL}?module=true`);
141
128
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = NODE_TLS_REJECT_UNAUTHORIZED;
142
129
  } else {
143
- this.socket = new ws(webSocketURL);
130
+ this.socket = new WS(webSocketURL);
144
131
  }
145
-
132
+
146
133
  this.addSocketListeners();
147
134
  }
148
135
 
149
136
  /**
150
137
  * Duplicates a BrokerClient in order to share the same WebSocket.
151
138
  * @param {object} params Parameters
152
- * @param {string} params.moduleName Module name of the duplicate BrokerClient (a duplicate
139
+ * @param {string} params.moduleName Module name of the duplicate BrokerClient (a duplicate
153
140
  * can have a different name than its parent)
154
141
  * @returns {BrokerClient}
155
142
  */
@@ -181,12 +168,10 @@ module.exports = class BrokerClient extends BrokerBase {
181
168
  duplicate.on('destroy', () => duplicates.delete(duplicate));
182
169
  duplicates.add(duplicate);
183
170
 
184
- duplicate
185
- .ping()
186
- .catch((ex) => {
187
- console.error(`Failed to send ping`);
188
- console.trace(ex.message);
189
- });
171
+ duplicate.ping().catch((ex) => {
172
+ console.error(`Failed to send ping`);
173
+ console.trace(ex.message);
174
+ });
190
175
 
191
176
  return duplicate;
192
177
  }
@@ -301,21 +286,20 @@ module.exports = class BrokerClient extends BrokerBase {
301
286
  }
302
287
  }
303
288
 
304
- await this.sendResponse(
305
- socket,
306
- message,
307
- false,
308
- [{ error: `${message.eventName} sent to ${this.moduleName}. This is probably a mistake.` }],
309
- );
289
+ await this.sendResponse(socket, message, false, [
290
+ {
291
+ error: `${message.eventName} sent to ${this.moduleName}. This is probably a mistake.`,
292
+ },
293
+ ]);
310
294
  }
311
295
 
312
296
  break;
313
297
  }
314
298
 
315
299
  case 'unsubscribe': {
316
- const [vendor, moduleName, ...rest] = message.eventName.split(".");
317
- const eventName = rest.join(".");
318
- const targetModuleName = [vendor, moduleName].join(".");
300
+ const [vendor, moduleName, ...rest] = message.eventName.split('.');
301
+ const eventName = rest.join('.');
302
+ const targetModuleName = [vendor, moduleName].join('.');
319
303
 
320
304
  if (this.moduleName === targetModuleName) {
321
305
  this.emit('unsubscribe', { eventName });
@@ -331,12 +315,11 @@ module.exports = class BrokerClient extends BrokerBase {
331
315
  }
332
316
  }
333
317
 
334
- await this.sendResponse(
335
- socket,
336
- message,
337
- false,
338
- [{ error: `${message.eventName} sent to ${this.moduleName}. This is probably a mistake.` }],
339
- );
318
+ await this.sendResponse(socket, message, false, [
319
+ {
320
+ error: `${message.eventName} sent to ${this.moduleName}. This is probably a mistake.`,
321
+ },
322
+ ]);
340
323
  }
341
324
 
342
325
  break;
@@ -371,12 +354,11 @@ module.exports = class BrokerClient extends BrokerBase {
371
354
 
372
355
  default: {
373
356
  if (!this.apiHandlers.has(message.type)) {
374
- await this.sendResponse(
375
- socket,
376
- message,
377
- false,
378
- [{ error: `There is no handler registered for this type of message: ${message.type}` }],
379
- );
357
+ await this.sendResponse(socket, message, false, [
358
+ {
359
+ error: `There is no handler registered for this type of message: ${message.type}`,
360
+ },
361
+ ]);
380
362
  return;
381
363
  }
382
364
 
@@ -425,23 +407,19 @@ module.exports = class BrokerClient extends BrokerBase {
425
407
  /**
426
408
  * Sends a message.
427
409
  * @async
428
- * @param {object} message
410
+ * @param {object} message
429
411
  * @returns {Promise.<Array, Error>}
430
412
  */
431
413
  async sendMessage(message) {
432
414
  const id = uuid();
433
415
  const socket = this.isDuplicate ? this.parent.getSocket() : this.socket;
434
- const webSocketMessage = Object.assign(
435
- {},
436
- message,
437
- {
438
- id,
439
- time: new Date().valueOf(),
440
- moduleName: this.moduleName,
441
- },
442
- );
443
-
444
- if (socket.readyState !== ws.OPEN) {
416
+ const webSocketMessage = Object.assign({}, message, {
417
+ id,
418
+ time: new Date().valueOf(),
419
+ moduleName: this.moduleName,
420
+ });
421
+
422
+ if (socket.readyState !== WS.OPEN) {
445
423
  try {
446
424
  await onceMultiple(this, ['connect'], webSocketMessage.timeout || this.messageTimeout);
447
425
  } catch (ex) {
@@ -488,18 +466,13 @@ module.exports = class BrokerClient extends BrokerBase {
488
466
  */
489
467
  resubscribeModuleEvents() {
490
468
  for (const eventName of this.events.keys()) {
491
- const moduleName = eventName
492
- .split('.')
493
- .slice(0, 2)
494
- .join('.');
495
-
496
- this
497
- .sendMessage({
498
- type: 'subscribe',
499
- eventName,
500
- targetModuleName: moduleName,
501
- })
502
- .catch(new Function());
469
+ const moduleName = eventName.split('.').slice(0, 2).join('.');
470
+
471
+ this.sendMessage({
472
+ type: 'subscribe',
473
+ eventName,
474
+ targetModuleName: moduleName,
475
+ }).catch(new Function());
503
476
  }
504
477
  }
505
478
 
@@ -532,7 +505,7 @@ module.exports = class BrokerClient extends BrokerBase {
532
505
 
533
506
  /**
534
507
  * @private
535
- * @param {ErrorEvent} err
508
+ * @param {ErrorEvent} err
536
509
  */
537
510
  onError(err) {
538
511
  if (err.error instanceof Error) {
@@ -656,13 +629,13 @@ module.exports = class BrokerClient extends BrokerBase {
656
629
  }
657
630
  }
658
631
 
659
- /**
632
+ /**
660
633
  * Register a module's API handlers to RealityHub
661
634
  * @async
662
- * @param {Object.<string, function>} handlers Key will be registered to the API tree.
635
+ * @param {Object.<string, function>} handlers Key will be registered to the API tree.
663
636
  * @param {*} [context=null] Handlers' `this` will be set to this context.
664
- * The value (function) will handle the API calls.
665
- * @param {string} [remote='hub.core'] Remote
637
+ * The value (function) will handle the API calls.
638
+ * @param {string} [remote='hub.core'] Remote
666
639
  * @example
667
640
  * // server.js
668
641
  * brokerClient.registerAPIHandlers(this, {
@@ -670,7 +643,7 @@ module.exports = class BrokerClient extends BrokerBase {
670
643
  * return number1 + number2;
671
644
  * },
672
645
  * }).catch((ex) => console.trace(ex));
673
- *
646
+ *
674
647
  * // client.js
675
648
  * brokerClient.api.moduleVendor.moduleName.addNumber(3, 5)
676
649
  * .then((result) => {
@@ -701,8 +674,8 @@ module.exports = class BrokerClient extends BrokerBase {
701
674
  * RealityHub will look for an `index.js` file in this path. This script file will be imported
702
675
  * by RealityHub's `index.html` via a `<script type="module">` tag. Relative paths in your scripts
703
676
  * will be proxied by RealityHub.
704
- * @param {string} [params.webSocketURL="/core"] WebSocket URL to connect. RealityHub's API Server
705
- * is serving at `/core` by default. *(Default: /core)*
677
+ * @param {string} [params.webSocketURL="/core"] WebSocket URL to connect. RealityHub's API Server
678
+ * is serving at `/core` by default. *(Default: /core)*
706
679
  * @param {{ host: string, port: number }} params.hub RealityHub connection parameters
707
680
  * @param {string} params.hub.host RealityHub hostname or IP address
708
681
  * @param {string} params.hub.port RealityHub port
@@ -716,7 +689,12 @@ module.exports = class BrokerClient extends BrokerBase {
716
689
  await hubClient.getConnectPromise();
717
690
  if (!serverURL) return hubClient;
718
691
 
719
- await hubClient.api.hub.core.registerProxyURL({ moduleName, serverURL, clientModuleName, menuTitle });
692
+ await hubClient.api.hub.core.registerProxyURL({
693
+ moduleName,
694
+ serverURL,
695
+ clientModuleName,
696
+ menuTitle,
697
+ });
720
698
  return hubClient;
721
699
  }
722
700
  }
@@ -3,7 +3,7 @@
3
3
  // This file is part of realityhub-api.
4
4
  //
5
5
  // realityhub-api is free software: you can redistribute it and/or modify
6
- // it under the terms of the GNU General Public License version 2, as published by
6
+ // it under the terms of the GNU General Public License version 2, as published by
7
7
  // the Free Software Foundation.
8
8
  //
9
9
  // realityhub-api is distributed in the hope that it will be useful,
@@ -14,5 +14,4 @@
14
14
  // You should have received a copy of the GNU General Public License
15
15
  // along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
16
16
 
17
- class BrokerError extends Error { }
18
- module.exports = BrokerError;
17
+ export default class BrokerError extends Error {}
@@ -3,7 +3,7 @@
3
3
  // This file is part of realityhub-api.
4
4
  //
5
5
  // realityhub-api is free software: you can redistribute it and/or modify
6
- // it under the terms of the GNU General Public License version 2, as published by
6
+ // it under the terms of the GNU General Public License version 2, as published by
7
7
  // the Free Software Foundation.
8
8
  //
9
9
  // realityhub-api is distributed in the hope that it will be useful,
@@ -14,7 +14,7 @@
14
14
  // You should have received a copy of the GNU General Public License
15
15
  // along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
16
16
 
17
- class RawRequest {
17
+ export default class RawRequest {
18
18
  setCallback(callback) {
19
19
  if (typeof callback !== 'function') {
20
20
  throw new Error('callback must be a function.');
@@ -37,5 +37,3 @@ class RawRequest {
37
37
  }
38
38
  }
39
39
  }
40
-
41
- module.exports = RawRequest;
@@ -3,7 +3,7 @@
3
3
  // This file is part of realityhub-api.
4
4
  //
5
5
  // realityhub-api is free software: you can redistribute it and/or modify
6
- // it under the terms of the GNU General Public License version 2, as published by
6
+ // it under the terms of the GNU General Public License version 2, as published by
7
7
  // the Free Software Foundation.
8
8
  //
9
9
  // realityhub-api is distributed in the hope that it will be useful,
@@ -14,7 +14,7 @@
14
14
  // You should have received a copy of the GNU General Public License
15
15
  // along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
16
16
 
17
- module.exports = function consoleLogger(moduleName, options = { silent: false }) {
17
+ export default function consoleLogger(moduleName, options = { silent: false }) {
18
18
  const { silent } = options;
19
19
 
20
20
  return ['log', 'info', 'warn', 'error', 'trace', 'debug'].reduce((o, item) => {
@@ -27,13 +27,13 @@ module.exports = function consoleLogger(moduleName, options = { silent: false })
27
27
  }
28
28
 
29
29
  if (['trace', 'debug'].includes(item)) {
30
- for (const arg of (args || [])) {
30
+ for (const arg of args || []) {
31
31
  console.log(arg);
32
32
  }
33
33
  }
34
34
 
35
35
  return console[item](...args);
36
- }
36
+ };
37
37
  return o;
38
38
  }, {});
39
- };
39
+ }
@@ -3,7 +3,7 @@
3
3
  // This file is part of realityhub-api.
4
4
  //
5
5
  // realityhub-api is free software: you can redistribute it and/or modify
6
- // it under the terms of the GNU General Public License version 2, as published by
6
+ // it under the terms of the GNU General Public License version 2, as published by
7
7
  // the Free Software Foundation.
8
8
  //
9
9
  // realityhub-api is distributed in the hope that it will be useful,
@@ -22,7 +22,7 @@ class TimeoutError extends Error {
22
22
  }
23
23
  }
24
24
 
25
- module.exports = function onceMultiple(target, eventNames, timeout = null) {
25
+ export default function onceMultiple(target, eventNames, timeout = null) {
26
26
  return new Promise((resolve, reject) => {
27
27
  let timer;
28
28
  let handler;