@zerodensity/realityhub-api 1.20.0 → 1.22.0
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.
|
@@ -7,15 +7,17 @@ on:
|
|
|
7
7
|
|
|
8
8
|
jobs:
|
|
9
9
|
publish-npm:
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
id-token: write
|
|
12
13
|
name: Publish Job
|
|
13
14
|
runs-on: ubuntu-latest
|
|
14
15
|
steps:
|
|
15
|
-
- uses: actions/checkout@
|
|
16
|
-
- uses: actions/setup-node@
|
|
16
|
+
- uses: actions/checkout@v6
|
|
17
|
+
- uses: actions/setup-node@v6
|
|
17
18
|
with:
|
|
18
|
-
node-version: '
|
|
19
|
+
node-version: '24'
|
|
19
20
|
registry-url: https://registry.npmjs.org/
|
|
20
|
-
|
|
21
|
-
- run: npm
|
|
21
|
+
package-manager-cache: false
|
|
22
|
+
- run: npm ci --ignore-scripts
|
|
23
|
+
- run: npm publish --tag stable
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Copyright (c) 2026 Zero Density Inc.
|
|
2
|
+
// SPDX-License-Identifier: GPL-2.0-only
|
|
3
|
+
const { EventEmitter } = require('node:events');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {Object} Snapshot
|
|
7
|
+
* @property {Object|null} state Auxiliary field state, persisted with the item.
|
|
8
|
+
* @property {*} value Controller/form output.
|
|
9
|
+
*
|
|
10
|
+
* @typedef {Object} DataSnapshot
|
|
11
|
+
* @property {boolean} hasValue
|
|
12
|
+
* @property {*} data
|
|
13
|
+
* @property {string|null} [error]
|
|
14
|
+
* @property {boolean} [stale]
|
|
15
|
+
* @property {string} [status] `disabled` when the host intentionally stops source traffic.
|
|
16
|
+
*
|
|
17
|
+
* @typedef {Object} Subscription
|
|
18
|
+
* @property {function(): void} stop
|
|
19
|
+
*
|
|
20
|
+
* @typedef {Object} Watch
|
|
21
|
+
* @property {function(Object): void} setParameters Replace parameters and discard obsolete deliveries.
|
|
22
|
+
* @property {function(): void} stop
|
|
23
|
+
*
|
|
24
|
+
* @typedef {Object} BackendAPI Injected into the partner's exported start(api).
|
|
25
|
+
* @property {number} apiVersion
|
|
26
|
+
* @property {Object} context
|
|
27
|
+
* @property {function(string, Function): void} export Register a frontend-callable function.
|
|
28
|
+
* @property {function(string, *=): void} emit Send a custom event to attached frontends.
|
|
29
|
+
* @property {function(string, Function): Function} on Subscribe using legacy direct callback delivery.
|
|
30
|
+
* @property {function(function(Snapshot): *): Function} onStateChange Await external state changes in the handler queue.
|
|
31
|
+
* @property {function(): Snapshot} getState Read the latest committed snapshot.
|
|
32
|
+
* @property {function(Object): Promise<Snapshot>} update Replace each supplied snapshot property.
|
|
33
|
+
* @property {function(Object): Promise<Snapshot>} patch Shallow-merge state and optionally commit output atomically.
|
|
34
|
+
* @property {function(*): Promise<Snapshot>} setValue
|
|
35
|
+
* @property {function(Object|null): Promise<Snapshot>} setState
|
|
36
|
+
* @property {function(Function): void} schedule Queue background work after the current handler/startup.
|
|
37
|
+
* @property {Object} data Named query bindings configured on the field.
|
|
38
|
+
* @property {boolean} data.enabled Whether bound query traffic is enabled for this field.
|
|
39
|
+
* @property {function(string, Object=): Promise<DataSnapshot>} data.request
|
|
40
|
+
* @property {function(string, Object, Function, Function=): Subscription} data.subscribe Legacy direct callbacks.
|
|
41
|
+
* @property {function(string, Object, Function, Function=): Watch} data.watch Await callbacks in the handler queue.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
// Transport and worker ownership belong to Hub. The same runtime supports memory-backed tests.
|
|
45
|
+
/**
|
|
46
|
+
* Create the API used by a Hub worker container or an isolated test harness.
|
|
47
|
+
* @param {Object} configuration
|
|
48
|
+
* @param {Snapshot} configuration.snapshot
|
|
49
|
+
* @param {Object} [configuration.context]
|
|
50
|
+
* @param {function(string, Object): Promise<*>} configuration.request Platform request transport.
|
|
51
|
+
* @param {function(string, *): void} configuration.emit Platform event transport.
|
|
52
|
+
*/
|
|
53
|
+
function createBackendRuntime({ snapshot: initial, context = {}, request, emit }) {
|
|
54
|
+
const methods = new Map();
|
|
55
|
+
const events = new EventEmitter();
|
|
56
|
+
const stateListeners = new Set();
|
|
57
|
+
let snapshot = structuredClone(initial);
|
|
58
|
+
let snapshotSequence = 0;
|
|
59
|
+
let subscriptionSequence = 0;
|
|
60
|
+
let tasks = Promise.resolve();
|
|
61
|
+
let writes = Promise.resolve();
|
|
62
|
+
|
|
63
|
+
function enqueue(operation) {
|
|
64
|
+
const run = tasks.then(operation);
|
|
65
|
+
tasks = run.catch(() => {});
|
|
66
|
+
return run;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function report(error) {
|
|
70
|
+
emit('backenderror', error.message || String(error));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function commit(makePatch) {
|
|
74
|
+
const run = writes.then(async () => {
|
|
75
|
+
const saved = await request('update', makePatch());
|
|
76
|
+
if (saved.sequence >= snapshotSequence) {
|
|
77
|
+
snapshot = saved.snapshot;
|
|
78
|
+
snapshotSequence = saved.sequence;
|
|
79
|
+
}
|
|
80
|
+
return structuredClone(snapshot);
|
|
81
|
+
});
|
|
82
|
+
writes = run.catch(() => {});
|
|
83
|
+
return run;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function subscribe(query, parameters, onData, onError = () => {}) {
|
|
87
|
+
const id = String(++subscriptionSequence);
|
|
88
|
+
const listener = ({ snapshot: data, error }) => {
|
|
89
|
+
if (error) onError(new Error(error));
|
|
90
|
+
else onData(data);
|
|
91
|
+
};
|
|
92
|
+
events.on(`data:${id}`, listener);
|
|
93
|
+
request('data.subscribe', { id, query, parameters }).catch((error) => {
|
|
94
|
+
if (events.listeners(`data:${id}`).includes(listener)) onError(error);
|
|
95
|
+
});
|
|
96
|
+
return {
|
|
97
|
+
stop: () => {
|
|
98
|
+
events.off(`data:${id}`, listener);
|
|
99
|
+
request('data.unsubscribe', { id }).catch(() => {});
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function watch(query, parameters, onData, onError = report) {
|
|
105
|
+
let subscription;
|
|
106
|
+
let generation = 0;
|
|
107
|
+
let stopped = false;
|
|
108
|
+
const deliver = (mine, handler, value) => {
|
|
109
|
+
enqueue(() => {
|
|
110
|
+
if (!stopped && generation === mine) return handler(value);
|
|
111
|
+
return undefined;
|
|
112
|
+
}).catch(report);
|
|
113
|
+
};
|
|
114
|
+
const setParameters = (next) => {
|
|
115
|
+
if (stopped) return;
|
|
116
|
+
const mine = ++generation;
|
|
117
|
+
subscription?.stop();
|
|
118
|
+
subscription = subscribe(
|
|
119
|
+
query,
|
|
120
|
+
next,
|
|
121
|
+
(data) => deliver(mine, onData, data),
|
|
122
|
+
(error) => deliver(mine, onError, error)
|
|
123
|
+
);
|
|
124
|
+
};
|
|
125
|
+
setParameters(parameters);
|
|
126
|
+
return {
|
|
127
|
+
setParameters,
|
|
128
|
+
stop: () => {
|
|
129
|
+
if (stopped) return;
|
|
130
|
+
stopped = true;
|
|
131
|
+
generation += 1;
|
|
132
|
+
subscription.stop();
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @type {BackendAPI} */
|
|
138
|
+
const api = {
|
|
139
|
+
apiVersion: 1,
|
|
140
|
+
context,
|
|
141
|
+
export: (name, handler) => {
|
|
142
|
+
if (typeof name !== 'string' || !name || typeof handler !== 'function' || name === 'getState') {
|
|
143
|
+
throw new Error('Invalid backend function.');
|
|
144
|
+
}
|
|
145
|
+
methods.set(name, handler);
|
|
146
|
+
},
|
|
147
|
+
emit: (name, payload = null) => emit(name, payload),
|
|
148
|
+
on: (name, handler) => {
|
|
149
|
+
events.on(name, handler);
|
|
150
|
+
return () => events.off(name, handler);
|
|
151
|
+
},
|
|
152
|
+
onStateChange: (handler) => {
|
|
153
|
+
stateListeners.add(handler);
|
|
154
|
+
return () => stateListeners.delete(handler);
|
|
155
|
+
},
|
|
156
|
+
getState: () => structuredClone(snapshot),
|
|
157
|
+
update: (patch) => {
|
|
158
|
+
const clean = structuredClone(patch);
|
|
159
|
+
return commit(() => clean);
|
|
160
|
+
},
|
|
161
|
+
patch: (patch) => {
|
|
162
|
+
const clean = structuredClone(patch);
|
|
163
|
+
if (Object.hasOwn(clean, 'state') && (!clean.state || Array.isArray(clean.state) || typeof clean.state !== 'object')) {
|
|
164
|
+
throw new Error('State patch must be an object. Use setState(null) to clear it.');
|
|
165
|
+
}
|
|
166
|
+
return commit(() => ({
|
|
167
|
+
...clean,
|
|
168
|
+
...(Object.hasOwn(clean, 'state') ? { state: { ...snapshot.state, ...clean.state } } : {}),
|
|
169
|
+
}));
|
|
170
|
+
},
|
|
171
|
+
setValue: (value) => api.update({ value }),
|
|
172
|
+
setState: (state) => api.update({ state }),
|
|
173
|
+
// Background tasks run after the current handler/initialization; failures are reported.
|
|
174
|
+
schedule: (operation) => {
|
|
175
|
+
enqueue(operation).catch(report);
|
|
176
|
+
},
|
|
177
|
+
data: {
|
|
178
|
+
enabled: context.dataSourceEnabled !== false,
|
|
179
|
+
request: (query, parameters = {}) => request('data.request', { query, parameters }),
|
|
180
|
+
subscribe,
|
|
181
|
+
watch,
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
api,
|
|
187
|
+
initialize: (start) => enqueue(() => start(api)),
|
|
188
|
+
call: (name, args = []) =>
|
|
189
|
+
enqueue(async () => {
|
|
190
|
+
if (name === 'getState') {
|
|
191
|
+
await writes;
|
|
192
|
+
return api.getState();
|
|
193
|
+
}
|
|
194
|
+
const handler = methods.get(name);
|
|
195
|
+
if (!handler) throw new Error(`Unknown backend function: ${name}`);
|
|
196
|
+
return handler(...args);
|
|
197
|
+
}),
|
|
198
|
+
sync: (next, sequence) =>
|
|
199
|
+
enqueue(async () => {
|
|
200
|
+
if (sequence <= snapshotSequence) return;
|
|
201
|
+
snapshot = structuredClone(next);
|
|
202
|
+
snapshotSequence = sequence;
|
|
203
|
+
const changed = api.getState();
|
|
204
|
+
events.emit('stateupdate', structuredClone(changed));
|
|
205
|
+
for (const handler of stateListeners) {
|
|
206
|
+
// eslint-disable-next-line no-await-in-loop -- State observers participate in the same serial queue.
|
|
207
|
+
await handler(structuredClone(changed));
|
|
208
|
+
}
|
|
209
|
+
}),
|
|
210
|
+
deliverData: (message) => events.emit(`data:${message.id}`, message),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
module.exports = { createBackendRuntime };
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// Copyright (c) 2026 Zero Density Inc.
|
|
2
|
+
// SPDX-License-Identifier: GPL-2.0-only
|
|
3
|
+
const clients = new WeakMap();
|
|
4
|
+
const copy = (value) => JSON.parse(JSON.stringify(value));
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {Object} ClientView
|
|
8
|
+
* @property {Object|null} state Latest authoritative field state.
|
|
9
|
+
* @property {*} value Latest controller/form output.
|
|
10
|
+
* @property {boolean} readOnly
|
|
11
|
+
* @property {Object} context
|
|
12
|
+
* @property {boolean} backend
|
|
13
|
+
* @property {boolean} paused
|
|
14
|
+
* @property {boolean} dataSourceEnabled
|
|
15
|
+
* @property {'connecting'|'connected'|'disconnected'|'closed'|'error'} connection
|
|
16
|
+
* @property {string|null} error
|
|
17
|
+
*
|
|
18
|
+
* @typedef {Object} Client
|
|
19
|
+
* @property {number} apiVersion
|
|
20
|
+
* @property {function(function(ClientView): void): Function} subscribe Replay the current view and observe changes.
|
|
21
|
+
* @property {function(): Promise<ClientView>} ready Wait for host initialization and backend readiness.
|
|
22
|
+
* @property {function(): Promise<{state: Object|null, value: *}>} getState Read on demand without replacing newer observed state.
|
|
23
|
+
* @property {function(string, ...*): Promise<*>} call Invoke a named backend function.
|
|
24
|
+
* @property {function(string, Function): Function} on Observe a custom backend event.
|
|
25
|
+
* @property {function(*): Promise<boolean>} setValue Update frontend-only output.
|
|
26
|
+
* @property {function(Object|null): Promise<Object|null>} setState Update frontend-only state.
|
|
27
|
+
* @property {Object} data Frontend query request/subscribe operations through the host.
|
|
28
|
+
* @property {function(string, Object=): Promise<import('./backend').DataSnapshot>} data.request
|
|
29
|
+
* @property {function(string, Object, Function, Function=): import('./backend').Subscription} data.subscribe
|
|
30
|
+
* @property {function(): void} destroy Release this client's resources; Hub retains worker ownership.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Join the iframe's existing Hub connection. Requests default to a 15-second deadline.
|
|
35
|
+
* @param {Object} [options]
|
|
36
|
+
* @param {Window} [options.window] The iframe window; injectable for tests.
|
|
37
|
+
* @param {number} [options.timeoutMs=15000]
|
|
38
|
+
* @returns {Client}
|
|
39
|
+
*/
|
|
40
|
+
function createClient({ window: target = window, timeoutMs = 15000 } = {}) {
|
|
41
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('Request timeout must be positive.');
|
|
42
|
+
if (clients.has(target)) return clients.get(target);
|
|
43
|
+
const backend = target.hubBackend;
|
|
44
|
+
const observers = new Set();
|
|
45
|
+
const subscriptions = new Map();
|
|
46
|
+
const operations = new Set();
|
|
47
|
+
const pending = new Map();
|
|
48
|
+
const cleanup = new Set();
|
|
49
|
+
let port;
|
|
50
|
+
let initialized = false;
|
|
51
|
+
let destroyed = false;
|
|
52
|
+
let fatalError;
|
|
53
|
+
let sequence = 0;
|
|
54
|
+
let backendConnection = 'connecting';
|
|
55
|
+
let view = {
|
|
56
|
+
state: null,
|
|
57
|
+
value: null,
|
|
58
|
+
readOnly: true,
|
|
59
|
+
context: {},
|
|
60
|
+
backend: Boolean(backend),
|
|
61
|
+
paused: false,
|
|
62
|
+
dataSourceEnabled: true,
|
|
63
|
+
connection: 'connecting',
|
|
64
|
+
error: null,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
function update(changes) {
|
|
68
|
+
view = { ...view, ...changes };
|
|
69
|
+
for (const observer of observers) {
|
|
70
|
+
try {
|
|
71
|
+
observer(copy(view));
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error(error);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const operation of [...operations]) operation.begin();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function perform(start, requireConnected = false, trackCancellation = null) {
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
let started = false;
|
|
82
|
+
let finished = false;
|
|
83
|
+
let cancel = () => {};
|
|
84
|
+
let requestId;
|
|
85
|
+
let timer;
|
|
86
|
+
let operation;
|
|
87
|
+
const deadlineAt = Date.now() + timeoutMs;
|
|
88
|
+
const finish = (error, result) => {
|
|
89
|
+
if (finished) return;
|
|
90
|
+
finished = true;
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
operations.delete(operation);
|
|
93
|
+
if (trackCancellation) trackCancellation(null);
|
|
94
|
+
if (requestId) pending.delete(requestId);
|
|
95
|
+
if (error) {
|
|
96
|
+
cancel();
|
|
97
|
+
if (!destroyed) update({ error: error.message });
|
|
98
|
+
reject(error);
|
|
99
|
+
} else resolve(result);
|
|
100
|
+
};
|
|
101
|
+
operation = {
|
|
102
|
+
finish,
|
|
103
|
+
begin: () => {
|
|
104
|
+
if (finished || started) return;
|
|
105
|
+
if (destroyed || fatalError) {
|
|
106
|
+
finish(fatalError || new Error('Custom UI client closed.'));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (view.connection === 'closed') {
|
|
110
|
+
finish(new Error('Backend closed.'));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (!initialized || (requireConnected && view.connection !== 'connected')) return;
|
|
114
|
+
started = true;
|
|
115
|
+
try {
|
|
116
|
+
start({
|
|
117
|
+
finish,
|
|
118
|
+
remaining: Math.max(1, deadlineAt - Date.now()),
|
|
119
|
+
setCancel: (handler) => {
|
|
120
|
+
cancel = handler;
|
|
121
|
+
},
|
|
122
|
+
hostRequest: (type, payload = {}) => {
|
|
123
|
+
requestId = String(++sequence);
|
|
124
|
+
pending.set(requestId, finish);
|
|
125
|
+
port.postMessage({ protocol: 1, id: requestId, type, ...payload });
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
finish(error);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
timer = setTimeout(() => finish(new Error('Custom UI request timed out.')), timeoutMs);
|
|
134
|
+
if (trackCancellation) trackCancellation(() => finish(null, true));
|
|
135
|
+
operations.add(operation);
|
|
136
|
+
operation.begin();
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function hostRequest(type, payload) {
|
|
141
|
+
return perform((operation) => operation.hostRequest(type, payload));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function backendRequest(name, args) {
|
|
145
|
+
return perform((operation) => {
|
|
146
|
+
if (!backend) throw new Error('This custom UI has no backend.');
|
|
147
|
+
if (view.readOnly && name !== 'getState') throw new Error('This field is read-only.');
|
|
148
|
+
const request = backend.request(name, args, operation.remaining);
|
|
149
|
+
operation.setCancel(request.cancel);
|
|
150
|
+
request.promise.then(
|
|
151
|
+
(result) => operation.finish(null, result),
|
|
152
|
+
(error) => operation.finish(error)
|
|
153
|
+
);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function unsubscribe(id) {
|
|
158
|
+
const subscription = subscriptions.get(id);
|
|
159
|
+
if (!subscription) return;
|
|
160
|
+
subscriptions.delete(id);
|
|
161
|
+
if (subscription.cancelRequest) subscription.cancelRequest();
|
|
162
|
+
if (port) port.postMessage({ protocol: 1, id: String(++sequence), type: 'unsubscribe', subscription: id });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function receive({ data: message }) {
|
|
166
|
+
if (destroyed || message.protocol !== 1) return;
|
|
167
|
+
if (message.type === 'result') {
|
|
168
|
+
const finish = pending.get(message.id);
|
|
169
|
+
if (finish) finish(message.error ? new Error(message.error) : null, message.result);
|
|
170
|
+
} else if (message.type === 'init') {
|
|
171
|
+
if (message.apiVersion !== 1 || (message.backend && !backend)) {
|
|
172
|
+
fatalError = new Error('This SDK requires Reality Hub custom UI API version 1.');
|
|
173
|
+
update({ connection: 'error', error: fatalError.message });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
initialized = true;
|
|
177
|
+
update({
|
|
178
|
+
readOnly: Boolean(message.readOnly),
|
|
179
|
+
context: message.context || {},
|
|
180
|
+
paused: Boolean(message.paused),
|
|
181
|
+
dataSourceEnabled: message.dataSourceEnabled !== false,
|
|
182
|
+
connection: backend ? backendConnection : 'connected',
|
|
183
|
+
...(!backend ? { state: message.state || null, value: message.value === undefined ? null : message.value } : {}),
|
|
184
|
+
});
|
|
185
|
+
} else if (message.type === 'value') {
|
|
186
|
+
update({ readOnly: Boolean(message.readOnly), ...(!backend ? { value: message.value } : {}) });
|
|
187
|
+
} else if (message.type === 'paused') {
|
|
188
|
+
update({ paused: Boolean(message.paused) });
|
|
189
|
+
} else if (message.type === 'data' || message.type === 'queryError') {
|
|
190
|
+
const handle = subscriptions.get(message.subscription);
|
|
191
|
+
if (handle) {
|
|
192
|
+
try {
|
|
193
|
+
if (message.type === 'data') handle.onData(message.snapshot);
|
|
194
|
+
else handle.onError(new Error(message.error));
|
|
195
|
+
} catch (error) {
|
|
196
|
+
update({ error: error.message });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function connect(event) {
|
|
203
|
+
if (event.source !== target.parent || !event.data || event.data.type !== 'hub.xui.connect') return;
|
|
204
|
+
if (event.data.protocol !== 1 || !event.ports[0] || port || destroyed) return;
|
|
205
|
+
[port] = event.ports;
|
|
206
|
+
target.removeEventListener('message', connect);
|
|
207
|
+
port.onmessage = receive;
|
|
208
|
+
port.start();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function destroy() {
|
|
212
|
+
if (destroyed) return;
|
|
213
|
+
destroyed = true;
|
|
214
|
+
target.removeEventListener('message', connect);
|
|
215
|
+
target.removeEventListener('pagehide', destroy);
|
|
216
|
+
for (const id of [...subscriptions.keys()]) unsubscribe(id);
|
|
217
|
+
for (const operation of [...operations]) operation.finish(new Error('Custom UI client closed.'));
|
|
218
|
+
for (const off of cleanup) off();
|
|
219
|
+
cleanup.clear();
|
|
220
|
+
if (port) port.close();
|
|
221
|
+
update({ connection: 'closed' });
|
|
222
|
+
observers.clear();
|
|
223
|
+
clients.delete(target);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const client = {
|
|
227
|
+
apiVersion: 1,
|
|
228
|
+
subscribe: (observer) => {
|
|
229
|
+
if (destroyed) throw new Error('Custom UI client closed.');
|
|
230
|
+
observers.add(observer);
|
|
231
|
+
observer(copy(view));
|
|
232
|
+
return () => observers.delete(observer);
|
|
233
|
+
},
|
|
234
|
+
ready: () => perform((operation) => operation.finish(null, copy(view)), true),
|
|
235
|
+
getState: () =>
|
|
236
|
+
backend ? backendRequest('getState', []) : hostRequest('loadState').then((state) => ({ state, value: view.value })),
|
|
237
|
+
call: (name, ...args) => backendRequest(name, args),
|
|
238
|
+
on: (name, handler) => {
|
|
239
|
+
if (destroyed) throw new Error('Custom UI client closed.');
|
|
240
|
+
if (!backend) throw new Error('This custom UI has no backend.');
|
|
241
|
+
const off = backend.on(name, handler);
|
|
242
|
+
const stop = () => {
|
|
243
|
+
off();
|
|
244
|
+
cleanup.delete(stop);
|
|
245
|
+
};
|
|
246
|
+
cleanup.add(stop);
|
|
247
|
+
return stop;
|
|
248
|
+
},
|
|
249
|
+
setValue: (value) =>
|
|
250
|
+
hostRequest('setValue', { value }).then((result) => {
|
|
251
|
+
if (!destroyed) update({ value });
|
|
252
|
+
return result;
|
|
253
|
+
}),
|
|
254
|
+
setState: (state) =>
|
|
255
|
+
hostRequest('saveState', { state }).then((saved) => {
|
|
256
|
+
if (!destroyed) update({ state: saved });
|
|
257
|
+
return saved;
|
|
258
|
+
}),
|
|
259
|
+
data: {
|
|
260
|
+
request: (query, parameters = {}) => hostRequest('request', { query, parameters }),
|
|
261
|
+
subscribe: (query, parameters, onData, onError = (error) => update({ error: error.message })) => {
|
|
262
|
+
if (destroyed) throw new Error('Custom UI client closed.');
|
|
263
|
+
const id = `query_${++sequence}`;
|
|
264
|
+
const handle = { onData, onError };
|
|
265
|
+
subscriptions.set(id, handle);
|
|
266
|
+
perform(
|
|
267
|
+
(operation) => operation.hostRequest('subscribe', { query, parameters, subscription: id }),
|
|
268
|
+
false,
|
|
269
|
+
(cancel) => {
|
|
270
|
+
handle.cancelRequest = cancel;
|
|
271
|
+
}
|
|
272
|
+
).catch((error) => {
|
|
273
|
+
if (subscriptions.has(id)) {
|
|
274
|
+
unsubscribe(id);
|
|
275
|
+
onError(error);
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
return { stop: () => unsubscribe(id) };
|
|
279
|
+
},
|
|
280
|
+
},
|
|
281
|
+
destroy,
|
|
282
|
+
};
|
|
283
|
+
clients.set(target, client);
|
|
284
|
+
if (backend) {
|
|
285
|
+
if (backend.apiVersion !== 1 || typeof backend.subscribe !== 'function' || typeof backend.request !== 'function') {
|
|
286
|
+
fatalError = new Error('This SDK requires Reality Hub custom UI API version 1.');
|
|
287
|
+
update({ connection: 'error', error: fatalError.message });
|
|
288
|
+
} else {
|
|
289
|
+
cleanup.add(
|
|
290
|
+
backend.subscribe(({ snapshot, connection, error }) => {
|
|
291
|
+
backendConnection = connection;
|
|
292
|
+
update({
|
|
293
|
+
connection: initialized ? connection : 'connecting',
|
|
294
|
+
error,
|
|
295
|
+
...(snapshot ? { state: snapshot.state, value: snapshot.value } : {}),
|
|
296
|
+
});
|
|
297
|
+
})
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
target.addEventListener('message', connect);
|
|
302
|
+
target.addEventListener('pagehide', destroy);
|
|
303
|
+
return client;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
exports.createClient = createClient;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zerodensity/realityhub-api",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.22.0",
|
|
4
4
|
"description": "RealityHub API Javascript Implementation",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"repository": {
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
"url": "git+ssh://git@github.com/zerodensity/realityhub-api.git"
|
|
9
9
|
},
|
|
10
10
|
"publishConfig": {
|
|
11
|
-
"access": "public"
|
|
11
|
+
"access": "public",
|
|
12
|
+
"tag": "stable"
|
|
12
13
|
},
|
|
13
14
|
"keywords": [
|
|
14
15
|
"realityhub",
|