@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/.github/workflows/npm-publish-next.yml +10 -2
- package/.github/workflows/npm-publish.yml +10 -2
- package/.prettierrc.json +18 -0
- package/README.md +72 -61
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/package.json +27 -4
- package/rollup.config.js +15 -0
- package/src/index.d.ts +115 -0
- package/src/index.js +7 -7
- package/src/lib/BrokerBase.js +181 -177
- package/src/lib/BrokerClient.js +68 -90
- package/src/lib/BrokerError.js +2 -3
- package/src/lib/RawRequest.js +2 -4
- package/src/lib/consoleLogger.js +5 -5
- package/src/lib/onceMultiple.js +2 -2
|
@@ -11,9 +11,17 @@ jobs:
|
|
|
11
11
|
- uses: actions/checkout@v4
|
|
12
12
|
- uses: actions/setup-node@v4
|
|
13
13
|
with:
|
|
14
|
-
node-version: '
|
|
14
|
+
node-version: '22'
|
|
15
15
|
registry-url: https://registry.npmjs.org/
|
|
16
|
-
- run: npm ci
|
|
16
|
+
- run: npm ci --ignore-scripts
|
|
17
|
+
- run: npm run build
|
|
17
18
|
- run: npm publish --tag next
|
|
18
19
|
env:
|
|
19
20
|
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
|
21
|
+
- name: Create Git Tag
|
|
22
|
+
run: |
|
|
23
|
+
VERSION=$(node -p "require('./package.json').version")
|
|
24
|
+
git config user.name "GitHub Actions"
|
|
25
|
+
git config user.email "actions@github.com"
|
|
26
|
+
git tag v$VERSION
|
|
27
|
+
git push origin v$VERSION
|
|
@@ -15,7 +15,15 @@ jobs:
|
|
|
15
15
|
- uses: actions/checkout@v4
|
|
16
16
|
- uses: actions/setup-node@v4
|
|
17
17
|
with:
|
|
18
|
-
node-version: '
|
|
18
|
+
node-version: '22'
|
|
19
19
|
registry-url: https://registry.npmjs.org/
|
|
20
|
-
- run: npm ci
|
|
20
|
+
- run: npm ci --ignore-scripts
|
|
21
|
+
- run: npm run build
|
|
21
22
|
- run: npm publish
|
|
23
|
+
- name: Create Git Tag
|
|
24
|
+
run: |
|
|
25
|
+
VERSION=$(node -p "require('./package.json').version")
|
|
26
|
+
git config user.name "GitHub Actions"
|
|
27
|
+
git config user.email "actions@github.com"
|
|
28
|
+
git tag v$VERSION
|
|
29
|
+
git push origin v$VERSION
|
package/.prettierrc.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"trailingComma": "es5",
|
|
3
|
+
"tabWidth": 2,
|
|
4
|
+
"useTabs": false,
|
|
5
|
+
"semi": true,
|
|
6
|
+
"singleQuote": true,
|
|
7
|
+
"bracketSameLine": false,
|
|
8
|
+
"arrowParens": "always",
|
|
9
|
+
"jsxSingleQuote": false,
|
|
10
|
+
"printWidth": 128,
|
|
11
|
+
"quoteProps": "as-needed",
|
|
12
|
+
"bracketSpacing": true,
|
|
13
|
+
"svelteSortOrder": "options-scripts-styles-markup",
|
|
14
|
+
"svelteStrictMode": false,
|
|
15
|
+
"svelteAllowShorthand": true,
|
|
16
|
+
"svelteIndentScriptAndStyle": true,
|
|
17
|
+
"htmlWhitespaceSensitivity": "ignore"
|
|
18
|
+
}
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
A helper module to connect third-party modules to RealityHub.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Support Requests
|
|
6
6
|
|
|
7
7
|
This repository is for distribution only. For support please visit: [Zero Density Support](https://support.zerodensity.io).
|
|
8
8
|
|
|
@@ -21,7 +21,7 @@ The client can be bundled for browsers with a bundling tool (e.g. rollup).
|
|
|
21
21
|
### Connecting to Hub
|
|
22
22
|
|
|
23
23
|
```js
|
|
24
|
-
|
|
24
|
+
import { BrokerClient } from '@zerodensity/realityhub-api';
|
|
25
25
|
|
|
26
26
|
BrokerClient.initModule({
|
|
27
27
|
menuTitle: '<menu title>',
|
|
@@ -40,7 +40,8 @@ BrokerClient.initModule({
|
|
|
40
40
|
### Listing Reality 5 (API v1.2+) engines
|
|
41
41
|
|
|
42
42
|
```js
|
|
43
|
-
brokerClient.api.hub.reality5_1_2_world
|
|
43
|
+
brokerClient.api.hub.reality5_1_2_world
|
|
44
|
+
.listEngines()
|
|
44
45
|
.then((engines) => {
|
|
45
46
|
console.log(engines);
|
|
46
47
|
|
|
@@ -65,28 +66,29 @@ brokerClient.api.hub.reality5_1_2_world.listEngines()
|
|
|
65
66
|
### Listing the nodes running on an Reality 5 engine (API v1.2+)
|
|
66
67
|
|
|
67
68
|
```js
|
|
68
|
-
brokerClient.api.hub.reality5_1_2_world
|
|
69
|
+
brokerClient.api.hub.reality5_1_2_world
|
|
70
|
+
.getNodes(79 /* id of the engine */)
|
|
69
71
|
.then((nodes) => {
|
|
70
72
|
console.log(nodes);
|
|
71
73
|
|
|
72
74
|
/**
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
75
|
+
* {
|
|
76
|
+
* ...
|
|
77
|
+
* // The keys are the NodePath
|
|
78
|
+
* Cyclorama: {
|
|
79
|
+
* ...
|
|
80
|
+
* Functions: {
|
|
81
|
+
* // The keys are the FunctionPath
|
|
82
|
+
* 'Cyclorama/AddProjection': {...},
|
|
83
|
+
* 'Cyclorama/ClearProjection': {...},
|
|
84
|
+
* }
|
|
85
|
+
* ...
|
|
86
|
+
* }
|
|
87
|
+
* ...
|
|
88
|
+
* }
|
|
89
|
+
*/
|
|
90
|
+
|
|
91
|
+
// NOTE: For backward compatiblity, the NodePath and FunctionPath omit the leading '/'.
|
|
90
92
|
})
|
|
91
93
|
.catch((ex) => console.trace(ex));
|
|
92
94
|
```
|
|
@@ -103,11 +105,16 @@ of engine IDs. If `engineIds` is not supplied then the function will be called o
|
|
|
103
105
|
* @param {string} params.NodePath
|
|
104
106
|
* @param {string} params.PropertyPath
|
|
105
107
|
* @param {number} [engineIds] - optional, default is all engines
|
|
106
|
-
*/
|
|
107
|
-
brokerClient.api.hub.reality5_1_2_world
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
*/
|
|
109
|
+
brokerClient.api.hub.reality5_1_2_world
|
|
110
|
+
.callNodeFunction(
|
|
111
|
+
{
|
|
112
|
+
NodePath: '/Cyclorama',
|
|
113
|
+
FunctionPath: '/Cyclorama/AddProjection',
|
|
114
|
+
},
|
|
115
|
+
[/* engine id = */ 79]
|
|
116
|
+
)
|
|
117
|
+
.catch((ex) => console.trace(ex));
|
|
111
118
|
```
|
|
112
119
|
|
|
113
120
|
### Setting a Node's Property Value
|
|
@@ -136,17 +143,22 @@ brokerClient.api.hub.reality5_1_2_world.setNodeProperty({
|
|
|
136
143
|
You can use `interpolate(params[, engineIds])` to interpolate a node's property value. `engineIds` is an array of engine IDs. If `engineIds` not supplied then all of the engines will receive the same interpolate command.
|
|
137
144
|
|
|
138
145
|
```js
|
|
139
|
-
brokerClient.api.hub.reality5_1_2_world
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
146
|
+
brokerClient.api.hub.reality5_1_2_world
|
|
147
|
+
.interpolate(
|
|
148
|
+
{
|
|
149
|
+
NodePath: '/Add_f32',
|
|
150
|
+
PropertyPath: 'X',
|
|
151
|
+
StartValue: 5.0, // optional, default is the current value
|
|
152
|
+
EndValue: 10.0,
|
|
153
|
+
Duration: 2000, // in milliseconds, optional, default is 0
|
|
154
|
+
Delay: 2000, // in milliseconds, optional, default is 0
|
|
155
|
+
|
|
156
|
+
/** @type {'Jump' | 'Linear' | 'EaseIn' | 'EaseOut' | 'EaseInOut'} */
|
|
157
|
+
InterpType: 'EaseIn', // optional, default is 'Jump'
|
|
158
|
+
},
|
|
159
|
+
[/* engine id = */ 79]
|
|
160
|
+
)
|
|
161
|
+
.catch((ex) => console.trace(ex));
|
|
150
162
|
```
|
|
151
163
|
|
|
152
164
|
### Getting a Node's Property Value
|
|
@@ -154,14 +166,12 @@ brokerClient.api.hub.reality5_1_2_world.interpolate({
|
|
|
154
166
|
You can use `getNodeProperty(params[, engineIds])` to get a node's property value. `engineIds` is an array of engine IDs. If `engineIds` not supplied then all of the engines will be queried. That is why this method returns an array of promises.
|
|
155
167
|
|
|
156
168
|
```js
|
|
157
|
-
brokerClient.api.hub.reality5_1_2_world
|
|
158
|
-
{ NodePath: '/Add_f32', PropertyPath: 'X'
|
|
159
|
-
|
|
160
|
-
)
|
|
161
|
-
|
|
162
|
-
console.
|
|
163
|
-
})
|
|
164
|
-
.catch((ex) => console.trace(ex));
|
|
169
|
+
brokerClient.api.hub.reality5_1_2_world
|
|
170
|
+
.getNodeProperty({ NodePath: '/Add_f32', PropertyPath: 'X' }, [/* engine id = */ 79])
|
|
171
|
+
.then((results) => {
|
|
172
|
+
console.log(results[0].Value);
|
|
173
|
+
})
|
|
174
|
+
.catch((ex) => console.trace(ex));
|
|
165
175
|
```
|
|
166
176
|
|
|
167
177
|
### Registering Your Own Methods to RealityHub
|
|
@@ -194,28 +204,29 @@ function longTask(taskDuration) {
|
|
|
194
204
|
}
|
|
195
205
|
|
|
196
206
|
// Let's register these as our API methods
|
|
197
|
-
brokerClient.api.exampleCompany.exampleModule
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
207
|
+
brokerClient.api.exampleCompany.exampleModule
|
|
208
|
+
.registerAPIHandlers({
|
|
209
|
+
addNumbers,
|
|
210
|
+
multiplyNumbers,
|
|
211
|
+
performSlowTask: longTask,
|
|
212
|
+
})
|
|
213
|
+
.catch((ex) => console.trace(ex));
|
|
202
214
|
```
|
|
203
215
|
|
|
204
216
|
```js
|
|
205
217
|
// client.js
|
|
206
|
-
brokerClient.api.exampleCompany.exampleModule.addNumbers(3, 5)
|
|
207
|
-
.
|
|
208
|
-
|
|
209
|
-
});
|
|
218
|
+
brokerClient.api.exampleCompany.exampleModule.addNumbers(3, 5).then((result) => {
|
|
219
|
+
console.log('The result of addNumbers() is', result);
|
|
220
|
+
});
|
|
210
221
|
|
|
211
|
-
brokerClient.api.exampleCompany.exampleModule.performAsyncMultiplication(3, 5)
|
|
212
|
-
.
|
|
213
|
-
|
|
214
|
-
});
|
|
222
|
+
brokerClient.api.exampleCompany.exampleModule.performAsyncMultiplication(3, 5).then((result) => {
|
|
223
|
+
console.log('The result of performAsyncMultiplication() is', result);
|
|
224
|
+
});
|
|
215
225
|
|
|
216
226
|
// Default timeout for API requests is 2 seconds. We need to specify a longer timeout for our slow async task.
|
|
217
227
|
const timeout = 10 * 1000; // 10 seconds
|
|
218
|
-
brokerClient.api.exampleCompany.exampleModule
|
|
228
|
+
brokerClient.api.exampleCompany.exampleModule
|
|
229
|
+
.callTimeout(timeout)
|
|
219
230
|
.slowAsyncTask(5)
|
|
220
231
|
.then((result) => console.log('Slow async task returned:', result));
|
|
221
232
|
```
|
|
@@ -229,7 +240,7 @@ brokerClient.api.exampleCompany.exampleModule.callTimeout(timeout)
|
|
|
229
240
|
setInterval(() => {
|
|
230
241
|
// A random number between 0 and 1000.
|
|
231
242
|
const randomNumber = Math.round(Math.random() * 1000);
|
|
232
|
-
brokerClient.api.exampleCompany.exampleModule.emit('randomnumber', randomNumber);
|
|
243
|
+
brokerClient.api.exampleCompany.exampleModule.emit('randomnumber', randomNumber);
|
|
233
244
|
}, 1000);
|
|
234
245
|
```
|
|
235
246
|
|
|
@@ -238,7 +249,7 @@ setInterval(() => {
|
|
|
238
249
|
|
|
239
250
|
brokerClient.api.exampleCompany.exampleModule.on('randomnumber', (randomNumber) => {
|
|
240
251
|
console.log('Received a random number from the server', randomNumber);
|
|
241
|
-
});
|
|
252
|
+
});
|
|
242
253
|
```
|
|
243
254
|
|
|
244
255
|
### Questions and Feedback
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var e=require("uuid"),t=require("events"),s=require("ws");class o extends Error{}class r extends Error{constructor(e){super(e),this.code="TIMEOUT",this.name=this.constructor.name}}function i(e,t,s=null){return new Promise((o,i)=>{let n,a,c;c=()=>{for(const s of t)e.removeListener(s,a)},a=(...e)=>{c(),clearTimeout(n),o(...e)};for(const s of t)e.once(s,a);s&&(n=setTimeout(()=>{c(),i(new r("Timeout exceeded."))},s))})}const n=52428800;class a extends t{constructor(e){super(),this.moduleName=e.moduleName,this.maxPacketSize=e.maxPacketSize||n,this.logger=e.logger,this.events=new Map,this.apiHandlers=new Map,this.messageTimeout=2e3,this.overridenTimeout=NaN;try{"undefined"!=typeof window&&"undefined"!=typeof localStorage?this.overridenTimeout=Number(localStorage.getItem("BROKER_TIMEOUT"))||NaN:process&&process.env&&(this.overridenTimeout=Number(process.env.BROKER_TIMEOUT)||NaN)}catch(e){}if(this.overridenTimeout){(this.logger||console).warn(`Broker Timeout is overriden to ${this.overridenTimeout} milliseconds!`)}let t=n;try{"undefined"!=typeof window&&"undefined"!=typeof localStorage?t||=Number(localStorage.getItem("MAX_WS_PACKET_SIZE")):process&&process.env&&(t||=Number(process.env.MAX_WS_PACKET_SIZE))}catch(e){(this.logger||console).error(`Cannot read maxPacketSize from either localStorage or env, defaulting to ${t}`)}if(this.maxPacketSize=Math.max(this.maxPacketSize,t),this.maxPacketSize!==n){(this.logger||console).log(`BrokerBase is created with maxPacketSize: ${this.maxPacketSize}`)}this.initProxy()}getMethodProxy(e,t,s){return s={timeout:2e3,excludedClients:[],...s},new Proxy({},{get:(o,r)=>{if("emit"===r&&this.moduleName!==`${e}.${t}`)throw new Error("A module can only emit its own events.");return(...o)=>{switch(r){case"emit":this.emitMessage(o,e,t,s);break;case"on":{const s=o.shift(),r=o.shift();if("string"!=typeof s)throw new Error("eventName must be a string");if("function"!=typeof r)throw new Error("eventHandler must be a function");const i=`${e}.${t}.${s}`;this.subscribeToAPIEvent(i,r).catch(e=>{console.error(`Couldn't subscribe to ${i}`),"TIMEOUT"!==e.code&&console.trace(e)});break}case"once":{const s=o.shift(),r=o.shift(),i=o.shift()||3e5;if("string"!=typeof s)throw new Error("eventName must be a string");if("function"!=typeof r)throw new Error("eventHandler must be a function");if("number"!=typeof i||isNaN(i))throw new Error("timeout must be a number");const n=`${e}.${t}.${s}`;this.subscribeToAPIEvent(n,r,{once:!0}).catch(e=>{console.error(`Couldn't subscribe to ${n}`),"TIMEOUT"!==e.code&&console.trace(e)});break}case"off":{const s=o.shift(),r=o.shift(),i=`${e}.${t}.${s}`;if("string"!=typeof s)throw new Error("eventName must be a string");if(r&&"function"!=typeof r)throw new Error("eventHandler must be a function");this.unsubscribeFromAPIEvent(i,r).catch(e=>{console.error(`Couldn't unsubscribe from ${i}`),"TIMEOUT"!==e.code&&console.trace(e)});break}case"callTimeout":{const r=o[0];if("number"!=typeof r)throw new Error("callTimeout: timeout is required.");const i=JSON.parse(JSON.stringify(s));return i.timeout=r,this.getMethodProxy(e,t,i)}case"excludeClients":{const r=o[0]||[];if(!(r instanceof Array))throw new Error("excludedClients requires 1 parameter: an array of strings");const i=JSON.parse(JSON.stringify(s));return i.excludedClients=i.excludedClients.concat(r),this.getMethodProxy(e,t,i)}default:return this.sendMessage({data:o,timeout:s.timeout,type:`${e}.${t}.${r}`,targetModuleName:`${e}.${t}`,excludedClients:s.excludedClients})}}},set:(s,o,r)=>{if(this.moduleName!==`${e}.${t}`)throw new Error("Cannot register methods to other modules.");if("function"!=typeof r)throw new Error("Handler must be a function.");if(["emit","on","off"].includes(o))throw new Error(`${o} is a reserved method name.`);return this.registerAPIHandler(o,r)}})}initProxy(){this.api=new Proxy({},{get:(e,t)=>new Proxy({},{get:(e,s)=>this.getMethodProxy(t,s),set:(e,s,o)=>{if(this.moduleName!==`${t}.${s}`)throw new Error("Cannot register methods to other modules.");if("object"!=typeof o)throw new Error("API must be set to an object.");for(const[e,t]of Object.entries(o)){if("function"!=typeof t)throw new Error("Handler must be a function.");if(["emit","on","off"].includes(e))throw new Error(`${e} is a reserved method name.`);this.registerAPIHandler(e,t)}return!0}}),set:function(){return console.warn("Module name and method name are required."),!1}})}sendResponse(e,t,s,o=[],r=!1){if(!e)return;const{id:i,moduleName:n,timeout:a,instigatorId:c}=t,l={type:"response",targetModuleName:n,instigatorId:c,requestId:i,timeout:a,success:s,data:o};return r&&(l.moduleName=t.targetModuleName),this.sendMessage(l,e,r)}registerAPIHandler(e,t){return e=`${this.moduleName}.${e}`,!this.apiHandlers.has(e)&&(this.apiHandlers.set(e,{relay:!1,messageHandler:t}),!0)}subscribeToAPIEvent(e,t,s){s={sendMessage:!0,once:!1,...s};const o=this.events.get(e)||[];if(o.push({eventHandler:t,once:s.once}),this.events.set(e,o),s.sendMessage){const t=e.split(".").slice(0,2).join(".");return this.sendMessage({type:"subscribe",eventName:e,targetModuleName:t})}}unsubscribeFromAPIEvent(e,t,s=!0){if(t){const s=(this.events.get(e)||[]).filter(e=>e.eventHandler!==t);this.events.set(e,s)}else this.events.delete(e);if(s){const t=e.split(".").slice(0,2).join(".");return this.sendMessage({type:"unsubscribe",eventName:e,targetModuleName:t})}}async sendMessage(t,s,r=!1){t.id=e.v4(),r||(t.moduleName=this.moduleName),t.time=(new Date).valueOf();const n=JSON.stringify(t);if(n.length>this.maxPacketSize&&this.logger.trace(new Error("MAX_WS_PACKET_SIZE")),s.send(n),!["event","response"].includes(t.type)){let e;try{e=await i(this,[`response::${t.id}`],this.overridenTimeout||t.timeout||this.messageTimeout)}catch(e){return void(this.logger||console).debug(`${this.moduleName} failed to send message ${t.type} to ${t.targetModuleName||""}`)}if(!e)return;if(e.success)return e.data;{let s=`${t.moduleName}'s "${t.type}" request has failed.`;throw e.data instanceof Array&&e.data.length&&e.data[0].error&&(s=e.data[0].error),this.logger.error(s),new o(s)}}}ping(e){return this.sendMessage({type:`${e}.ping`})}emitMessage(e,t,s,o={}){const r=e.shift();if("string"!=typeof r)throw new Error("eventName must be a string");const i=`${t}.${s}.${r}`;this.sendMessage({type:"event",eventName:i,data:e,excludedClients:o.excludedClients||[]}).catch(e=>{console.error(`Couldn't emit ${i}`),"TIMEOUT"!==e.code&&console.trace(e)})}destroy(){this.removeAllListeners()}}class c{setCallback(e){if("function"!=typeof e)throw new Error("callback must be a function.");this.callback=e}setAncillaryData(e){this.ancillaryData=e||{}}getAncillaryData(){return this.ancillaryData||{}}call(...e){if(this.callback)return this.callback(...e)}}const l="undefined"!=typeof window?window.WebSocket:s;class h extends a{constructor(e={}){super(e),this.setMaxListeners(20);for(const e of[this.onOpen,this.onClose,this.onError,this.connect,this.onSocketMessage]){this[e.name]=e.bind(this)}this.logger=e.logger||function(e,t={silent:!1}){const{silent:s}=t;return["log","info","warn","error","trace","debug"].reduce((t,o)=>(t[o]=(...t)=>{if(s||(t=[`NOTICE (${o}): Current module: ${e} has no Logger object available, outputting to the console`,...t]),["trace","debug"].includes(o))for(const e of t||[])console.log(e);return console[o](...t)},t),{})}(this.moduleName,{silent:!0}),this.isDuplicate=e.isDuplicate,this.parent=e.parent,this.ssl=e.ssl,this.duplicates=new Set,this.serverModuleName=null,this.registrars=new Set,this.webSocketURL=e.webSocketURL,this.connected=!1,this.isDuplicate&&(this.connected=this.isConnected())}getConnectPromise(){return new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},0)})}forceReconnect(){this.removeSocketListeners(),this.socket=null,this.connect(this.connectOptions)}connect(e){if(this.isDuplicate)return;let t;this.connectOptions=e,t=e?{hostname:e.host,port:e.port}:new URL(location.href);const s="https:"===t.protocol||this.ssl?"wss":"ws",o=t.port?`${s}://${t.hostname}:${t.port}${this.webSocketURL}`:`${s}://${t.hostname}${this.webSocketURL}`;if(this.logger.info(`BrokerClient is connecting to ${o}`),"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node){const e=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=0,this.socket=new l(`${o}?module=true`),process.env.NODE_TLS_REJECT_UNAUTHORIZED=e}else this.socket=new l(o);this.addSocketListeners()}duplicate(e){const{moduleName:t}=e;let s,o;return this.isDuplicate?(s=this.parent.duplicates,o=new h({parent:this.parent,isDuplicate:!0,webSocketURL:this.webSocketURL,logger:this.logger,moduleName:t})):(s=this.duplicates,o=new h({parent:this,isDuplicate:!0,webSocketURL:this.webSocketURL,logger:this.logger,moduleName:t})),o.on("destroy",()=>s.delete(o)),s.add(o),o.ping().catch(e=>{console.error("Failed to send ping"),console.trace(e.message)}),o}isConnected(){return this.isDuplicate?this.parent.isConnected():this.connected}ping(){return this.sendMessage({type:"ping"})}getSocket(){return this.socket}async onSocketMessage(e){try{await this.handleMessage(e.data,this.socket)}catch(e){console.trace(e)}}async handleMessage(e){let t;try{t=JSON.parse(e);const s=this.isDuplicate?this.parent.getSocket():this.socket;switch(t.type){case"response":if(this.emit(`response::${t.requestId}`,t),!this.isDuplicate)for(const t of this.duplicates)t.handleMessage(e);break;case"event":for(const[e,s]of this.events.entries())if(e===t.eventName)for(const o of s)try{o.eventHandler(...t.data)}catch(e){this.logger.warn(e)}finally{o.once&&this.unsubscribeFromAPIEvent(e,o.eventHandler)}if(!this.isDuplicate)for(const t of this.duplicates)t.handleMessage(e);break;case"subscribe":{const[o,r,...i]=t.eventName.split("."),n=i.join("."),a=[o,r].join(".");if(this.moduleName===a)this.emit("subscribe",{eventName:n}),await this.sendResponse(s,t,!0);else{if(!this.isDuplicate)for(const t of this.duplicates)if(t.moduleName===a)return void t.handleMessage(e);await this.sendResponse(s,t,!1,[{error:`${t.eventName} sent to ${this.moduleName}. This is probably a mistake.`}])}break}case"unsubscribe":{const[o,r,...i]=t.eventName.split("."),n=i.join("."),a=[o,r].join(".");if(this.moduleName===a)this.emit("unsubscribe",{eventName:n}),await this.sendResponse(s,t,!0);else{if(!this.isDuplicate)for(const t of this.duplicates)if(t.moduleName===a)return void t.handleMessage(e);await this.sendResponse(s,t,!1,[{error:`${t.eventName} sent to ${this.moduleName}. This is probably a mistake.`}])}break}case"ping":if(this.serverModuleName=t.moduleName,!this.isDuplicate&&t.targetModuleName!==this.moduleName)for(const s of this.duplicates)if(s.moduleName===t.targetModuleName)return void s.handleMessage(e);await Promise.all([this.sendResponse(s,t,!0),this.resubscribeModuleEvents(),this.subscribeToAPIEvent(`${t.moduleName}.moduleconnect`,({moduleName:e})=>{this.emit("moduleconnect",{moduleName:e}),this.resubscribeModuleEvents()}),this.subscribeToAPIEvent(`${t.moduleName}.moduledisconnect`,({moduleName:e})=>{this.emit("moduledisconnect",{moduleName:e})})]);break;default:{if(!this.apiHandlers.has(t.type))return void await this.sendResponse(s,t,!1,[{error:`There is no handler registered for this type of message: ${t.type}`}]);const{messageHandler:e,relay:r}=this.apiHandlers.get(t.type);try{let o=await e(...t.data);if(o instanceof c){const e=o;e.setAncillaryData({...t.ancillaryData,caller:{moduleName:t.moduleName}}),o=await e.call(...t.data)}await this.sendResponse(s,t,!0,o,r)}catch(e){if(e instanceof o)return this.logger.error(e.message),void await this.sendResponse(s,t,!1,[{error:e.message}],r);this.logger.trace(e),await this.sendResponse(s,t,!1,[{error:"ERROR"}],r)}break}}}catch(e){if("TIMEOUT"===e.code)return console.warn("Message timed out."),void console.log(t);console.trace(e)}}async sendMessage(t){const s=e.v4(),o=this.isDuplicate?this.parent.getSocket():this.socket,r=Object.assign({},t,{id:s,time:(new Date).valueOf(),moduleName:this.moduleName});if(o.readyState!==l.OPEN)try{await i(this,["connect"],r.timeout||this.messageTimeout)}catch(e){throw console.error("Timeout: Socket is not ready"),e}let n;try{n=super.sendMessage(r,o)}catch(e){throw console.error("BrokerBase::sendMessage throwed an exception"),e}return n}addSocketListeners(){this.isDuplicate||(this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("message",this.onSocketMessage),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose))}removeSocketListeners(){this.socket&&(this.socket.removeEventListener("open",this.onOpen),this.socket.removeEventListener("message",this.onSocketMessage),this.socket.removeEventListener("error",this.onError),this.socket.removeEventListener("close",this.onClose))}resubscribeModuleEvents(){for(const e of this.events.keys()){const t=e.split(".").slice(0,2).join(".");this.sendMessage({type:"subscribe",eventName:e,targetModuleName:t}).catch(new Function)}}async onOpen(){try{this.connected=!0,this.emit("connect"),this.isDuplicate&&await this.ping();for(const e of this.registrars)await this.registerHandlersToRemote(e);if(!this.isDuplicate)for(const e of this.duplicates)e.onOpen()}catch(e){console.trace(e.message)}}onError(e){if(e.error instanceof Error&&(e=e.error.message),this.isDuplicate||this.logger.trace(e),!this.isDuplicate){this.logger.warn(`${this.moduleName} couldn't connect to WebSocket server.`);for(const t of this.duplicates)t.onError(e)}}onClose(e){if(this.connected){if(this.connected=!1,this.emit("disconnect",e),this.events.delete(`${this.serverModuleName}.moduleconnect`),!this.isDuplicate)for(const e of this.duplicates)e.onClose()}else this.emit("reconnectfailure");setTimeout(()=>this.connect(this.connectOptions),1e3)}registerHandlersToRemote(e){return this.registrars.add(e),this.sendMessage({type:`${e}.registerAPIHandlers`,data:Array.from(this.apiHandlers.keys()),targetModuleName:e})}async deregisterHandlersFromRemotes(){try{const e=[];for(const t of this.registrars)e.push(this.sendMessage({type:`${targetModuleName}.deregisterAPIHandlers`,data:Array.from(this.apiHandlers.keys()),targetModuleName:t}));return Promise.all(e)}catch(e){console.trace(e.message)}}unsubscribeFromAllEvents(){const e=[];for(const t of this.events.keys())e.push(this.unsubscribeFromAPIEvent(t));return Promise.all(e)}async destroy(){try{this.isDuplicate?(await Promise.all([this.deregisterHandlersFromRemotes(),this.unsubscribeFromAllEvents(),this.sendMessage({type:"event",eventName:`${this.moduleName}.disconnect`,targetModuleName:this.serverModuleName})]),this.emit("destroy")):(this.socket.close(),this.removeSocketListeners(),super.destroy())}catch(e){console.trace(e.message)}}async registerAPIHandlers(e,t=null,s="hub.core"){for(const[s,o]of Object.entries(e))this.registerAPIHandler(s,o.bind(t));return this.registerHandlersToRemote(s)}static async initModule(e){const{moduleName:t,serverURL:s,hub:o,webSocketURL:r="/core",clientModuleName:i,menuTitle:n}=e,a=new h({moduleName:t,webSocketURL:r});return a.connect(o),await a.getConnectPromise(),s?(await a.api.hub.core.registerProxyURL({moduleName:t,serverURL:s,clientModuleName:i,menuTitle:n}),a):a}}exports.BrokerBase=a,exports.BrokerClient=h,exports.BrokerError=o,exports.RawRequest=c;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/lib/BrokerError.js","../src/lib/onceMultiple.js","../src/lib/BrokerBase.js","../src/lib/RawRequest.js","../src/lib/BrokerClient.js","../src/lib/consoleLogger.js"],"sourcesContent":["// Copyright (c) 2019-2021 Zero Density Inc.\n//\n// This file is part of realityhub-api.\n//\n// realityhub-api is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2, as published by\n// the Free Software Foundation.\n//\n// realityhub-api is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.\n\nexport default class BrokerError extends Error {}\n","// Copyright (c) 2019-2021 Zero Density Inc.\n//\n// This file is part of realityhub-api.\n//\n// realityhub-api is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2, as published by\n// the Free Software Foundation.\n//\n// realityhub-api is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.\n\nclass TimeoutError extends Error {\n constructor(params) {\n super(params);\n this.code = 'TIMEOUT';\n this.name = this.constructor.name;\n }\n}\n\nexport default function onceMultiple(target, eventNames, timeout = null) {\n return new Promise((resolve, reject) => {\n let timer;\n let handler;\n let removeListeners;\n\n removeListeners = () => {\n for (const eventName of eventNames) {\n target.removeListener(eventName, handler);\n }\n };\n\n handler = (...args) => {\n removeListeners();\n clearTimeout(timer);\n resolve(...args);\n };\n\n for (const eventName of eventNames) {\n target.once(eventName, handler);\n }\n\n if (timeout) {\n timer = setTimeout(() => {\n removeListeners();\n reject(new TimeoutError('Timeout exceeded.'));\n }, timeout);\n }\n });\n}\n","// Copyright (c) 2019-2021 Zero Density Inc.\n//\n// This file is part of realityhub-api.\n//\n// realityhub-api is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2, as published by\n// the Free Software Foundation.\n//\n// realityhub-api is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.\n\nimport { v4 as uuid } from 'uuid';\nimport EventEmitter from 'events';\nimport BrokerError from './BrokerError.js';\nimport onceMultiple from './onceMultiple.js';\n\nconst DEFAULT_MAX_WS_PACKET_SIZE = 50 /*MB*/ * 1024 * 1024;\n\n/**\n * BrokerBase constructor\n * @param {object} params Parameters\n * @param {string} [params.moduleName] Module name\n * @param {number} [params.maxPacketSize] Maximum websocket packet size\n * @param {Logger} [params.logger] Logger instance\n */\nexport default class BrokerBase extends EventEmitter {\n constructor(params) {\n super();\n this.moduleName = params.moduleName;\n this.maxPacketSize = params.maxPacketSize || DEFAULT_MAX_WS_PACKET_SIZE;\n\n this.logger = params.logger;\n\n this.events = new Map();\n this.apiHandlers = new Map();\n\n this.messageTimeout = 2000;\n\n this.overridenTimeout = NaN; // NaN = use the implementation\n\n try {\n if (typeof window != 'undefined' && typeof localStorage != 'undefined') {\n this.overridenTimeout = Number(localStorage.getItem('BROKER_TIMEOUT')) || NaN;\n } else if (process && process.env) {\n this.overridenTimeout = Number(process.env.BROKER_TIMEOUT) || NaN;\n }\n } catch (ex) {}\n\n if (this.overridenTimeout) {\n const logger = this.logger || console;\n logger.warn(`Broker Timeout is overriden to ${this.overridenTimeout} milliseconds!`);\n }\n\n let maxPacketSizeRead = DEFAULT_MAX_WS_PACKET_SIZE;\n\n try {\n if (typeof window != 'undefined' && typeof localStorage != 'undefined') {\n maxPacketSizeRead ||= Number(localStorage.getItem('MAX_WS_PACKET_SIZE'));\n } else if (process && process.env) {\n maxPacketSizeRead ||= Number(process.env.MAX_WS_PACKET_SIZE);\n }\n } catch (ex) {\n const logger = this.logger || console;\n logger.error(`Cannot read maxPacketSize from either localStorage or env, defaulting to ${maxPacketSizeRead}`);\n }\n\n this.maxPacketSize = Math.max(this.maxPacketSize, maxPacketSizeRead);\n\n if (this.maxPacketSize !== DEFAULT_MAX_WS_PACKET_SIZE) {\n const logger = this.logger || console;\n logger.log(`BrokerBase is created with maxPacketSize: ${this.maxPacketSize}`);\n }\n\n this.initProxy();\n }\n\n getMethodProxy(vendorName, moduleName, options) {\n options = {\n timeout: 2000,\n excludedClients: [],\n ...options,\n };\n\n return new Proxy(\n {},\n {\n get: (_, methodName) => {\n if (methodName === 'emit' && this.moduleName !== `${vendorName}.${moduleName}`) {\n throw new Error('A module can only emit its own events.');\n }\n\n return (...args) => {\n switch (methodName) {\n case 'emit': {\n this.emitMessage(args, vendorName, moduleName, options);\n break;\n }\n\n case 'on': {\n const eventName = args.shift();\n const eventHandler = args.shift();\n\n if (typeof eventName !== 'string') {\n throw new Error('eventName must be a string');\n }\n\n if (typeof eventHandler !== 'function') {\n throw new Error('eventHandler must be a function');\n }\n\n const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;\n\n this.subscribeToAPIEvent(fullyQualifiedName, eventHandler).catch((err) => {\n console.error(`Couldn't subscribe to ${fullyQualifiedName}`);\n\n if (err.code !== 'TIMEOUT') {\n console.trace(err);\n }\n });\n\n break;\n }\n\n case 'once': {\n const eventName = args.shift();\n const eventHandler = args.shift();\n\n /**\n * If the subscribed event is not emitted within the given timeout then the\n * event handler will be removed automatically to prevent memory leak.\n * If a timeout is not provided by caller than a default timeout of 5 minutes is set.\n */\n const timeout = args.shift() || 60 * 1000 * 5;\n\n if (typeof eventName !== 'string') {\n throw new Error('eventName must be a string');\n }\n\n if (typeof eventHandler !== 'function') {\n throw new Error('eventHandler must be a function');\n }\n\n if (typeof timeout !== 'number' || isNaN(timeout)) {\n throw new Error('timeout must be a number');\n }\n\n const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;\n\n this.subscribeToAPIEvent(fullyQualifiedName, eventHandler, {\n once: true,\n }).catch((err) => {\n console.error(`Couldn't subscribe to ${fullyQualifiedName}`);\n\n if (err.code !== 'TIMEOUT') {\n console.trace(err);\n }\n });\n break;\n }\n\n case 'off': {\n const eventName = args.shift();\n const eventHandler = args.shift();\n const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;\n\n if (typeof eventName !== 'string') {\n throw new Error('eventName must be a string');\n }\n\n if (eventHandler && typeof eventHandler !== 'function') {\n throw new Error('eventHandler must be a function');\n }\n\n this.unsubscribeFromAPIEvent(fullyQualifiedName, eventHandler).catch((err) => {\n console.error(`Couldn't unsubscribe from ${fullyQualifiedName}`);\n\n if (err.code !== 'TIMEOUT') {\n console.trace(err);\n }\n });\n\n break;\n }\n\n case 'callTimeout': {\n const timeout = args[0];\n\n if (typeof timeout !== 'number') {\n throw new Error('callTimeout: timeout is required.');\n }\n\n const clonedOptions = JSON.parse(JSON.stringify(options));\n clonedOptions.timeout = timeout;\n return this.getMethodProxy(vendorName, moduleName, clonedOptions);\n }\n\n case 'excludeClients': {\n const excludedClients = args[0] || [];\n\n if (!(excludedClients instanceof Array)) {\n throw new Error('excludedClients requires 1 parameter: an array of strings');\n }\n\n const clonedOptions = JSON.parse(JSON.stringify(options));\n clonedOptions.excludedClients = clonedOptions.excludedClients.concat(excludedClients);\n return this.getMethodProxy(vendorName, moduleName, clonedOptions);\n }\n\n default: {\n return this.sendMessage({\n data: args,\n timeout: options.timeout,\n type: `${vendorName}.${moduleName}.${methodName}`,\n targetModuleName: `${vendorName}.${moduleName}`,\n excludedClients: options.excludedClients,\n });\n }\n }\n };\n },\n set: (_, methodName, handler) => {\n if (this.moduleName !== `${vendorName}.${moduleName}`) {\n throw new Error('Cannot register methods to other modules.');\n }\n\n if (typeof handler !== 'function') {\n throw new Error('Handler must be a function.');\n }\n\n if (['emit', 'on', 'off'].includes(methodName)) {\n throw new Error(`${methodName} is a reserved method name.`);\n }\n\n return this.registerAPIHandler(methodName, handler);\n },\n }\n );\n }\n\n /**\n * Initializes the Proxy object.\n * @private\n */\n initProxy() {\n // These nested proxies allow us to get vendorName, moduleName and methodName.\n // e.g. const pong = await this.api.hub.core.ping();\n this.api = new Proxy(\n {},\n {\n get: (_, vendorName) => {\n return new Proxy(\n {},\n {\n get: (_, moduleName) => {\n return this.getMethodProxy(vendorName, moduleName);\n },\n set: (_, moduleName, api) => {\n if (this.moduleName !== `${vendorName}.${moduleName}`) {\n throw new Error('Cannot register methods to other modules.');\n }\n\n if (typeof api !== 'object') {\n throw new Error('API must be set to an object.');\n }\n\n for (const [methodName, handler] of Object.entries(api)) {\n if (typeof handler !== 'function') {\n throw new Error('Handler must be a function.');\n }\n\n if (['emit', 'on', 'off'].includes(methodName)) {\n throw new Error(`${methodName} is a reserved method name.`);\n }\n\n this.registerAPIHandler(methodName, handler);\n }\n\n return true;\n },\n }\n );\n },\n set: function () {\n console.warn('Module name and method name are required.');\n return false;\n },\n }\n );\n }\n\n /**\n * Send a response message through `socket`.\n * @private\n * @param {WebSocket} socket Target socket.\n * @param {object} message The message to respond.\n * @param {boolean} success Whether the request was successfully processed or not.\n * @param {array} [data] Additional payload\n * @param {boolean} [relayedMessage=false]\n * @returns {Promise.<array, Error>}\n */\n sendResponse(socket, message, success, data = [], relayedMessage = false) {\n if (!socket) return;\n\n const { id: requestId, moduleName: targetModuleName, timeout, instigatorId } = message;\n const websocketMessage = {\n type: 'response',\n targetModuleName,\n instigatorId,\n requestId,\n timeout,\n success,\n data,\n };\n\n if (relayedMessage) {\n websocketMessage.moduleName = message.targetModuleName;\n }\n\n return this.sendMessage(websocketMessage, socket, relayedMessage);\n }\n\n /**\n * Registers an API request handler.\n * @param {string} messageType Message type.\n * @param {function} messageHandler Handler function.\n * @returns {boolean} `false` if a handler has already been assigned to the `messageType`.\n */\n registerAPIHandler(messageType, messageHandler) {\n messageType = `${this.moduleName}.${messageType}`;\n\n if (this.apiHandlers.has(messageType)) return false;\n\n this.apiHandlers.set(messageType, {\n relay: false,\n messageHandler,\n });\n\n return true;\n }\n\n /**\n * Subscribe to an API event.\n * @param {string} eventName Fully qualified event name.\n * @param {function} eventHandler A function which will be called when the event is received.\n * @param {object} [options] Options\n * @param {boolean} [options.sendMessage=true] If set to `true`, it will send a subscription message over WebSocket.\n * Otherwise the message will only be registered internally.\n * @param {boolean} [options.once=false] If true then the handler will be invoked only once and it won't be invoked for\n * the future events that are emitted.\n * @returns {Promise.<array, Error>}\n */\n subscribeToAPIEvent(eventName, eventHandler, options) {\n options = {\n sendMessage: true,\n once: false,\n ...options,\n };\n\n // Add handler to handlers map\n const handlerArray = this.events.get(eventName) || [];\n handlerArray.push({ eventHandler, once: options.once });\n this.events.set(eventName, handlerArray);\n\n // Send a subscription message over WebSocket\n if (options.sendMessage) {\n const targetModuleName = eventName.split('.').slice(0, 2).join('.');\n\n return this.sendMessage({\n type: 'subscribe',\n eventName,\n targetModuleName,\n });\n }\n }\n\n /**\n * Unsubscribe from an API event.\n * @param {string} eventName Fully qualified event name.\n * @param {function} [eventHandler] A previously registered handler function. All handlers of the event will\n * be removed unless `eventHandler` is provided.\n * @param {boolean} [sendMessage=true] Will send an unsubscription request when set to `true`.\n * @returns {Promise.<array, Error>}\n */\n unsubscribeFromAPIEvent(eventName, eventHandler, sendMessage = true) {\n if (eventHandler) {\n const handlerArray = (this.events.get(eventName) || []).filter((entry) => entry.eventHandler !== eventHandler);\n this.events.set(eventName, handlerArray);\n } else {\n this.events.delete(eventName);\n }\n\n if (sendMessage) {\n const targetModuleName = eventName.split('.').slice(0, 2).join('.');\n\n return this.sendMessage({\n type: 'unsubscribe',\n eventName,\n targetModuleName,\n });\n }\n }\n\n /**\n * Send an API message through a socket.\n * @async\n * @private\n * @param {object} message Message object. `time`, `id`, `moduleName` and `data` keys will be added\n * to the message object. Unlike other mentioned fields `data` will not get overridden when provided.\n * @param {object} socket Socket instance.\n * @param {boolean} [relayedMessage=false]\n * @returns {Promise.<array, Error>}\n */\n async sendMessage(message, socket, relayedMessage = false) {\n message.id = uuid();\n\n if (!relayedMessage) {\n message.moduleName = this.moduleName;\n }\n\n message.time = new Date().valueOf();\n const packet = JSON.stringify(message);\n\n if (packet.length > this.maxPacketSize) {\n this.logger.trace(new Error('MAX_WS_PACKET_SIZE'));\n }\n\n socket.send(packet);\n\n if (!['event', 'response'].includes(message.type)) {\n let responseMessage;\n\n try {\n responseMessage = await onceMultiple(\n this,\n [`response::${message.id}`],\n this.overridenTimeout || message.timeout || this.messageTimeout\n );\n } catch (ex) {\n const logger = this.logger || console;\n logger.debug(`${this.moduleName} failed to send message ${message.type} to ${message.targetModuleName || ''}`);\n return;\n }\n\n if (!responseMessage) return;\n\n if (responseMessage.success) {\n return responseMessage.data;\n } else {\n let errorMessage = `${message.moduleName}'s \"${message.type}\" request has failed.`;\n\n if (responseMessage.data instanceof Array && responseMessage.data.length && responseMessage.data[0].error) {\n errorMessage = responseMessage.data[0].error;\n }\n\n this.logger.error(errorMessage);\n throw new BrokerError(errorMessage);\n }\n }\n }\n\n /**\n * Send a ping request.\n * @param {string} targetModuleName\n * @private\n */\n ping(targetModuleName) {\n return this.sendMessage({ type: `${targetModuleName}.ping` });\n }\n\n /**\n * @private\n * @param {array} args\n * @param {string} vendorName\n * @param {string} moduleName\n */\n emitMessage(args, vendorName, moduleName, options = {}) {\n const eventName = args.shift();\n\n if (typeof eventName !== 'string') {\n throw new Error('eventName must be a string');\n }\n\n const fullyQualifiedName = `${vendorName}.${moduleName}.${eventName}`;\n\n this.sendMessage({\n type: 'event',\n eventName: fullyQualifiedName,\n data: args,\n excludedClients: options.excludedClients || [],\n }).catch((err) => {\n console.error(`Couldn't emit ${fullyQualifiedName}`);\n\n if (err.code !== 'TIMEOUT') {\n console.trace(err);\n }\n });\n }\n\n destroy() {\n this.removeAllListeners();\n }\n}\n","// Copyright (c) 2019-2021 Zero Density Inc.\n//\n// This file is part of realityhub-api.\n//\n// realityhub-api is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2, as published by\n// the Free Software Foundation.\n//\n// realityhub-api is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.\n\nexport default class RawRequest {\n setCallback(callback) {\n if (typeof callback !== 'function') {\n throw new Error('callback must be a function.');\n }\n\n this.callback = callback;\n }\n\n setAncillaryData(ancillaryData) {\n this.ancillaryData = ancillaryData || {};\n }\n\n getAncillaryData() {\n return this.ancillaryData || {};\n }\n\n call(...args) {\n if (this.callback) {\n return this.callback(...args);\n }\n }\n}\n","// Copyright (c) 2019-2021 Zero Density Inc.\n//\n// This file is part of realityhub-api.\n//\n// realityhub-api is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2, as published by\n// the Free Software Foundation.\n//\n// realityhub-api is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.\n\nimport { v4 as uuid } from 'uuid';\nimport BrokerBase from './BrokerBase.js';\nimport BrokerError from './BrokerError.js';\nimport RawRequest from './RawRequest.js';\nimport consoleLogger from './consoleLogger.js';\nimport onceMultiple from './onceMultiple.js';\nimport WebSocket from 'ws';\n\nconst WS = typeof window !== 'undefined' ? window.WebSocket : WebSocket;\n\nexport default class BrokerClient extends BrokerBase {\n /**\n * BrokerClient constructor\n * @param {object} params Parameters\n * @param {string} params.webSocketURL WebSocket URL\n * @param {string} [params.moduleName] Module name\n * @param {number} [params.maxPacketSize] Maximum websocket packet size\n * @param {Logger} [params.logger] Logger instance\n * @param {boolean} [params.isDuplicate] [Private property, used internally]\n * @param {boolean} [params.parent] [Private property, used internally]\n */\n constructor(params = {}) {\n super(params);\n\n this.setMaxListeners(20);\n\n for (const func of [this.onOpen, this.onClose, this.onError, this.connect, this.onSocketMessage]) {\n const name = func.name;\n this[name] = func.bind(this);\n }\n\n this.logger = params.logger || consoleLogger(this.moduleName, { silent: true });\n\n this.isDuplicate = params.isDuplicate;\n this.parent = params.parent;\n this.ssl = params.ssl;\n this.duplicates = new Set();\n\n // moduleName of the server (will be set when we receive a ping message)\n this.serverModuleName = null;\n\n /**\n * A set of module names\n * Each time registerHandlersToRemote is called, the `remote` is added to this set.\n * BrokerClient uses the list of the remote endpoints for re-registering after a\n * reconnect.\n * @type {Set<string>}\n */\n this.registrars = new Set();\n\n this.webSocketURL = params.webSocketURL;\n this.connected = false;\n\n if (this.isDuplicate) {\n this.connected = this.isConnected();\n }\n }\n\n /**\n * Returns a `Promise` that will resolve once a `connect` event is emitted.\n * If BrokerClient is already connected then it will resolve in the next\n * event loop.\n * @returns {Promise}\n */\n getConnectPromise() {\n return new Promise((resolve) => {\n const looper = setInterval(() => {\n if (this.connected) {\n clearInterval(looper);\n resolve();\n }\n }, 0);\n });\n }\n\n forceReconnect() {\n this.removeSocketListeners();\n this.socket = null;\n this.connect(this.connectOptions);\n }\n\n /**\n * Connect to server.\n * @param {object} options Options\n * @param {string} options.host Hostname or IP of the target server.\n * @param {number} options.port WebSocket port of the target server.\n */\n connect(options) {\n if (this.isDuplicate) return;\n\n this.connectOptions = options;\n let url;\n\n if (!options) {\n url = new URL(location.href);\n } else {\n url = { hostname: options.host, port: options.port };\n }\n\n const scheme = url.protocol === 'https:' || this.ssl ? 'wss' : 'ws';\n\n const webSocketURL = url.port\n ? `${scheme}://${url.hostname}:${url.port}${this.webSocketURL}`\n : `${scheme}://${url.hostname}${this.webSocketURL}`;\n\n this.logger.info(`BrokerClient is connecting to ${webSocketURL}`);\n\n if (typeof process !== 'undefined' && process.versions != null && process.versions.node != null) {\n const NODE_TLS_REJECT_UNAUTHORIZED = process.env.NODE_TLS_REJECT_UNAUTHORIZED;\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;\n this.socket = new WS(`${webSocketURL}?module=true`);\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = NODE_TLS_REJECT_UNAUTHORIZED;\n } else {\n this.socket = new WS(webSocketURL);\n }\n\n this.addSocketListeners();\n }\n\n /**\n * Duplicates a BrokerClient in order to share the same WebSocket.\n * @param {object} params Parameters\n * @param {string} params.moduleName Module name of the duplicate BrokerClient (a duplicate\n * can have a different name than its parent)\n * @returns {BrokerClient}\n */\n duplicate(params) {\n const { moduleName } = params;\n let duplicates;\n let duplicate;\n\n if (this.isDuplicate) {\n duplicates = this.parent.duplicates;\n duplicate = new BrokerClient({\n parent: this.parent,\n isDuplicate: true,\n webSocketURL: this.webSocketURL,\n logger: this.logger,\n moduleName,\n });\n } else {\n duplicates = this.duplicates;\n duplicate = new BrokerClient({\n parent: this,\n isDuplicate: true,\n webSocketURL: this.webSocketURL,\n logger: this.logger,\n moduleName,\n });\n }\n\n duplicate.on('destroy', () => duplicates.delete(duplicate));\n duplicates.add(duplicate);\n\n duplicate.ping().catch((ex) => {\n console.error(`Failed to send ping`);\n console.trace(ex.message);\n });\n\n return duplicate;\n }\n\n /**\n * Returns `true` if WebSocket connection is established.\n * @returns {boolean}\n */\n isConnected() {\n if (this.isDuplicate) {\n return this.parent.isConnected();\n }\n\n return this.connected;\n }\n\n /**\n * Sends a ping message to server.\n * @private\n */\n ping() {\n return this.sendMessage({ type: 'ping' });\n }\n\n /**\n * Returns the WebSocket instance.\n * @private\n */\n getSocket() {\n return this.socket;\n }\n\n async onSocketMessage(event) {\n try {\n await this.handleMessage(event.data, this.socket);\n } catch (ex) {\n console.trace(ex);\n }\n }\n\n /**\n * Handles incoming messages.\n * @param {string} rawMessage Raw message\n * @async\n * @private\n */\n async handleMessage(rawMessage) {\n let message;\n\n try {\n message = JSON.parse(rawMessage);\n const socket = this.isDuplicate ? this.parent.getSocket() : this.socket;\n\n switch (message.type) {\n case 'response': {\n this.emit(`response::${message.requestId}`, message);\n\n // Send the response to other duplicates (if we are parent)\n if (!this.isDuplicate) {\n for (const duplicate of this.duplicates) {\n duplicate.handleMessage(rawMessage);\n }\n }\n\n break;\n }\n\n case 'event': {\n // Run previously registered event handlers\n for (const [subscribedEvent, entries] of this.events.entries()) {\n if (subscribedEvent === message.eventName) {\n for (const entry of entries) {\n try {\n entry.eventHandler(...message.data);\n } catch (ex) {\n this.logger.warn(ex);\n } finally {\n if (entry.once) {\n this.unsubscribeFromAPIEvent(subscribedEvent, entry.eventHandler);\n }\n }\n }\n }\n }\n\n // Send the event to other duplicates (if we are parent)\n if (!this.isDuplicate) {\n for (const duplicate of this.duplicates) {\n duplicate.handleMessage(rawMessage);\n }\n }\n\n break;\n }\n\n case 'subscribe': {\n const [vendor, moduleName, ...rest] = message.eventName.split('.');\n const eventName = rest.join('.');\n const targetModuleName = [vendor, moduleName].join('.');\n\n if (this.moduleName === targetModuleName) {\n this.emit('subscribe', { eventName });\n await this.sendResponse(socket, message, true);\n } else {\n // Check if the target is one of the duplicates (if we are parent)\n if (!this.isDuplicate) {\n for (const duplicate of this.duplicates) {\n if (duplicate.moduleName === targetModuleName) {\n duplicate.handleMessage(rawMessage);\n return;\n }\n }\n }\n\n await this.sendResponse(socket, message, false, [\n {\n error: `${message.eventName} sent to ${this.moduleName}. This is probably a mistake.`,\n },\n ]);\n }\n\n break;\n }\n\n case 'unsubscribe': {\n const [vendor, moduleName, ...rest] = message.eventName.split('.');\n const eventName = rest.join('.');\n const targetModuleName = [vendor, moduleName].join('.');\n\n if (this.moduleName === targetModuleName) {\n this.emit('unsubscribe', { eventName });\n await this.sendResponse(socket, message, true);\n } else {\n // Check if the target is one of the duplicates (if we are parent)\n if (!this.isDuplicate) {\n for (const duplicate of this.duplicates) {\n if (duplicate.moduleName === targetModuleName) {\n duplicate.handleMessage(rawMessage);\n return;\n }\n }\n }\n\n await this.sendResponse(socket, message, false, [\n {\n error: `${message.eventName} sent to ${this.moduleName}. This is probably a mistake.`,\n },\n ]);\n }\n\n break;\n }\n\n case 'ping': {\n this.serverModuleName = message.moduleName;\n\n if (!this.isDuplicate && message.targetModuleName !== this.moduleName) {\n for (const duplicate of this.duplicates) {\n if (duplicate.moduleName === message.targetModuleName) {\n duplicate.handleMessage(rawMessage);\n return;\n }\n }\n }\n\n await Promise.all([\n this.sendResponse(socket, message, true),\n this.resubscribeModuleEvents(),\n this.subscribeToAPIEvent(`${message.moduleName}.moduleconnect`, ({ moduleName }) => {\n this.emit('moduleconnect', { moduleName });\n this.resubscribeModuleEvents();\n }),\n this.subscribeToAPIEvent(`${message.moduleName}.moduledisconnect`, ({ moduleName }) => {\n this.emit('moduledisconnect', { moduleName });\n }),\n ]);\n\n break;\n }\n\n default: {\n if (!this.apiHandlers.has(message.type)) {\n await this.sendResponse(socket, message, false, [\n {\n error: `There is no handler registered for this type of message: ${message.type}`,\n },\n ]);\n return;\n }\n\n const { messageHandler, relay } = this.apiHandlers.get(message.type);\n\n try {\n let responseMessage = await messageHandler(...message.data);\n\n if (responseMessage instanceof RawRequest) {\n const rawRequest = responseMessage;\n rawRequest.setAncillaryData({\n ...message.ancillaryData,\n caller: {\n moduleName: message.moduleName,\n },\n });\n responseMessage = await rawRequest.call(...message.data);\n }\n\n await this.sendResponse(socket, message, true, responseMessage, relay);\n } catch (ex) {\n if (ex instanceof BrokerError) {\n this.logger.error(ex.message);\n await this.sendResponse(socket, message, false, [{ error: ex.message }], relay);\n return;\n }\n\n this.logger.trace(ex);\n await this.sendResponse(socket, message, false, [{ error: 'ERROR' }], relay);\n }\n\n break;\n }\n }\n } catch (ex) {\n if (ex.code === 'TIMEOUT') {\n console.warn('Message timed out.');\n console.log(message);\n return;\n }\n\n console.trace(ex);\n }\n }\n\n /**\n * Sends a message.\n * @async\n * @param {object} message\n * @returns {Promise.<Array, Error>}\n */\n async sendMessage(message) {\n const id = uuid();\n const socket = this.isDuplicate ? this.parent.getSocket() : this.socket;\n const webSocketMessage = Object.assign({}, message, {\n id,\n time: new Date().valueOf(),\n moduleName: this.moduleName,\n });\n\n if (socket.readyState !== WS.OPEN) {\n try {\n await onceMultiple(this, ['connect'], webSocketMessage.timeout || this.messageTimeout);\n } catch (ex) {\n console.error(`Timeout: Socket is not ready`);\n throw ex;\n }\n }\n\n let ret;\n\n try {\n ret = super.sendMessage(webSocketMessage, socket);\n } catch (ex) {\n console.error(`BrokerBase::sendMessage throwed an exception`);\n throw ex;\n }\n\n return ret;\n }\n\n /**\n * @private\n */\n addSocketListeners() {\n if (this.isDuplicate) return;\n\n this.socket.addEventListener('open', this.onOpen);\n this.socket.addEventListener('message', this.onSocketMessage);\n this.socket.addEventListener('error', this.onError);\n this.socket.addEventListener('close', this.onClose);\n }\n\n removeSocketListeners() {\n if (!this.socket) return;\n\n this.socket.removeEventListener('open', this.onOpen);\n this.socket.removeEventListener('message', this.onSocketMessage);\n this.socket.removeEventListener('error', this.onError);\n this.socket.removeEventListener('close', this.onClose);\n }\n\n /**\n * @private\n */\n resubscribeModuleEvents() {\n for (const eventName of this.events.keys()) {\n const moduleName = eventName.split('.').slice(0, 2).join('.');\n\n this.sendMessage({\n type: 'subscribe',\n eventName,\n targetModuleName: moduleName,\n }).catch(new Function());\n }\n }\n\n /**\n * @async\n * @private\n */\n async onOpen() {\n try {\n this.connected = true;\n this.emit('connect');\n\n if (this.isDuplicate) {\n await this.ping();\n }\n\n for (const registrar of this.registrars) {\n await this.registerHandlersToRemote(registrar);\n }\n\n if (!this.isDuplicate) {\n for (const duplicate of this.duplicates) {\n duplicate.onOpen();\n }\n }\n } catch (ex) {\n console.trace(ex.message);\n }\n }\n\n /**\n * @private\n * @param {ErrorEvent} err\n */\n onError(err) {\n if (err.error instanceof Error) {\n err = err.error.message;\n }\n\n if (!this.isDuplicate) {\n this.logger.trace(err);\n }\n\n if (!this.isDuplicate) {\n this.logger.warn(`${this.moduleName} couldn't connect to WebSocket server.`);\n\n for (const duplicate of this.duplicates) {\n duplicate.onError(err);\n }\n }\n }\n\n /**\n * @private\n */\n onClose(e) {\n if (this.connected) {\n this.connected = false;\n this.emit('disconnect', e);\n this.events.delete(`${this.serverModuleName}.moduleconnect`);\n\n if (!this.isDuplicate) {\n for (const duplicate of this.duplicates) {\n duplicate.onClose();\n }\n }\n } else {\n this.emit('reconnectfailure');\n }\n\n setTimeout(() => this.connect(this.connectOptions), 1000);\n }\n\n /**\n * Send the local API handler list to the `targetModuleName` so it will relay\n * messages targeting those handlers.\n * @param {string} targetModuleName Module name of the API Server\n * @returns {Promise.<Array, Error>}\n */\n registerHandlersToRemote(targetModuleName) {\n this.registrars.add(targetModuleName);\n\n return this.sendMessage({\n type: `${targetModuleName}.registerAPIHandlers`,\n data: Array.from(this.apiHandlers.keys()),\n targetModuleName,\n });\n }\n\n /**\n * Send a message to all remote endpoints telling them not to relay any messages\n * to this module anymore.\n * @async\n * @returns {Promise.<Array, Error>[]}\n */\n async deregisterHandlersFromRemotes() {\n try {\n const promises = [];\n\n for (const registrar of this.registrars) {\n promises.push(\n this.sendMessage({\n type: `${targetModuleName}.deregisterAPIHandlers`,\n data: Array.from(this.apiHandlers.keys()),\n targetModuleName: registrar,\n })\n );\n }\n\n return Promise.all(promises);\n } catch (ex) {\n console.trace(ex.message);\n }\n }\n\n /**\n * Unsubscribes from all subscriptions.\n * @returns {Promise.<Array, Error>[]}\n */\n unsubscribeFromAllEvents() {\n const promises = [];\n\n for (const eventName of this.events.keys()) {\n promises.push(this.unsubscribeFromAPIEvent(eventName));\n }\n\n return Promise.all(promises);\n }\n\n /**\n * Performs cleanup.\n * @async\n */\n async destroy() {\n try {\n if (this.isDuplicate) {\n await Promise.all([\n this.deregisterHandlersFromRemotes(),\n this.unsubscribeFromAllEvents(),\n this.sendMessage({\n type: 'event',\n eventName: `${this.moduleName}.disconnect`,\n targetModuleName: this.serverModuleName,\n }),\n ]);\n this.emit('destroy');\n } else {\n this.socket.close();\n this.removeSocketListeners();\n super.destroy();\n }\n } catch (ex) {\n console.trace(ex.message);\n }\n }\n\n /**\n * Register a module's API handlers to RealityHub\n * @async\n * @param {Object.<string, function>} handlers Key will be registered to the API tree.\n * @param {*} [context=null] Handlers' `this` will be set to this context.\n * The value (function) will handle the API calls.\n * @param {string} [remote='hub.core'] Remote\n * @example\n * // server.js\n * brokerClient.registerAPIHandlers(this, {\n * addNumbers: function (number1, number2) {\n * return number1 + number2;\n * },\n * }).catch((ex) => console.trace(ex));\n *\n * // client.js\n * brokerClient.api.moduleVendor.moduleName.addNumber(3, 5)\n * .then((result) => {\n * // Will log 15\n * console.log(result);\n * })\n * .catch((ex) => console.trace(ex));\n * @returns {Promise}\n */\n async registerAPIHandlers(handlers, context = null, remote = 'hub.core') {\n for (const [handlerName, handler] of Object.entries(handlers)) {\n this.registerAPIHandler(handlerName, handler.bind(context));\n }\n\n return this.registerHandlersToRemote(remote);\n }\n\n /**\n * Third-party modules can use this method to initialize a BrokerClient\n * and register themselves to RealityHub.\n * @async\n * @static\n * @param {{ clientModuleName?: string, menuTitle?: string, moduleName: string, serverURL: string, webSocketURL?: string, hub: {host: string, port: number }}} params Parameters\n * @param {string} [params.clientModuleName] Client Module Name (`<vendor>.<client module name>`)\n * @param {string} [params.menuTitle] Menu Title\n * @param {string} params.moduleName Backend Module Name (`<vendor>.<backend module name>`)\n * @param {string} params.serverURL Your module has to serve your client files over HTTP or HTTPS.\n * RealityHub will look for an `index.js` file in this path. This script file will be imported\n * by RealityHub's `index.html` via a `<script type=\"module\">` tag. Relative paths in your scripts\n * will be proxied by RealityHub.\n * @param {string} [params.webSocketURL=\"/core\"] WebSocket URL to connect. RealityHub's API Server\n * is serving at `/core` by default. *(Default: /core)*\n * @param {{ host: string, port: number }} params.hub RealityHub connection parameters\n * @param {string} params.hub.host RealityHub hostname or IP address\n * @param {string} params.hub.port RealityHub port\n * @returns {Promise<BrokerClient, Error>} A BrokerClient instance.\n */\n static async initModule(params) {\n const { moduleName, serverURL, hub, webSocketURL = '/core', clientModuleName, menuTitle } = params;\n const hubClient = new BrokerClient({ moduleName, webSocketURL });\n\n hubClient.connect(hub);\n await hubClient.getConnectPromise();\n if (!serverURL) return hubClient;\n\n await hubClient.api.hub.core.registerProxyURL({\n moduleName,\n serverURL,\n clientModuleName,\n menuTitle,\n });\n return hubClient;\n }\n}\n","// Copyright (c) 2019-2021 Zero Density Inc.\n//\n// This file is part of realityhub-api.\n//\n// realityhub-api is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2, as published by\n// the Free Software Foundation.\n//\n// realityhub-api is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.\n\nexport default function consoleLogger(moduleName, options = { silent: false }) {\n const { silent } = options;\n\n return ['log', 'info', 'warn', 'error', 'trace', 'debug'].reduce((o, item) => {\n o[item] = (...args) => {\n if (!silent) {\n args = [\n `NOTICE (${item}): Current module: ${moduleName} has no Logger object available, outputting to the console`,\n ...args,\n ];\n }\n\n if (['trace', 'debug'].includes(item)) {\n for (const arg of args || []) {\n console.log(arg);\n }\n }\n\n return console[item](...args);\n };\n return o;\n }, {});\n}\n"],"names":["BrokerError","Error","TimeoutError","constructor","params","super","this","code","name","onceMultiple","target","eventNames","timeout","Promise","resolve","reject","timer","handler","removeListeners","eventName","removeListener","args","clearTimeout","once","setTimeout","DEFAULT_MAX_WS_PACKET_SIZE","BrokerBase","EventEmitter","moduleName","maxPacketSize","logger","events","Map","apiHandlers","messageTimeout","overridenTimeout","NaN","window","localStorage","Number","getItem","process","env","BROKER_TIMEOUT","ex","console","warn","maxPacketSizeRead","MAX_WS_PACKET_SIZE","error","Math","max","log","initProxy","getMethodProxy","vendorName","options","excludedClients","Proxy","get","_","methodName","emitMessage","shift","eventHandler","fullyQualifiedName","subscribeToAPIEvent","catch","err","trace","isNaN","unsubscribeFromAPIEvent","clonedOptions","JSON","parse","stringify","Array","concat","sendMessage","data","type","targetModuleName","set","includes","registerAPIHandler","api","Object","entries","sendResponse","socket","message","success","relayedMessage","id","requestId","instigatorId","websocketMessage","messageType","messageHandler","has","relay","handlerArray","push","split","slice","join","filter","entry","delete","uuid","time","Date","valueOf","packet","length","send","responseMessage","debug","errorMessage","ping","destroy","removeAllListeners","RawRequest","setCallback","callback","setAncillaryData","ancillaryData","getAncillaryData","call","WS","WebSocket","BrokerClient","setMaxListeners","func","onOpen","onClose","onError","connect","onSocketMessage","bind","silent","reduce","o","item","arg","consoleLogger","isDuplicate","parent","ssl","duplicates","Set","serverModuleName","registrars","webSocketURL","connected","isConnected","getConnectPromise","looper","setInterval","clearInterval","forceReconnect","removeSocketListeners","connectOptions","url","hostname","host","port","URL","location","href","scheme","protocol","info","versions","node","NODE_TLS_REJECT_UNAUTHORIZED","addSocketListeners","duplicate","on","add","getSocket","event","handleMessage","rawMessage","emit","subscribedEvent","vendor","rest","all","resubscribeModuleEvents","rawRequest","caller","webSocketMessage","assign","readyState","OPEN","ret","addEventListener","removeEventListener","keys","Function","registrar","registerHandlersToRemote","e","from","deregisterHandlersFromRemotes","promises","unsubscribeFromAllEvents","close","registerAPIHandlers","handlers","context","remote","handlerName","initModule","serverUR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MwB,WAAEA,EAAU2L,UAAEA,EAASC,IAAEA,EAAG/D,aAAEA,EAAe,QAAOgE,iBAAEA,EAAgBC,UAAEA,GAActN,EACtFuN,EAAY,IAAIxF,EAAa,CAAEvG,aAAY6H,iBAIjD,OAFAkE,EAAUlF,QAAQ+E,SACZG,EAAU/D,oBACX2D,SAECI,EAAUtI,IAAImI,IAAII,KAAKC,iBAAiB,CAC5CjM,aACA2L,YACAE,mBACAC,cAEKC,GARgBA,CASzB"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zerodensity/realityhub-api",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "RealityHub API Javascript Implementation",
|
|
5
|
-
"
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.cjs",
|
|
7
|
+
"module": "src/index.js",
|
|
8
|
+
"types": "./src/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./src/index.d.ts",
|
|
12
|
+
"import": "./src/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "rollup -c"
|
|
19
|
+
},
|
|
6
20
|
"repository": {
|
|
7
21
|
"type": "git",
|
|
8
22
|
"url": "git+ssh://git@github.com/zerodensity/realityhub-api.git"
|
|
@@ -30,7 +44,16 @@
|
|
|
30
44
|
},
|
|
31
45
|
"homepage": "https://github.com/zerodensity/realityhub-api#readme",
|
|
32
46
|
"dependencies": {
|
|
33
|
-
"uuid": "^
|
|
34
|
-
"ws": "^8.18.
|
|
47
|
+
"uuid": "^13.0.0",
|
|
48
|
+
"ws": "^8.18.3"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@rollup/plugin-commonjs": "^29.0.0",
|
|
52
|
+
"@rollup/plugin-node-resolve": "^16.0.3",
|
|
53
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
54
|
+
"rollup": "^4.53.3"
|
|
55
|
+
},
|
|
56
|
+
"optionalDependencies": {
|
|
57
|
+
"@rollup/rollup-linux-x64-gnu": "^4.53.3"
|
|
35
58
|
}
|
|
36
59
|
}
|
package/rollup.config.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import resolve from '@rollup/plugin-node-resolve';
|
|
2
|
+
import commonjs from '@rollup/plugin-commonjs';
|
|
3
|
+
import terser from '@rollup/plugin-terser';
|
|
4
|
+
|
|
5
|
+
export default {
|
|
6
|
+
input: 'src/index.js',
|
|
7
|
+
output: {
|
|
8
|
+
file: 'dist/index.cjs',
|
|
9
|
+
format: 'cjs',
|
|
10
|
+
exports: 'named',
|
|
11
|
+
sourcemap: true,
|
|
12
|
+
},
|
|
13
|
+
plugins: [resolve(), commonjs(), terser()],
|
|
14
|
+
external: ['ws', 'uuid'],
|
|
15
|
+
};
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
|
|
3
|
+
export class BrokerError extends Error {}
|
|
4
|
+
|
|
5
|
+
export class RawRequest {
|
|
6
|
+
setCallback(callback: Function): void;
|
|
7
|
+
setAncillaryData(ancillaryData: any): void;
|
|
8
|
+
getAncillaryData(): any;
|
|
9
|
+
call(...args: any[]): any;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface Logger {
|
|
13
|
+
log(...args: any[]): void;
|
|
14
|
+
info(...args: any[]): void;
|
|
15
|
+
warn(...args: any[]): void;
|
|
16
|
+
error(...args: any[]): void;
|
|
17
|
+
debug(...args: any[]): void;
|
|
18
|
+
trace(...args: any[]): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface BrokerBaseParams {
|
|
22
|
+
moduleName?: string;
|
|
23
|
+
maxPacketSize?: number;
|
|
24
|
+
logger?: Logger;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class BrokerBase extends EventEmitter {
|
|
28
|
+
constructor(params: BrokerBaseParams);
|
|
29
|
+
moduleName: string;
|
|
30
|
+
maxPacketSize: number;
|
|
31
|
+
logger: Logger;
|
|
32
|
+
apiHandlers: Map<string, any>;
|
|
33
|
+
events: Map<string, any>;
|
|
34
|
+
api: {
|
|
35
|
+
[vendor: string]: {
|
|
36
|
+
[module: string]: {
|
|
37
|
+
emit(eventName: string, ...args: any[]): void;
|
|
38
|
+
on(eventName: string, handler: Function): void;
|
|
39
|
+
off(eventName: string, handler: Function): void;
|
|
40
|
+
once(eventName: string, handler: Function): void;
|
|
41
|
+
} & {
|
|
42
|
+
[method: string]: <T = any>(...args: any[]) => Promise<T>;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
getMethodProxy(vendorName: string, moduleName: string, options?: any): any;
|
|
48
|
+
initProxy(): void;
|
|
49
|
+
sendResponse(socket: any, message: any, success: boolean, data?: any[], relayedMessage?: boolean): Promise<any>;
|
|
50
|
+
registerAPIHandler(messageType: string, messageHandler: Function): boolean;
|
|
51
|
+
subscribeToAPIEvent(
|
|
52
|
+
eventName: string,
|
|
53
|
+
eventHandler: Function,
|
|
54
|
+
options?: { sendMessage?: boolean; once?: boolean }
|
|
55
|
+
): Promise<any>;
|
|
56
|
+
unsubscribeFromAPIEvent(eventName: string, eventHandler?: Function, sendMessage?: boolean): Promise<any>;
|
|
57
|
+
sendMessage(message: any, socket: any, relayedMessage?: boolean): Promise<any>;
|
|
58
|
+
ping(targetModuleName: string): Promise<any>;
|
|
59
|
+
emitMessage(args: any[], vendorName: string, moduleName: string, options?: any): void;
|
|
60
|
+
destroy(): void | Promise<void>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface BrokerClientParams extends BrokerBaseParams {
|
|
64
|
+
webSocketURL?: string;
|
|
65
|
+
isDuplicate?: boolean;
|
|
66
|
+
parent?: BrokerClient;
|
|
67
|
+
ssl?: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ConnectOptions {
|
|
71
|
+
host: string;
|
|
72
|
+
port: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface InitModuleParams {
|
|
76
|
+
clientModuleName?: string;
|
|
77
|
+
menuTitle?: string;
|
|
78
|
+
moduleName: string;
|
|
79
|
+
serverURL?: string;
|
|
80
|
+
webSocketURL?: string;
|
|
81
|
+
hub: ConnectOptions;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class BrokerClient extends BrokerBase {
|
|
85
|
+
constructor(params?: BrokerClientParams);
|
|
86
|
+
webSocketURL: string;
|
|
87
|
+
connected: boolean;
|
|
88
|
+
isDuplicate: boolean;
|
|
89
|
+
parent: BrokerClient;
|
|
90
|
+
ssl: boolean;
|
|
91
|
+
socket: any;
|
|
92
|
+
|
|
93
|
+
getConnectPromise(): Promise<void>;
|
|
94
|
+
forceReconnect(): void;
|
|
95
|
+
connect(options: ConnectOptions): void;
|
|
96
|
+
duplicate(params: { moduleName: string }): BrokerClient;
|
|
97
|
+
isConnected(): boolean;
|
|
98
|
+
ping(): Promise<any>;
|
|
99
|
+
getSocket(): any;
|
|
100
|
+
handleMessage(rawMessage: string): Promise<void>;
|
|
101
|
+
sendMessage(message: any): Promise<any>;
|
|
102
|
+
addSocketListeners(): void;
|
|
103
|
+
removeSocketListeners(): void;
|
|
104
|
+
resubscribeModuleEvents(): void;
|
|
105
|
+
onOpen(): Promise<void>;
|
|
106
|
+
onError(err: any): void;
|
|
107
|
+
onClose(e: any): void;
|
|
108
|
+
registerHandlersToRemote(targetModuleName: string): Promise<any>;
|
|
109
|
+
deregisterHandlersFromRemotes(): Promise<any>;
|
|
110
|
+
unsubscribeFromAllEvents(): Promise<any>;
|
|
111
|
+
destroy(): Promise<void>;
|
|
112
|
+
registerAPIHandlers(handlers: { [key: string]: Function }, context?: any, remote?: string): Promise<any>;
|
|
113
|
+
|
|
114
|
+
static initModule(params: InitModuleParams): Promise<BrokerClient>;
|
|
115
|
+
}
|