@mml-io/networked-dom-web-client 0.0.42

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/build/index.js ADDED
@@ -0,0 +1,519 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../networked-dom-web/build/index.js
28
+ var require_build = __commonJS({
29
+ "../networked-dom-web/build/index.js"(exports, module2) {
30
+ var __defProp2 = Object.defineProperty;
31
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
32
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
33
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
34
+ var __export = (target, all) => {
35
+ for (var name in all)
36
+ __defProp2(target, name, { get: all[name], enumerable: true });
37
+ };
38
+ var __copyProps2 = (to, from, except, desc) => {
39
+ if (from && typeof from === "object" || typeof from === "function") {
40
+ for (let key of __getOwnPropNames2(from))
41
+ if (!__hasOwnProp2.call(to, key) && key !== except)
42
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
43
+ }
44
+ return to;
45
+ };
46
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
47
+ var src_exports = {};
48
+ __export(src_exports, {
49
+ DOMSanitizer: () => DOMSanitizer,
50
+ NetworkedDOMWebsocket: () => NetworkedDOMWebsocket2,
51
+ NetworkedDOMWebsocketStatus: () => NetworkedDOMWebsocketStatus
52
+ });
53
+ module2.exports = __toCommonJS(src_exports);
54
+ var DOMSanitizer = class {
55
+ static sanitise(node) {
56
+ if (node.getAttributeNames) {
57
+ for (const attr of node.getAttributeNames()) {
58
+ if (!DOMSanitizer.IsValidAttributeName(attr)) {
59
+ node.removeAttribute(attr);
60
+ }
61
+ }
62
+ }
63
+ if (node.nodeName === "SCRIPT") {
64
+ node.innerText = "";
65
+ } else {
66
+ if (node.getAttributeNames) {
67
+ for (const attr of node.getAttributeNames()) {
68
+ if (!DOMSanitizer.shouldAcceptAttribute(attr)) {
69
+ node.removeAttribute(attr);
70
+ }
71
+ }
72
+ }
73
+ for (let i = 0; i < node.childNodes.length; i++) {
74
+ DOMSanitizer.sanitise(node.childNodes[i]);
75
+ }
76
+ }
77
+ }
78
+ static IsASCIIDigit(c) {
79
+ return c >= "0" && c <= "9";
80
+ }
81
+ static IsASCIIAlpha(c) {
82
+ return c >= "a" && c <= "z";
83
+ }
84
+ static IsValidAttributeName(characters) {
85
+ const c = characters[0];
86
+ if (!(DOMSanitizer.IsASCIIAlpha(c) || c === ":" || c === "_")) {
87
+ return false;
88
+ }
89
+ for (let i = 1; i < characters.length; i++) {
90
+ const c2 = characters[i];
91
+ if (!(DOMSanitizer.IsASCIIDigit(c2) || DOMSanitizer.IsASCIIAlpha(c2) || c2 === ":" || c2 === "_" || c2 === "-" || c2 === ".")) {
92
+ return false;
93
+ }
94
+ }
95
+ return true;
96
+ }
97
+ static shouldAcceptAttribute(attribute) {
98
+ if (!DOMSanitizer.IsValidAttributeName(attribute)) {
99
+ console.warn("Invalid attribute name", attribute);
100
+ return false;
101
+ }
102
+ return !attribute.startsWith("on");
103
+ }
104
+ };
105
+ var websocketProtocol = "networked-dom-v0.1";
106
+ var startingBackoffTimeMilliseconds = 100;
107
+ var maximumBackoffTimeMilliseconds = 1e4;
108
+ var maximumWebsocketConnectionTimeout = 5e3;
109
+ var NetworkedDOMWebsocketStatus = /* @__PURE__ */ ((NetworkedDOMWebsocketStatus2) => {
110
+ NetworkedDOMWebsocketStatus2[NetworkedDOMWebsocketStatus2["Connecting"] = 0] = "Connecting";
111
+ NetworkedDOMWebsocketStatus2[NetworkedDOMWebsocketStatus2["Connected"] = 1] = "Connected";
112
+ NetworkedDOMWebsocketStatus2[NetworkedDOMWebsocketStatus2["Reconnecting"] = 2] = "Reconnecting";
113
+ NetworkedDOMWebsocketStatus2[NetworkedDOMWebsocketStatus2["Disconnected"] = 3] = "Disconnected";
114
+ return NetworkedDOMWebsocketStatus2;
115
+ })(NetworkedDOMWebsocketStatus || {});
116
+ var NetworkedDOMWebsocket2 = class {
117
+ constructor(url, websocketFactory, parentElement, timeCallback, statusUpdateCallback) {
118
+ this.idToElement = /* @__PURE__ */ new Map();
119
+ this.elementToId = /* @__PURE__ */ new Map();
120
+ this.websocket = null;
121
+ this.currentRoot = null;
122
+ this.stopped = false;
123
+ this.backoffTime = startingBackoffTimeMilliseconds;
124
+ this.status = null;
125
+ this.url = url;
126
+ this.websocketFactory = websocketFactory;
127
+ this.parentElement = parentElement;
128
+ this.timeCallback = timeCallback || (() => {
129
+ });
130
+ this.statusUpdateCallback = statusUpdateCallback || (() => {
131
+ });
132
+ this.setStatus(
133
+ 0
134
+ /* Connecting */
135
+ );
136
+ this.startWebSocketConnectionAttempt();
137
+ }
138
+ static createWebSocket(url) {
139
+ return new WebSocket(url, [websocketProtocol]);
140
+ }
141
+ setStatus(status) {
142
+ if (this.status !== status) {
143
+ this.status = status;
144
+ this.statusUpdateCallback(status);
145
+ }
146
+ }
147
+ createWebsocketWithTimeout(timeout) {
148
+ return new Promise((resolve, reject) => {
149
+ const timeoutId = setTimeout(() => {
150
+ reject(new Error("websocket connection timed out"));
151
+ }, timeout);
152
+ const websocket = this.websocketFactory(this.url);
153
+ websocket.addEventListener("open", () => {
154
+ clearTimeout(timeoutId);
155
+ this.websocket = websocket;
156
+ websocket.addEventListener("message", (event) => {
157
+ if (websocket !== this.websocket) {
158
+ console.log("Ignoring websocket message event because it is no longer current");
159
+ websocket.close();
160
+ return;
161
+ }
162
+ this.handleIncomingWebsocketMessage(event);
163
+ });
164
+ const onWebsocketClose = async () => {
165
+ const hadContents = this.currentRoot !== null;
166
+ this.clearContents();
167
+ if (this.stopped) {
168
+ this.setStatus(
169
+ 3
170
+ /* Disconnected */
171
+ );
172
+ return;
173
+ }
174
+ if (!hadContents) {
175
+ await this.waitBackoffTime();
176
+ }
177
+ this.setStatus(
178
+ 2
179
+ /* Reconnecting */
180
+ );
181
+ this.startWebSocketConnectionAttempt();
182
+ };
183
+ websocket.addEventListener("close", (e) => {
184
+ if (websocket !== this.websocket) {
185
+ console.warn("Ignoring websocket close event because it is no longer current");
186
+ return;
187
+ }
188
+ console.log("NetworkedDOMWebsocket close", e);
189
+ onWebsocketClose();
190
+ });
191
+ websocket.addEventListener("error", (e) => {
192
+ if (websocket !== this.websocket) {
193
+ console.log("Ignoring websocket error event because it is no longer current");
194
+ return;
195
+ }
196
+ console.error("NetworkedDOMWebsocket error", e);
197
+ onWebsocketClose();
198
+ });
199
+ resolve(websocket);
200
+ });
201
+ websocket.addEventListener("error", (e) => {
202
+ clearTimeout(timeoutId);
203
+ reject(e);
204
+ });
205
+ });
206
+ }
207
+ async waitBackoffTime() {
208
+ console.warn(`Websocket connection to '${this.url}' failed: retrying in ${this.backoffTime}ms`);
209
+ await new Promise((resolve) => setTimeout(resolve, this.backoffTime));
210
+ this.backoffTime = Math.min(
211
+ // Introduce a small amount of randomness to prevent clients from retrying in lockstep
212
+ this.backoffTime * (1.5 + Math.random() * 0.5),
213
+ maximumBackoffTimeMilliseconds
214
+ );
215
+ }
216
+ async startWebSocketConnectionAttempt() {
217
+ if (this.stopped) {
218
+ return;
219
+ }
220
+ while (true) {
221
+ if (this.stopped) {
222
+ return;
223
+ }
224
+ try {
225
+ await this.createWebsocketWithTimeout(maximumWebsocketConnectionTimeout);
226
+ break;
227
+ } catch (e) {
228
+ this.setStatus(
229
+ 2
230
+ /* Reconnecting */
231
+ );
232
+ await this.waitBackoffTime();
233
+ }
234
+ }
235
+ }
236
+ handleIncomingWebsocketMessage(event) {
237
+ const messages = JSON.parse(event.data);
238
+ for (const message of messages) {
239
+ if (message.type === "error") {
240
+ console.error("Error from server", message);
241
+ } else if (message.type === "warning") {
242
+ console.warn("Warning from server", message);
243
+ } else {
244
+ if (message.documentTime) {
245
+ if (this.timeCallback) {
246
+ this.timeCallback(message.documentTime);
247
+ }
248
+ }
249
+ if (message.type === "snapshot") {
250
+ this.backoffTime = startingBackoffTimeMilliseconds;
251
+ this.setStatus(
252
+ 1
253
+ /* Connected */
254
+ );
255
+ if (this.currentRoot) {
256
+ this.currentRoot.remove();
257
+ this.currentRoot = null;
258
+ this.elementToId.clear();
259
+ this.idToElement.clear();
260
+ }
261
+ const element = this.handleNewElement(message.snapshot);
262
+ if (!element) {
263
+ throw new Error("Snapshot element not created");
264
+ }
265
+ if (!(element instanceof HTMLElement)) {
266
+ throw new Error("Snapshot element is not an HTMLElement");
267
+ }
268
+ this.currentRoot = element;
269
+ this.parentElement.append(element);
270
+ } else if (message.type === "attributeChange") {
271
+ this.handleAttributeChange(message);
272
+ } else if (message.type === "childrenChanged") {
273
+ this.handleChildrenChanged(message);
274
+ } else if (message.type === "textChanged") {
275
+ this.handleTextChanged(message);
276
+ } else if (message.type === "ping") {
277
+ this.send({
278
+ type: "pong",
279
+ pong: message.ping
280
+ });
281
+ } else {
282
+ console.warn("unknown message type", message);
283
+ }
284
+ }
285
+ }
286
+ }
287
+ stop() {
288
+ this.stopped = true;
289
+ if (this.websocket !== null) {
290
+ this.websocket.close();
291
+ this.websocket = null;
292
+ }
293
+ }
294
+ handleEvent(element, event) {
295
+ const nodeId = this.elementToId.get(element);
296
+ if (nodeId === void 0 || nodeId === null) {
297
+ throw new Error("Element not found");
298
+ }
299
+ console.log(
300
+ `Sending event to websocket: "${event.type}" on node: ${nodeId} type: ${element.tagName}`
301
+ );
302
+ const detailWithoutElement = {
303
+ ...event.detail
304
+ };
305
+ delete detailWithoutElement.element;
306
+ const remoteEvent = {
307
+ type: "event",
308
+ nodeId,
309
+ name: event.type,
310
+ bubbles: event.bubbles,
311
+ params: detailWithoutElement
312
+ };
313
+ this.send(remoteEvent);
314
+ }
315
+ send(fromClientMessage) {
316
+ if (!this.websocket) {
317
+ throw new Error("No websocket created");
318
+ }
319
+ this.websocket.send(JSON.stringify(fromClientMessage));
320
+ }
321
+ handleTextChanged(message) {
322
+ const { nodeId, text } = message;
323
+ if (nodeId === void 0 || nodeId === null) {
324
+ console.warn("No nodeId in textChanged message");
325
+ return;
326
+ }
327
+ const node = this.idToElement.get(nodeId);
328
+ if (!node) {
329
+ throw new Error("No node found for textChanged message");
330
+ }
331
+ if (!(node instanceof Text)) {
332
+ throw new Error("Node for textChanged message is not a Text node");
333
+ }
334
+ node.textContent = text;
335
+ }
336
+ handleChildrenChanged(message) {
337
+ const { nodeId, addedNodes, removedNodes, previousNodeId } = message;
338
+ if (nodeId === void 0 || nodeId === null) {
339
+ console.warn("No nodeId in childrenChanged message");
340
+ return;
341
+ }
342
+ const parent = this.idToElement.get(nodeId);
343
+ if (!parent) {
344
+ throw new Error("No parent found for childrenChanged message");
345
+ }
346
+ if (!parent.isConnected) {
347
+ console.error("Parent is not connected", parent);
348
+ }
349
+ if (!(parent instanceof HTMLElement)) {
350
+ throw new Error("Parent is not an HTMLElement (that supports children)");
351
+ }
352
+ let previousElement;
353
+ if (previousNodeId) {
354
+ previousElement = this.idToElement.get(previousNodeId);
355
+ if (!previousElement) {
356
+ throw new Error("No previous element found for childrenChanged message");
357
+ }
358
+ }
359
+ for (const addedNode of addedNodes) {
360
+ const childElement = this.handleNewElement(addedNode);
361
+ if (childElement) {
362
+ if (previousElement) {
363
+ const nextElement = previousElement.nextSibling;
364
+ if (nextElement) {
365
+ parent.insertBefore(childElement, nextElement);
366
+ } else {
367
+ parent.append(childElement);
368
+ }
369
+ } else {
370
+ parent.append(childElement);
371
+ }
372
+ }
373
+ }
374
+ for (const removedNode of removedNodes) {
375
+ const childElement = this.idToElement.get(removedNode);
376
+ if (!childElement) {
377
+ throw new Error(`Child element not found: ${removedNode}`);
378
+ }
379
+ this.elementToId.delete(childElement);
380
+ this.idToElement.delete(removedNode);
381
+ parent.removeChild(childElement);
382
+ if (childElement instanceof HTMLElement) {
383
+ this.removeChildElementIds(childElement);
384
+ }
385
+ }
386
+ }
387
+ removeChildElementIds(parent) {
388
+ for (let i = 0; i < parent.children.length; i++) {
389
+ const child = parent.children[i];
390
+ const childId = this.elementToId.get(child);
391
+ if (!childId) {
392
+ console.error("Inner child of removed element had no id", child);
393
+ } else {
394
+ this.elementToId.delete(child);
395
+ this.idToElement.delete(childId);
396
+ }
397
+ this.removeChildElementIds(child);
398
+ }
399
+ }
400
+ handleAttributeChange(message) {
401
+ const { nodeId, attribute, newValue } = message;
402
+ if (nodeId === void 0 || nodeId === null) {
403
+ console.warn("No nodeId in attributeChange message");
404
+ return;
405
+ }
406
+ const element = this.idToElement.get(nodeId);
407
+ if (element) {
408
+ if (element instanceof HTMLElement) {
409
+ if (newValue === null) {
410
+ element.removeAttribute(attribute);
411
+ } else {
412
+ if (DOMSanitizer.shouldAcceptAttribute(attribute)) {
413
+ element.setAttribute(attribute, newValue);
414
+ }
415
+ }
416
+ } else {
417
+ console.error("Element is not an HTMLElement and cannot support attributes", element);
418
+ }
419
+ } else {
420
+ console.error("No element found for attributeChange message");
421
+ }
422
+ }
423
+ handleNewElement(message) {
424
+ if (message.type === "text") {
425
+ const { nodeId: nodeId2, text: text2 } = message;
426
+ const textNode = document.createTextNode("");
427
+ textNode.textContent = text2;
428
+ this.idToElement.set(nodeId2, textNode);
429
+ this.elementToId.set(textNode, nodeId2);
430
+ return textNode;
431
+ }
432
+ const { tag, nodeId, attributes, children, text } = message;
433
+ if (nodeId === void 0 || nodeId === null) {
434
+ console.warn("No nodeId in handleNewElement message", message);
435
+ return null;
436
+ }
437
+ if (this.idToElement.has(nodeId)) {
438
+ console.error(
439
+ "Received nodeId to add that is already present",
440
+ nodeId,
441
+ this.idToElement.get(nodeId)
442
+ );
443
+ }
444
+ if (tag === "#text") {
445
+ const textNode = document.createTextNode("");
446
+ textNode.textContent = text || null;
447
+ this.idToElement.set(nodeId, textNode);
448
+ this.elementToId.set(textNode, nodeId);
449
+ return textNode;
450
+ }
451
+ const element = document.createElement(tag);
452
+ this.idToElement.set(nodeId, element);
453
+ this.elementToId.set(element, nodeId);
454
+ for (const key in attributes) {
455
+ if (DOMSanitizer.shouldAcceptAttribute(key)) {
456
+ const value = attributes[key];
457
+ element.setAttribute(key, value);
458
+ }
459
+ }
460
+ if (children) {
461
+ for (const child of children) {
462
+ const childElement = this.handleNewElement(child);
463
+ if (childElement) {
464
+ element.append(childElement);
465
+ }
466
+ }
467
+ }
468
+ return element;
469
+ }
470
+ clearContents() {
471
+ this.idToElement.clear();
472
+ this.elementToId.clear();
473
+ if (this.currentRoot) {
474
+ this.currentRoot.remove();
475
+ this.currentRoot = null;
476
+ }
477
+ }
478
+ };
479
+ }
480
+ });
481
+
482
+ // src/index.ts
483
+ var import_networked_dom_web = __toESM(require_build());
484
+ var thisScript = document.currentScript;
485
+ var scriptUrl = new URL(thisScript.src);
486
+ (function() {
487
+ const websocketUrl = scriptUrl.searchParams.get("websocketUrl");
488
+ if (!websocketUrl) {
489
+ console.error("websocketUrl not set");
490
+ return;
491
+ }
492
+ window.addEventListener("load", () => {
493
+ const documentWebsocketUrls = websocketUrl.split(",");
494
+ for (const documentWebsocketUrl of documentWebsocketUrls) {
495
+ let overriddenHandler = null;
496
+ const eventHandler = (element, event) => {
497
+ if (!overriddenHandler) {
498
+ throw new Error("overriddenHandler not set");
499
+ }
500
+ overriddenHandler(element, event);
501
+ };
502
+ const remoteDocumentHolder = document.createElement("div");
503
+ document.body.append(remoteDocumentHolder);
504
+ remoteDocumentHolder.addEventListener("click", (event) => {
505
+ eventHandler(event.target, event);
506
+ return false;
507
+ });
508
+ const websocket = new import_networked_dom_web.NetworkedDOMWebsocket(
509
+ documentWebsocketUrl,
510
+ import_networked_dom_web.NetworkedDOMWebsocket.createWebSocket,
511
+ remoteDocumentHolder
512
+ );
513
+ overriddenHandler = (element, event) => {
514
+ websocket.handleEvent(element, event);
515
+ };
516
+ }
517
+ });
518
+ })();
519
+ //# sourceMappingURL=/index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../networked-dom-web/src/index.ts", "../../networked-dom-web/src/DOMSanitizer.ts", "../../networked-dom-web/src/NetworkedDOMWebsocket.ts", "../src/index.ts"],
4
+ "sourcesContent": ["export * from \"./NetworkedDOMWebsocket\";\nexport * from \"./DOMSanitizer\";\n", "export class DOMSanitizer {\n static sanitise(node: HTMLElement) {\n if (node.getAttributeNames) {\n for (const attr of node.getAttributeNames()) {\n if (!DOMSanitizer.IsValidAttributeName(attr)) {\n node.removeAttribute(attr);\n }\n }\n }\n if (node.nodeName === \"SCRIPT\") {\n // set text to empty string\n node.innerText = \"\";\n } else {\n if (node.getAttributeNames) {\n for (const attr of node.getAttributeNames()) {\n if (!DOMSanitizer.shouldAcceptAttribute(attr)) {\n node.removeAttribute(attr);\n }\n }\n }\n for (let i = 0; i < node.childNodes.length; i++) {\n DOMSanitizer.sanitise(node.childNodes[i] as HTMLElement);\n }\n }\n }\n\n static IsASCIIDigit(c: string): boolean {\n return c >= \"0\" && c <= \"9\";\n }\n\n static IsASCIIAlpha(c: string) {\n return c >= \"a\" && c <= \"z\";\n }\n\n static IsValidAttributeName(characters: string): boolean {\n const c = characters[0];\n if (!(DOMSanitizer.IsASCIIAlpha(c) || c === \":\" || c === \"_\")) {\n return false;\n }\n\n for (let i = 1; i < characters.length; i++) {\n const c = characters[i];\n if (\n !(\n DOMSanitizer.IsASCIIDigit(c) ||\n DOMSanitizer.IsASCIIAlpha(c) ||\n c === \":\" ||\n c === \"_\" ||\n c === \"-\" ||\n c === \".\"\n )\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n static shouldAcceptAttribute(attribute: string) {\n if (!DOMSanitizer.IsValidAttributeName(attribute)) {\n console.warn(\"Invalid attribute name\", attribute);\n return false;\n }\n\n // TODO - this might be overly restrictive - apologies to someone that finds this because you have a non-event attribute filtered by this\n return !attribute.startsWith(\"on\");\n }\n}\n", "import {\n AttributeChangedDiff,\n ChildrenChangedDiff,\n ClientMessage,\n NodeDescription,\n RemoteEvent,\n ServerMessage,\n TextChangedDiff,\n} from \"@mml-io/networked-dom-protocol\";\n\nimport { DOMSanitizer } from \"./DOMSanitizer\";\n\nconst websocketProtocol = \"networked-dom-v0.1\";\n\nconst startingBackoffTimeMilliseconds = 100;\nconst maximumBackoffTimeMilliseconds = 10000;\nconst maximumWebsocketConnectionTimeout = 5000;\n\nexport type NetworkedDOMWebsocketFactory = (url: string) => WebSocket;\n\nexport enum NetworkedDOMWebsocketStatus {\n Connecting,\n Connected,\n Reconnecting,\n Disconnected,\n}\n\nexport class NetworkedDOMWebsocket {\n private idToElement = new Map<number, Node>();\n private elementToId = new Map<Node, number>();\n private websocket: WebSocket | null = null;\n private currentRoot: HTMLElement | null = null;\n\n private url: string;\n private websocketFactory: NetworkedDOMWebsocketFactory;\n private parentElement: HTMLElement;\n private timeCallback: (time: number) => void;\n private statusUpdateCallback: (status: NetworkedDOMWebsocketStatus) => void;\n private stopped = false;\n private backoffTime = startingBackoffTimeMilliseconds;\n private status: NetworkedDOMWebsocketStatus | null = null;\n\n public static createWebSocket(url: string): WebSocket {\n return new WebSocket(url, [websocketProtocol]);\n }\n\n constructor(\n url: string,\n websocketFactory: NetworkedDOMWebsocketFactory,\n parentElement: HTMLElement,\n timeCallback?: (time: number) => void,\n statusUpdateCallback?: (status: NetworkedDOMWebsocketStatus) => void,\n ) {\n this.url = url;\n this.websocketFactory = websocketFactory;\n this.parentElement = parentElement;\n this.timeCallback =\n timeCallback ||\n (() => {\n // no-op\n });\n this.statusUpdateCallback =\n statusUpdateCallback ||\n (() => {\n // no-op\n });\n this.setStatus(NetworkedDOMWebsocketStatus.Connecting);\n this.startWebSocketConnectionAttempt();\n }\n\n private setStatus(status: NetworkedDOMWebsocketStatus) {\n if (this.status !== status) {\n this.status = status;\n this.statusUpdateCallback(status);\n }\n }\n\n private createWebsocketWithTimeout(timeout: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"websocket connection timed out\"));\n }, timeout);\n const websocket = this.websocketFactory(this.url);\n websocket.addEventListener(\"open\", () => {\n clearTimeout(timeoutId);\n\n this.websocket = websocket;\n\n websocket.addEventListener(\"message\", (event) => {\n if (websocket !== this.websocket) {\n console.log(\"Ignoring websocket message event because it is no longer current\");\n websocket.close();\n return;\n }\n this.handleIncomingWebsocketMessage(event);\n });\n\n const onWebsocketClose = async () => {\n const hadContents = this.currentRoot !== null;\n this.clearContents();\n if (this.stopped) {\n // This closing is expected. The client closed the websocket.\n this.setStatus(NetworkedDOMWebsocketStatus.Disconnected);\n return;\n }\n if (!hadContents) {\n // The websocket did not deliver any contents. It may have been successfully opened, but immediately closed. This client should back off to prevent this happening in a rapid loop.\n await this.waitBackoffTime();\n }\n // The websocket closed unexpectedly. Try to reconnect.\n this.setStatus(NetworkedDOMWebsocketStatus.Reconnecting);\n this.startWebSocketConnectionAttempt();\n };\n\n websocket.addEventListener(\"close\", (e) => {\n if (websocket !== this.websocket) {\n console.warn(\"Ignoring websocket close event because it is no longer current\");\n return;\n }\n console.log(\"NetworkedDOMWebsocket close\", e);\n onWebsocketClose();\n });\n websocket.addEventListener(\"error\", (e) => {\n if (websocket !== this.websocket) {\n console.log(\"Ignoring websocket error event because it is no longer current\");\n return;\n }\n console.error(\"NetworkedDOMWebsocket error\", e);\n onWebsocketClose();\n });\n\n resolve(websocket);\n });\n websocket.addEventListener(\"error\", (e) => {\n clearTimeout(timeoutId);\n reject(e);\n });\n });\n }\n\n private async waitBackoffTime(): Promise<void> {\n console.warn(`Websocket connection to '${this.url}' failed: retrying in ${this.backoffTime}ms`);\n await new Promise((resolve) => setTimeout(resolve, this.backoffTime));\n this.backoffTime = Math.min(\n // Introduce a small amount of randomness to prevent clients from retrying in lockstep\n this.backoffTime * (1.5 + Math.random() * 0.5),\n maximumBackoffTimeMilliseconds,\n );\n }\n\n private async startWebSocketConnectionAttempt() {\n if (this.stopped) {\n return;\n }\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (this.stopped) {\n return;\n }\n try {\n await this.createWebsocketWithTimeout(maximumWebsocketConnectionTimeout);\n break;\n } catch (e) {\n // Connection failed, retry with backoff\n this.setStatus(NetworkedDOMWebsocketStatus.Reconnecting);\n await this.waitBackoffTime();\n }\n }\n }\n\n private handleIncomingWebsocketMessage(event: MessageEvent) {\n const messages = JSON.parse(event.data) as Array<ServerMessage>;\n for (const message of messages) {\n if (message.type === \"error\") {\n console.error(\"Error from server\", message);\n } else if (message.type === \"warning\") {\n console.warn(\"Warning from server\", message);\n } else {\n if (message.documentTime) {\n if (this.timeCallback) {\n this.timeCallback(message.documentTime);\n }\n }\n if (message.type === \"snapshot\") {\n // This websocket is successfully connected. Reset the backoff time.\n this.backoffTime = startingBackoffTimeMilliseconds;\n this.setStatus(NetworkedDOMWebsocketStatus.Connected);\n\n if (this.currentRoot) {\n this.currentRoot.remove();\n this.currentRoot = null;\n this.elementToId.clear();\n this.idToElement.clear();\n }\n\n // create a tree of DOM elements\n // NOTE: the MLElement contructors are not executed during this stage\n const element = this.handleNewElement(message.snapshot);\n if (!element) {\n throw new Error(\"Snapshot element not created\");\n }\n if (!(element instanceof HTMLElement)) {\n throw new Error(\"Snapshot element is not an HTMLElement\");\n }\n this.currentRoot = element;\n // appending to the tree causes MElements to be constructed\n this.parentElement.append(element);\n } else if (message.type === \"attributeChange\") {\n this.handleAttributeChange(message);\n } else if (message.type === \"childrenChanged\") {\n this.handleChildrenChanged(message);\n } else if (message.type === \"textChanged\") {\n this.handleTextChanged(message);\n } else if (message.type === \"ping\") {\n this.send({\n type: \"pong\",\n pong: message.ping,\n });\n } else {\n console.warn(\"unknown message type\", message);\n }\n }\n }\n }\n\n public stop() {\n this.stopped = true;\n if (this.websocket !== null) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n public handleEvent(element: HTMLElement, event: CustomEvent<{ element: HTMLElement }>) {\n const nodeId = this.elementToId.get(element);\n if (nodeId === undefined || nodeId === null) {\n throw new Error(\"Element not found\");\n }\n\n console.log(\n `Sending event to websocket: \"${event.type}\" on node: ${nodeId} type: ${element.tagName}`,\n );\n\n const detailWithoutElement: Partial<typeof event.detail> = {\n ...event.detail,\n };\n delete detailWithoutElement.element;\n\n const remoteEvent: RemoteEvent = {\n type: \"event\",\n nodeId,\n name: event.type,\n bubbles: event.bubbles,\n params: detailWithoutElement,\n };\n\n this.send(remoteEvent);\n }\n\n private send(fromClientMessage: ClientMessage) {\n if (!this.websocket) {\n throw new Error(\"No websocket created\");\n }\n this.websocket.send(JSON.stringify(fromClientMessage));\n }\n\n private handleTextChanged(message: TextChangedDiff) {\n const { nodeId, text } = message;\n\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in textChanged message\");\n return;\n }\n const node = this.idToElement.get(nodeId);\n if (!node) {\n throw new Error(\"No node found for textChanged message\");\n }\n if (!(node instanceof Text)) {\n throw new Error(\"Node for textChanged message is not a Text node\");\n }\n node.textContent = text;\n }\n\n private handleChildrenChanged(message: ChildrenChangedDiff) {\n const { nodeId, addedNodes, removedNodes, previousNodeId } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in childrenChanged message\");\n return;\n }\n const parent = this.idToElement.get(nodeId);\n if (!parent) {\n throw new Error(\"No parent found for childrenChanged message\");\n }\n if (!parent.isConnected) {\n console.error(\"Parent is not connected\", parent);\n }\n if (!(parent instanceof HTMLElement)) {\n throw new Error(\"Parent is not an HTMLElement (that supports children)\");\n }\n let previousElement;\n if (previousNodeId) {\n previousElement = this.idToElement.get(previousNodeId);\n if (!previousElement) {\n throw new Error(\"No previous element found for childrenChanged message\");\n }\n }\n\n for (const addedNode of addedNodes) {\n const childElement = this.handleNewElement(addedNode);\n if (childElement) {\n if (previousElement) {\n const nextElement = previousElement.nextSibling;\n if (nextElement) {\n parent.insertBefore(childElement, nextElement);\n } else {\n parent.append(childElement);\n }\n } else {\n parent.append(childElement);\n }\n }\n }\n for (const removedNode of removedNodes) {\n const childElement = this.idToElement.get(removedNode);\n if (!childElement) {\n throw new Error(`Child element not found: ${removedNode}`);\n }\n this.elementToId.delete(childElement);\n this.idToElement.delete(removedNode);\n parent.removeChild(childElement);\n if (childElement instanceof HTMLElement) {\n // If child is capable of supporting children then remove any that exist\n this.removeChildElementIds(childElement);\n }\n }\n }\n\n private removeChildElementIds(parent: HTMLElement) {\n for (let i = 0; i < parent.children.length; i++) {\n const child = parent.children[i];\n const childId = this.elementToId.get(child as HTMLElement);\n if (!childId) {\n console.error(\"Inner child of removed element had no id\", child);\n } else {\n this.elementToId.delete(child);\n this.idToElement.delete(childId);\n }\n this.removeChildElementIds(child as HTMLElement);\n }\n }\n\n private handleAttributeChange(message: AttributeChangedDiff) {\n const { nodeId, attribute, newValue } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in attributeChange message\");\n return;\n }\n const element = this.idToElement.get(nodeId);\n if (element) {\n if (element instanceof HTMLElement) {\n if (newValue === null) {\n element.removeAttribute(attribute);\n } else {\n if (DOMSanitizer.shouldAcceptAttribute(attribute)) {\n element.setAttribute(attribute, newValue);\n }\n }\n } else {\n console.error(\"Element is not an HTMLElement and cannot support attributes\", element);\n }\n } else {\n console.error(\"No element found for attributeChange message\");\n }\n }\n\n private handleNewElement(message: NodeDescription): Node | null {\n if (message.type === \"text\") {\n const { nodeId, text } = message;\n const textNode = document.createTextNode(\"\");\n textNode.textContent = text;\n this.idToElement.set(nodeId, textNode);\n this.elementToId.set(textNode, nodeId);\n return textNode;\n }\n const { tag, nodeId, attributes, children, text } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in handleNewElement message\", message);\n return null;\n }\n if (this.idToElement.has(nodeId)) {\n console.error(\n \"Received nodeId to add that is already present\",\n nodeId,\n this.idToElement.get(nodeId),\n );\n }\n if (tag === \"#text\") {\n const textNode = document.createTextNode(\"\");\n textNode.textContent = text || null;\n this.idToElement.set(nodeId, textNode);\n this.elementToId.set(textNode, nodeId);\n return textNode;\n }\n\n const element = document.createElement(tag);\n this.idToElement.set(nodeId, element);\n this.elementToId.set(element, nodeId);\n for (const key in attributes) {\n if (DOMSanitizer.shouldAcceptAttribute(key)) {\n const value = attributes[key];\n element.setAttribute(key, value);\n }\n }\n if (children) {\n for (const child of children) {\n const childElement = this.handleNewElement(child);\n if (childElement) {\n element.append(childElement);\n }\n }\n }\n return element;\n }\n\n private clearContents() {\n this.idToElement.clear();\n this.elementToId.clear();\n if (this.currentRoot) {\n this.currentRoot.remove();\n this.currentRoot = null;\n }\n }\n}\n", "import { NetworkedDOMWebsocket } from \"@mml-io/networked-dom-web\";\n\nconst thisScript = document.currentScript as HTMLScriptElement;\nconst scriptUrl = new URL(thisScript.src);\n\n(function () {\n const websocketUrl = scriptUrl.searchParams.get(\"websocketUrl\");\n if (!websocketUrl) {\n console.error(\"websocketUrl not set\");\n return;\n }\n window.addEventListener(\"load\", () => {\n const documentWebsocketUrls = websocketUrl.split(\",\");\n\n for (const documentWebsocketUrl of documentWebsocketUrls) {\n let overriddenHandler: ((element: HTMLElement, event: CustomEvent) => void) | null = null;\n const eventHandler = (element: HTMLElement, event: CustomEvent) => {\n if (!overriddenHandler) {\n throw new Error(\"overriddenHandler not set\");\n }\n overriddenHandler(element, event);\n };\n const remoteDocumentHolder = document.createElement(\"div\");\n document.body.append(remoteDocumentHolder);\n\n remoteDocumentHolder.addEventListener(\"click\", (event: Event) => {\n eventHandler(event.target as HTMLElement, event as CustomEvent);\n return false;\n });\n\n const websocket = new NetworkedDOMWebsocket(\n documentWebsocketUrl,\n NetworkedDOMWebsocket.createWebSocket,\n remoteDocumentHolder,\n );\n overriddenHandler = (element: HTMLElement, event: CustomEvent) => {\n websocket.handleEvent(element, event);\n };\n }\n });\n})();\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,QAAA,cAAA,CAAA;AAAA,aAAA,aAAA;MAAA,cAAA,MAAA;MAAA,uBAAA,MAAAA;MAAA,6BAAA,MAAA;IAAA,CAAA;AAAA,IAAAC,QAAA,UAAA,aAAA,WAAA;ACAO,QAAM,eAAN,MAAmB;MACxB,OAAO,SAAS,MAAmB;AACjC,YAAI,KAAK,mBAAmB;AAC1B,qBAAW,QAAQ,KAAK,kBAAkB,GAAG;AAC3C,gBAAI,CAAC,aAAa,qBAAqB,IAAI,GAAG;AAC5C,mBAAK,gBAAgB,IAAI;YAC3B;UACF;QACF;AACA,YAAI,KAAK,aAAa,UAAU;AAE9B,eAAK,YAAY;QACnB,OAAO;AACL,cAAI,KAAK,mBAAmB;AAC1B,uBAAW,QAAQ,KAAK,kBAAkB,GAAG;AAC3C,kBAAI,CAAC,aAAa,sBAAsB,IAAI,GAAG;AAC7C,qBAAK,gBAAgB,IAAI;cAC3B;YACF;UACF;AACA,mBAAS,IAAI,GAAG,IAAI,KAAK,WAAW,QAAQ,KAAK;AAC/C,yBAAa,SAAS,KAAK,WAAW,CAAC,CAAgB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;QACrB;MACF;IACF;;;;;AChbA,+BAAsC;AAEtC,IAAM,aAAa,SAAS;AAC5B,IAAM,YAAY,IAAI,IAAI,WAAW,GAAG;AAAA,CAEvC,WAAY;AACX,QAAM,eAAe,UAAU,aAAa,IAAI,cAAc;AAC9D,MAAI,CAAC,cAAc;AACjB,YAAQ,MAAM,sBAAsB;AACpC;AAAA,EACF;AACA,SAAO,iBAAiB,QAAQ,MAAM;AACpC,UAAM,wBAAwB,aAAa,MAAM,GAAG;AAEpD,eAAW,wBAAwB,uBAAuB;AACxD,UAAI,oBAAiF;AACrF,YAAM,eAAe,CAAC,SAAsB,UAAuB;AACjE,YAAI,CAAC,mBAAmB;AACtB,gBAAM,IAAI,MAAM,2BAA2B;AAAA,QAC7C;AACA,0BAAkB,SAAS,KAAK;AAAA,MAClC;AACA,YAAM,uBAAuB,SAAS,cAAc,KAAK;AACzD,eAAS,KAAK,OAAO,oBAAoB;AAEzC,2BAAqB,iBAAiB,SAAS,CAAC,UAAiB;AAC/D,qBAAa,MAAM,QAAuB,KAAoB;AAC9D,eAAO;AAAA,MACT,CAAC;AAED,YAAM,YAAY,IAAI;AAAA,QACpB;AAAA,QACA,+CAAsB;AAAA,QACtB;AAAA,MACF;AACA,0BAAoB,CAAC,SAAsB,UAAuB;AAChE,kBAAU,YAAY,SAAS,KAAK;AAAA,MACtC;AAAA,IACF;AAAA,EACF,CAAC;AACH,GAAG;",
6
+ "names": ["NetworkedDOMWebsocket", "module", "c", "NetworkedDOMWebsocketStatus", "nodeId", "text"]
7
+ }
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@mml-io/networked-dom-web-client",
3
+ "version": "0.0.42",
4
+ "files": [
5
+ "/build",
6
+ "/src"
7
+ ],
8
+ "main": "build/index.js",
9
+ "scripts": {
10
+ "type-check": "tsc --noEmit",
11
+ "build": "node ./build.js --build",
12
+ "iterate": "cross-env PORT=28892 node ./build.js --serve",
13
+ "npm-publish": "npm run build && publish-if-not-exists --access=public",
14
+ "lint": "eslint \"./src/**/*.{js,jsx,ts,tsx}\" --max-warnings 0",
15
+ "lint-fix": "eslint \"./src/**/*.{js,jsx,ts,tsx}\" --fix"
16
+ },
17
+ "dependencies": {
18
+ "@mml-io/networked-dom-web": "^0.0.42"
19
+ }
20
+ }
package/src/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { NetworkedDOMWebsocket } from "@mml-io/networked-dom-web";
2
+
3
+ const thisScript = document.currentScript as HTMLScriptElement;
4
+ const scriptUrl = new URL(thisScript.src);
5
+
6
+ (function () {
7
+ const websocketUrl = scriptUrl.searchParams.get("websocketUrl");
8
+ if (!websocketUrl) {
9
+ console.error("websocketUrl not set");
10
+ return;
11
+ }
12
+ window.addEventListener("load", () => {
13
+ const documentWebsocketUrls = websocketUrl.split(",");
14
+
15
+ for (const documentWebsocketUrl of documentWebsocketUrls) {
16
+ let overriddenHandler: ((element: HTMLElement, event: CustomEvent) => void) | null = null;
17
+ const eventHandler = (element: HTMLElement, event: CustomEvent) => {
18
+ if (!overriddenHandler) {
19
+ throw new Error("overriddenHandler not set");
20
+ }
21
+ overriddenHandler(element, event);
22
+ };
23
+ const remoteDocumentHolder = document.createElement("div");
24
+ document.body.append(remoteDocumentHolder);
25
+
26
+ remoteDocumentHolder.addEventListener("click", (event: Event) => {
27
+ eventHandler(event.target as HTMLElement, event as CustomEvent);
28
+ return false;
29
+ });
30
+
31
+ const websocket = new NetworkedDOMWebsocket(
32
+ documentWebsocketUrl,
33
+ NetworkedDOMWebsocket.createWebSocket,
34
+ remoteDocumentHolder,
35
+ );
36
+ overriddenHandler = (element: HTMLElement, event: CustomEvent) => {
37
+ websocket.handleEvent(element, event);
38
+ };
39
+ }
40
+ });
41
+ })();