easel-canvas 0.4.0 → 0.6.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.
@@ -0,0 +1,168 @@
1
+ // AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
2
+ // What a live-share guest may ask, and the answers. Guest requests never go through the app's HTTP routes: each allowed request is
3
+ // answered here, in process, by a handler written for guests (local paths and owner-only fields left out, the guest's name and
4
+ // role decided by the owner's side). Anything not in GUEST_ROUTES or the static rules is 403 and no app code runs for it.
5
+ // Every app route must be classified in inventory.mjs (a test fails when a new route is not).
6
+ import fs from "node:fs/promises";
7
+ import path from "node:path";
8
+
9
+ import { MIME, injectProbe, safeJoin } from "../index.mjs";
10
+ import { readComments, writeComments } from "../routes.mjs";
11
+
12
+ const enc = new TextEncoder();
13
+ const json = (status, body) => ({ status, type: MIME[".json"], body: enc.encode(JSON.stringify(body)) });
14
+ const deny = (status = 403, why = "not allowed") => json(status, { error: why });
15
+ /** The largest file a guest is sent */
16
+ export const MAX_FILE = 32 * 1024 * 1024;
17
+ /** Comment text and reply length */
18
+ export const MAX_TEXT = 4000;
19
+ const ROLE_RANK = { view: 1, comment: 2 };
20
+ /** Files at the design folder's root that guests get through the API only (filtered), never as files */
21
+ const PRIVATE_ROOT = new Set(["comments.json", "board.json"]);
22
+
23
+ /** A comment as a guest sees it: no AI request state, no addressing, nothing but what the canvas shows */
24
+ function guestComment(c) {
25
+ const out = { id: c.id, file: c.file, path: c.path ?? "", text: c.text, author: c.author, createdAt: c.createdAt, resolved: !!c.resolved };
26
+ if (c.guest) out.guest = true;
27
+ if (Array.isArray(c.replies)) out.replies = c.replies.map((r) => ({ id: r.id, author: r.author, text: r.text, createdAt: r.createdAt, ...(r.guest ? { guest: true } : {}) }));
28
+ return out;
29
+ }
30
+
31
+ /** [method, path, least role, handler(ctx, guest, body)] */
32
+ export const GUEST_ROUTES = [
33
+ [
34
+ "GET",
35
+ "/api/board",
36
+ "view",
37
+ async (ctx) => {
38
+ const { board, files, missing } = await ctx.store.syncBoard();
39
+ return json(200, { board, files, missing, stamps: await ctx.stamps.stampAll(files) });
40
+ },
41
+ ],
42
+ [
43
+ "GET",
44
+ "/api/comments",
45
+ "view",
46
+ // Comments for AI are the owner's requests to their agents: not shown to guests
47
+ async (ctx) => json(200, { comments: (await readComments(ctx)).filter((c) => !c.forAgent).map(guestComment) }),
48
+ ],
49
+ [
50
+ "POST",
51
+ "/api/comments",
52
+ "comment",
53
+ async (ctx, guest, body) => {
54
+ let b;
55
+ try {
56
+ b = JSON.parse(new TextDecoder().decode(body ?? new Uint8Array(0)) || "{}");
57
+ } catch {
58
+ return deny(400, "bad body");
59
+ }
60
+ if (!guest.name) return deny(403, "name first");
61
+ const text = String(b.text ?? "").trim();
62
+ if (!text || text.length > MAX_TEXT) return deny(400, "text is required (at most 4000 characters)");
63
+ const now = new Date().toISOString();
64
+ const rand = () => Math.random().toString(36).slice(2, 5);
65
+ // The author is the name the guest gave, never a field of the request; a guest comment is never a request for AI
66
+ return ctx.store.exclusive(async () => {
67
+ const list = await readComments(ctx);
68
+ if (b.action === "reply") {
69
+ const c = list.find((x) => x.id === b.id && !x.forAgent);
70
+ if (!c) return deny(404, "Comment not found");
71
+ const r = { id: `r${Date.now().toString(36)}${rand()}`, author: guest.name, text, createdAt: now, guest: true, guestKey: guest.key };
72
+ c.replies = [...(c.replies ?? []), r];
73
+ await writeComments(ctx, list);
74
+ return json(200, { comment: guestComment(c) });
75
+ }
76
+ if (b.action != null) return deny(403, "guests can add comments and replies only");
77
+ const board = await ctx.store.readBoard();
78
+ const file = String(b.file ?? "");
79
+ if (!board.boards[file]) return deny(400, "no such board");
80
+ const p = String(b.path ?? "");
81
+ if (!/^[0-9/]{0,200}$/.test(p)) return deny(400, "bad element path");
82
+ const c = { id: `c${Date.now().toString(36)}${rand()}`, file, path: p, text, author: guest.name, createdAt: now, resolved: false, guest: true, guestKey: guest.key };
83
+ list.push(c);
84
+ await writeComments(ctx, list);
85
+ return json(200, { comment: guestComment(c) });
86
+ });
87
+ },
88
+ ],
89
+ ];
90
+
91
+ /** "/screens/a b.html?x" → ["screens", "a b.html"], or null for anything with an empty, "." or ".." segment or a dot-name */
92
+ export function splitPath(p) {
93
+ let s;
94
+ try {
95
+ s = decodeURIComponent(String(p ?? "").split(/[?#]/)[0]);
96
+ } catch {
97
+ return null;
98
+ }
99
+ if (!s.startsWith("/") || s.includes("\\") || s.includes("\0")) return null;
100
+ const parts = s.slice(1).split("/");
101
+ if (!parts.length || parts.some((x) => !x || x.startsWith("."))) return null;
102
+ return parts;
103
+ }
104
+
105
+ async function sendFile(file, { probe = false } = {}) {
106
+ const ext = path.extname(file).toLowerCase();
107
+ if (!MIME[ext]) return null;
108
+ const st = await fs.stat(file).catch(() => null);
109
+ if (!st?.isFile()) return null;
110
+ if (st.size > MAX_FILE) return deny(413, "file too large");
111
+ if (probe && ext === ".html") return { status: 200, type: MIME[".html"], body: enc.encode(injectProbe(await fs.readFile(file, "utf8"))) };
112
+ return { status: 200, type: MIME[ext], body: new Uint8Array(await fs.readFile(file)) };
113
+ }
114
+
115
+ /**
116
+ * Board documents and what they load: screens/** (HTML with the error probe, as the app serves it), assets/**, and a board's
117
+ * root paths ("/x.css": the file in screens/ when there is one, else in the design folder) except the private root files
118
+ */
119
+ async function staticFile(ctx, parts) {
120
+ if (parts[0] === "screens" && parts.length > 1) {
121
+ const p = safeJoin(ctx.store.screensDir, parts.slice(1).join("/"));
122
+ return p ? sendFile(p, { probe: true }) : null;
123
+ }
124
+ if (parts[0] === "assets" && parts.length > 1) {
125
+ const p = safeJoin(ctx.dir, parts.join("/"));
126
+ return p ? sendFile(p) : null;
127
+ }
128
+ if (!path.extname(parts.at(-1))) return null;
129
+ const inScreens = safeJoin(ctx.store.screensDir, parts.join("/"));
130
+ const hit = inScreens && (await sendFile(inScreens, { probe: true }));
131
+ if (hit) return hit;
132
+ if (parts.length === 1 && PRIVATE_ROOT.has(parts[0].toLowerCase())) return null;
133
+ const inDir = safeJoin(ctx.dir, parts.join("/"));
134
+ return inDir ? sendFile(inDir) : null;
135
+ }
136
+
137
+ /**
138
+ * One guest request. guest: { role, name, key } decided by the owner's side (the link the guest came by); req: { m, p, body }.
139
+ * Resolves to { status, type, body: Uint8Array }
140
+ */
141
+ export async function dispatch(ctx, guest, req) {
142
+ if (req.tooBig) return deny(413, "request too large");
143
+ const m = String(req.m ?? "");
144
+ const p = String(req.p ?? "");
145
+ const pathname = p.split(/[?#]/)[0];
146
+ const route = GUEST_ROUTES.find(([rm, rp]) => rm === m && rp === pathname);
147
+ if (route) {
148
+ if ((ROLE_RANK[guest.role] ?? 0) < ROLE_RANK[route[2]]) return deny(403, "this link cannot do that");
149
+ return route[3](ctx, guest, req.body);
150
+ }
151
+ if (m !== "GET" || pathname.startsWith("/api/")) return deny();
152
+ const parts = splitPath(p);
153
+ if (!parts) return deny();
154
+ return (await staticFile(ctx, parts)) ?? json(404, { error: "not found" });
155
+ }
156
+
157
+ /** Canvas events guests get (others are the owner's: AI runs, selection, errors, updates…). Fields that name local things go */
158
+ export function guestEvent(msg) {
159
+ if (!msg || typeof msg !== "object") return null;
160
+ if (msg.type === "file-changed") {
161
+ const { type, file, kind, hash, stamp, via } = msg;
162
+ // via: the stylesheet, image or page that changed under this board, so the guest drops just that one from its cache
163
+ return { type, file, kind, ...(hash ? { hash } : {}), ...(stamp ? { stamp } : {}), ...(typeof via === "string" ? { via } : {}) };
164
+ }
165
+ if (msg.type === "board-changed") return { type: "board-changed", source: null };
166
+ if (msg.type === "comments-changed") return { type: "comments-changed" };
167
+ return null;
168
+ }
@@ -0,0 +1,101 @@
1
+ // AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
2
+ // Every app route, classified for live share. "view"/"comment": a guest with that link gets a guest version of it (dispatch.mjs
3
+ // GUEST_ROUTES must implement exactly these). "later": a guest may get it in a later stage (editing). "owner": never reaches a
4
+ // guest. test/live-inventory.test.mjs fails when the server has a route this table does not name, so a new route is a decision.
5
+ // Static files (screens/**, assets/**, a board's root paths) are served by dispatch.mjs staticFile, not by this table.
6
+ export const INVENTORY = {
7
+ // index.mjs
8
+ "GET /api/update": "owner",
9
+ "POST /api/update": "owner",
10
+ "GET /api/health": "owner", // dir, root, pid
11
+ "GET /api/projects": "owner",
12
+ "GET /api/board": "view", // guest version: no dir, no screens path
13
+ "GET /api/file": "later",
14
+ // routes.mjs
15
+ "POST /api/edit": "later", // stage 2: setText and setStyle only, guarded
16
+ "POST /api/undo": "owner",
17
+ "POST /api/redo": "owner",
18
+ "GET /api/thumb": "later", // renders with a headless browser on the owner's machine
19
+ "GET /api/assets": "later",
20
+ "POST /api/assets": "owner",
21
+ "GET /api/element": "later",
22
+ "GET /api/file-hash": "later",
23
+ "GET /api/outline": "later",
24
+ "GET /api/selection": "owner", // the owner's selection for AI
25
+ "PUT /api/selection": "owner",
26
+ "GET /api/comments": "view", // guest version: no requests for AI
27
+ "POST /api/comments": "comment", // guest version: add and reply, author set by the owner's side, never for AI
28
+ "POST /api/screenshot": "owner",
29
+ "POST /api/place": "owner",
30
+ // boards.mjs
31
+ "PUT /api/board": "owner",
32
+ "POST /api/boards/create": "owner",
33
+ "GET /api/boards/templates": "owner",
34
+ "POST /api/boards/delete": "owner",
35
+ "POST /api/boards/duplicate": "owner",
36
+ "GET /api/boards/refs": "owner",
37
+ "POST /api/boards/rename": "owner",
38
+ "POST /api/history/undo": "owner",
39
+ "POST /api/history/redo": "owner",
40
+ "GET /api/history": "owner",
41
+ "POST /api/notes": "owner",
42
+ "POST /api/pages": "owner",
43
+ // forks.mjs
44
+ "GET /api/boards/occupancy": "later",
45
+ "POST /api/boards/write": "owner",
46
+ "POST /api/boards/claim": "owner",
47
+ "POST /api/boards/release": "owner",
48
+ "POST /api/boards/use": "owner",
49
+ "POST /api/boards/keep": "owner",
50
+ // activity.mjs
51
+ "GET /api/activity": "owner",
52
+ "POST /api/history/goto": "owner",
53
+ "POST /api/history/undo-steps": "owner",
54
+ "GET /api/history/step-file": "owner",
55
+ // chat.mjs: local AI agents
56
+ "POST /api/chat": "owner",
57
+ "POST /api/chat/cancel": "owner",
58
+ "GET /api/chat": "owner",
59
+ "POST /api/chat/permission": "owner",
60
+ "GET /api/chat/permission": "owner",
61
+ "POST /api/chat/permission/answer": "owner",
62
+ "POST /api/chat/revert": "owner",
63
+ "POST /api/chat/undo-run": "owner",
64
+ "POST /api/chat/redo-run": "owner",
65
+ "GET /api/chat/runs": "owner",
66
+ "GET /api/chat/run-file": "owner",
67
+ "GET /api/agents": "owner",
68
+ "POST /api/agents/custom": "owner",
69
+ "POST /api/refs": "owner",
70
+ "PUT /api/context": "owner",
71
+ "PUT /api/errors": "owner",
72
+ "GET /api/errors": "owner",
73
+ // requests.mjs
74
+ "POST /api/agents/hello": "owner",
75
+ "POST /api/agents/bye": "owner",
76
+ "GET /api/agents/connected": "owner",
77
+ "GET /api/requests/settings": "owner",
78
+ "POST /api/requests/settings": "owner",
79
+ "GET /api/requests": "owner",
80
+ "POST /api/requests": "owner",
81
+ "POST /api/pick/resolve": "owner",
82
+ // tokens.mjs
83
+ "GET /api/tokens": "later",
84
+ "PUT /api/tokens": "owner",
85
+ "GET /api/lint": "owner",
86
+ // snapshot.mjs
87
+ "GET /api/me": "owner", // git user.name
88
+ "GET /api/snapshots": "owner",
89
+ "POST /api/snapshot": "owner",
90
+ // export.mjs
91
+ "GET /api/export": "owner",
92
+ "POST /api/export": "owner",
93
+ "POST /api/export/estimate": "owner",
94
+ "POST /api/export/reveal": "owner",
95
+ // live share itself (server/live/routes.mjs)
96
+ "GET /api/live": "owner",
97
+ "POST /api/live/start": "owner",
98
+ "POST /api/live/stop": "owner",
99
+ "POST /api/live/rotate": "owner",
100
+ "POST /api/live/owner": "owner",
101
+ };
@@ -0,0 +1,366 @@
1
+ // AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
2
+ // Live share, the owner's side: one outbound WebSocket to the relay, one link (and key) per role, guests' frames opened with the
3
+ // key of the link they came by, their requests answered by the allow-list dispatcher (dispatch.mjs), a few canvas events and the
4
+ // people's cursors passed on. Everything here is in memory: closing Easel or pressing Stop ends the room; links never touch disk.
5
+ import { promisify } from "node:util";
6
+ import zlib from "node:zlib";
7
+
8
+ import { WebSocket } from "ws";
9
+
10
+ import { dispatch, guestEvent } from "./dispatch.mjs";
11
+ import { CHUNK, CLOSE, KIND, b64u, deriveLink, frame, linkFragment, open, randomBytes, seal, untext, unframe } from "./proto.mjs";
12
+
13
+ /** Where owners connect when nothing else is configured: the production relay (see docs/live-share-deploy.md) */
14
+ export const DEFAULT_RELAY = "wss://easel.d-t-it.com/live/ws";
15
+ /** Roles a link can carry in this stage (edit comes with stage 2) */
16
+ export const ROLES = ["view", "comment"];
17
+ export const LIMITS = {
18
+ /** Requests a guest may have in flight; more wait in a queue of QUEUE, beyond that 429 */
19
+ concurrent: 8,
20
+ queue: 64,
21
+ /** Token bucket per guest: requests per second and burst */
22
+ rate: 50,
23
+ burst: 100,
24
+ /** Cursor updates per second per guest (more are dropped) */
25
+ presence: 20,
26
+ /** Bytes the relay socket may hold before the owner waits */
27
+ buffered: 4 * 1024 * 1024,
28
+ /** A request body (comments) */
29
+ body: 64 * 1024,
30
+ /** Owner start: how long to wait for the relay's welcome */
31
+ connectMs: 6000,
32
+ /** A guest that says nothing after HELLO this long is dropped */
33
+ helloMs: 10000,
34
+ };
35
+ /** Guest cursor and avatar colours, by order of arrival (the owner is the selection blue) */
36
+ export const COLORS = ["#7a5af8", "#0e9384", "#c11574", "#b54708", "#155eef", "#4e5ba6", "#099250", "#dd2590"];
37
+
38
+ /** Text the owner deflates before sealing (images, fonts and other packed formats go as they are) */
39
+ const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|manifest\+json)|image\/svg\+xml)/i;
40
+ /** Smaller bodies are not worth a compressed frame */
41
+ const COMPRESS_MIN = 1024;
42
+ const deflate = promisify(zlib.deflateRaw);
43
+
44
+ const cleanName = (s) =>
45
+ String(s ?? "")
46
+ .replace(/[\u0000-\u001f\u007f‎‏‪-‮⁦-⁩]/g, "")
47
+ .trim()
48
+ .slice(0, 40);
49
+
50
+ /**
51
+ * ctx: the app server's context (store, broadcast, …). relay: wss URL of the relay (…/live/ws). WS: WebSocket class (tests).
52
+ * The app sees changes as { type: "live" } (read GET /api/live) and { type: "live-presence", peers } on its own socket.
53
+ */
54
+ export function createLive(ctx, { relay = DEFAULT_RELAY, WS = WebSocket, limits = LIMITS } = {}) {
55
+ let st = fresh();
56
+ function fresh() {
57
+ return { status: "off", error: null, room: null, token: null, links: {}, guestUrl: null, guests: new Map(), owner: "", sock: null, retry: 0, timer: null, ownerCursor: null, reconnecting: false };
58
+ }
59
+ const notify = () => ctx.broadcast({ type: "live" });
60
+
61
+ /** One link per role: a 16-byte secret only ever in the link's fragment, its key and the id the relay sees */
62
+ async function makeLink(role) {
63
+ const secret = randomBytes(16);
64
+ const { key, linkId } = await deriveLink(secret, st.room);
65
+ st.links[role] = { role, secret, key, linkId };
66
+ }
67
+ const linkById = (id) => Object.values(st.links).find((l) => l.linkId === id) ?? null;
68
+ const linkUrl = (role) => (st.guestUrl && st.links[role] ? `${st.guestUrl}#${linkFragment(st.room, st.links[role].secret)}` : null);
69
+
70
+ function publicState() {
71
+ return {
72
+ status: st.status,
73
+ error: st.error,
74
+ /** On, but the relay connection dropped: guests see the last state until it is back */
75
+ reconnecting: st.status === "on" && st.reconnecting,
76
+ relay,
77
+ links: st.status === "on" ? Object.fromEntries(ROLES.map((r) => [r, linkUrl(r)])) : {},
78
+ guests: [...st.guests.values()].filter((g) => g.link && g.name).map((g) => ({ id: g.conn, name: g.name, role: g.link.role, color: g.color })),
79
+ };
80
+ }
81
+
82
+ async function sendTo(g, hdr, body) {
83
+ if (!st.sock || st.sock.readyState !== 1 || !g.link) return;
84
+ const ct = await seal(g.link.key, st.room, "o2g", hdr, body);
85
+ while (st.sock && st.sock.bufferedAmount > limits.buffered) await new Promise((r) => setTimeout(r, 10));
86
+ st.sock?.send(frame(KIND.DATA, g.conn, ct));
87
+ }
88
+ const ready = () => [...st.guests.values()].filter((g) => g.link);
89
+ const people = () => [
90
+ { id: 0, name: st.owner || "", owner: true, color: "owner" },
91
+ ...ready()
92
+ .filter((g) => g.name)
93
+ .map((g) => ({ id: g.conn, name: g.name, role: g.link.role, color: g.color })),
94
+ ];
95
+ const sendPeople = () => {
96
+ for (const g of ready()) void sendTo(g, { t: "people", people: people() });
97
+ notify();
98
+ };
99
+
100
+ let presTimer = null;
101
+ /** Cursors go out at most every 50 ms, batched (Cloudflare bills incoming messages; batching keeps both sides cheap) */
102
+ function schedulePresence() {
103
+ if (presTimer) return;
104
+ presTimer = setTimeout(() => {
105
+ presTimer = null;
106
+ const peers = ready()
107
+ .filter((g) => g.name && g.cursor)
108
+ .map((g) => ({ id: g.conn, name: g.name, color: g.color, ...g.cursor }));
109
+ ctx.broadcast({ type: "live-presence", peers });
110
+ const all = st.ownerCursor ? [{ id: 0, name: st.owner, color: "owner", ...st.ownerCursor }, ...peers] : peers;
111
+ for (const g of ready()) void sendTo(g, { t: "pres", peers: all.filter((p) => p.id !== g.conn) });
112
+ }, 50);
113
+ presTimer.unref?.();
114
+ }
115
+
116
+ /** Guest requests: a token bucket, at most `concurrent` in flight, a short queue, then 429 */
117
+ function admit(g) {
118
+ const now = Date.now();
119
+ g.tokens = Math.min(limits.burst, g.tokens + ((now - g.at) / 1000) * limits.rate);
120
+ g.at = now;
121
+ if (g.tokens < 1) return false;
122
+ g.tokens -= 1;
123
+ return true;
124
+ }
125
+ async function runRequest(g, hdr, body, queued = false) {
126
+ // A queued request was admitted when it arrived: it is not charged again (and so always runs, keeping the queue moving)
127
+ if (!queued && !admit(g)) return reply(g, hdr.id, { status: 429, type: "text/plain", body: new TextEncoder().encode("slow down") });
128
+ if (!queued && g.inflight >= limits.concurrent) {
129
+ if (g.queue.length >= limits.queue) return reply(g, hdr.id, { status: 429, type: "text/plain", body: new TextEncoder().encode("too many requests") });
130
+ return void g.queue.push([hdr, body]);
131
+ }
132
+ g.inflight++;
133
+ try {
134
+ const res = await dispatch(ctx, { role: g.link.role, name: g.name, key: `${g.link.linkId}:${g.conn}` }, { m: hdr.m, p: hdr.p, body: body.length > limits.body ? null : body, tooBig: body.length > limits.body });
135
+ await reply(g, hdr.id, res);
136
+ } catch (e) {
137
+ await reply(g, hdr.id, { status: 500, type: "text/plain", body: new TextEncoder().encode("error") });
138
+ if (process.env.EASEL_DEBUG) console.error(e);
139
+ } finally {
140
+ g.inflight--;
141
+ const next = g.queue.shift();
142
+ if (next) void runRequest(g, ...next, true);
143
+ }
144
+ }
145
+ async function reply(g, id, res) {
146
+ let body = res.body ?? new Uint8Array(0);
147
+ // Text is deflated before it is sealed (sealed bytes do not compress): the guest shell inflates it once all chunks are in
148
+ let z;
149
+ if (body.length >= COMPRESS_MIN && COMPRESSIBLE.test(res.type ?? "")) {
150
+ const packed = await deflate(body);
151
+ if (packed.length < body.length) (body = new Uint8Array(packed.buffer, packed.byteOffset, packed.length)), (z = "deflate-raw");
152
+ }
153
+ for (let off = 0, seq = 0; off < body.length || seq === 0; off += CHUNK, seq++) {
154
+ await sendTo(g, { t: "res", id, status: res.status, type: res.type, size: body.length, ...(z && { z }), seq, last: off + CHUNK >= body.length }, body.subarray(off, off + CHUNK));
155
+ }
156
+ }
157
+
158
+ async function onGuestFrame(f) {
159
+ const g = st.guests.get(f.conn);
160
+ if (f.kind === KIND.JOIN) {
161
+ if (g) return; // the relay lists who is still here after we reconnect: they keep their link and name
162
+ const n = st.guests.size;
163
+ const entry = { conn: f.conn, link: null, name: "", color: COLORS[n % COLORS.length], cursor: null, tokens: limits.burst, at: Date.now(), inflight: 0, queue: [], pres: { n: 0, t: 0 } };
164
+ entry.helloTimer = setTimeout(() => !entry.link && kick(f.conn), limits.helloMs);
165
+ entry.helloTimer.unref?.();
166
+ st.guests.set(f.conn, entry);
167
+ return;
168
+ }
169
+ if (!g) return;
170
+ if (f.kind === KIND.LEAVE) {
171
+ clearTimeout(g.helloTimer);
172
+ st.guests.delete(f.conn);
173
+ if (g.link) {
174
+ sendPeople();
175
+ schedulePresence();
176
+ }
177
+ return;
178
+ }
179
+ if (f.kind === KIND.HELLO) {
180
+ const link = linkById(untext(f.payload));
181
+ if (!link) return kick(f.conn);
182
+ g.link = link;
183
+ clearTimeout(g.helloTimer);
184
+ await sendTo(g, { t: "hello", role: link.role, owner: st.owner, title: (await ctx.store.readBoard().catch(() => ({}))).title ?? "", you: { id: g.conn, color: g.color } });
185
+ await sendTo(g, { t: "people", people: people() });
186
+ return;
187
+ }
188
+ if (f.kind !== KIND.DATA || !g.link) return;
189
+ let msg;
190
+ try {
191
+ msg = await open(g.link.key, st.room, "g2o", f.payload);
192
+ } catch {
193
+ return; // not sealed with this guest's link key: dropped
194
+ }
195
+ const h = msg.hdr ?? {};
196
+ if (h.t === "req" && Number.isInteger(h.id)) return runRequest(g, h, msg.body);
197
+ if (h.t === "join") {
198
+ const name = cleanName(h.name);
199
+ if (!name) return;
200
+ g.name = name;
201
+ return sendPeople();
202
+ }
203
+ if (h.t === "pres") {
204
+ const now = Date.now();
205
+ if (now - g.pres.t > 1000) g.pres = { n: 0, t: now };
206
+ if (++g.pres.n > limits.presence) return;
207
+ g.cursor = h.at && Number.isFinite(h.at.x) && Number.isFinite(h.at.y) ? { x: Math.round(h.at.x), y: Math.round(h.at.y) } : null;
208
+ schedulePresence();
209
+ }
210
+ }
211
+
212
+ function kick(conn) {
213
+ st.guests.delete(conn);
214
+ if (st.sock?.readyState === 1) st.sock.send(frame(KIND.KICK, conn));
215
+ }
216
+
217
+ /** Opens (or reopens) the relay socket. Resolves once the relay welcomed us, rejects when it cannot be reached */
218
+ function connect() {
219
+ return new Promise((resolve, reject) => {
220
+ let settled = false;
221
+ const sock = new WS(`${relay}/${st.room}?as=owner&token=${st.token}`);
222
+ sock.binaryType = "nodebuffer";
223
+ st.sock = sock;
224
+ const fail = (why) => {
225
+ if (settled) return;
226
+ settled = true;
227
+ clearTimeout(t);
228
+ try {
229
+ sock.terminate?.() ?? sock.close();
230
+ } catch {
231
+ /* gone */
232
+ }
233
+ reject(new Error(why));
234
+ };
235
+ const t = setTimeout(() => fail("The live share relay did not answer"), limits.connectMs);
236
+ sock.on("error", (e) => fail(e?.message || "The live share relay cannot be reached"));
237
+ sock.on("message", (data) => {
238
+ const f = unframe(new Uint8Array(data));
239
+ if (!f) return;
240
+ if (f.kind === KIND.WELCOME) {
241
+ let url = "";
242
+ let freshRoom = false;
243
+ try {
244
+ const w = JSON.parse(untext(f.payload));
245
+ url = w.guestUrl ?? "";
246
+ freshRoom = w.fresh === true;
247
+ } catch {
248
+ /* none */
249
+ }
250
+ // Back on a relay that had to make the room anew (it restarted, or we were away past the grace period): the guests we knew
251
+ // are not on it; they come back as new connections, and their old entries would be ghosts in the people list
252
+ if (freshRoom && st.guests.size) {
253
+ for (const g of st.guests.values()) clearTimeout(g.helloTimer);
254
+ st.guests.clear();
255
+ sendPeople();
256
+ schedulePresence();
257
+ }
258
+ // Links must point at https, or at a loopback page for a local relay
259
+ st.guestUrl = /^https:\/\/|^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?\//.test(url) ? url : null;
260
+ if (!settled) {
261
+ settled = true;
262
+ clearTimeout(t);
263
+ if (!st.guestUrl) return reject(new Error("The relay did not say where guests open links"));
264
+ resolve();
265
+ }
266
+ return;
267
+ }
268
+ void onGuestFrame(f).catch(() => {});
269
+ });
270
+ sock.on("close", (code) => {
271
+ if (!settled) return fail(`The live share relay closed the connection (${code})`);
272
+ if (st.sock !== sock || st.status !== "on") return;
273
+ // Dropped: try again (the relay keeps the room for 30 s and tells guests to wait; after that they keep the last state and retry)
274
+ st.sock = null;
275
+ if (!st.reconnecting) (st.reconnecting = true), notify();
276
+ const wait = Math.min(30000, 1000 * 2 ** st.retry++);
277
+ st.timer = setTimeout(() => {
278
+ if (st.status !== "on") return;
279
+ connect().then(
280
+ () => {
281
+ st.retry = 0;
282
+ st.reconnecting = false;
283
+ notify();
284
+ },
285
+ () => {},
286
+ );
287
+ }, wait);
288
+ st.timer.unref?.();
289
+ });
290
+ });
291
+ }
292
+
293
+ return {
294
+ state: publicState,
295
+ /** Starts a room (or returns the one that is on). owner: the name guests see */
296
+ async start({ owner } = {}) {
297
+ if (st.status === "on" || st.status === "connecting") return publicState();
298
+ st = fresh();
299
+ st.status = "connecting";
300
+ st.owner = cleanName(owner);
301
+ st.room = b64u(randomBytes(12));
302
+ st.token = b64u(randomBytes(16));
303
+ for (const r of ROLES) await makeLink(r);
304
+ notify();
305
+ try {
306
+ await connect();
307
+ st.status = "on";
308
+ } catch (e) {
309
+ st = { ...fresh(), status: "unavailable", error: String(e.message ?? e) };
310
+ }
311
+ notify();
312
+ return publicState();
313
+ },
314
+ /** Ends the room: every guest sees "ended" at once */
315
+ stop() {
316
+ if (st.sock?.readyState === 1) st.sock.send(frame(KIND.BYE));
317
+ const s = st.sock;
318
+ clearTimeout(st.timer);
319
+ st = fresh();
320
+ st.sock = null;
321
+ try {
322
+ s?.close(1000, "stopped");
323
+ } catch {
324
+ /* gone */
325
+ }
326
+ ctx.broadcast({ type: "live-presence", peers: [] });
327
+ notify();
328
+ return publicState();
329
+ },
330
+ /** The name guests see, changed while on: they get it in the next people list (the shell and canvas take the owner's entry) */
331
+ rename(owner) {
332
+ const name = cleanName(owner);
333
+ if (st.status === "on" && name !== st.owner) {
334
+ st.owner = name;
335
+ sendPeople();
336
+ }
337
+ return publicState();
338
+ },
339
+ /** A new link for this role: the old one stops working now and the guests who came by it are closed */
340
+ async rotate(role) {
341
+ if (st.status !== "on" || !ROLES.includes(role)) return publicState();
342
+ const old = st.links[role];
343
+ await makeLink(role);
344
+ for (const g of [...st.guests.values()]) if (g.link === old) kick(g.conn);
345
+ sendPeople();
346
+ return publicState();
347
+ },
348
+ /** A canvas event: passed on (filtered, see dispatch.mjs guestEvent) to every guest */
349
+ forward(msg) {
350
+ if (st.status !== "on") return;
351
+ const ev = guestEvent(msg);
352
+ if (ev) for (const g of ready()) void sendTo(g, { t: "ev", ev });
353
+ },
354
+ /** The owner's own cursor on the canvas (world coordinates), from the app's socket; null when it leaves the canvas */
355
+ ownerCursor(at) {
356
+ if (st.status !== "on") return;
357
+ st.ownerCursor = at && Number.isFinite(at.x) && Number.isFinite(at.y) ? { x: Math.round(at.x), y: Math.round(at.y) } : null;
358
+ schedulePresence();
359
+ },
360
+ close() {
361
+ if (st.status === "on") this.stop();
362
+ },
363
+ /** Tests: the guest frames' close codes */
364
+ CLOSE,
365
+ };
366
+ }