@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.
package/src/index.js CHANGED
@@ -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,9 +14,9 @@
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 = {
18
- BrokerBase: require('./lib/BrokerBase'),
19
- BrokerClient: require('./lib/BrokerClient'),
20
- BrokerError: require('./lib/BrokerError'),
21
- RawRequest: require('./lib/RawRequest'),
22
- };
17
+ import BrokerBase from './lib/BrokerBase.js';
18
+ import BrokerClient from './lib/BrokerClient.js';
19
+ import BrokerError from './lib/BrokerError.js';
20
+ import RawRequest from './lib/RawRequest.js';
21
+
22
+ export { BrokerBase, BrokerClient, BrokerError, 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,21 +14,21 @@
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 EventEmitter = require('events');
19
- const BrokerError = require('./BrokerError.js');
20
- const onceMultiple = require('./onceMultiple.js');
17
+ import { v4 as uuid } from 'uuid';
18
+ import EventEmitter from 'events';
19
+ import BrokerError from './BrokerError.js';
20
+ import onceMultiple from './onceMultiple.js';
21
21
 
22
22
  const DEFAULT_MAX_WS_PACKET_SIZE = 50 /*MB*/ * 1024 * 1024;
23
23
 
24
- /**
25
- * BrokerBase constructor
26
- * @param {object} params Parameters
27
- * @param {string} [params.moduleName] Module name
28
- * @param {number} [params.maxPacketSize] Maximum websocket packet size
29
- * @param {Logger} [params.logger] Logger instance
30
- */
31
- module.exports = class BrokerBase extends EventEmitter {
24
+ /**
25
+ * BrokerBase constructor
26
+ * @param {object} params Parameters
27
+ * @param {string} [params.moduleName] Module name
28
+ * @param {number} [params.maxPacketSize] Maximum websocket packet size
29
+ * @param {Logger} [params.logger] Logger instance
30
+ */
31
+ export default class BrokerBase extends EventEmitter {
32
32
  constructor(params) {
33
33
  super();
34
34
  this.moduleName = params.moduleName;
@@ -40,7 +40,7 @@ module.exports = class BrokerBase extends EventEmitter {
40
40
  this.apiHandlers = new Map();
41
41
 
42
42
  this.messageTimeout = 2000;
43
-
43
+
44
44
  this.overridenTimeout = NaN; // NaN = use the implementation
45
45
 
46
46
  try {
@@ -50,14 +50,14 @@ module.exports = class BrokerBase extends EventEmitter {
50
50
  this.overridenTimeout = Number(process.env.BROKER_TIMEOUT) || NaN;
51
51
  }
52
52
  } catch (ex) {}
53
-
53
+
54
54
  if (this.overridenTimeout) {
55
55
  const logger = this.logger || console;
56
56
  logger.warn(`Broker Timeout is overriden to ${this.overridenTimeout} milliseconds!`);
57
57
  }
58
58
 
59
59
  let maxPacketSizeRead = DEFAULT_MAX_WS_PACKET_SIZE;
60
-
60
+
61
61
  try {
62
62
  if (typeof window != 'undefined' && typeof localStorage != 'undefined') {
63
63
  maxPacketSizeRead ||= Number(localStorage.getItem('MAX_WS_PACKET_SIZE'));
@@ -66,12 +66,12 @@ module.exports = class BrokerBase extends EventEmitter {
66
66
  }
67
67
  } catch (ex) {
68
68
  const logger = this.logger || console;
69
- logger.error(`Cannot read maxPacketSize from either localStorage or env, defaulting to ${maxPacketSizeRead}`)
69
+ logger.error(`Cannot read maxPacketSize from either localStorage or env, defaulting to ${maxPacketSizeRead}`);
70
70
  }
71
71
 
72
72
  this.maxPacketSize = Math.max(this.maxPacketSize, maxPacketSizeRead);
73
-
74
- if(this.maxPacketSize !== DEFAULT_MAX_WS_PACKET_SIZE) {
73
+
74
+ if (this.maxPacketSize !== DEFAULT_MAX_WS_PACKET_SIZE) {
75
75
  const logger = this.logger || console;
76
76
  logger.log(`BrokerBase is created with maxPacketSize: ${this.maxPacketSize}`);
77
77
  }
@@ -86,36 +86,36 @@ module.exports = class BrokerBase extends EventEmitter {
86
86
  ...options,
87
87
  };
88
88
 
89
- return new Proxy({}, {
90
- get: (_, methodName) => {
91
- if (methodName === 'emit' && this.moduleName !== `${vendorName}.${moduleName}`) {
92
- throw new Error('A module can only emit its own events.');
93
- }
89
+ return new Proxy(
90
+ {},
91
+ {
92
+ get: (_, methodName) => {
93
+ if (methodName === 'emit' && this.moduleName !== `${vendorName}.${moduleName}`) {
94
+ throw new Error('A module can only emit its own events.');
95
+ }
94
96
 
95
- return (...args) => {
96
- switch (methodName) {
97
- case 'emit': {
98
- this.emitMessage(args, vendorName, moduleName, options);
99
- break;
100
- }
97
+ return (...args) => {
98
+ switch (methodName) {
99
+ case 'emit': {
100
+ this.emitMessage(args, vendorName, moduleName, options);
101
+ break;
102
+ }
101
103
 
102
- case 'on': {
103
- const eventName = args.shift();
104
- const eventHandler = args.shift();
104
+ case 'on': {
105
+ const eventName = args.shift();
106
+ const eventHandler = args.shift();
105
107
 
106
- if (typeof eventName !== 'string') {
107
- throw new Error('eventName must be a string');
108
- }
108
+ if (typeof eventName !== 'string') {
109
+ throw new Error('eventName must be a string');
110
+ }
109
111
 
110
- if (typeof eventHandler !== 'function') {
111
- throw new Error('eventHandler must be a function');
112
- }
112
+ if (typeof eventHandler !== 'function') {
113
+ throw new Error('eventHandler must be a function');
114
+ }
113
115
 
114
- const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;
116
+ const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;
115
117
 
116
- this
117
- .subscribeToAPIEvent(fullyQualifiedName, eventHandler)
118
- .catch((err) => {
118
+ this.subscribeToAPIEvent(fullyQualifiedName, eventHandler).catch((err) => {
119
119
  console.error(`Couldn't subscribe to ${fullyQualifiedName}`);
120
120
 
121
121
  if (err.code !== 'TIMEOUT') {
@@ -123,62 +123,60 @@ module.exports = class BrokerBase extends EventEmitter {
123
123
  }
124
124
  });
125
125
 
126
- break;
127
- }
126
+ break;
127
+ }
128
128
 
129
- case 'once': {
130
- const eventName = args.shift();
131
- const eventHandler = args.shift();
129
+ case 'once': {
130
+ const eventName = args.shift();
131
+ const eventHandler = args.shift();
132
132
 
133
- /**
134
- * If the subscribed event is not emitted within the given timeout then the
135
- * event handler will be removed automatically to prevent memory leak.
136
- * If a timeout is not provided by caller than a default timeout of 5 minutes is set.
137
- */
138
- const timeout = args.shift() || 60 * 1000 * 5;
133
+ /**
134
+ * If the subscribed event is not emitted within the given timeout then the
135
+ * event handler will be removed automatically to prevent memory leak.
136
+ * If a timeout is not provided by caller than a default timeout of 5 minutes is set.
137
+ */
138
+ const timeout = args.shift() || 60 * 1000 * 5;
139
139
 
140
- if (typeof eventName !== 'string') {
141
- throw new Error('eventName must be a string');
142
- }
140
+ if (typeof eventName !== 'string') {
141
+ throw new Error('eventName must be a string');
142
+ }
143
143
 
144
- if (typeof eventHandler !== 'function') {
145
- throw new Error('eventHandler must be a function');
146
- }
144
+ if (typeof eventHandler !== 'function') {
145
+ throw new Error('eventHandler must be a function');
146
+ }
147
147
 
148
- if (typeof timeout !== 'number' || isNaN(timeout)) {
149
- throw new Error('timeout must be a number');
150
- }
148
+ if (typeof timeout !== 'number' || isNaN(timeout)) {
149
+ throw new Error('timeout must be a number');
150
+ }
151
151
 
152
- const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;
152
+ const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;
153
153
 
154
- this
155
- .subscribeToAPIEvent(fullyQualifiedName, eventHandler, { once: true })
156
- .catch((err) => {
154
+ this.subscribeToAPIEvent(fullyQualifiedName, eventHandler, {
155
+ once: true,
156
+ }).catch((err) => {
157
157
  console.error(`Couldn't subscribe to ${fullyQualifiedName}`);
158
158
 
159
159
  if (err.code !== 'TIMEOUT') {
160
160
  console.trace(err);
161
161
  }
162
162
  });
163
- break;
164
- }
163
+ break;
164
+ }
165
165
 
166
- case 'off': {
167
- const eventName = args.shift();
168
- const eventHandler = args.shift();
169
- const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;
166
+ case 'off': {
167
+ const eventName = args.shift();
168
+ const eventHandler = args.shift();
169
+ const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;
170
170
 
171
- if (typeof eventName !== 'string') {
172
- throw new Error('eventName must be a string');
173
- }
171
+ if (typeof eventName !== 'string') {
172
+ throw new Error('eventName must be a string');
173
+ }
174
174
 
175
- if (eventHandler && typeof eventHandler !== 'function') {
176
- throw new Error('eventHandler must be a function');
177
- }
175
+ if (eventHandler && typeof eventHandler !== 'function') {
176
+ throw new Error('eventHandler must be a function');
177
+ }
178
178
 
179
- this
180
- .unsubscribeFromAPIEvent(fullyQualifiedName, eventHandler)
181
- .catch((err) => {
179
+ this.unsubscribeFromAPIEvent(fullyQualifiedName, eventHandler).catch((err) => {
182
180
  console.error(`Couldn't unsubscribe from ${fullyQualifiedName}`);
183
181
 
184
182
  if (err.code !== 'TIMEOUT') {
@@ -186,61 +184,62 @@ module.exports = class BrokerBase extends EventEmitter {
186
184
  }
187
185
  });
188
186
 
189
- break;
190
- }
187
+ break;
188
+ }
191
189
 
192
- case 'callTimeout': {
193
- const timeout = args[0];
190
+ case 'callTimeout': {
191
+ const timeout = args[0];
194
192
 
195
- if (typeof timeout !== 'number') {
196
- throw new Error('callTimeout: timeout is required.');
193
+ if (typeof timeout !== 'number') {
194
+ throw new Error('callTimeout: timeout is required.');
195
+ }
196
+
197
+ const clonedOptions = JSON.parse(JSON.stringify(options));
198
+ clonedOptions.timeout = timeout;
199
+ return this.getMethodProxy(vendorName, moduleName, clonedOptions);
197
200
  }
198
201
 
199
- const clonedOptions = JSON.parse(JSON.stringify(options));
200
- clonedOptions.timeout = timeout;
201
- return this.getMethodProxy(vendorName, moduleName, clonedOptions);
202
- }
202
+ case 'excludeClients': {
203
+ const excludedClients = args[0] || [];
203
204
 
204
- case 'excludeClients': {
205
- const excludedClients = args[0] || [];
205
+ if (!(excludedClients instanceof Array)) {
206
+ throw new Error('excludedClients requires 1 parameter: an array of strings');
207
+ }
206
208
 
207
- if (!(excludedClients instanceof Array)) {
208
- throw new Error('excludedClients requires 1 parameter: an array of strings');
209
+ const clonedOptions = JSON.parse(JSON.stringify(options));
210
+ clonedOptions.excludedClients = clonedOptions.excludedClients.concat(excludedClients);
211
+ return this.getMethodProxy(vendorName, moduleName, clonedOptions);
209
212
  }
210
213
 
211
- const clonedOptions = JSON.parse(JSON.stringify(options));
212
- clonedOptions.excludedClients = clonedOptions.excludedClients.concat(excludedClients);
213
- return this.getMethodProxy(vendorName, moduleName, clonedOptions);
214
- }
215
-
216
- default: {
217
- return this.sendMessage({
218
- data: args,
219
- timeout: options.timeout,
220
- type: `${vendorName}.${moduleName}.${methodName}`,
221
- targetModuleName: `${vendorName}.${moduleName}`,
222
- excludedClients: options.excludedClients,
223
- });
214
+ default: {
215
+ return this.sendMessage({
216
+ data: args,
217
+ timeout: options.timeout,
218
+ type: `${vendorName}.${moduleName}.${methodName}`,
219
+ targetModuleName: `${vendorName}.${moduleName}`,
220
+ excludedClients: options.excludedClients,
221
+ });
222
+ }
224
223
  }
224
+ };
225
+ },
226
+ set: (_, methodName, handler) => {
227
+ if (this.moduleName !== `${vendorName}.${moduleName}`) {
228
+ throw new Error('Cannot register methods to other modules.');
225
229
  }
226
- };
227
- },
228
- set: (_, methodName, handler) => {
229
- if (this.moduleName !== `${vendorName}.${moduleName}`) {
230
- throw new Error('Cannot register methods to other modules.');
231
- }
232
230
 
233
- if (typeof handler !== 'function') {
234
- throw new Error('Handler must be a function.');
235
- }
231
+ if (typeof handler !== 'function') {
232
+ throw new Error('Handler must be a function.');
233
+ }
236
234
 
237
- if (['emit', 'on', 'off'].includes(methodName)) {
238
- throw new Error(`${methodName} is a reserved method name.`);
239
- }
235
+ if (['emit', 'on', 'off'].includes(methodName)) {
236
+ throw new Error(`${methodName} is a reserved method name.`);
237
+ }
240
238
 
241
- return this.registerAPIHandler(methodName, handler);
242
- },
243
- });
239
+ return this.registerAPIHandler(methodName, handler);
240
+ },
241
+ }
242
+ );
244
243
  }
245
244
 
246
245
  /**
@@ -250,42 +249,48 @@ module.exports = class BrokerBase extends EventEmitter {
250
249
  initProxy() {
251
250
  // These nested proxies allow us to get vendorName, moduleName and methodName.
252
251
  // e.g. const pong = await this.api.hub.core.ping();
253
- this.api = new Proxy({}, {
254
- get: (_, vendorName) => {
255
- return new Proxy({}, {
256
- get: (_, moduleName) => {
257
- return this.getMethodProxy(vendorName, moduleName);
258
- },
259
- set: (_, moduleName, api) => {
260
- if (this.moduleName !== `${vendorName}.${moduleName}`) {
261
- throw new Error('Cannot register methods to other modules.');
262
- }
263
-
264
- if (typeof api !== 'object') {
265
- throw new Error('API must be set to an object.');
266
- }
252
+ this.api = new Proxy(
253
+ {},
254
+ {
255
+ get: (_, vendorName) => {
256
+ return new Proxy(
257
+ {},
258
+ {
259
+ get: (_, moduleName) => {
260
+ return this.getMethodProxy(vendorName, moduleName);
261
+ },
262
+ set: (_, moduleName, api) => {
263
+ if (this.moduleName !== `${vendorName}.${moduleName}`) {
264
+ throw new Error('Cannot register methods to other modules.');
265
+ }
266
+
267
+ if (typeof api !== 'object') {
268
+ throw new Error('API must be set to an object.');
269
+ }
270
+
271
+ for (const [methodName, handler] of Object.entries(api)) {
272
+ if (typeof handler !== 'function') {
273
+ throw new Error('Handler must be a function.');
274
+ }
267
275
 
268
- for (const [methodName, handler] of Object.entries(api)) {
269
- if (typeof handler !== 'function') {
270
- throw new Error('Handler must be a function.');
271
- }
276
+ if (['emit', 'on', 'off'].includes(methodName)) {
277
+ throw new Error(`${methodName} is a reserved method name.`);
278
+ }
272
279
 
273
- if (['emit', 'on', 'off'].includes(methodName)) {
274
- throw new Error(`${methodName} is a reserved method name.`);
275
- }
280
+ this.registerAPIHandler(methodName, handler);
281
+ }
276
282
 
277
- this.registerAPIHandler(methodName, handler);
283
+ return true;
284
+ },
278
285
  }
279
-
280
- return true;
281
- },
282
- });
283
- },
284
- set: function () {
285
- console.warn('Module name and method name are required.');
286
- return false;
287
- },
288
- });
286
+ );
287
+ },
288
+ set: function () {
289
+ console.warn('Module name and method name are required.');
290
+ return false;
291
+ },
292
+ }
293
+ );
289
294
  }
290
295
 
291
296
  /**
@@ -322,7 +327,7 @@ module.exports = class BrokerBase extends EventEmitter {
322
327
  /**
323
328
  * Registers an API request handler.
324
329
  * @param {string} messageType Message type.
325
- * @param {function} messageHandler Handler function.
330
+ * @param {function} messageHandler Handler function.
326
331
  * @returns {boolean} `false` if a handler has already been assigned to the `messageType`.
327
332
  */
328
333
  registerAPIHandler(messageType, messageHandler) {
@@ -341,7 +346,7 @@ module.exports = class BrokerBase extends EventEmitter {
341
346
  /**
342
347
  * Subscribe to an API event.
343
348
  * @param {string} eventName Fully qualified event name.
344
- * @param {function} eventHandler A function which will be called when the event is received.
349
+ * @param {function} eventHandler A function which will be called when the event is received.
345
350
  * @param {object} [options] Options
346
351
  * @param {boolean} [options.sendMessage=true] If set to `true`, it will send a subscription message over WebSocket.
347
352
  * Otherwise the message will only be registered internally.
@@ -363,9 +368,7 @@ module.exports = class BrokerBase extends EventEmitter {
363
368
 
364
369
  // Send a subscription message over WebSocket
365
370
  if (options.sendMessage) {
366
- const targetModuleName = eventName.split('.')
367
- .slice(0, 2)
368
- .join('.');
371
+ const targetModuleName = eventName.split('.').slice(0, 2).join('.');
369
372
 
370
373
  return this.sendMessage({
371
374
  type: 'subscribe',
@@ -392,9 +395,7 @@ module.exports = class BrokerBase extends EventEmitter {
392
395
  }
393
396
 
394
397
  if (sendMessage) {
395
- const targetModuleName = eventName.split('.')
396
- .slice(0, 2)
397
- .join('.');
398
+ const targetModuleName = eventName.split('.').slice(0, 2).join('.');
398
399
 
399
400
  return this.sendMessage({
400
401
  type: 'unsubscribe',
@@ -434,7 +435,11 @@ module.exports = class BrokerBase extends EventEmitter {
434
435
  let responseMessage;
435
436
 
436
437
  try {
437
- responseMessage = await onceMultiple(this, [`response::${message.id}`], this.overridenTimeout || message.timeout || this.messageTimeout);
438
+ responseMessage = await onceMultiple(
439
+ this,
440
+ [`response::${message.id}`],
441
+ this.overridenTimeout || message.timeout || this.messageTimeout
442
+ );
438
443
  } catch (ex) {
439
444
  const logger = this.logger || console;
440
445
  logger.debug(`${this.moduleName} failed to send message ${message.type} to ${message.targetModuleName || ''}`);
@@ -460,7 +465,7 @@ module.exports = class BrokerBase extends EventEmitter {
460
465
 
461
466
  /**
462
467
  * Send a ping request.
463
- * @param {string} targetModuleName
468
+ * @param {string} targetModuleName
464
469
  * @private
465
470
  */
466
471
  ping(targetModuleName) {
@@ -468,10 +473,10 @@ module.exports = class BrokerBase extends EventEmitter {
468
473
  }
469
474
 
470
475
  /**
471
- * @private
472
- * @param {array} args
473
- * @param {string} vendorName
474
- * @param {string} moduleName
476
+ * @private
477
+ * @param {array} args
478
+ * @param {string} vendorName
479
+ * @param {string} moduleName
475
480
  */
476
481
  emitMessage(args, vendorName, moduleName, options = {}) {
477
482
  const eventName = args.shift();
@@ -487,14 +492,13 @@ module.exports = class BrokerBase extends EventEmitter {
487
492
  eventName: fullyQualifiedName,
488
493
  data: args,
489
494
  excludedClients: options.excludedClients || [],
490
- })
491
- .catch((err) => {
492
- console.error(`Couldn't emit ${fullyQualifiedName}`);
495
+ }).catch((err) => {
496
+ console.error(`Couldn't emit ${fullyQualifiedName}`);
493
497
 
494
- if (err.code !== 'TIMEOUT') {
495
- console.trace(err);
496
- }
497
- });
498
+ if (err.code !== 'TIMEOUT') {
499
+ console.trace(err);
500
+ }
501
+ });
498
502
  }
499
503
 
500
504
  destroy() {