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,101 @@
1
+ // AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
2
+ // Live share wire protocol, shared by the owner's connector (server/live/live.mjs), the relays (relay/) and the guest shell
3
+ // (copied next to it by the build). Plain ESM with Web Crypto only, so it runs in Node 20+, Workers and browsers unchanged.
4
+ //
5
+ // Wire frame, what the relay sees: [kind u8][conn u32 big-endian][payload]
6
+ // DATA 1 payload = iv(12) ‖ AES-GCM-256(plaintext), AAD "easel-live:<room>:<g2o|o2g>"; owner→relay: conn = the guest
7
+ // JOIN 2 relay→owner: a guest connected (no payload)
8
+ // LEAVE 3 relay→owner: a guest left
9
+ // HELLO 4 guest→relay→owner: payload = link id (ascii, clear): which link key opens this guest's frames
10
+ // BYE 5 owner→relay: the owner ended the room; every guest is closed with CLOSE.ENDED (and drops what it saw)
11
+ // (an owner that stays away past the grace period closes guests with CLOSE.GONE instead: they keep the last view and retry)
12
+ // KICK 6 owner→relay: close guest `conn` with CLOSE.LINK (unknown or rotated link)
13
+ // WELCOME 7 relay→owner: payload = JSON {guestUrl}: where guests open links on this relay
14
+ // AWAY 8 relay→guest: the owner's connection dropped; the room waits GRACE_MS for it
15
+ // BACK 9 relay→guest: the owner is back
16
+ // Plaintext inside DATA: [header length u32][header JSON][body bytes]
17
+ export const KIND = { DATA: 1, JOIN: 2, LEAVE: 3, HELLO: 4, BYE: 5, KICK: 6, WELCOME: 7, AWAY: 8, BACK: 9 };
18
+ /** WebSocket close codes the guest page tells apart */
19
+ export const CLOSE = { ENDED: 4001, GONE: 4002, LINK: 4003, NO_ROOM: 4004, FULL: 4005, SLOW: 4008 };
20
+ /** Largest wire frame either side accepts (Cloudflare takes up to 32 MiB; we stay far below) */
21
+ export const MAX_FRAME = 1 << 20;
22
+ /** Body bytes per DATA frame */
23
+ export const CHUNK = 256 * 1024;
24
+ /** How long a room waits for an owner whose connection dropped without BYE */
25
+ export const GRACE_MS = 30000;
26
+ /** How long the relay remembers that a room was ended (its id and when, nothing else), so a guest who was away at the time gets ENDED */
27
+ export const ENDED_MS = 24 * 60 * 60 * 1000;
28
+ export const MAX_GUESTS = 20;
29
+ /** Room ids: 12 random bytes, base64url (16 characters) */
30
+ export const ROOM_RE = /^[A-Za-z0-9_-]{16}$/;
31
+
32
+ const enc = new TextEncoder();
33
+ const dec = new TextDecoder();
34
+ const subtle = () => globalThis.crypto.subtle;
35
+
36
+ export const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
37
+
38
+ export function b64u(bytes) {
39
+ let s = "";
40
+ for (const b of bytes) s += String.fromCharCode(b);
41
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
42
+ }
43
+ export function unb64u(s) {
44
+ const b = atob(String(s).replace(/-/g, "+").replace(/_/g, "/"));
45
+ return Uint8Array.from(b, (c) => c.charCodeAt(0));
46
+ }
47
+
48
+ /** A link: https://<guest page>#<room>.<secret>. Both parts base64url, so "." cannot occur in them */
49
+ export function linkFragment(room, secret) {
50
+ return `${room}.${b64u(secret)}`;
51
+ }
52
+ export function parseFragment(hash) {
53
+ const m = /^#?([A-Za-z0-9_-]{16})\.([A-Za-z0-9_-]{22})$/.exec(String(hash ?? ""));
54
+ return m ? { room: m[1], secret: unb64u(m[2]) } : null;
55
+ }
56
+
57
+ /** secret (16 bytes, only ever in the fragment) → { key: AES-GCM-256, linkId: 16 hex characters the relay may see } */
58
+ export async function deriveLink(secret, room) {
59
+ const base = await subtle().importKey("raw", secret, "HKDF", false, ["deriveKey", "deriveBits"]);
60
+ const salt = enc.encode(`easel-live:${room}`);
61
+ const key = await subtle().deriveKey({ name: "HKDF", hash: "SHA-256", salt, info: enc.encode("enc v1") }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
62
+ const bits = new Uint8Array(await subtle().deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: enc.encode("link id v1") }, base, 64));
63
+ return { key, linkId: [...bits].map((b) => b.toString(16).padStart(2, "0")).join("") };
64
+ }
65
+
66
+ export function frame(kind, conn = 0, payload = new Uint8Array(0)) {
67
+ const out = new Uint8Array(5 + payload.length);
68
+ out[0] = kind;
69
+ new DataView(out.buffer).setUint32(1, conn >>> 0);
70
+ out.set(payload, 5);
71
+ return out;
72
+ }
73
+ export function unframe(data) {
74
+ const u = data instanceof Uint8Array ? data : new Uint8Array(data);
75
+ if (u.length < 5) return null;
76
+ return { kind: u[0], conn: new DataView(u.buffer, u.byteOffset, u.byteLength).getUint32(1), payload: u.subarray(5) };
77
+ }
78
+ export const text = (s) => enc.encode(s);
79
+ export const untext = (b) => dec.decode(b);
80
+
81
+ /** dir: "g2o" (guest to owner) or "o2g". The AAD binds a frame to its room and direction */
82
+ export async function seal(key, room, dir, hdr, body = new Uint8Array(0)) {
83
+ const h = enc.encode(JSON.stringify(hdr));
84
+ const plain = new Uint8Array(4 + h.length + body.length);
85
+ new DataView(plain.buffer).setUint32(0, h.length);
86
+ plain.set(h, 4);
87
+ plain.set(body, 4 + h.length);
88
+ const iv = randomBytes(12);
89
+ const ct = new Uint8Array(await subtle().encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(`easel-live:${room}:${dir}`) }, key, plain));
90
+ const out = new Uint8Array(12 + ct.length);
91
+ out.set(iv);
92
+ out.set(ct, 12);
93
+ return out;
94
+ }
95
+ /** Throws when the frame was not sealed with this key, for this room and direction */
96
+ export async function open(key, room, dir, data) {
97
+ const plain = new Uint8Array(await subtle().decrypt({ name: "AES-GCM", iv: data.subarray(0, 12), additionalData: enc.encode(`easel-live:${room}:${dir}`) }, key, data.subarray(12)));
98
+ const n = new DataView(plain.buffer).getUint32(0);
99
+ if (n > plain.length - 4) throw new Error("bad header length");
100
+ return { hdr: JSON.parse(dec.decode(plain.subarray(4, 4 + n))), body: plain.subarray(4 + n) };
101
+ }
@@ -0,0 +1,49 @@
1
+ // AI-generated with Claude Code, 2026-12-05, reviewed by Hyun Park
2
+ // The owner's live-share controls, for the canvas page only: state (links included, so the Host must be local even for GET),
3
+ // start, stop and a new link for a role. Never reachable by guests (inventory.mjs: owner).
4
+ import { originAllowed, readBody, sendJson } from "../index.mjs";
5
+
6
+ /** POSTs need the page's own Origin (like the one-click update): no other site and no plain script starts a room */
7
+ const fromPage = (req) => !!req.headers.origin && originAllowed(req.headers);
8
+
9
+ export function liveRoutes() {
10
+ return [
11
+ ["GET", "/api/live", async (req, res, url, ctx) => (originAllowed(req.headers) ? sendJson(res, 200, ctx.live?.state() ?? { status: "off", links: {}, guests: [] }) : sendJson(res, 403, { error: "Only the canvas page" }))],
12
+ [
13
+ "POST",
14
+ "/api/live/start",
15
+ async (req, res, url, ctx) => {
16
+ if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can start live share" });
17
+ const b = await readBody(req);
18
+ sendJson(res, 200, await ctx.live.start({ owner: b.owner }));
19
+ },
20
+ ],
21
+ [
22
+ "POST",
23
+ "/api/live/stop",
24
+ async (req, res, url, ctx) => {
25
+ if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can stop live share" });
26
+ await readBody(req);
27
+ sendJson(res, 200, ctx.live.stop());
28
+ },
29
+ ],
30
+ [
31
+ "POST",
32
+ "/api/live/owner",
33
+ async (req, res, url, ctx) => {
34
+ if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can change the name" });
35
+ const b = await readBody(req);
36
+ sendJson(res, 200, ctx.live.rename(b.owner));
37
+ },
38
+ ],
39
+ [
40
+ "POST",
41
+ "/api/live/rotate",
42
+ async (req, res, url, ctx) => {
43
+ if (!fromPage(req)) return sendJson(res, 403, { error: "Only the canvas page can change a link" });
44
+ const b = await readBody(req);
45
+ sendJson(res, 200, await ctx.live.rotate(String(b.role ?? "")));
46
+ },
47
+ ],
48
+ ];
49
+ }
@@ -310,6 +310,8 @@ const brief = (c, by) => ({
310
310
  ...(c.request.attach?.kind ? { kind: c.request.attach.kind } : {}),
311
311
  ...(c.request.by ? { by: c.request.by } : {}),
312
312
  ...(c.request.left ? { left: c.request.left } : {}),
313
+ // When an agent first listed it while waiting (the Claude Code wake hook announces a request again only while this is unset)
314
+ ...(c.request.seenAt ? { seenAt: c.request.seenAt } : {}),
313
315
  });
314
316
 
315
317
  /** In-memory: each taken request's board contents when it was taken, so finishing can tell which boards changed */
package/server/routes.mjs CHANGED
@@ -18,6 +18,8 @@ import { contentHash, livePatch } from "./livePatch.mjs";
18
18
  import { readBody, safeJoin, sendJson } from "./index.mjs";
19
19
  import { requestRoutes, undoState } from "./requests.mjs";
20
20
  import { watchDesign } from "./watch.mjs";
21
+ import { createLive, DEFAULT_RELAY } from "./live/live.mjs";
22
+ import { liveRoutes } from "./live/routes.mjs";
21
23
 
22
24
  const OUTER_LIMIT = 4096;
23
25
  let selection = null;
@@ -38,7 +40,7 @@ async function readScreen(ctx, file) {
38
40
  }
39
41
 
40
42
  /* ---------- Comments (docs/design/comments.json) ---------- */
41
- async function readComments(ctx) {
43
+ export async function readComments(ctx) {
42
44
  try {
43
45
  const d = JSON.parse(await fs.readFile(path.join(ctx.dir, "comments.json"), "utf8"));
44
46
  return Array.isArray(d.comments) ? d.comments : [];
@@ -46,7 +48,7 @@ async function readComments(ctx) {
46
48
  return [];
47
49
  }
48
50
  }
49
- async function writeComments(ctx, comments) {
51
+ export async function writeComments(ctx, comments) {
50
52
  await writeAtomic(path.join(ctx.dir, "comments.json"), JSON.stringify({ comments }, null, 1) + "\n");
51
53
  ctx.broadcast({ type: "comments-changed" });
52
54
  }
@@ -234,6 +236,7 @@ export const extraRoutes = [
234
236
  ],
235
237
  ...snapshotRoutes(),
236
238
  ...exportRoutes(),
239
+ ...liveRoutes(),
237
240
  // Assets: list and upload docs/design/assets/ (images, fonts). Screens reference them as ../assets/<name>
238
241
  [
239
242
  "GET",
@@ -458,10 +461,21 @@ export const extraRoutes = [
458
461
  ];
459
462
 
460
463
  /** Things to attach after the server starts (file watching etc.) */
461
- export async function attach(app) {
464
+ export async function attach(app, { relay } = {}) {
465
+ app.ctx.busy = chat.busy; // the one-click update waits while an Easel AI run is going
466
+ // Live share: off until the owner turns it on. Every app event also goes to the connector, which
467
+ // passes only the guest-safe ones (dispatch.mjs guestEvent) to the room.
468
+ const live = createLive(app.ctx, { relay: relay || process.env.EASEL_RELAY || DEFAULT_RELAY });
469
+ app.ctx.live = live;
470
+ const broadcast = app.ctx.broadcast;
471
+ app.ctx.broadcast = (msg) => {
472
+ broadcast(msg);
473
+ live.forward(msg);
474
+ };
462
475
  const stop = watchDesign(app.ctx);
463
476
  const close = app.close;
464
477
  app.close = async () => {
478
+ live.close(); // closing Easel ends the room
465
479
  chat.close(); // open permission requests are denied, so a waiting agent does not hang
466
480
  await stop();
467
481
  await closeBrowser();
@@ -0,0 +1,98 @@
1
+ // AI-generated with Claude Code, 2026-12-03, reviewed by Hyun Park
2
+ // One-click update, where Easel can replace itself (an npx cache or a global install; see update.mjs installKind): npm installs
3
+ // easel-canvas@<x.y.z> into the prefix this copy runs from, the version on disk is checked, and only then is the canvas handed over to
4
+ // the new files (bin/server.mjs: the old server closes its port, starts the new one on the same port and folder, and goes back to
5
+ // listening if the new one does not answer). Nothing from the registry reaches a shell: the version must be x.y.z and npm is spawned
6
+ // with an argument array. EASEL_UPDATE_INSTALLER (a JSON argument array, as DESIGN_CANVAS_AGENT_CMD) stands in for npm in tests.
7
+ import { spawn } from "node:child_process";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import path from "node:path";
10
+
11
+ import { TOOL_ROOT } from "./args.mjs";
12
+ import { installKind, validVersion } from "./update.mjs";
13
+
14
+ /** How to run npm without a shell: node + npm-cli.js beside this node when it is there (also on Windows, where npm is a .cmd), else npm */
15
+ export function npmCommand({ execPath = process.execPath, exists = existsSync, platform = process.platform } = {}) {
16
+ const dir = path.dirname(execPath);
17
+ for (const cli of [path.join(dir, "node_modules/npm/bin/npm-cli.js"), path.join(dir, "../lib/node_modules/npm/bin/npm-cli.js")]) if (exists(cli)) return [execPath, cli];
18
+ return platform === "win32" ? null : ["npm"];
19
+ }
20
+
21
+ /** npm's arguments for this install kind: into npx's cache dir as its own package, or -g into the global prefix this copy lives under */
22
+ export function installArgs(kind, prefix, version) {
23
+ if (!validVersion(version)) throw new Error(`Not a release version: ${String(version).slice(0, 40)}`);
24
+ if (!prefix || !path.isAbsolute(prefix)) throw new Error("No install folder");
25
+ const common = ["--no-audit", "--no-fund", "--loglevel=error"];
26
+ if (kind === "npx") return ["install", `easel-canvas@${version}`, "--prefix", prefix, ...common];
27
+ if (kind === "global") return ["install", "-g", `easel-canvas@${version}`, "--prefix", prefix, ...common];
28
+ throw new Error(`Easel cannot update itself here (${kind})`);
29
+ }
30
+
31
+ /** Why an install failed, in a word the page turns into plain words (strings.update.why): permission, network or failed */
32
+ export function classifyInstallFailure(text = "", code = null) {
33
+ if (/EACCES|EPERM|permission denied|operation not permitted/i.test(text)) return "permission";
34
+ if (/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|ECONNREFUSED|network|fetch failed|ENETUNREACH/i.test(text)) return "network";
35
+ if (code === "ENOENT") return "nonpm";
36
+ return "failed";
37
+ }
38
+
39
+ /** The version in <root>/package.json, or null */
40
+ export function versionOnDisk(root) {
41
+ try {
42
+ const v = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version;
43
+ return validVersion(v) ? v : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Installs easel-canvas@version where the copy at root came from. Resolves to { ok: true, root } (the folder to start the new server
51
+ * from, its package.json at that version) or { ok: false, why, detail }; never throws. Times out after `timeout` (npm hanging on a
52
+ * registry that does not answer).
53
+ */
54
+ export async function install({ version, root = TOOL_ROOT, env = process.env, spawnImpl = spawn, timeout = 180_000, npm = npmCommand() } = {}) {
55
+ try {
56
+ const { kind, prefix } = installKind(root);
57
+ const args = installArgs(kind, prefix, version);
58
+ let cmd;
59
+ if (env.EASEL_UPDATE_INSTALLER) {
60
+ const fake = JSON.parse(env.EASEL_UPDATE_INSTALLER);
61
+ if (!Array.isArray(fake) || !fake.every((a) => typeof a === "string")) throw new Error("EASEL_UPDATE_INSTALLER is not an argument array");
62
+ cmd = [...fake, ...args];
63
+ } else {
64
+ if (!npm) return { ok: false, why: "nonpm", detail: "npm was not found beside node" };
65
+ cmd = [...npm, ...args];
66
+ }
67
+ const out = await new Promise((resolve) => {
68
+ let text = "";
69
+ const p = spawnImpl(cmd[0], cmd.slice(1), { stdio: ["ignore", "pipe", "pipe"], env: { ...env, npm_config_update_notifier: "false" }, windowsHide: true });
70
+ const t = setTimeout(() => (p.kill("SIGTERM"), (text += "\nTimed out (network)")), timeout);
71
+ p.stdout?.on("data", (d) => (text += d));
72
+ p.stderr?.on("data", (d) => (text += d));
73
+ p.on("error", (e) => (clearTimeout(t), resolve({ code: e.code ?? "error", text: text + String(e.message) })));
74
+ p.on("close", (code) => (clearTimeout(t), resolve({ code, text })));
75
+ });
76
+ if (out.code !== 0) return { ok: false, why: classifyInstallFailure(out.text, out.code), detail: out.text.trim().split("\n").slice(-3).join("\n").slice(0, 400) };
77
+ const got = versionOnDisk(root);
78
+ if (got !== version) return { ok: false, why: "failed", detail: `After the install ${root} holds ${got ?? "no version"}, not ${version}` };
79
+ if (!existsSync(path.join(root, "bin", "server.mjs"))) return { ok: false, why: "failed", detail: "The new copy has no bin/server.mjs" };
80
+ return { ok: true, root };
81
+ } catch (e) {
82
+ return { ok: false, why: "failed", detail: String(e?.message ?? e) };
83
+ }
84
+ }
85
+
86
+ /** Polls http://127.0.0.1:port/api/health until a server with another pid answers, or the time is up; false if `alive()` says the new process died */
87
+ export async function waitForNew({ port, pid, ms = 30_000, alive = () => true, fetchImpl = fetch }) {
88
+ const end = Date.now() + ms;
89
+ while (Date.now() < end) {
90
+ if (!alive()) return false;
91
+ try {
92
+ const r = await fetchImpl(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1000) });
93
+ if (r.ok && (await r.json()).pid !== pid) return true;
94
+ } catch {}
95
+ await new Promise((r) => setTimeout(r, 250));
96
+ }
97
+ return false;
98
+ }
package/server/up.mjs CHANGED
@@ -80,6 +80,6 @@ export async function up({ dir, dirGiven = false, port = null, init = false, ope
80
80
 
81
81
  /** One line for people (and agents reading the output) */
82
82
  export function describe(r, dir) {
83
- if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas up`;
83
+ if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas@latest up`;
84
84
  return `${r.started ? "Started Easel" : "Easel is already running"}: ${r.url} (design folder ${r.dir}, pid ${r.pid})${r.log ? `\nLog: ${r.log}` : ""}`;
85
85
  }
package/server/update.mjs CHANGED
@@ -1,17 +1,25 @@
1
1
  // AI-generated with Claude Code, 2026-11-15, reviewed by Hyun Park
2
- // New-version notice: npx keeps the copy it cached, so nothing tells people a newer Easel exists. Once a day the canvas asks
3
- // the npm registry for easel-canvas's latest version (only that: one GET, nothing about the project) and, when it is newer,
4
- // says which command updates this install. Silent whenever it cannot ask: EASEL_NO_UPDATE_CHECK=1, CI, a source checkout
5
- // (git clone or submodule: updated with git), offline, a slow or broken registry.
6
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ // New-version notice: npx keeps the copy it cached, so nothing tells people a newer Easel exists. The canvas asks the npm registry
3
+ // for easel-canvas's latest version (only that: one GET, nothing about the project) when the page loads and every few hours while it
4
+ // runs, keeping the answer an hour, and when it is newer says how this install updates: in one click where Easel can replace itself
5
+ // (npx's cache, a global install; see selfupdate.mjs), else the command to run. Silent whenever it cannot ask:
6
+ // EASEL_NO_UPDATE_CHECK=1, CI, a source checkout (git clone or submodule: updated with git), offline, a slow or broken registry.
7
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
8
  import path from "node:path";
8
9
 
9
10
  import { TOOL_ROOT } from "./args.mjs";
10
11
  import { easelHome } from "./registry.mjs";
11
12
 
12
- const DAY = 24 * 60 * 60 * 1000;
13
+ export const HOUR = 60 * 60 * 1000;
14
+ /** How long an answer from the registry is kept (in memory and in <EASEL_HOME>/update.json) */
15
+ export const CACHE_MS = HOUR;
16
+ /** How often a running canvas asks again on its own (a page load asks too, when the answer is older than CACHE_MS) */
17
+ export const EVERY_MS = 3 * HOUR;
13
18
  const REGISTRY = "https://registry.npmjs.org/easel-canvas/latest";
14
19
 
20
+ /** A plain release version, x.y.z: the only thing ever passed on to npm (never a tag, a range or a URL) */
21
+ export const validVersion = (v) => typeof v === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(v);
22
+
15
23
  /** a > b for x.y.z versions; a pre-release (0.3.0-beta.1) is older than its release and never offered */
16
24
  export function isNewer(a, b) {
17
25
  const parse = (v) => String(v).replace(/^v/, "").split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
@@ -21,21 +29,48 @@ export function isNewer(a, b) {
21
29
  return /-/.test(String(b)); // 0.3.0 is newer than 0.3.0-beta.1
22
30
  }
23
31
 
32
+ /**
33
+ * Where the running copy comes from, and so how it updates:
34
+ * npx (npx's cache, <prefix>/_npx/<hash>/node_modules/easel-canvas): installs into that prefix in place, so plain `npx easel-canvas` starts
35
+ * the new one too; global (<prefix>/lib/node_modules, or <prefix>\node_modules on Windows): `npm i -g` into that prefix; project (a
36
+ * project's node_modules: its lockfile is the owner's call) and source (a checkout: git) only say the command; other: as npx.
37
+ */
38
+ export function installKind(root = TOOL_ROOT) {
39
+ const p = root.split(path.sep).join("/").replace(/\/+$/, "");
40
+ if (existsSync(path.join(root, "app")) || existsSync(path.join(root, ".git"))) return { kind: "source", prefix: null };
41
+ const m = p.match(/^(.*\/_npx\/[^/]+)\/node_modules\/easel-canvas$/);
42
+ if (m) return { kind: "npx", prefix: m[1].split("/").join(path.sep) };
43
+ const g = p.match(/^(.*)\/lib\/node_modules\/easel-canvas$/) ?? p.match(/^(.*\/npm)\/node_modules\/easel-canvas$/i);
44
+ if (g) return { kind: "global", prefix: g[1].split("/").join(path.sep) };
45
+ if (/\/node_modules\/easel-canvas$/.test(p)) return { kind: "project", prefix: null };
46
+ return { kind: "other", prefix: null };
47
+ }
48
+
24
49
  /** The command that updates the copy running from root: npx's cache, a project's node_modules, or a global install */
25
50
  export function updateCommand(root = TOOL_ROOT) {
26
- const p = root.split(path.sep).join("/");
27
- if (p.includes("/_npx/")) return "npx easel-canvas@latest";
28
- if (/\/node_modules\/easel-canvas\/?$/.test(p)) {
29
- const global = /\/lib\/node_modules\/easel-canvas\/?$/.test(p) || /\/npm\/node_modules\/easel-canvas\/?$/i.test(p);
30
- return global ? "npm i -g easel-canvas@latest" : "npm i -D easel-canvas@latest";
51
+ const { kind } = installKind(root);
52
+ return kind === "global" ? "npm i -g easel-canvas@latest" : kind === "project" ? "npm i -D easel-canvas@latest" : kind === "source" ? "git pull" : "npx easel-canvas@latest";
53
+ }
54
+
55
+ /** Whether Easel can replace this copy itself, and if not, why (shown under the row in plain words; see strings.update.why) */
56
+ export function selfUpdatable(root = TOOL_ROOT) {
57
+ const { kind } = installKind(root);
58
+ if (kind === "npx") return { self: true };
59
+ if (kind === "global") {
60
+ try {
61
+ accessSync(path.dirname(root), constants.W_OK); // …/lib/node_modules: npm writes there
62
+ return { self: true };
63
+ } catch {
64
+ return { self: false, why: "permission" };
65
+ }
31
66
  }
32
- return "npx easel-canvas@latest";
67
+ return { self: false, why: kind === "project" ? "project" : kind === "source" ? "source" : "other" };
33
68
  }
34
69
 
35
70
  /**
36
- * Resolves to { current, latest, command } when the registry has a newer version, else null; never throws.
37
- * The answer is kept a day in <EASEL_HOME>/update.json. EASEL_UPDATE_URL points the check elsewhere (tests, trying it out
38
- * from a source checkout).
71
+ * Resolves to { current, latest, command, kind, self, why? } when the registry has a newer version, else null; never throws.
72
+ * The answer is kept CACHE_MS in <EASEL_HOME>/update.json. EASEL_UPDATE_URL points the check elsewhere (tests, trying it out from a
73
+ * source checkout).
39
74
  */
40
75
  export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT, home = easelHome(env), now = Date.now(), fetchImpl = fetch } = {}) {
41
76
  try {
@@ -46,18 +81,45 @@ export async function checkUpdate({ current, env = process.env, root = TOOL_ROOT
46
81
  let latest = null;
47
82
  try {
48
83
  const c = JSON.parse(readFileSync(file, "utf8"));
49
- if (c.url === url && now - c.checkedAt < DAY) latest = c.latest;
84
+ if (c.url === url && now - c.checkedAt < CACHE_MS && now >= c.checkedAt) latest = c.latest;
50
85
  } catch {}
51
86
  if (!latest) {
52
87
  const r = await fetchImpl(url, { signal: AbortSignal.timeout(2000), headers: { accept: "application/json" } });
53
88
  if (!r.ok) return null;
54
89
  latest = (await r.json())?.version;
55
- if (typeof latest !== "string") return null;
90
+ if (!validVersion(latest)) return null;
56
91
  mkdirSync(home, { recursive: true });
57
92
  writeFileSync(file, JSON.stringify({ url, checkedAt: now, latest }));
58
93
  }
59
- return isNewer(latest, current) ? { current, latest, command: updateCommand(root) } : null;
94
+ if (!validVersion(latest) || !isNewer(latest, current)) return null;
95
+ const { kind } = installKind(root);
96
+ return { current, latest, command: updateCommand(root), kind, ...selfUpdatable(root) };
60
97
  } catch {
61
98
  return null;
62
99
  }
63
100
  }
101
+
102
+ /**
103
+ * The server's view of the notice: get() answers from memory while the last check is younger than CACHE_MS, else asks again (one at a
104
+ * time); a timer asks every EVERY_MS while the canvas runs (unref'd: it never keeps the process alive). onNews(u) is told the first time
105
+ * each newer version is seen (the terminal line).
106
+ */
107
+ export function createUpdater({ current, env = process.env, root = TOOL_ROOT, home, now = () => Date.now(), fetchImpl = fetch, onNews = () => {}, every = EVERY_MS } = {}) {
108
+ let last = null; // { at, value }
109
+ let pending = null;
110
+ let told = null;
111
+ const get = () => {
112
+ if (last && now() - last.at < CACHE_MS && now() >= last.at) return Promise.resolve(last.value);
113
+ pending ??= checkUpdate({ current, env, root, home: home ?? easelHome(env), now: now(), fetchImpl })
114
+ .then((value) => {
115
+ last = { at: now(), value };
116
+ if (value && told !== value.latest) (told = value.latest), onNews(value);
117
+ return value;
118
+ })
119
+ .finally(() => (pending = null));
120
+ return pending;
121
+ };
122
+ const timer = setInterval(() => void get(), every);
123
+ timer.unref?.();
124
+ return { get, close: () => clearInterval(timer) };
125
+ }