@hcikn/colibri 1.3.2 → 2.0.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.
- package/LICENSE +21 -0
- package/README.md +226 -88
- package/dist/index.cjs +1514 -972
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +235 -22
- package/dist/index.d.ts +235 -22
- package/dist/index.js +1480 -884
- package/dist/index.js.map +1 -1
- package/package.json +98 -41
package/dist/index.js
CHANGED
|
@@ -1,966 +1,1562 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
|
|
5
|
+
var __typeError = (msg) => {
|
|
6
|
+
throw TypeError(msg);
|
|
7
|
+
};
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
|
+
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
|
|
11
|
+
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
|
|
12
|
+
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
|
|
13
|
+
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
|
|
14
|
+
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
|
|
15
|
+
var __runInitializers = (array, flags, self, value) => {
|
|
16
|
+
for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
var __decorateElement = (array, flags, name, decorators, target, extra) => {
|
|
20
|
+
var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
|
|
21
|
+
var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
|
|
22
|
+
var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
|
|
23
|
+
var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
|
|
24
|
+
return __privateGet(this, extra);
|
|
25
|
+
}, set [name](x) {
|
|
26
|
+
return __privateSet(this, extra, x);
|
|
27
|
+
} }, name));
|
|
28
|
+
k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
|
|
29
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
30
|
+
ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
|
|
31
|
+
if (k) {
|
|
32
|
+
ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
|
|
33
|
+
if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
|
|
34
|
+
if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
|
|
12
35
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
36
|
+
it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
|
|
37
|
+
if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
|
|
38
|
+
else if (typeof it !== "object" || it === null) __typeError("Object expected");
|
|
39
|
+
else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
|
|
40
|
+
}
|
|
41
|
+
return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
|
|
42
|
+
};
|
|
43
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
44
|
+
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
|
|
45
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
46
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
47
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
48
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
49
|
+
|
|
50
|
+
// src/Colibri.ts
|
|
51
|
+
import { Subject } from "rxjs";
|
|
52
|
+
import { connect } from "socket.io-client";
|
|
53
|
+
|
|
54
|
+
// src/ColibriError.ts
|
|
55
|
+
import { CustomError } from "ts-custom-error";
|
|
56
|
+
var ColibriError = class extends CustomError {
|
|
57
|
+
};
|
|
58
|
+
var ProtocolMismatchError = class extends ColibriError {
|
|
59
|
+
constructor(message, serverVersion, clientVersion, fatal = true) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.serverVersion = serverVersion;
|
|
62
|
+
this.clientVersion = clientVersion;
|
|
63
|
+
this.fatal = fatal;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// src/lifecycle.ts
|
|
68
|
+
var awaitingInstance = [];
|
|
69
|
+
var whenColibriCreated = (action) => {
|
|
70
|
+
awaitingInstance.push(action);
|
|
71
|
+
return () => {
|
|
72
|
+
const index = awaitingInstance.indexOf(action);
|
|
73
|
+
if (index >= 0) awaitingInstance.splice(index, 1);
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
var colibriCreated = (colibri) => {
|
|
77
|
+
for (const action of awaitingInstance.splice(0)) {
|
|
16
78
|
try {
|
|
17
|
-
|
|
18
|
-
var value = info.value;
|
|
79
|
+
action(colibri);
|
|
19
80
|
} catch (error) {
|
|
20
|
-
|
|
21
|
-
return;
|
|
81
|
+
console.error("Colibri: a registration made before new Colibri() failed to attach.", error);
|
|
22
82
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var reconnectActions = /* @__PURE__ */ new WeakMap();
|
|
86
|
+
var disconnectActions = /* @__PURE__ */ new WeakMap();
|
|
87
|
+
var addAction = (actions, colibri, action) => {
|
|
88
|
+
const forInstance = actions.get(colibri);
|
|
89
|
+
if (forInstance) forInstance.push(action);
|
|
90
|
+
else actions.set(colibri, [action]);
|
|
91
|
+
};
|
|
92
|
+
var runActions = (actions, colibri, failure) => {
|
|
93
|
+
for (const action of actions.get(colibri) ?? []) {
|
|
94
|
+
try {
|
|
95
|
+
action(colibri);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
console.error(failure, error);
|
|
27
98
|
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
var onColibriReconnected = (colibri, action) => {
|
|
102
|
+
addAction(reconnectActions, colibri, action);
|
|
103
|
+
};
|
|
104
|
+
var colibriReconnected = (colibri) => {
|
|
105
|
+
runActions(reconnectActions, colibri, "Colibri: catching up after a reconnect failed.");
|
|
106
|
+
};
|
|
107
|
+
var onColibriDisconnected = (colibri, action) => {
|
|
108
|
+
addAction(disconnectActions, colibri, action);
|
|
109
|
+
};
|
|
110
|
+
var colibriDisconnected = (colibri) => {
|
|
111
|
+
runActions(disconnectActions, colibri, "Colibri: handling a disconnect failed.");
|
|
112
|
+
};
|
|
113
|
+
var lastHeard = /* @__PURE__ */ new WeakMap();
|
|
114
|
+
var colibriHeardFrom = (colibri) => {
|
|
115
|
+
lastHeard.set(colibri, Date.now());
|
|
116
|
+
};
|
|
117
|
+
var lastHeardFrom = (colibri) => lastHeard.get(colibri);
|
|
118
|
+
|
|
119
|
+
// src/Colibri.ts
|
|
120
|
+
var PROTOCOL_VERSION = "2";
|
|
121
|
+
var REST_MEDIA_TYPE = `application/vnd.colibri.v${PROTOCOL_VERSION}+json`;
|
|
122
|
+
var COLIBRI_CHANNEL = "colibri";
|
|
123
|
+
var ADMIN_APP = "colibri";
|
|
124
|
+
var PROTOCOL_REJECTED_COMMAND = "protocol::rejected";
|
|
125
|
+
var PROTOCOL_ACCEPTED_COMMAND = "protocol::accepted";
|
|
126
|
+
var LATENCY_COMMAND = "latency";
|
|
127
|
+
var OLD_SERVER_TIMEOUT_MS = 5e3;
|
|
128
|
+
var OLD_SERVER_PROTOCOL_VERSION = "1";
|
|
129
|
+
var pageHostname = () => typeof window !== "undefined" ? window.location?.hostname ?? "" : "";
|
|
130
|
+
var SCHEMES = {
|
|
131
|
+
ws: { socket: "ws", rest: "http" },
|
|
132
|
+
http: { socket: "ws", rest: "http" },
|
|
133
|
+
wss: { socket: "wss", rest: "https" },
|
|
134
|
+
https: { socket: "wss", rest: "https" }
|
|
135
|
+
};
|
|
136
|
+
var parseServerAddress = (server) => {
|
|
137
|
+
const address = server.trim();
|
|
138
|
+
const match = /^([a-z][a-z0-9+.-]*):\/\/(.*)$/i.exec(address);
|
|
139
|
+
const schemes = match ? SCHEMES[match[1].toLowerCase()] : SCHEMES.ws;
|
|
140
|
+
if (!schemes) {
|
|
141
|
+
throw new ColibriError(
|
|
142
|
+
`Unsupported scheme in server address '${server}' - use ws://, wss://, http://, https:// or none.`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
const authority = (match ? match[2] : address).replace(/\/+$/, "");
|
|
146
|
+
if (authority.length === 0) {
|
|
147
|
+
throw new ColibriError("Server Address missing or empty!");
|
|
148
|
+
}
|
|
149
|
+
if (/[/?#]/.test(authority)) {
|
|
150
|
+
throw new ColibriError(
|
|
151
|
+
`Server address '${server}' has a path or query after the host - pass only the host and, optionally, the port, e.g. 'http://example.com:9211'.`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
const hostAndPort = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(authority);
|
|
155
|
+
if (!hostAndPort) {
|
|
156
|
+
throw new ColibriError(
|
|
157
|
+
`Server address '${server}' is not a host, or a host and a numeric port - an IPv6 address goes in brackets.`
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
const portText = hostAndPort.at(2);
|
|
161
|
+
return { ...schemes, host: hostAndPort[1], port: portText === void 0 ? void 0 : Number(portText) };
|
|
162
|
+
};
|
|
163
|
+
var DEFAULT_PORT = 9211;
|
|
164
|
+
var checkPort = (port) => {
|
|
165
|
+
if (!Number.isInteger(port)) {
|
|
166
|
+
throw new ColibriError(`Port must be a whole number (1 - 65535): ${port}`);
|
|
167
|
+
}
|
|
168
|
+
if (port < 1 || port > 65535) {
|
|
169
|
+
throw new ColibriError(`Port out of allowed range (1 - 65535): ${port}`);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
var coercePort = (port) => typeof port === "string" && /^\s*\d+\s*$/.test(port) ? Number(port) : port;
|
|
173
|
+
var resolvePort = (server, fromAddress, given) => {
|
|
174
|
+
if (given !== void 0) checkPort(given);
|
|
175
|
+
if (fromAddress === void 0) return given ?? DEFAULT_PORT;
|
|
176
|
+
checkPort(fromAddress);
|
|
177
|
+
if (given !== void 0 && given !== fromAddress) {
|
|
178
|
+
throw new ColibriError(
|
|
179
|
+
`Server address '${server}' has port ${fromAddress}, but port ${given} was passed as well - give the port once.`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
return fromAddress;
|
|
183
|
+
};
|
|
184
|
+
var pendingRegistrations = [];
|
|
185
|
+
var Colibri = class _Colibri {
|
|
186
|
+
/**
|
|
187
|
+
* Connects to a Colibri server. Only one instance may exist.
|
|
188
|
+
* @param app the application name; clients only see each other's messages within one app
|
|
189
|
+
* @param server the host, optionally after `ws://`, `wss://`, `http://` or `https://` (the
|
|
190
|
+
* secure ones mean `wss` for the socket and `https` for REST) and optionally with a port,
|
|
191
|
+
* as in `'http://example.com:9211'`; no path. Defaults to the host that served the page,
|
|
192
|
+
* and is required outside a browser.
|
|
193
|
+
* @param port the server port, if the address has none; 9211 if neither does. When both have
|
|
194
|
+
* one, they must agree.
|
|
195
|
+
* @throws ColibriError for an address or port this client cannot connect to, or when an
|
|
196
|
+
* instance already exists
|
|
197
|
+
*/
|
|
198
|
+
constructor(app, server = pageHostname(), port) {
|
|
199
|
+
this.app = app;
|
|
200
|
+
this.server = server;
|
|
201
|
+
if (server.trim().length <= 0) {
|
|
202
|
+
throw new ColibriError(
|
|
203
|
+
typeof window === "undefined" ? "Server Address missing or empty! Outside a browser there is no page to take it from, so pass it as the second argument." : "Server Address missing or empty!"
|
|
204
|
+
);
|
|
51
205
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
206
|
+
const address = parseServerAddress(server);
|
|
207
|
+
this.port = resolvePort(server, address.port, coercePort(port));
|
|
208
|
+
this.uri = `${address.socket}://${address.host}:${this.port}`;
|
|
209
|
+
this.uriRestApi = `${address.rest}://${address.host}:${this.port}/api/store/${encodeURIComponent(app)}/`;
|
|
210
|
+
if (_Colibri.instance) throw new ColibriError("A Colibri instance already exists!");
|
|
211
|
+
else _Colibri.instance = this;
|
|
212
|
+
if (app === ADMIN_APP) {
|
|
213
|
+
console.warn(
|
|
214
|
+
`Colibri: the app name '${ADMIN_APP}' is reserved for the server's admin UI, and the server treats this client as one: it sends it the server's log as it is written and every client's connects and disconnects, shares its messages with every open admin UI, and skips the protocol version check. Give your app a name of its own.`
|
|
215
|
+
);
|
|
60
216
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (staticProps) _defineProperties(Constructor, staticProps);
|
|
65
|
-
return Constructor;
|
|
66
|
-
}
|
|
67
|
-
function _get_prototype_of(o) {
|
|
68
|
-
_get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
|
|
69
|
-
return o.__proto__ || Object.getPrototypeOf(o);
|
|
70
|
-
};
|
|
71
|
-
return _get_prototype_of(o);
|
|
72
|
-
}
|
|
73
|
-
function _inherits(subClass, superClass) {
|
|
74
|
-
if (typeof superClass !== "function" && superClass !== null) {
|
|
75
|
-
throw new TypeError("Super expression must either be null or a function");
|
|
76
|
-
}
|
|
77
|
-
subClass.prototype = Object.create(superClass && superClass.prototype, {
|
|
78
|
-
constructor: {
|
|
79
|
-
value: subClass,
|
|
80
|
-
writable: true,
|
|
81
|
-
configurable: true
|
|
82
|
-
}
|
|
217
|
+
this.socket = connect(this.uri, {
|
|
218
|
+
query: { app, version: PROTOCOL_VERSION },
|
|
219
|
+
transports: ["websocket"]
|
|
83
220
|
});
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
221
|
+
this.socket.on("connect", this.onSocketConnect.bind(this));
|
|
222
|
+
this.socket.on("disconnect", this.onSocketDisconnect.bind(this));
|
|
223
|
+
this.socket.on("connect_error", this.onSocketConnectError.bind(this));
|
|
224
|
+
this.socket.onAny(this.onSocketAny.bind(this));
|
|
225
|
+
this.registerChannel(COLIBRI_CHANNEL, (msg) => {
|
|
226
|
+
if (msg.command === LATENCY_COMMAND) {
|
|
227
|
+
SendMessage(COLIBRI_CHANNEL, LATENCY_COMMAND, msg.payload);
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
for (const { channel, handler, once } of pendingRegistrations.splice(0)) {
|
|
231
|
+
if (once) this.registerOnce(channel, handler);
|
|
232
|
+
else this.registerChannel(channel, handler);
|
|
92
233
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
234
|
+
colibriCreated(this);
|
|
235
|
+
}
|
|
236
|
+
static instance = null;
|
|
237
|
+
socket;
|
|
238
|
+
messageSubject = new Subject();
|
|
239
|
+
messages = this.messageSubject.asObservable();
|
|
240
|
+
protocolMismatchSubject = new Subject();
|
|
241
|
+
/**
|
|
242
|
+
* Reports that this client and the server do not speak the same wire protocol. Two kinds,
|
|
243
|
+
* told apart by {@link ProtocolMismatchError.fatal `fatal`}, each emitted at most once per
|
|
244
|
+
* instance:
|
|
245
|
+
*
|
|
246
|
+
* - `fatal: true`: the server refused this client. The connection is closed and not retried.
|
|
247
|
+
* - `fatal: false`: the server did not announce itself within 5s of connecting, so it is
|
|
248
|
+
* suspected to predate colibri-server 2.0.0. The connection stays up.
|
|
249
|
+
*
|
|
250
|
+
* A suspicion can be followed by a refusal, never the other way round. Nothing is replayed to
|
|
251
|
+
* a late subscriber, so subscribe right after construction. Both kinds are also logged.
|
|
252
|
+
*/
|
|
253
|
+
protocolMismatch = this.protocolMismatchSubject.asObservable();
|
|
254
|
+
uri;
|
|
255
|
+
uriRestApi;
|
|
256
|
+
/** The port connected to: the one in the server address, else the one passed, else 9211. */
|
|
257
|
+
port;
|
|
258
|
+
oldServerTimer;
|
|
259
|
+
// Once per instance, not per connection, so a reconnect does not repeat the warning.
|
|
260
|
+
hasReportedOldServer = false;
|
|
261
|
+
// Once per instance, not once per `protocol::rejected` received.
|
|
262
|
+
hasReportedRefusal = false;
|
|
263
|
+
hasConnected = false;
|
|
264
|
+
// An outage runs from a failed connection attempt to the next connect.
|
|
265
|
+
hasReportedOutage = false;
|
|
266
|
+
onSocketConnect() {
|
|
267
|
+
console.debug(`Connected to colibri server on ${this.server}`);
|
|
268
|
+
this.hasReportedOutage = false;
|
|
269
|
+
this.waitForServerHello();
|
|
270
|
+
if (this.hasConnected) colibriReconnected(this);
|
|
271
|
+
this.hasConnected = true;
|
|
272
|
+
}
|
|
273
|
+
// Until the next connect, sends wait in Socket.IO's buffer and go out ahead of anything a
|
|
274
|
+
// catch-up sends, which is the wrong order for some of them.
|
|
275
|
+
onSocketDisconnect() {
|
|
276
|
+
colibriDisconnected(this);
|
|
277
|
+
}
|
|
278
|
+
// Socket.IO retries silently, so a mistyped address, a server that is down and a firewall all
|
|
279
|
+
// look like a slow connection. Reported once per outage, on its first failed attempt, not on
|
|
280
|
+
// every retry.
|
|
281
|
+
onSocketConnectError(error) {
|
|
282
|
+
if (this.hasReportedOutage) return;
|
|
283
|
+
this.hasReportedOutage = true;
|
|
284
|
+
const cause = error.description?.message;
|
|
285
|
+
const reason = typeof cause === "string" && cause.length > 0 ? `${error.message}: ${cause}` : error.message;
|
|
286
|
+
console.warn(
|
|
287
|
+
`Colibri: could not connect to ${this.uri} (${reason}). ` + (this.socket.active ? "Retrying until it answers - check the server address and that the server is running." : "Not retrying.")
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
/*
|
|
291
|
+
* Detecting a server that predates the protocol version check.
|
|
292
|
+
*
|
|
293
|
+
* Such a server neither refuses this client nor says what it speaks, so a current one
|
|
294
|
+
* announces itself unprompted and the missing announcement is the signal. The timer only
|
|
295
|
+
* observes; it does not gate message delivery.
|
|
296
|
+
*/
|
|
297
|
+
waitForServerHello() {
|
|
298
|
+
if (this.hasReportedOldServer) return;
|
|
299
|
+
clearTimeout(this.oldServerTimer);
|
|
300
|
+
this.oldServerTimer = setTimeout(() => {
|
|
301
|
+
this.onServerHelloMissing();
|
|
302
|
+
}, OLD_SERVER_TIMEOUT_MS);
|
|
303
|
+
}
|
|
304
|
+
stopWaitingForServerHello() {
|
|
305
|
+
clearTimeout(this.oldServerTimer);
|
|
306
|
+
this.oldServerTimer = void 0;
|
|
307
|
+
}
|
|
308
|
+
onServerHelloMissing() {
|
|
309
|
+
if (!this.socket.connected) return;
|
|
310
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
|
311
|
+
this.waitForServerHello();
|
|
312
|
+
return;
|
|
103
313
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
124
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
125
|
-
if (n === "Map" || n === "Set") return Array.from(n);
|
|
126
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
127
|
-
}
|
|
128
|
-
function _is_native_reflect_construct() {
|
|
129
|
-
try {
|
|
130
|
-
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
|
|
131
|
-
} catch (_) {}
|
|
132
|
-
return (_is_native_reflect_construct = function() {
|
|
133
|
-
return !!result;
|
|
134
|
-
})();
|
|
135
|
-
}
|
|
136
|
-
function _ts_generator(thisArg, body) {
|
|
137
|
-
var f, y, t, _ = {
|
|
138
|
-
label: 0,
|
|
139
|
-
sent: function() {
|
|
140
|
-
if (t[0] & 1) throw t[1];
|
|
141
|
-
return t[1];
|
|
142
|
-
},
|
|
143
|
-
trys: [],
|
|
144
|
-
ops: []
|
|
145
|
-
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
|
|
146
|
-
return d(g, "next", {
|
|
147
|
-
value: verb(0)
|
|
148
|
-
}), d(g, "throw", {
|
|
149
|
-
value: verb(1)
|
|
150
|
-
}), d(g, "return", {
|
|
151
|
-
value: verb(2)
|
|
152
|
-
}), typeof Symbol === "function" && d(g, Symbol.iterator, {
|
|
153
|
-
value: function() {
|
|
154
|
-
return this;
|
|
155
|
-
}
|
|
156
|
-
}), g;
|
|
157
|
-
function verb(n) {
|
|
158
|
-
return function(v) {
|
|
159
|
-
return step([
|
|
160
|
-
n,
|
|
161
|
-
v
|
|
162
|
-
]);
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
function step(op) {
|
|
166
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
167
|
-
while(g && (g = 0, op[0] && (_ = 0)), _)try {
|
|
168
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
169
|
-
if (y = 0, t) op = [
|
|
170
|
-
op[0] & 2,
|
|
171
|
-
t.value
|
|
172
|
-
];
|
|
173
|
-
switch(op[0]){
|
|
174
|
-
case 0:
|
|
175
|
-
case 1:
|
|
176
|
-
t = op;
|
|
177
|
-
break;
|
|
178
|
-
case 4:
|
|
179
|
-
_.label++;
|
|
180
|
-
return {
|
|
181
|
-
value: op[1],
|
|
182
|
-
done: false
|
|
183
|
-
};
|
|
184
|
-
case 5:
|
|
185
|
-
_.label++;
|
|
186
|
-
y = op[1];
|
|
187
|
-
op = [
|
|
188
|
-
0
|
|
189
|
-
];
|
|
190
|
-
continue;
|
|
191
|
-
case 7:
|
|
192
|
-
op = _.ops.pop();
|
|
193
|
-
_.trys.pop();
|
|
194
|
-
continue;
|
|
195
|
-
default:
|
|
196
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
197
|
-
_ = 0;
|
|
198
|
-
continue;
|
|
199
|
-
}
|
|
200
|
-
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
201
|
-
_.label = op[1];
|
|
202
|
-
break;
|
|
203
|
-
}
|
|
204
|
-
if (op[0] === 6 && _.label < t[1]) {
|
|
205
|
-
_.label = t[1];
|
|
206
|
-
t = op;
|
|
207
|
-
break;
|
|
208
|
-
}
|
|
209
|
-
if (t && _.label < t[2]) {
|
|
210
|
-
_.label = t[2];
|
|
211
|
-
_.ops.push(op);
|
|
212
|
-
break;
|
|
213
|
-
}
|
|
214
|
-
if (t[2]) _.ops.pop();
|
|
215
|
-
_.trys.pop();
|
|
216
|
-
continue;
|
|
217
|
-
}
|
|
218
|
-
op = body.call(thisArg, _);
|
|
219
|
-
} catch (e) {
|
|
220
|
-
op = [
|
|
221
|
-
6,
|
|
222
|
-
e
|
|
223
|
-
];
|
|
224
|
-
y = 0;
|
|
225
|
-
} finally{
|
|
226
|
-
f = t = 0;
|
|
227
|
-
}
|
|
228
|
-
if (op[0] & 5) throw op[1];
|
|
229
|
-
return {
|
|
230
|
-
value: op[0] ? op[1] : void 0,
|
|
231
|
-
done: true
|
|
232
|
-
};
|
|
314
|
+
this.hasReportedOldServer = true;
|
|
315
|
+
this.stopWaitingForServerHello();
|
|
316
|
+
const error = new ProtocolMismatchError(
|
|
317
|
+
`The server did not identify itself within ${OLD_SERVER_TIMEOUT_MS / 1e3}s, so it predates colibri-server 2.0.0 and speaks protocol v1; this client speaks v${PROTOCOL_VERSION}.`,
|
|
318
|
+
// A protocol version, as in the refusal. Inferred, not received: every 2.0.0+ server
|
|
319
|
+
// announces itself, and everything older speaks v1.
|
|
320
|
+
OLD_SERVER_PROTOCOL_VERSION,
|
|
321
|
+
PROTOCOL_VERSION,
|
|
322
|
+
false
|
|
323
|
+
);
|
|
324
|
+
console.warn(`Colibri: ${error.message} The connection still works; upgrade the server when you can.`);
|
|
325
|
+
this.protocolMismatchSubject.next(error);
|
|
326
|
+
}
|
|
327
|
+
onSocketAny(channel, msg) {
|
|
328
|
+
colibriHeardFrom(this);
|
|
329
|
+
const { command, payload } = msg;
|
|
330
|
+
if (channel === COLIBRI_CHANNEL && command === PROTOCOL_REJECTED_COMMAND) {
|
|
331
|
+
this.onProtocolRejected(payload);
|
|
332
|
+
return;
|
|
233
333
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
}
|
|
269
|
-
if (port < 1 || port > 65535) {
|
|
270
|
-
throw new ColibriError("Port out of allowed range (0 - 65535)");
|
|
271
|
-
}
|
|
272
|
-
this.uri = "".concat(server, ":").concat(port);
|
|
273
|
-
if (!new RegExp("wss?://", "i").test(this.uri)) {
|
|
274
|
-
this.uri = "ws://".concat(this.uri);
|
|
275
|
-
}
|
|
276
|
-
this.uriRestApi = "".concat(this.uri, "/api/store/").concat(app, "/");
|
|
277
|
-
if (_Colibri.instance) throw new ColibriError("A Colibri instance already exists!");
|
|
278
|
-
else _Colibri.instance = this;
|
|
279
|
-
this.socket = connect(this.uri, {
|
|
280
|
-
query: {
|
|
281
|
-
app: app,
|
|
282
|
-
version: "1"
|
|
283
|
-
},
|
|
284
|
-
transports: [
|
|
285
|
-
"websocket"
|
|
286
|
-
]
|
|
287
|
-
});
|
|
288
|
-
this.socket.on("connect", this.onSocketConnect.bind(this));
|
|
289
|
-
this.socket.onAny(this.onSocketAny.bind(this));
|
|
290
|
-
this.registerChannel("colibri", function(msg) {
|
|
291
|
-
if (msg.command === "latency") {
|
|
292
|
-
SendMessage("colibri", "latency", msg.payload);
|
|
293
|
-
}
|
|
294
|
-
});
|
|
334
|
+
if (channel === COLIBRI_CHANNEL && command === PROTOCOL_ACCEPTED_COMMAND) {
|
|
335
|
+
this.stopWaitingForServerHello();
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
this.messageSubject.next({ channel, command, payload });
|
|
339
|
+
}
|
|
340
|
+
// `rejection` is optional because it comes off the wire, and a bare `protocol::rejected` must
|
|
341
|
+
// still give a usable error rather than a TypeError.
|
|
342
|
+
onProtocolRejected(rejection) {
|
|
343
|
+
this.stopWaitingForServerHello();
|
|
344
|
+
this.hasReportedOldServer = true;
|
|
345
|
+
this.socket.io.reconnection(false);
|
|
346
|
+
this.socket.disconnect();
|
|
347
|
+
if (this.hasReportedRefusal) return;
|
|
348
|
+
this.hasReportedRefusal = true;
|
|
349
|
+
const serverVersion = rejection?.serverVersion ?? "unknown";
|
|
350
|
+
const error = new ProtocolMismatchError(
|
|
351
|
+
rejection?.reason ?? `Server refused the connection: it speaks protocol v${serverVersion}, this client speaks v${PROTOCOL_VERSION}.`,
|
|
352
|
+
serverVersion,
|
|
353
|
+
rejection?.clientVersion ?? PROTOCOL_VERSION
|
|
354
|
+
);
|
|
355
|
+
console.error(
|
|
356
|
+
`Colibri: ${error.message} Update colibri-web and colibri-server to matching versions. Not reconnecting.`
|
|
357
|
+
);
|
|
358
|
+
this.protocolMismatchSubject.next(error);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Returns the existing Colibri instance or null if there's none yet
|
|
362
|
+
* @param warnIfNotInitialized true => print Log message if Colibri has not been initialized yet
|
|
363
|
+
* @returns
|
|
364
|
+
*/
|
|
365
|
+
static getInstance(warnIfNotInitialized = true) {
|
|
366
|
+
if (warnIfNotInitialized && !_Colibri.instance) {
|
|
367
|
+
console.warn("Colibri not initialized yet! (Instance is null)");
|
|
295
368
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
value: function onSocketConnect() {
|
|
300
|
-
console.debug("Connected to colibri server on ".concat(this.server));
|
|
301
|
-
}
|
|
302
|
-
},
|
|
303
|
-
{
|
|
304
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
305
|
-
key: "onSocketAny",
|
|
306
|
-
value: function onSocketAny(channel, msg) {
|
|
307
|
-
this.messageSubject.next({
|
|
308
|
-
channel: channel,
|
|
309
|
-
command: msg.command,
|
|
310
|
-
payload: msg.payload
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
},
|
|
314
|
-
{
|
|
315
|
-
/**
|
|
369
|
+
return _Colibri.instance;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
316
372
|
* Sends a single message in the given `channel`.
|
|
317
373
|
* @param channel message channel
|
|
318
374
|
* @param command message command
|
|
319
375
|
* @param payload message payload
|
|
320
|
-
*/
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
{
|
|
330
|
-
//#region Socket Events
|
|
331
|
-
/**
|
|
376
|
+
*/
|
|
377
|
+
sendMessage(channel, command, payload = {}) {
|
|
378
|
+
this.socket.emit(channel, {
|
|
379
|
+
command,
|
|
380
|
+
payload
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
// #region Socket Events
|
|
384
|
+
/**
|
|
332
385
|
* Adds a `handler` function listening for messages in `channel`.
|
|
333
386
|
* @param channel message channel
|
|
334
387
|
* @param handler handler to be executed when a message is received
|
|
335
|
-
*/
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
{
|
|
341
|
-
/**
|
|
388
|
+
*/
|
|
389
|
+
registerChannel(channel, handler) {
|
|
390
|
+
this.socket.on(channel, handler);
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
342
393
|
* Removes the `handler` function listening for messages in `channel`.
|
|
343
394
|
* @param channel message channel
|
|
344
395
|
* @param handler handler to be executed when a message is received
|
|
345
|
-
*/
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
{
|
|
351
|
-
/**
|
|
396
|
+
*/
|
|
397
|
+
unregisterChannel(channel, handler) {
|
|
398
|
+
this.socket.off(channel, handler);
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
352
401
|
* Adds a one-time `handler` function listening for the next message in `channel`.
|
|
353
402
|
* @param channel message channel
|
|
354
403
|
* @param handler handler to be executed when a message is received
|
|
355
|
-
*/
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
*
|
|
404
|
+
*/
|
|
405
|
+
registerOnce(channel, handler) {
|
|
406
|
+
this.socket.once(channel, handler);
|
|
407
|
+
}
|
|
408
|
+
// #endregion
|
|
409
|
+
// #region Rest API
|
|
410
|
+
/**
|
|
411
|
+
* Returns the REST API Endpoint for a given `key`, or null if the key is empty, `.` or `..`.
|
|
412
|
+
* Any other key is stored under exactly that name (`#`, `?`, `/`, `%` and spaces included)
|
|
413
|
+
* after surrounding whitespace and leading slashes are stripped.
|
|
365
414
|
* @param key REST API storage key
|
|
366
415
|
* @returns
|
|
367
|
-
*/
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
key: "getRestObject",
|
|
376
|
-
value: /**
|
|
416
|
+
*/
|
|
417
|
+
getRestUri(key) {
|
|
418
|
+
key = key.trim();
|
|
419
|
+
while (key.startsWith("/")) key = key.substring(1);
|
|
420
|
+
if (key.length === 0 || key === "." || key === "..") return null;
|
|
421
|
+
return this.uriRestApi + encodeURIComponent(key);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
377
424
|
* Queries an object from the REST API identified by `key`.
|
|
425
|
+
*
|
|
426
|
+
* Rejects when the server cannot be reached (wrong address, server down, no network) or an
|
|
427
|
+
* answer with a success status is not JSON.
|
|
378
428
|
* @param key REST API storage key
|
|
379
|
-
* @returns
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
];
|
|
401
|
-
case 1:
|
|
402
|
-
response = _state.sent();
|
|
403
|
-
if (response.status >= 400) return [
|
|
404
|
-
2,
|
|
405
|
-
null
|
|
406
|
-
];
|
|
407
|
-
else return [
|
|
408
|
-
2,
|
|
409
|
-
response.json()
|
|
410
|
-
];
|
|
411
|
-
return [
|
|
412
|
-
2
|
|
413
|
-
];
|
|
414
|
-
}
|
|
415
|
-
});
|
|
416
|
-
}).call(this);
|
|
417
|
-
}
|
|
418
|
-
},
|
|
419
|
-
{
|
|
420
|
-
key: "setRestObject",
|
|
421
|
-
value: /**
|
|
422
|
-
* Sets or updatees an object in the REST API identified by `key`.
|
|
429
|
+
* @returns the stored value; or null if `key` is empty or the server answered with an error
|
|
430
|
+
* status, such as 404 for a key that was never stored. A stored `null` looks the same.
|
|
431
|
+
*/
|
|
432
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
433
|
+
async getRestObject(key) {
|
|
434
|
+
const uri = this.getRestUri(key);
|
|
435
|
+
if (!uri) return null;
|
|
436
|
+
const response = await fetch(uri, {
|
|
437
|
+
method: "GET",
|
|
438
|
+
headers: {
|
|
439
|
+
Accept: REST_MEDIA_TYPE
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
if (response.status >= 400) return null;
|
|
443
|
+
else return response.json();
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Sets or updates an object in the REST API identified by `key`.
|
|
447
|
+
*
|
|
448
|
+
* Rejects when the server cannot be reached (wrong address, server down, no network) or
|
|
449
|
+
* `data` cannot be serialized to JSON (circular structure, BigInt).
|
|
423
450
|
* @param key REST API storage key
|
|
424
451
|
* @param data JSON data to write
|
|
425
|
-
* @returns true if data
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
_Colibri.instance = null;
|
|
477
|
-
var Colibri = _Colibri;
|
|
478
|
-
var SendMessage = function SendMessage(channel, command) {
|
|
479
|
-
var payload = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
|
|
480
|
-
var _Colibri_getInstance;
|
|
481
|
-
return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.sendMessage(channel, command, payload);
|
|
482
|
-
};
|
|
483
|
-
var RegisterChannel = function RegisterChannel(channel, handler) {
|
|
484
|
-
var _Colibri_getInstance;
|
|
485
|
-
return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.registerChannel(channel, handler);
|
|
486
|
-
};
|
|
487
|
-
var UnregisterChannel = function UnregisterChannel(channel, handler) {
|
|
488
|
-
var _Colibri_getInstance;
|
|
489
|
-
return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.unregisterChannel(channel, handler);
|
|
490
|
-
};
|
|
491
|
-
var RegisterOnce = function RegisterOnce(channel, handler) {
|
|
492
|
-
var _Colibri_getInstance;
|
|
493
|
-
return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.registerOnce(channel, handler);
|
|
494
|
-
};
|
|
495
|
-
var GetRestApi = function GetRestApi(key) {
|
|
496
|
-
var _Colibri_getInstance;
|
|
497
|
-
return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.getRestObject(key);
|
|
498
|
-
};
|
|
499
|
-
var PutRestApi = function PutRestApi(key, data) {
|
|
500
|
-
var _Colibri_getInstance;
|
|
501
|
-
return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.setRestObject(key, data);
|
|
452
|
+
* @returns true if the server stored the data; false if `key` is empty or the server answered
|
|
453
|
+
* with any other status
|
|
454
|
+
*/
|
|
455
|
+
async setRestObject(key, data) {
|
|
456
|
+
const uri = this.getRestUri(key);
|
|
457
|
+
if (!uri) return false;
|
|
458
|
+
const response = await fetch(uri, {
|
|
459
|
+
method: "PUT",
|
|
460
|
+
headers: {
|
|
461
|
+
Accept: REST_MEDIA_TYPE,
|
|
462
|
+
"Content-Type": REST_MEDIA_TYPE
|
|
463
|
+
},
|
|
464
|
+
body: JSON.stringify(data)
|
|
465
|
+
});
|
|
466
|
+
return response.status >= 200 && response.status < 300;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Deletes the object identified by `key` from the REST API.
|
|
470
|
+
*
|
|
471
|
+
* Rejects when the server cannot be reached (wrong address, server down, no network).
|
|
472
|
+
* @param key REST API storage key
|
|
473
|
+
* @returns true if the server deleted the value; false if `key` is empty or the server answered
|
|
474
|
+
* with any other status, such as 404 for a key that holds no value
|
|
475
|
+
*/
|
|
476
|
+
async deleteRestObject(key) {
|
|
477
|
+
const uri = this.getRestUri(key);
|
|
478
|
+
if (!uri) return false;
|
|
479
|
+
const response = await fetch(uri, {
|
|
480
|
+
method: "DELETE",
|
|
481
|
+
headers: {
|
|
482
|
+
Accept: REST_MEDIA_TYPE
|
|
483
|
+
}
|
|
484
|
+
});
|
|
485
|
+
return response.status >= 200 && response.status < 300;
|
|
486
|
+
}
|
|
487
|
+
// #endregion
|
|
488
|
+
};
|
|
489
|
+
var SendMessage = (channel, command, payload = {}) => Colibri.getInstance()?.sendMessage(channel, command, payload);
|
|
490
|
+
var RegisterChannel = (channel, handler) => {
|
|
491
|
+
const colibri = Colibri.getInstance(false);
|
|
492
|
+
if (colibri) colibri.registerChannel(channel, handler);
|
|
493
|
+
else pendingRegistrations.push({ channel, handler, once: false });
|
|
494
|
+
};
|
|
495
|
+
var UnregisterChannel = (channel, handler) => {
|
|
496
|
+
const colibri = Colibri.getInstance(false);
|
|
497
|
+
if (colibri) {
|
|
498
|
+
colibri.unregisterChannel(channel, handler);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const index = pendingRegistrations.findIndex((p) => p.channel === channel && p.handler === handler);
|
|
502
|
+
if (index >= 0) pendingRegistrations.splice(index, 1);
|
|
502
503
|
};
|
|
504
|
+
var RegisterOnce = (channel, handler) => {
|
|
505
|
+
const colibri = Colibri.getInstance(false);
|
|
506
|
+
if (colibri) colibri.registerOnce(channel, handler);
|
|
507
|
+
else pendingRegistrations.push({ channel, handler, once: true });
|
|
508
|
+
};
|
|
509
|
+
var GetRestApi = (key) => Colibri.getInstance()?.getRestObject(key);
|
|
510
|
+
var PutRestApi = (key, data) => Colibri.getInstance()?.setRestObject(key, data);
|
|
511
|
+
var DeleteRestApi = (key) => Colibri.getInstance()?.deleteRestObject(key);
|
|
512
|
+
|
|
503
513
|
// src/Broadcasting.ts
|
|
504
|
-
var sendBool =
|
|
505
|
-
|
|
514
|
+
var sendBool = (channel, val) => {
|
|
515
|
+
SendMessage(channel, "broadcast::bool", val);
|
|
516
|
+
};
|
|
517
|
+
var sendBoolArray = (channel, val) => {
|
|
518
|
+
SendMessage(channel, "broadcast::bool[]", val);
|
|
519
|
+
};
|
|
520
|
+
var sendNumber = (channel, val) => {
|
|
521
|
+
SendMessage(channel, "broadcast::float", val);
|
|
506
522
|
};
|
|
507
|
-
var
|
|
508
|
-
|
|
523
|
+
var sendNumberArray = (channel, val) => {
|
|
524
|
+
SendMessage(channel, "broadcast::float[]", val);
|
|
509
525
|
};
|
|
510
|
-
var
|
|
511
|
-
|
|
526
|
+
var sendString = (channel, val) => {
|
|
527
|
+
SendMessage(channel, "broadcast::string", val);
|
|
512
528
|
};
|
|
513
|
-
var
|
|
514
|
-
|
|
529
|
+
var sendStringArray = (channel, val) => {
|
|
530
|
+
SendMessage(channel, "broadcast::string[]", val);
|
|
515
531
|
};
|
|
516
|
-
var
|
|
517
|
-
|
|
532
|
+
var sendVector2 = (channel, val) => {
|
|
533
|
+
SendMessage(channel, "broadcast::vector2", val);
|
|
518
534
|
};
|
|
519
|
-
var
|
|
520
|
-
|
|
535
|
+
var sendVector2Array = (channel, val) => {
|
|
536
|
+
SendMessage(channel, "broadcast::vector2[]", val);
|
|
521
537
|
};
|
|
522
|
-
var sendVector3 =
|
|
523
|
-
|
|
538
|
+
var sendVector3 = (channel, val) => {
|
|
539
|
+
SendMessage(channel, "broadcast::vector3", val);
|
|
524
540
|
};
|
|
525
|
-
var sendVector3Array =
|
|
526
|
-
|
|
541
|
+
var sendVector3Array = (channel, val) => {
|
|
542
|
+
SendMessage(channel, "broadcast::vector3[]", val);
|
|
527
543
|
};
|
|
528
|
-
var sendQuaternion =
|
|
529
|
-
|
|
544
|
+
var sendQuaternion = (channel, val) => {
|
|
545
|
+
SendMessage(channel, "broadcast::quaternion", val);
|
|
530
546
|
};
|
|
531
|
-
var sendQuaternionArray =
|
|
532
|
-
|
|
547
|
+
var sendQuaternionArray = (channel, val) => {
|
|
548
|
+
SendMessage(channel, "broadcast::quaternion[]", val);
|
|
533
549
|
};
|
|
534
|
-
var sendColor =
|
|
535
|
-
|
|
550
|
+
var sendColor = (channel, val) => {
|
|
551
|
+
SendMessage(channel, "broadcast::color", val);
|
|
536
552
|
};
|
|
537
|
-
var sendColorArray =
|
|
538
|
-
|
|
553
|
+
var sendColorArray = (channel, val) => {
|
|
554
|
+
SendMessage(channel, "broadcast::color[]", val);
|
|
539
555
|
};
|
|
540
|
-
var sendJson =
|
|
541
|
-
|
|
556
|
+
var sendJson = (channel, val) => {
|
|
557
|
+
SendMessage(channel, "broadcast::json", val);
|
|
542
558
|
};
|
|
543
559
|
var listeners = {};
|
|
544
|
-
var
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
560
|
+
var channelHandlers = {};
|
|
561
|
+
var registerListener = (channel, type, callback) => {
|
|
562
|
+
let channelListeners = listeners[channel];
|
|
563
|
+
if (channelListeners === void 0) {
|
|
564
|
+
const newChannelListeners = {};
|
|
565
|
+
channelListeners = newChannelListeners;
|
|
566
|
+
listeners[channel] = newChannelListeners;
|
|
567
|
+
const handler = (msg) => {
|
|
568
|
+
const commandListeners = newChannelListeners[msg.command];
|
|
569
|
+
if (commandListeners !== void 0) {
|
|
570
|
+
commandListeners.forEach((cb) => {
|
|
571
|
+
cb(msg.payload);
|
|
553
572
|
});
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
channelHandlers[channel] = handler;
|
|
576
|
+
RegisterChannel(channel, handler);
|
|
577
|
+
}
|
|
578
|
+
let typeListeners = channelListeners[type];
|
|
579
|
+
if (typeListeners === void 0) {
|
|
580
|
+
typeListeners = [];
|
|
581
|
+
channelListeners[type] = typeListeners;
|
|
582
|
+
}
|
|
583
|
+
typeListeners.push(callback);
|
|
559
584
|
};
|
|
560
|
-
var receiveBool =
|
|
561
|
-
|
|
585
|
+
var receiveBool = (channel, callback) => {
|
|
586
|
+
registerListener(channel, "broadcast::bool", callback);
|
|
562
587
|
};
|
|
563
|
-
var receiveBoolArray =
|
|
564
|
-
|
|
588
|
+
var receiveBoolArray = (channel, callback) => {
|
|
589
|
+
registerListener(channel, "broadcast::bool[]", callback);
|
|
565
590
|
};
|
|
566
|
-
var receiveNumber =
|
|
567
|
-
|
|
591
|
+
var receiveNumber = (channel, callback) => {
|
|
592
|
+
registerListener(channel, "broadcast::float", callback);
|
|
593
|
+
registerListener(channel, "broadcast::int", callback);
|
|
568
594
|
};
|
|
569
|
-
var receiveNumberArray =
|
|
570
|
-
|
|
595
|
+
var receiveNumberArray = (channel, callback) => {
|
|
596
|
+
registerListener(channel, "broadcast::float[]", callback);
|
|
597
|
+
registerListener(channel, "broadcast::int[]", callback);
|
|
571
598
|
};
|
|
572
|
-
var receiveString =
|
|
573
|
-
|
|
599
|
+
var receiveString = (channel, callback) => {
|
|
600
|
+
registerListener(channel, "broadcast::string", callback);
|
|
574
601
|
};
|
|
575
|
-
var receiveStringArray =
|
|
576
|
-
|
|
602
|
+
var receiveStringArray = (channel, callback) => {
|
|
603
|
+
registerListener(channel, "broadcast::string[]", callback);
|
|
577
604
|
};
|
|
578
|
-
var
|
|
579
|
-
|
|
605
|
+
var receiveVector2 = (channel, callback) => {
|
|
606
|
+
registerListener(channel, "broadcast::vector2", callback);
|
|
580
607
|
};
|
|
581
|
-
var
|
|
582
|
-
|
|
608
|
+
var receiveVector2Array = (channel, callback) => {
|
|
609
|
+
registerListener(channel, "broadcast::vector2[]", callback);
|
|
583
610
|
};
|
|
584
|
-
var
|
|
585
|
-
|
|
611
|
+
var receiveVector3 = (channel, callback) => {
|
|
612
|
+
registerListener(channel, "broadcast::vector3", callback);
|
|
586
613
|
};
|
|
587
|
-
var
|
|
588
|
-
|
|
614
|
+
var receiveVector3Array = (channel, callback) => {
|
|
615
|
+
registerListener(channel, "broadcast::vector3[]", callback);
|
|
589
616
|
};
|
|
590
|
-
var
|
|
591
|
-
|
|
617
|
+
var receiveQuaternion = (channel, callback) => {
|
|
618
|
+
registerListener(channel, "broadcast::quaternion", callback);
|
|
592
619
|
};
|
|
593
|
-
var
|
|
594
|
-
|
|
620
|
+
var receiveQuaternionArray = (channel, callback) => {
|
|
621
|
+
registerListener(channel, "broadcast::quaternion[]", callback);
|
|
595
622
|
};
|
|
596
|
-
var
|
|
597
|
-
|
|
623
|
+
var receiveColor = (channel, callback) => {
|
|
624
|
+
registerListener(channel, "broadcast::color", callback);
|
|
598
625
|
};
|
|
599
|
-
var
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
626
|
+
var receiveColorArray = (channel, callback) => {
|
|
627
|
+
registerListener(channel, "broadcast::color[]", callback);
|
|
628
|
+
};
|
|
629
|
+
var receiveJson = (channel, callback) => {
|
|
630
|
+
registerListener(channel, "broadcast::json", callback);
|
|
631
|
+
};
|
|
632
|
+
var clamp01 = (n) => Math.min(1, Math.max(0, n));
|
|
633
|
+
var hexPair = (n) => Math.round(clamp01(n) * 255).toString(16).padStart(2, "0");
|
|
634
|
+
var warnNotAColor = (val) => {
|
|
635
|
+
console.warn(`Colibri: '${JSON.stringify(val)}' is not a colour - expected "#RRGGBBAA" or [r,g,b,a]. Using black.`);
|
|
636
|
+
};
|
|
637
|
+
var asComponents = (val) => {
|
|
638
|
+
if (!Array.isArray(val) || val.length < 3) return null;
|
|
639
|
+
const numbers = val;
|
|
640
|
+
if (!numbers.every((c) => typeof c === "number" && !Number.isNaN(c))) return null;
|
|
641
|
+
return numbers;
|
|
642
|
+
};
|
|
643
|
+
var toHexColor = (val) => {
|
|
644
|
+
const rgba = toRgbaColor(val);
|
|
645
|
+
return `#${hexPair(rgba[0])}${hexPair(rgba[1])}${hexPair(rgba[2])}${hexPair(rgba[3])}`;
|
|
646
|
+
};
|
|
647
|
+
var toRgbaColor = (val) => {
|
|
648
|
+
const components = asComponents(val);
|
|
649
|
+
if (components !== null) {
|
|
650
|
+
return [
|
|
651
|
+
clamp01(components[0]),
|
|
652
|
+
clamp01(components[1]),
|
|
653
|
+
clamp01(components[2]),
|
|
654
|
+
components.length > 3 ? clamp01(components[3]) : 1
|
|
655
|
+
];
|
|
656
|
+
}
|
|
657
|
+
if (typeof val === "string") {
|
|
658
|
+
const hex = val.startsWith("#") ? val.slice(1) : val;
|
|
659
|
+
const digits = hex.length === 3 || hex.length === 4 ? hex.replace(/./g, (c) => c + c) : hex;
|
|
660
|
+
if ((digits.length === 6 || digits.length === 8) && /^[0-9a-f]+$/i.test(digits)) {
|
|
661
|
+
const byteAt = (i) => parseInt(digits.slice(i, i + 2), 16) / 255;
|
|
662
|
+
return [byteAt(0), byteAt(2), byteAt(4), digits.length === 8 ? byteAt(6) : 1];
|
|
605
663
|
}
|
|
664
|
+
}
|
|
665
|
+
warnNotAColor(val);
|
|
666
|
+
return [0, 0, 0, 1];
|
|
667
|
+
};
|
|
668
|
+
var unregister = (channel, callback) => {
|
|
669
|
+
const channelListeners = listeners[channel];
|
|
670
|
+
if (channelListeners === void 0) return;
|
|
671
|
+
let hasRemainingListeners = false;
|
|
672
|
+
for (const command in channelListeners) {
|
|
673
|
+
const commandListeners = channelListeners[command];
|
|
674
|
+
const index = commandListeners?.indexOf(callback) ?? -1;
|
|
675
|
+
if (index >= 0) {
|
|
676
|
+
commandListeners?.splice(index, 1);
|
|
677
|
+
}
|
|
678
|
+
if ((commandListeners?.length ?? 0) > 0) {
|
|
679
|
+
hasRemainingListeners = true;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (!hasRemainingListeners) {
|
|
683
|
+
const handler = channelHandlers[channel];
|
|
684
|
+
if (handler !== void 0) {
|
|
685
|
+
UnregisterChannel(channel, handler);
|
|
686
|
+
}
|
|
687
|
+
Reflect.deleteProperty(listeners, channel);
|
|
688
|
+
Reflect.deleteProperty(channelHandlers, channel);
|
|
689
|
+
}
|
|
606
690
|
};
|
|
607
691
|
var Sync = {
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
692
|
+
sendBool,
|
|
693
|
+
sendBoolArray,
|
|
694
|
+
sendNumber,
|
|
695
|
+
sendNumberArray,
|
|
696
|
+
sendString,
|
|
697
|
+
sendStringArray,
|
|
698
|
+
sendVector2,
|
|
699
|
+
sendVector2Array,
|
|
700
|
+
sendVector3,
|
|
701
|
+
sendVector3Array,
|
|
702
|
+
sendQuaternion,
|
|
703
|
+
sendQuaternionArray,
|
|
704
|
+
sendColor,
|
|
705
|
+
sendColorArray,
|
|
706
|
+
sendJson,
|
|
707
|
+
receiveBool,
|
|
708
|
+
receiveBoolArray,
|
|
709
|
+
receiveNumber,
|
|
710
|
+
receiveNumberArray,
|
|
711
|
+
receiveString,
|
|
712
|
+
receiveStringArray,
|
|
713
|
+
receiveVector2,
|
|
714
|
+
receiveVector2Array,
|
|
715
|
+
receiveVector3,
|
|
716
|
+
receiveVector3Array,
|
|
717
|
+
receiveQuaternion,
|
|
718
|
+
receiveQuaternionArray,
|
|
719
|
+
receiveColor,
|
|
720
|
+
receiveColorArray,
|
|
721
|
+
receiveJson,
|
|
722
|
+
unregister,
|
|
723
|
+
// for better compatibility with Unity Colibri
|
|
724
|
+
// sendInt and sendIntArray still send the float commands (JS cannot tell 5 from 5.0), so a
|
|
725
|
+
// Unity client has to listen for float, not int.
|
|
726
|
+
sendFloat: sendNumber,
|
|
727
|
+
sendInt: sendNumber,
|
|
728
|
+
sendFloatArray: sendNumberArray,
|
|
729
|
+
sendIntArray: sendNumberArray
|
|
640
730
|
};
|
|
731
|
+
|
|
641
732
|
// src/RemoteLogger.ts
|
|
642
|
-
var
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
value: function disable() {
|
|
707
|
-
this.enabled = false;
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
], [
|
|
711
|
-
{
|
|
712
|
-
key: "init",
|
|
713
|
-
value: /**
|
|
733
|
+
var MAX_EARLY_LINES = 100;
|
|
734
|
+
var RemoteLogger = class _RemoteLogger {
|
|
735
|
+
/**
|
|
736
|
+
* Forwards everything logged through `console` to the server's log. Create one, at startup.
|
|
737
|
+
* A further instance warns once and does not patch again; its `enabled` argument, `enable()` and
|
|
738
|
+
* `disable()` act on the first one.
|
|
739
|
+
* @param enabled whether to forward from the start
|
|
740
|
+
*/
|
|
741
|
+
constructor(enabled = true) {
|
|
742
|
+
this.enabled = enabled;
|
|
743
|
+
const patched = _RemoteLogger.patched;
|
|
744
|
+
if (patched) {
|
|
745
|
+
this.forwarder = patched;
|
|
746
|
+
patched.enabled = enabled;
|
|
747
|
+
if (!patched.hasWarnedOfAnotherInstance) {
|
|
748
|
+
patched.hasWarnedOfAnotherInstance = true;
|
|
749
|
+
console.warn(
|
|
750
|
+
"RemoteLogger: the console is already forwarded by an earlier new RemoteLogger(), so this one controls that instead of forwarding every line a second time. Create one, at startup."
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
_RemoteLogger.patched = this;
|
|
756
|
+
this.forwarder = this;
|
|
757
|
+
console.debug = (...args) => {
|
|
758
|
+
this.consoleDebug(...args);
|
|
759
|
+
this.sendMessage("debug", args);
|
|
760
|
+
};
|
|
761
|
+
console.log = (...args) => {
|
|
762
|
+
this.consoleLog(...args);
|
|
763
|
+
this.sendMessage("info", args);
|
|
764
|
+
};
|
|
765
|
+
console.info = (...args) => {
|
|
766
|
+
this.consoleInfo(...args);
|
|
767
|
+
this.sendMessage("info", args);
|
|
768
|
+
};
|
|
769
|
+
console.warn = (...args) => {
|
|
770
|
+
this.consoleWarn(...args);
|
|
771
|
+
this.sendMessage("warn", args);
|
|
772
|
+
};
|
|
773
|
+
console.error = (...args) => {
|
|
774
|
+
this.consoleError(...args);
|
|
775
|
+
this.sendMessage("error", args);
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
// The instance that patched the console. Later instances delegate to it, since patching again
|
|
779
|
+
// would forward every line once per instance (StrictMode and hot reload create extras).
|
|
780
|
+
static patched = null;
|
|
781
|
+
// Itself, or the instance that patched the console.
|
|
782
|
+
forwarder;
|
|
783
|
+
hasWarnedOfAnotherInstance = false;
|
|
784
|
+
consoleDebug = console.debug;
|
|
785
|
+
consoleLog = console.log;
|
|
786
|
+
consoleInfo = console.info;
|
|
787
|
+
consoleWarn = console.warn;
|
|
788
|
+
consoleError = console.error;
|
|
789
|
+
// Recursion guard: lines logged while forwarding (by Colibri, or by a getter that JSON.stringify
|
|
790
|
+
// runs) go to the console only.
|
|
791
|
+
forwarding = false;
|
|
792
|
+
// Lines logged before `new Colibri()`.
|
|
793
|
+
earlyLines = [];
|
|
794
|
+
droppedEarlyLines = 0;
|
|
795
|
+
waitingForColibri = false;
|
|
796
|
+
/**
|
|
714
797
|
* @deprecated use new class constructor directly
|
|
715
|
-
*/
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
798
|
+
*/
|
|
799
|
+
static init(enabled = true) {
|
|
800
|
+
return new _RemoteLogger(enabled);
|
|
801
|
+
}
|
|
802
|
+
sendMessage(level, args) {
|
|
803
|
+
if (!this.enabled || this.forwarding) return;
|
|
804
|
+
this.forwarding = true;
|
|
805
|
+
try {
|
|
806
|
+
const message = [...args].map(stringify).join().trim();
|
|
807
|
+
const colibri = Colibri.getInstance(false);
|
|
808
|
+
if (colibri) colibri.sendMessage("log", level, message);
|
|
809
|
+
else this.keepUntilColibriExists(level, message);
|
|
810
|
+
} catch (error) {
|
|
811
|
+
this.consoleError("RemoteLogger: could not forward a log line.", error);
|
|
812
|
+
} finally {
|
|
813
|
+
this.forwarding = false;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
keepUntilColibriExists(level, message) {
|
|
817
|
+
if (this.earlyLines.length >= MAX_EARLY_LINES) {
|
|
818
|
+
this.droppedEarlyLines++;
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
this.earlyLines.push({ level, message });
|
|
822
|
+
if (!this.waitingForColibri) {
|
|
823
|
+
this.waitingForColibri = true;
|
|
824
|
+
whenColibriCreated((colibri) => {
|
|
825
|
+
this.sendEarlyLines(colibri);
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
// Socket.IO buffers emits until connected, so there is no need to wait for the connection.
|
|
830
|
+
sendEarlyLines(colibri) {
|
|
831
|
+
this.waitingForColibri = false;
|
|
832
|
+
for (const { level, message } of this.earlyLines.splice(0)) {
|
|
833
|
+
colibri.sendMessage("log", level, message);
|
|
834
|
+
}
|
|
835
|
+
if (this.droppedEarlyLines > 0) {
|
|
836
|
+
colibri.sendMessage(
|
|
837
|
+
"log",
|
|
838
|
+
"warn",
|
|
839
|
+
`RemoteLogger: ${this.droppedEarlyLines} more line(s) logged before new Colibri() were not kept, only the first ${MAX_EARLY_LINES}.`
|
|
840
|
+
);
|
|
841
|
+
this.droppedEarlyLines = 0;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
/** Starts forwarding console output to the server's log. */
|
|
845
|
+
enable() {
|
|
846
|
+
this.forwarder.enabled = true;
|
|
847
|
+
}
|
|
848
|
+
/** Stops forwarding to the server's log; the console still prints. */
|
|
849
|
+
disable() {
|
|
850
|
+
this.forwarder.enabled = false;
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
var stringify = (obj) => {
|
|
854
|
+
if (obj instanceof Error) {
|
|
855
|
+
return obj.message + "\n" + (obj.stack ?? "");
|
|
856
|
+
}
|
|
857
|
+
if (typeof obj === "string") return obj;
|
|
858
|
+
const cache = [];
|
|
859
|
+
let str;
|
|
860
|
+
try {
|
|
861
|
+
str = JSON.stringify(
|
|
862
|
+
obj,
|
|
863
|
+
(_, value) => {
|
|
864
|
+
if (typeof value === "bigint") return value.toString();
|
|
865
|
+
if (typeof value === "object" && value !== null) {
|
|
866
|
+
if (cache.indexOf(value) !== -1) {
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
cache.push(value);
|
|
735
870
|
}
|
|
736
871
|
return value;
|
|
737
|
-
|
|
738
|
-
|
|
872
|
+
},
|
|
873
|
+
2
|
|
874
|
+
);
|
|
875
|
+
} catch {
|
|
876
|
+
str = String(obj);
|
|
877
|
+
}
|
|
878
|
+
return str;
|
|
739
879
|
};
|
|
880
|
+
|
|
740
881
|
// src/ModelSynchronization.ts
|
|
741
882
|
import { BehaviorSubject } from "rxjs";
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
883
|
+
|
|
884
|
+
// src/SyncModel.ts
|
|
885
|
+
import { Subject as Subject2, auditTime, buffer, filter, map, share } from "rxjs";
|
|
886
|
+
var SyncModel = class _SyncModel {
|
|
887
|
+
id;
|
|
888
|
+
// True while update() applies a remote update, so the setters do not echo it.
|
|
889
|
+
applyingRemoteUpdate = false;
|
|
890
|
+
modelChanges = new Subject2();
|
|
891
|
+
modelChanges$ = this.modelChanges.pipe(
|
|
892
|
+
// auditTime arms its timer on the first change only; bufferTime keeps an interval running while idle.
|
|
893
|
+
buffer(this.modelChanges.pipe(auditTime(1))),
|
|
894
|
+
map((changes) => changes.filter(this.uniq)),
|
|
895
|
+
filter((changes) => changes.length > 0),
|
|
896
|
+
share()
|
|
897
|
+
);
|
|
898
|
+
// Emits once on delete(), which RegisterModelSync sends on as model::delete. Public only for RegisterModelSync.
|
|
899
|
+
deletions = new Subject2();
|
|
900
|
+
// ES private: a subclass may have a `deleted` of its own.
|
|
901
|
+
#deleted = false;
|
|
902
|
+
constructor(id) {
|
|
903
|
+
this.id = id;
|
|
904
|
+
}
|
|
905
|
+
uniq(value, index, array) {
|
|
906
|
+
return array.indexOf(value) === index;
|
|
907
|
+
}
|
|
908
|
+
onModelChanges(prop) {
|
|
909
|
+
this.modelChanges.next(prop);
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Deletes the model for every client of the app (Unity destroys its GameObject) and removes it
|
|
913
|
+
* from this client's list. The model stops syncing.
|
|
914
|
+
*/
|
|
915
|
+
delete() {
|
|
916
|
+
if (this.#deleted) return;
|
|
917
|
+
this.#deleted = true;
|
|
918
|
+
if (!this.deletions.observed) {
|
|
919
|
+
console.warn(
|
|
920
|
+
`Colibri: delete() of '${this.id}', which no RegisterModelSync lists. Register it, or take it from the list RegisterModelSync gives, to delete it for every client.`
|
|
921
|
+
);
|
|
922
|
+
}
|
|
923
|
+
_SyncModel.prototype.detach.call(this);
|
|
924
|
+
this.deletions.next();
|
|
925
|
+
this.deletions.complete();
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Stops syncing the model on this client only; every other client keeps it. RegisterModelSync
|
|
929
|
+
* calls it on a remote delete and when registerModel replaces a listed copy.
|
|
930
|
+
*/
|
|
931
|
+
detach() {
|
|
932
|
+
this.modelChanges.complete();
|
|
933
|
+
}
|
|
934
|
+
registerSyncedProperty(name, prop) {
|
|
935
|
+
let syncedProperties = this.__syncedProperties;
|
|
936
|
+
if (syncedProperties === void 0) {
|
|
937
|
+
syncedProperties = {};
|
|
938
|
+
Object.defineProperty(this, "__syncedProperties", {
|
|
939
|
+
value: syncedProperties,
|
|
940
|
+
enumerable: false,
|
|
941
|
+
writable: true,
|
|
942
|
+
configurable: true
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
syncedProperties[name] = prop;
|
|
946
|
+
}
|
|
947
|
+
getSyncedProperties() {
|
|
948
|
+
return this.__syncedProperties ?? {};
|
|
949
|
+
}
|
|
950
|
+
update(updates) {
|
|
951
|
+
const syncedProps = this.getSyncedProperties();
|
|
952
|
+
this.applyingRemoteUpdate = true;
|
|
953
|
+
try {
|
|
954
|
+
for (const key of Object.keys(updates)) {
|
|
955
|
+
if (key !== "id") {
|
|
956
|
+
const localKey = syncedProps[key];
|
|
957
|
+
if (localKey) {
|
|
958
|
+
this[localKey] = updates[key];
|
|
959
|
+
} else {
|
|
960
|
+
console.warn(`Unknown property ${key} in ${this.constructor.name}`);
|
|
961
|
+
}
|
|
754
962
|
}
|
|
963
|
+
}
|
|
964
|
+
} finally {
|
|
965
|
+
this.applyingRemoteUpdate = false;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
toJson(attributes = []) {
|
|
969
|
+
const json = { id: this.id };
|
|
970
|
+
const syncedProps = this.getSyncedProperties();
|
|
971
|
+
for (const key of Object.keys(syncedProps)) {
|
|
972
|
+
const localKey = syncedProps[key];
|
|
973
|
+
if (attributes.length === 0 || attributes.includes(localKey)) {
|
|
974
|
+
json[key] = this[localKey];
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
return json;
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
// src/ModelSynchronization.ts
|
|
982
|
+
var toJsonOf = (model, attributes) => SyncModel.prototype.toJson.call(model, attributes);
|
|
983
|
+
var updateOf = (model, updates) => {
|
|
984
|
+
SyncModel.prototype.update.call(model, updates);
|
|
985
|
+
};
|
|
986
|
+
var detachOf = (model) => {
|
|
987
|
+
if (model) SyncModel.prototype.detach.call(model);
|
|
988
|
+
};
|
|
989
|
+
var withColibri = (action) => {
|
|
990
|
+
const colibri = Colibri.getInstance(false);
|
|
991
|
+
if (colibri) action(colibri);
|
|
992
|
+
else whenColibriCreated(action);
|
|
993
|
+
};
|
|
994
|
+
var warnedMinifiedNames = /* @__PURE__ */ new Set();
|
|
995
|
+
var warnIfMinified = (className, channel) => {
|
|
996
|
+
if (channel.length > 2 && !channel.includes("$") || warnedMinifiedNames.has(channel)) return;
|
|
997
|
+
warnedMinifiedNames.add(channel);
|
|
998
|
+
console.warn(
|
|
999
|
+
`Colibri: RegisterModelSync is syncing on channel '${channel}', derived from the class name '${className}', which looks minified. A minified build renames classes, so this will not sync with another build or with Unity. Pass the channel explicitly: RegisterModelSync({ name: '...', type: ${className || "YourModel"} }).`
|
|
1000
|
+
);
|
|
1001
|
+
};
|
|
1002
|
+
var isBare = (modelData) => Object.keys(modelData).every((key) => key === "id");
|
|
1003
|
+
var ownOnChannel = /* @__PURE__ */ new Map();
|
|
1004
|
+
var guardsOnChannel = /* @__PURE__ */ new Map();
|
|
1005
|
+
var END_CHANNEL = "colibri::reconnect";
|
|
1006
|
+
var endRequests = 0;
|
|
1007
|
+
var askForEnd = (colibri) => {
|
|
1008
|
+
const id = `colibri-web-${++endRequests}`;
|
|
1009
|
+
colibri.sendMessage(END_CHANNEL, "model::request", { id, again: true });
|
|
1010
|
+
return id;
|
|
1011
|
+
};
|
|
1012
|
+
var KNOWN_VALUES_KEPT = 8;
|
|
1013
|
+
var KNOWN_VALUES_MS = 1e4;
|
|
1014
|
+
var DELETED_HERE_MS = 6e4;
|
|
1015
|
+
var AFRESH_ANSWER_MS = 1e4;
|
|
1016
|
+
var RegisterModelSync = (registration) => {
|
|
1017
|
+
const name = registration.name || registration.type.name.toLowerCase();
|
|
1018
|
+
if (!registration.name) warnIfMinified(registration.type.name, name);
|
|
1019
|
+
const models = new BehaviorSubject([]);
|
|
1020
|
+
const deletedHere = /* @__PURE__ */ new Map();
|
|
1021
|
+
const rememberDeletedHere = (id) => {
|
|
1022
|
+
const now = Date.now();
|
|
1023
|
+
for (const [old, at] of deletedHere) {
|
|
1024
|
+
if (now - at < DELETED_HERE_MS) break;
|
|
1025
|
+
deletedHere.delete(old);
|
|
1026
|
+
}
|
|
1027
|
+
deletedHere.delete(id);
|
|
1028
|
+
deletedHere.set(id, now);
|
|
1029
|
+
};
|
|
1030
|
+
const afresh = /* @__PURE__ */ new Map();
|
|
1031
|
+
const recentlyDeletedHere = (id) => {
|
|
1032
|
+
const at = deletedHere.get(id);
|
|
1033
|
+
if (at === void 0) return false;
|
|
1034
|
+
if (Date.now() - at < DELETED_HERE_MS) return true;
|
|
1035
|
+
deletedHere.delete(id);
|
|
1036
|
+
return false;
|
|
1037
|
+
};
|
|
1038
|
+
const ownModels = /* @__PURE__ */ new WeakSet();
|
|
1039
|
+
const awaitingAnswer = /* @__PURE__ */ new Map();
|
|
1040
|
+
const answered = /* @__PURE__ */ new WeakSet();
|
|
1041
|
+
let catchingUpThrough;
|
|
1042
|
+
const deletedWhileAwaited = /* @__PURE__ */ new Set();
|
|
1043
|
+
const heldChanges = /* @__PURE__ */ new WeakMap();
|
|
1044
|
+
const changesToSend = /* @__PURE__ */ new WeakMap();
|
|
1045
|
+
const noteChangeToSend = (model, change) => {
|
|
1046
|
+
const toSend = changesToSend.get(model);
|
|
1047
|
+
if (toSend) toSend.add(change);
|
|
1048
|
+
else changesToSend.set(model, /* @__PURE__ */ new Set([change]));
|
|
1049
|
+
};
|
|
1050
|
+
const confirming = /* @__PURE__ */ new Map();
|
|
1051
|
+
const endConfirmation = (id) => {
|
|
1052
|
+
const confirmation = confirming.get(id);
|
|
1053
|
+
confirming.delete(id);
|
|
1054
|
+
return confirmation;
|
|
1055
|
+
};
|
|
1056
|
+
const knownValues = /* @__PURE__ */ new WeakMap();
|
|
1057
|
+
const askedAfterOutage = /* @__PURE__ */ new Map();
|
|
1058
|
+
let roundEnd;
|
|
1059
|
+
let guardEnds = [];
|
|
1060
|
+
let keptOut = /* @__PURE__ */ new WeakMap();
|
|
1061
|
+
const answerMayFollow = /* @__PURE__ */ new Map();
|
|
1062
|
+
let lastHeardBeforeOutage = 0;
|
|
1063
|
+
let disconnected = false;
|
|
1064
|
+
const hasOwn = (id) => models.value.some((m) => m.id === id && ownModels.has(m));
|
|
1065
|
+
const onChannel = ownOnChannel.get(name);
|
|
1066
|
+
if (onChannel) onChannel.add(hasOwn);
|
|
1067
|
+
else ownOnChannel.set(name, /* @__PURE__ */ new Set([hasOwn]));
|
|
1068
|
+
const guard = (end) => {
|
|
1069
|
+
guardEnds.push(end);
|
|
1070
|
+
};
|
|
1071
|
+
const guards = guardsOnChannel.get(name);
|
|
1072
|
+
if (guards) guards.add(guard);
|
|
1073
|
+
else guardsOnChannel.set(name, /* @__PURE__ */ new Set([guard]));
|
|
1074
|
+
const askFor = (colibri, model) => {
|
|
1075
|
+
awaitingAnswer.set(model.id, colibri);
|
|
1076
|
+
colibri.sendMessage(
|
|
1077
|
+
name,
|
|
1078
|
+
"model::request",
|
|
1079
|
+
answered.has(model) ? { id: model.id, again: true } : { id: model.id }
|
|
1080
|
+
);
|
|
1081
|
+
};
|
|
1082
|
+
const sendAfresh = (colibri, model) => {
|
|
1083
|
+
colibri.sendMessage(name, "model::request", { id: model.id });
|
|
1084
|
+
afresh.set(model.id, Date.now());
|
|
1085
|
+
answered.add(model);
|
|
1086
|
+
releaseHeldChanges(model);
|
|
1087
|
+
sendUpdate(colibri, model, toJsonOf(model));
|
|
1088
|
+
};
|
|
1089
|
+
const catchUpOnceAnswered = () => {
|
|
1090
|
+
if (!catchingUpThrough || awaitingAnswer.size > 0) return false;
|
|
1091
|
+
const colibri = catchingUpThrough;
|
|
1092
|
+
catchingUpThrough = void 0;
|
|
1093
|
+
colibri.sendMessage(name, "model::request");
|
|
1094
|
+
guardFrom(colibri);
|
|
1095
|
+
return true;
|
|
1096
|
+
};
|
|
1097
|
+
const guardFrom = (colibri) => {
|
|
1098
|
+
const end = askForEnd(colibri);
|
|
1099
|
+
for (const guardOnChannel of guardsOnChannel.get(name) ?? []) guardOnChannel(end);
|
|
1100
|
+
};
|
|
1101
|
+
const keepOut = (model, update) => {
|
|
1102
|
+
const end = guardEnds.at(-1);
|
|
1103
|
+
if (end === void 0) return;
|
|
1104
|
+
let kept = keptOut.get(model);
|
|
1105
|
+
if (!kept) keptOut.set(model, kept = /* @__PURE__ */ new Map());
|
|
1106
|
+
for (const key of Object.keys(update)) if (key !== "id") kept.set(key, end);
|
|
1107
|
+
};
|
|
1108
|
+
const keptOutOf = (model) => [...keptOut.get(model) ?? []].filter(([, end]) => guardEnds.includes(end)).map(([key]) => key);
|
|
1109
|
+
const endGuard = (end) => {
|
|
1110
|
+
guardEnds = end === void 0 ? [] : guardEnds.slice(guardEnds.indexOf(end) + 1);
|
|
1111
|
+
if (guardEnds.length > 0) return;
|
|
1112
|
+
keptOut = /* @__PURE__ */ new WeakMap();
|
|
1113
|
+
answerMayFollow.clear();
|
|
1114
|
+
};
|
|
1115
|
+
withColibri((colibri) => {
|
|
1116
|
+
catchingUpThrough = colibri;
|
|
1117
|
+
setTimeout(catchUpOnceAnswered, 0);
|
|
1118
|
+
onColibriDisconnected(colibri, () => {
|
|
1119
|
+
disconnected = true;
|
|
1120
|
+
endGuard();
|
|
1121
|
+
if (askedAfterOutage.size === 0) lastHeardBeforeOutage = lastHeardFrom(colibri) ?? Date.now();
|
|
1122
|
+
const since = (lastHeardFrom(colibri) ?? Date.now()) - 1e3;
|
|
1123
|
+
for (const [id, at] of deletedHere) {
|
|
1124
|
+
if (at >= since) colibri.sendMessage(name, "model::delete", { id });
|
|
1125
|
+
}
|
|
755
1126
|
});
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1127
|
+
onColibriReconnected(colibri, () => {
|
|
1128
|
+
disconnected = false;
|
|
1129
|
+
awaitingAnswer.clear();
|
|
1130
|
+
deletedWhileAwaited.clear();
|
|
1131
|
+
askedAfterOutage.clear();
|
|
1132
|
+
afresh.clear();
|
|
1133
|
+
for (const id of [...confirming.keys()]) {
|
|
1134
|
+
const confirmation = endConfirmation(id);
|
|
1135
|
+
const model = models.value.find((m) => m.id === id);
|
|
1136
|
+
if (confirmation && model && ownModels.has(model)) holdChanges(model, confirmation.props);
|
|
1137
|
+
}
|
|
1138
|
+
catchingUpThrough = colibri;
|
|
1139
|
+
for (const model of models.value) {
|
|
1140
|
+
if (!ownModels.has(model)) continue;
|
|
1141
|
+
if (answered.has(model)) askedAfterOutage.set(model.id, { shown: /* @__PURE__ */ new Map(), lost: /* @__PURE__ */ new Set() });
|
|
1142
|
+
askFor(colibri, model);
|
|
1143
|
+
}
|
|
1144
|
+
roundEnd = askedAfterOutage.size > 0 ? askForEnd(colibri) : void 0;
|
|
1145
|
+
catchUpOnceAnswered();
|
|
1146
|
+
});
|
|
1147
|
+
});
|
|
1148
|
+
RegisterChannel(name, (payload) => {
|
|
1149
|
+
if (payload.command === "model::update") {
|
|
1150
|
+
onUpdate(payload.payload);
|
|
1151
|
+
} else if (payload.command === "model::delete") {
|
|
1152
|
+
onDelete(payload.payload.id);
|
|
1153
|
+
} else {
|
|
1154
|
+
console.error(`Unknown model command: ${payload.command}`);
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
RegisterChannel(END_CHANNEL, (message) => {
|
|
1158
|
+
if (message.command !== "model::update") return;
|
|
1159
|
+
const id = message.payload?.id;
|
|
1160
|
+
if (typeof id !== "string") return;
|
|
1161
|
+
if (id === roundEnd) endRound();
|
|
1162
|
+
if (guardEnds.includes(id)) endGuard(id);
|
|
1163
|
+
const confirmed = [...confirming].find(([, confirmation]) => confirmation.end === id);
|
|
1164
|
+
if (confirmed) endWait(confirmed[0]);
|
|
1165
|
+
});
|
|
1166
|
+
const onUpdate = (modelData) => {
|
|
1167
|
+
const model = models.value.find((m) => m.id === modelData.id);
|
|
1168
|
+
const id = modelData.id;
|
|
1169
|
+
const afreshSince = id === void 0 ? void 0 : afresh.get(id);
|
|
1170
|
+
if (id !== void 0 && afreshSince !== void 0) {
|
|
1171
|
+
const waiting = Date.now() - afreshSince < AFRESH_ANSWER_MS;
|
|
1172
|
+
if (isBare(modelData) || !waiting) afresh.delete(id);
|
|
1173
|
+
if (isBare(modelData) || waiting) return;
|
|
1174
|
+
}
|
|
1175
|
+
if (id !== void 0 && deletedWhileAwaited.delete(id) && !model && isBare(modelData)) return;
|
|
1176
|
+
const asker = id === void 0 ? void 0 : awaitingAnswer.get(id);
|
|
1177
|
+
if (id !== void 0 && asker) {
|
|
1178
|
+
takeAnswer(id, asker, model, modelData);
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
if (!model && id !== void 0 && isBare(modelData) && ownElsewhere(id)) return;
|
|
1182
|
+
applyUpdate(model, modelData);
|
|
1183
|
+
};
|
|
1184
|
+
const ownElsewhere = (id) => [...ownOnChannel.get(name) ?? []].some((has) => has !== hasOwn && has(id));
|
|
1185
|
+
const takeAnswer = (id, asker, model, modelData) => {
|
|
1186
|
+
if (model) answered.add(model);
|
|
1187
|
+
if (model && !ownModels.has(model)) {
|
|
1188
|
+
askedAfterOutage.delete(id);
|
|
1189
|
+
awaitingAnswer.delete(id);
|
|
1190
|
+
endConfirmation(id);
|
|
1191
|
+
if (!isBare(modelData)) applyUpdate(model, modelData);
|
|
1192
|
+
catchUpOnceAnswered();
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
if (!model || isBare(modelData)) {
|
|
1196
|
+
askedAfterOutage.delete(id);
|
|
1197
|
+
awaitingAnswer.delete(id);
|
|
1198
|
+
endConfirmation(id);
|
|
1199
|
+
if (model) {
|
|
1200
|
+
heldChanges.delete(model);
|
|
1201
|
+
sendUpdate(asker, model, toJsonOf(model));
|
|
1202
|
+
} else if (!isBare(modelData)) {
|
|
1203
|
+
applyUpdate(model, modelData);
|
|
1204
|
+
}
|
|
1205
|
+
catchUpOnceAnswered();
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
const afterOutage = askedAfterOutage.get(id);
|
|
1209
|
+
if (afterOutage) {
|
|
1210
|
+
const held2 = [...heldChanges.get(model) ?? []];
|
|
1211
|
+
for (const key of lostChanges(model, modelData, held2)) afterOutage.lost.add(key);
|
|
1212
|
+
for (const [key, value] of Object.entries(modelData)) afterOutage.shown.set(key, value);
|
|
1213
|
+
applyUpdate(model, withoutKeys(withoutChanges(modelData, model, held2), afterOutage.lost));
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
const confirmation = confirming.get(id);
|
|
1217
|
+
if (confirmation) {
|
|
1218
|
+
for (const key of confirmation.sent.keys()) {
|
|
1219
|
+
if (key in modelData) confirmation.shown.set(key, modelData[key]);
|
|
1220
|
+
}
|
|
1221
|
+
const held2 = [...heldChanges.get(model) ?? []];
|
|
1222
|
+
applyUpdate(model, withoutKeys(withoutChanges(modelData, model, held2), confirmation.sent.keys()));
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
awaitingAnswer.delete(id);
|
|
1226
|
+
const held = releaseHeldChanges(model);
|
|
1227
|
+
applyUpdate(model, withoutChanges(modelData, model, held));
|
|
1228
|
+
if (!models.value.includes(model)) {
|
|
1229
|
+
catchUpOnceAnswered();
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
if (sendOnTop(id, asker, model, modelData, held, [])) return;
|
|
1233
|
+
if (!catchUpOnceAnswered()) guardFrom(asker);
|
|
1234
|
+
const end = guardEnds.at(-1);
|
|
1235
|
+
if (end !== void 0) answerMayFollow.set(id, end);
|
|
1236
|
+
};
|
|
1237
|
+
const endRound = () => {
|
|
1238
|
+
roundEnd = void 0;
|
|
1239
|
+
const asked = [...askedAfterOutage];
|
|
1240
|
+
askedAfterOutage.clear();
|
|
1241
|
+
for (const [id, { shown, lost }] of asked) {
|
|
1242
|
+
const asker = awaitingAnswer.get(id);
|
|
1243
|
+
const model = models.value.find((m) => m.id === id);
|
|
1244
|
+
if (!asker || !model) continue;
|
|
1245
|
+
awaitingAnswer.delete(id);
|
|
1246
|
+
if (!ownModels.has(model)) continue;
|
|
1247
|
+
const held = releaseHeldChanges(model);
|
|
1248
|
+
if (lost.size > 0)
|
|
1249
|
+
remember(model, Object.fromEntries([...lost].map((key) => [key, shown.get(key)])));
|
|
1250
|
+
sendOnTop(id, asker, model, Object.fromEntries(shown), held, [...lost]);
|
|
1251
|
+
}
|
|
1252
|
+
catchUpOnceAnswered();
|
|
1253
|
+
};
|
|
1254
|
+
const sendOnTop = (id, asker, model, shown, held, lost) => {
|
|
1255
|
+
if (held.length === 0 && lost.length === 0) return false;
|
|
1256
|
+
const current = toJsonOf(model);
|
|
1257
|
+
const sent = held.length > 0 ? toJsonOf(model, held) : { id };
|
|
1258
|
+
for (const key of lost) sent[key] = current[key];
|
|
1259
|
+
sendUpdate(asker, model, sent);
|
|
1260
|
+
const differs = /* @__PURE__ */ new Map();
|
|
1261
|
+
for (const [key, value] of Object.entries(sent)) {
|
|
1262
|
+
const json = JSON.stringify(value);
|
|
1263
|
+
if (key === "id" || json === void 0) continue;
|
|
1264
|
+
if (!(key in shown) || JSON.stringify(shown[key]) !== json) differs.set(key, json);
|
|
1265
|
+
}
|
|
1266
|
+
if (differs.size === 0) return false;
|
|
1267
|
+
const replaced = /* @__PURE__ */ new Map();
|
|
1268
|
+
for (const key of differs.keys()) {
|
|
1269
|
+
replaced.set(key, key in shown ? JSON.stringify(shown[key]) : void 0);
|
|
1270
|
+
}
|
|
1271
|
+
askFor(asker, model);
|
|
1272
|
+
confirming.set(id, { sent: differs, replaced, props: held, shown: /* @__PURE__ */ new Map(), end: askForEnd(asker) });
|
|
1273
|
+
return true;
|
|
1274
|
+
};
|
|
1275
|
+
const endWait = (id) => {
|
|
1276
|
+
const confirmation = endConfirmation(id);
|
|
1277
|
+
const asker = awaitingAnswer.get(id);
|
|
1278
|
+
const model = models.value.find((m) => m.id === id);
|
|
1279
|
+
if (!confirmation || !asker || !model) return;
|
|
1280
|
+
awaitingAnswer.delete(id);
|
|
1281
|
+
const held = releaseHeldChanges(model);
|
|
1282
|
+
const theirs = { id };
|
|
1283
|
+
const again = [];
|
|
1284
|
+
for (const [key, json] of confirmation.sent) {
|
|
1285
|
+
const shown = confirmation.shown.has(key) ? JSON.stringify(confirmation.shown.get(key)) : void 0;
|
|
1286
|
+
if (shown === json) continue;
|
|
1287
|
+
if (shown === void 0 || shown === confirmation.replaced.get(key)) again.push(key);
|
|
1288
|
+
else theirs[key] = confirmation.shown.get(key);
|
|
1289
|
+
}
|
|
1290
|
+
applyUpdate(model, withoutChanges(theirs, model, held));
|
|
1291
|
+
const current = toJsonOf(model);
|
|
1292
|
+
const update = held.length > 0 ? toJsonOf(model, held) : { id };
|
|
1293
|
+
for (const key of again) update[key] = current[key];
|
|
1294
|
+
if (ownModels.has(model) && Object.keys(update).length > 1) sendUpdate(asker, model, update);
|
|
1295
|
+
catchUpOnceAnswered();
|
|
1296
|
+
};
|
|
1297
|
+
const sendUpdate = (colibri, model, update) => {
|
|
1298
|
+
colibri.sendMessage(name, "model::update", update);
|
|
1299
|
+
remember(model, update, lastHeardFrom(colibri) ?? Number.POSITIVE_INFINITY);
|
|
1300
|
+
keepOut(model, update);
|
|
1301
|
+
};
|
|
1302
|
+
const remember = (model, fields, heardAt) => {
|
|
1303
|
+
let known = knownValues.get(model);
|
|
1304
|
+
if (!known) knownValues.set(model, known = /* @__PURE__ */ new Map());
|
|
1305
|
+
const at = Date.now();
|
|
1306
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
1307
|
+
const json = JSON.stringify(field);
|
|
1308
|
+
if (key === "id" || json === void 0) continue;
|
|
1309
|
+
const value = { json, at, sent: heardAt !== void 0 };
|
|
1310
|
+
known.set(key, heardAt === void 0 ? [value] : keepKnown([...known.get(key) ?? [], value], heardAt));
|
|
1311
|
+
}
|
|
1312
|
+
};
|
|
1313
|
+
const keepKnown = (values, heardAt) => {
|
|
1314
|
+
const split = values.findIndex((v) => v.at > heardAt);
|
|
1315
|
+
if (split < 0) return values.slice(-KNOWN_VALUES_KEPT);
|
|
1316
|
+
const after = values.slice(split);
|
|
1317
|
+
const newest = after.slice(KNOWN_VALUES_KEPT).slice(-1);
|
|
1318
|
+
return [...values.slice(0, split).slice(-KNOWN_VALUES_KEPT), ...after.slice(0, KNOWN_VALUES_KEPT), ...newest];
|
|
1319
|
+
};
|
|
1320
|
+
const lostChanges = (model, modelData, held) => {
|
|
1321
|
+
const known = knownValues.get(model);
|
|
1322
|
+
if (!known) return [];
|
|
1323
|
+
const since = lastHeardBeforeOutage - KNOWN_VALUES_MS;
|
|
1324
|
+
const heldKeys = new Set(held.length > 0 ? Object.keys(toJsonOf(model, held)) : []);
|
|
1325
|
+
const current = toJsonOf(model);
|
|
1326
|
+
return Object.entries(modelData).filter(([key, value]) => {
|
|
1327
|
+
const values = known.get(key) ?? [];
|
|
1328
|
+
const last = values.at(-1);
|
|
1329
|
+
if (!last?.sent || heldKeys.has(key) || !(key in current)) return false;
|
|
1330
|
+
const json = JSON.stringify(value);
|
|
1331
|
+
const earlier = values.filter((_, i) => i + 1 < values.length && values[i + 1].at >= since);
|
|
1332
|
+
return json !== last.json && earlier.some((v) => v.json === json) && // Nothing to send when this client has what the server has anyway.
|
|
1333
|
+
JSON.stringify(current[key]) !== json;
|
|
1334
|
+
}).map(([key]) => key);
|
|
1335
|
+
};
|
|
1336
|
+
const withoutKeys = (modelData, keys) => {
|
|
1337
|
+
const drop = new Set(keys);
|
|
1338
|
+
return Object.fromEntries(Object.entries(modelData).filter(([key]) => !drop.has(key)));
|
|
1339
|
+
};
|
|
1340
|
+
const applyUpdate = (model, modelData) => {
|
|
1341
|
+
if (model) {
|
|
1342
|
+
const unsent = [...changesToSend.get(model) ?? []];
|
|
1343
|
+
const update = withoutKeys(withoutChanges(modelData, model, unsent), keptOutOf(model));
|
|
1344
|
+
if (ownModels.has(model)) remember(model, update);
|
|
1345
|
+
updateOf(model, update);
|
|
1346
|
+
models.next([...models.value]);
|
|
1347
|
+
} else if (modelData.id) {
|
|
1348
|
+
if (recentlyDeletedHere(modelData.id)) return;
|
|
1349
|
+
const newModel = new registration.type(modelData.id);
|
|
1350
|
+
newModel.deletions.subscribe(() => {
|
|
1351
|
+
deleteHere(newModel);
|
|
1352
|
+
});
|
|
1353
|
+
newModel.modelChanges.subscribe((change) => {
|
|
1354
|
+
noteChangeToSend(newModel, change);
|
|
1355
|
+
});
|
|
1356
|
+
newModel.modelChanges$.subscribe((changes) => {
|
|
1357
|
+
changesToSend.delete(newModel);
|
|
1358
|
+
const update = toJsonOf(newModel, changes);
|
|
1359
|
+
SendMessage(name, "model::update", update);
|
|
1360
|
+
keepOut(newModel, update);
|
|
1361
|
+
models.next([...models.value]);
|
|
1362
|
+
});
|
|
1363
|
+
updateOf(newModel, modelData);
|
|
1364
|
+
models.next([...models.value, newModel]);
|
|
1365
|
+
}
|
|
1366
|
+
};
|
|
1367
|
+
const holdChanges = (model, changes) => {
|
|
1368
|
+
const held = heldChanges.get(model);
|
|
1369
|
+
if (held) for (const change of changes) held.add(change);
|
|
1370
|
+
else heldChanges.set(model, new Set(changes));
|
|
1371
|
+
};
|
|
1372
|
+
const releaseHeldChanges = (model) => {
|
|
1373
|
+
const held = [...heldChanges.get(model) ?? []];
|
|
1374
|
+
heldChanges.delete(model);
|
|
1375
|
+
return held;
|
|
1376
|
+
};
|
|
1377
|
+
const withoutChanges = (modelData, model, changes) => {
|
|
1378
|
+
if (changes.length === 0) return modelData;
|
|
1379
|
+
const changed = new Set(Object.keys(toJsonOf(model, changes)).filter((key) => key !== "id"));
|
|
1380
|
+
return Object.fromEntries(Object.entries(modelData).filter(([key]) => !changed.has(key)));
|
|
1381
|
+
};
|
|
1382
|
+
const onDelete = (id) => {
|
|
1383
|
+
const model = models.value.find((m) => m.id === id);
|
|
1384
|
+
detachOf(model);
|
|
1385
|
+
forget(id, model);
|
|
1386
|
+
};
|
|
1387
|
+
const deleteHere = (model) => {
|
|
1388
|
+
if (models.value.find((m) => m.id === model.id) !== model) return;
|
|
1389
|
+
rememberDeletedHere(model.id);
|
|
1390
|
+
forget(model.id, model);
|
|
1391
|
+
withColibri((colibri) => {
|
|
1392
|
+
colibri.sendMessage(name, "model::delete", { id: model.id });
|
|
1393
|
+
});
|
|
1394
|
+
};
|
|
1395
|
+
const forget = (id, model) => {
|
|
1396
|
+
if (model) heldChanges.delete(model);
|
|
1397
|
+
askedAfterOutage.delete(id);
|
|
1398
|
+
models.next(models.value.filter((m) => m.id !== id));
|
|
1399
|
+
endConfirmation(id);
|
|
1400
|
+
const answerEnd = answerMayFollow.get(id);
|
|
1401
|
+
answerMayFollow.delete(id);
|
|
1402
|
+
if (awaitingAnswer.delete(id)) {
|
|
1403
|
+
deletedWhileAwaited.add(id);
|
|
1404
|
+
catchUpOnceAnswered();
|
|
1405
|
+
} else if (answerEnd !== void 0 && guardEnds.includes(answerEnd)) {
|
|
1406
|
+
deletedWhileAwaited.add(id);
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
const registerModel = (model) => {
|
|
1410
|
+
const listed = models.value.find((m) => m.id === model.id);
|
|
1411
|
+
if (listed === model) return;
|
|
1412
|
+
if (listed && ownModels.has(listed)) {
|
|
1413
|
+
console.warn(
|
|
1414
|
+
`Colibri: registerModel was given a second model with the id '${model.id}' on channel '${name}'. It replaces the first one, which no longer syncs.`
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
const mustHold = () => !Colibri.getInstance(false) || disconnected || awaitingAnswer.has(model.id);
|
|
1418
|
+
model.modelChanges.subscribe((change) => {
|
|
1419
|
+
if (mustHold()) holdChanges(model, [change]);
|
|
1420
|
+
else noteChangeToSend(model, change);
|
|
1421
|
+
});
|
|
1422
|
+
model.modelChanges$.subscribe({
|
|
1423
|
+
next: () => {
|
|
1424
|
+
const changes = [...changesToSend.get(model) ?? []];
|
|
1425
|
+
changesToSend.delete(model);
|
|
1426
|
+
if (changes.length > 0) {
|
|
1427
|
+
const colibri = Colibri.getInstance(false);
|
|
1428
|
+
if (!colibri || mustHold()) holdChanges(model, changes);
|
|
1429
|
+
else sendUpdate(colibri, model, toJsonOf(model, changes));
|
|
777
1430
|
}
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
};
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
1431
|
+
if (models.value.includes(model)) models.next([...models.value]);
|
|
1432
|
+
},
|
|
1433
|
+
// delete() and detach() end the stream: nothing more is sent for the model, neither held changes
|
|
1434
|
+
// nor the whole model after a reconnect.
|
|
1435
|
+
complete: () => {
|
|
1436
|
+
ownModels.delete(model);
|
|
1437
|
+
heldChanges.delete(model);
|
|
1438
|
+
changesToSend.delete(model);
|
|
1439
|
+
}
|
|
1440
|
+
});
|
|
1441
|
+
model.deletions.subscribe(() => {
|
|
1442
|
+
deleteHere(model);
|
|
1443
|
+
});
|
|
1444
|
+
const reused = recentlyDeletedHere(model.id);
|
|
1445
|
+
deletedHere.delete(model.id);
|
|
1446
|
+
ownModels.add(model);
|
|
1447
|
+
if (listed) {
|
|
1448
|
+
endConfirmation(model.id);
|
|
1449
|
+
askedAfterOutage.delete(model.id);
|
|
1450
|
+
detachOf(listed);
|
|
1451
|
+
models.next(models.value.map((m) => m === listed ? model : m));
|
|
1452
|
+
} else {
|
|
1453
|
+
models.next([...models.value, model]);
|
|
1454
|
+
}
|
|
1455
|
+
withColibri((colibri) => {
|
|
1456
|
+
if (disconnected || !ownModels.has(model)) return;
|
|
1457
|
+
if (reused) sendAfresh(colibri, model);
|
|
1458
|
+
else askFor(colibri, model);
|
|
1459
|
+
});
|
|
1460
|
+
};
|
|
1461
|
+
return [models.asObservable(), registerModel];
|
|
804
1462
|
};
|
|
805
|
-
|
|
806
|
-
import { Subject as Subject2, bufferTime, filter, map, share } from "rxjs";
|
|
807
|
-
var SyncModel = /*#__PURE__*/ function() {
|
|
808
|
-
"use strict";
|
|
809
|
-
function SyncModel(id) {
|
|
810
|
-
var _this = this;
|
|
811
|
-
_class_call_check(this, SyncModel);
|
|
812
|
-
// TODO: move to ModelSynchronization or use a much better structure or something like that?
|
|
813
|
-
this.ignoreNextChange = false;
|
|
814
|
-
this.modelChanges = new Subject2();
|
|
815
|
-
this.modelChanges$ = this.modelChanges.pipe(bufferTime(1), map(function(changes) {
|
|
816
|
-
return changes.filter(_this.uniq);
|
|
817
|
-
}), filter(function(changes) {
|
|
818
|
-
return changes.length > 0;
|
|
819
|
-
}), share());
|
|
820
|
-
this.id = id;
|
|
821
|
-
}
|
|
822
|
-
_create_class(SyncModel, [
|
|
823
|
-
{
|
|
824
|
-
key: "uniq",
|
|
825
|
-
value: function uniq(value, index, array) {
|
|
826
|
-
return array.indexOf(value) === index;
|
|
827
|
-
}
|
|
828
|
-
},
|
|
829
|
-
{
|
|
830
|
-
key: "onModelChanges",
|
|
831
|
-
value: function onModelChanges(prop) {
|
|
832
|
-
this.modelChanges.next(prop);
|
|
833
|
-
}
|
|
834
|
-
},
|
|
835
|
-
{
|
|
836
|
-
key: "delete",
|
|
837
|
-
value: function _delete() {
|
|
838
|
-
this.modelChanges.complete();
|
|
839
|
-
}
|
|
840
|
-
},
|
|
841
|
-
{
|
|
842
|
-
key: "registerSyncedProperty",
|
|
843
|
-
value: function registerSyncedProperty(name, prop) {
|
|
844
|
-
if (!this.syncedProperties) {
|
|
845
|
-
this.syncedProperties = {};
|
|
846
|
-
}
|
|
847
|
-
this.syncedProperties[name] = prop;
|
|
848
|
-
}
|
|
849
|
-
},
|
|
850
|
-
{
|
|
851
|
-
key: "update",
|
|
852
|
-
value: function update(updates) {
|
|
853
|
-
var syncedProps = Object.getPrototypeOf(this).syncedProperties;
|
|
854
|
-
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
855
|
-
try {
|
|
856
|
-
for(var _iterator = Object.keys(updates)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
|
|
857
|
-
var key = _step.value;
|
|
858
|
-
if (key !== "id") {
|
|
859
|
-
var localKey = syncedProps[key];
|
|
860
|
-
if (localKey) {
|
|
861
|
-
this[localKey] = updates[key];
|
|
862
|
-
this.ignoreNextChange = true;
|
|
863
|
-
} else {
|
|
864
|
-
console.warn("Unknown property ".concat(key, " in ").concat(this.constructor.name));
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
|
-
} catch (err) {
|
|
869
|
-
_didIteratorError = true;
|
|
870
|
-
_iteratorError = err;
|
|
871
|
-
} finally{
|
|
872
|
-
try {
|
|
873
|
-
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
874
|
-
_iterator.return();
|
|
875
|
-
}
|
|
876
|
-
} finally{
|
|
877
|
-
if (_didIteratorError) {
|
|
878
|
-
throw _iteratorError;
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
},
|
|
884
|
-
{
|
|
885
|
-
key: "toJson",
|
|
886
|
-
value: function toJson() {
|
|
887
|
-
var attributes = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
|
|
888
|
-
var json = {
|
|
889
|
-
id: this.id
|
|
890
|
-
};
|
|
891
|
-
var syncedProps = Object.getPrototypeOf(this).syncedProperties;
|
|
892
|
-
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
893
|
-
try {
|
|
894
|
-
for(var _iterator = Object.keys(syncedProps)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
|
|
895
|
-
var key = _step.value;
|
|
896
|
-
var localKey = syncedProps[key];
|
|
897
|
-
if (attributes.length === 0 || attributes.includes(localKey)) {
|
|
898
|
-
json[key] = this[localKey];
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
} catch (err) {
|
|
902
|
-
_didIteratorError = true;
|
|
903
|
-
_iteratorError = err;
|
|
904
|
-
} finally{
|
|
905
|
-
try {
|
|
906
|
-
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
907
|
-
_iterator.return();
|
|
908
|
-
}
|
|
909
|
-
} finally{
|
|
910
|
-
if (_didIteratorError) {
|
|
911
|
-
throw _iteratorError;
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
return json;
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
]);
|
|
919
|
-
return SyncModel;
|
|
920
|
-
}();
|
|
1463
|
+
|
|
921
1464
|
// src/Synced.ts
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
console.log("Set ".concat(key.toString(), " to ").concat(newVal));
|
|
941
|
-
original = newVal;
|
|
942
|
-
},
|
|
943
|
-
enumerable: true,
|
|
944
|
-
configurable: true
|
|
945
|
-
});
|
|
946
|
-
} else {
|
|
947
|
-
var originalAccessors = {
|
|
948
|
-
get: descriptor.get,
|
|
949
|
-
set: descriptor.set
|
|
950
|
-
};
|
|
951
|
-
descriptor.get = function() {
|
|
952
|
-
var ret = originalAccessors.get.call(this);
|
|
953
|
-
return ret;
|
|
954
|
-
};
|
|
955
|
-
descriptor.set = function(newval) {
|
|
956
|
-
var model = this;
|
|
957
|
-
model.modelChanges.next(String(key));
|
|
958
|
-
if (originalAccessors.set) {
|
|
959
|
-
originalAccessors.set.call(this, newval);
|
|
960
|
-
}
|
|
961
|
-
};
|
|
1465
|
+
function Synced(syncedName = "") {
|
|
1466
|
+
return function(value, context) {
|
|
1467
|
+
if (context.kind !== "accessor") {
|
|
1468
|
+
throw new Error("@Synced() must decorate an `accessor` member");
|
|
1469
|
+
}
|
|
1470
|
+
const key = String(context.name);
|
|
1471
|
+
const name = (syncedName || key).toLowerCase();
|
|
1472
|
+
context.addInitializer(function() {
|
|
1473
|
+
this.registerSyncedProperty(name, key);
|
|
1474
|
+
});
|
|
1475
|
+
return {
|
|
1476
|
+
get() {
|
|
1477
|
+
return value.get.call(this);
|
|
1478
|
+
},
|
|
1479
|
+
set(newVal) {
|
|
1480
|
+
value.set.call(this, newVal);
|
|
1481
|
+
if (!this.applyingRemoteUpdate) {
|
|
1482
|
+
this.modelChanges.next(key);
|
|
962
1483
|
}
|
|
1484
|
+
}
|
|
963
1485
|
};
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
function synced(model, values, names = {}) {
|
|
1489
|
+
for (const [key, initial] of Object.entries(values)) {
|
|
1490
|
+
if (initial === void 0) {
|
|
1491
|
+
throw new Error(`synced(): '${key}' has no start value. undefined is not JSON: use null for none.`);
|
|
1492
|
+
}
|
|
1493
|
+
if (key in model) {
|
|
1494
|
+
throw new Error(
|
|
1495
|
+
`synced(): '${key}' is already a member of ${model.constructor.name}, a synced property or one of SyncModel's. Give it another name.`
|
|
1496
|
+
);
|
|
1497
|
+
}
|
|
1498
|
+
let value = initial;
|
|
1499
|
+
model.registerSyncedProperty((names[key] || key).toLowerCase(), key);
|
|
1500
|
+
Object.defineProperty(model, key, {
|
|
1501
|
+
enumerable: true,
|
|
1502
|
+
get: () => value,
|
|
1503
|
+
set: (newValue) => {
|
|
1504
|
+
value = newValue;
|
|
1505
|
+
if (!model.applyingRemoteUpdate) model.modelChanges.next(key);
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
// src/SyncTransform.ts
|
|
1512
|
+
var _physicsId_dec, _scale_dec, _rotation_dec, _position_dec, _active_dec, _a, _init, _active, _position, _rotation, _scale, _physicsId;
|
|
1513
|
+
var SyncTransform = class extends (_a = SyncModel, _active_dec = [Synced()], _position_dec = [Synced()], _rotation_dec = [Synced()], _scale_dec = [Synced()], _physicsId_dec = [Synced()], _a) {
|
|
1514
|
+
constructor() {
|
|
1515
|
+
super(...arguments);
|
|
1516
|
+
__privateAdd(this, _active, __runInitializers(_init, 8, this, true)), __runInitializers(_init, 11, this);
|
|
1517
|
+
__privateAdd(this, _position, __runInitializers(_init, 12, this, [0, 0, 0])), __runInitializers(_init, 15, this);
|
|
1518
|
+
__privateAdd(this, _rotation, __runInitializers(_init, 16, this, [0, 0, 0, 1])), __runInitializers(_init, 19, this);
|
|
1519
|
+
__privateAdd(this, _scale, __runInitializers(_init, 20, this, [1, 1, 1])), __runInitializers(_init, 23, this);
|
|
1520
|
+
__privateAdd(this, _physicsId, __runInitializers(_init, 24, this, "")), __runInitializers(_init, 27, this);
|
|
1521
|
+
}
|
|
1522
|
+
};
|
|
1523
|
+
_init = __decoratorStart(_a);
|
|
1524
|
+
_active = new WeakMap();
|
|
1525
|
+
_position = new WeakMap();
|
|
1526
|
+
_rotation = new WeakMap();
|
|
1527
|
+
_scale = new WeakMap();
|
|
1528
|
+
_physicsId = new WeakMap();
|
|
1529
|
+
__decorateElement(_init, 4, "active", _active_dec, SyncTransform, _active);
|
|
1530
|
+
__decorateElement(_init, 4, "position", _position_dec, SyncTransform, _position);
|
|
1531
|
+
__decorateElement(_init, 4, "rotation", _rotation_dec, SyncTransform, _rotation);
|
|
1532
|
+
__decorateElement(_init, 4, "scale", _scale_dec, SyncTransform, _scale);
|
|
1533
|
+
__decorateElement(_init, 4, "physicsId", _physicsId_dec, SyncTransform, _physicsId);
|
|
1534
|
+
__decoratorMetadata(_init, SyncTransform);
|
|
1535
|
+
var RegisterSyncTransforms = (modelId = "") => RegisterModelSync({
|
|
1536
|
+
name: modelId ? `synctransform_${modelId}` : "synctransform",
|
|
1537
|
+
type: SyncTransform
|
|
1538
|
+
});
|
|
1539
|
+
export {
|
|
1540
|
+
Colibri,
|
|
1541
|
+
ColibriError,
|
|
1542
|
+
DeleteRestApi,
|
|
1543
|
+
GetRestApi,
|
|
1544
|
+
PROTOCOL_VERSION,
|
|
1545
|
+
ProtocolMismatchError,
|
|
1546
|
+
PutRestApi,
|
|
1547
|
+
RegisterChannel,
|
|
1548
|
+
RegisterModelSync,
|
|
1549
|
+
RegisterOnce,
|
|
1550
|
+
RegisterSyncTransforms,
|
|
1551
|
+
RemoteLogger,
|
|
1552
|
+
SendMessage,
|
|
1553
|
+
Sync,
|
|
1554
|
+
SyncModel,
|
|
1555
|
+
SyncTransform,
|
|
1556
|
+
Synced,
|
|
1557
|
+
UnregisterChannel,
|
|
1558
|
+
synced,
|
|
1559
|
+
toHexColor,
|
|
1560
|
+
toRgbaColor
|
|
964
1561
|
};
|
|
965
|
-
export { Colibri, GetRestApi, PutRestApi, RegisterChannel, RegisterModelSync, RegisterOnce, RemoteLogger, SendMessage, Sync, SyncModel, Synced, UnregisterChannel };
|
|
966
1562
|
//# sourceMappingURL=index.js.map
|