easel-canvas 0.2.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -9
- package/bin/mcp.mjs +109 -9
- package/bin/server.mjs +22 -1
- package/dist/assets/index-DuziykA0.css +1 -0
- package/dist/assets/index-o294phw7.js +74 -0
- package/dist/index.html +2 -2
- package/dist/viewer/viewer.css +1 -1
- package/dist/viewer/viewer.js +20 -14
- package/examples/demo/.thumbs/home.html.1791613627606.jpg +0 -0
- package/package.json +8 -2
- package/server/activity.mjs +17 -2
- package/server/args.mjs +5 -4
- package/server/boards.mjs +64 -8
- package/server/browser.mjs +262 -32
- package/server/edit.mjs +27 -0
- package/server/export.mjs +40 -27
- package/server/index.mjs +33 -5
- package/server/livePatch.mjs +109 -0
- package/server/occupancy.mjs +14 -3
- package/server/place.mjs +11 -0
- package/server/registry.mjs +1 -1
- package/server/requests.mjs +560 -0
- package/server/routes.mjs +123 -42
- package/server/stamps.mjs +134 -0
- package/server/up.mjs +85 -0
- package/server/watch.mjs +31 -9
- package/dist/assets/index-CjyXUlEx.css +0 -1
- package/dist/assets/index-DFCSLJXY.js +0 -66
package/server/routes.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import fs from "node:fs/promises";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
|
|
6
6
|
import { activityRoutes } from "./activity.mjs";
|
|
7
|
-
import { closeBrowser,
|
|
7
|
+
import { closeBrowser, gotoSettled, withPage } from "./browser.mjs";
|
|
8
8
|
import { boardRoutes } from "./boards.mjs";
|
|
9
9
|
import { chatRoutes } from "./chat.mjs";
|
|
10
10
|
import { tokenRoutes } from "./tokens.mjs";
|
|
@@ -14,7 +14,9 @@ import { exportRoutes } from "./export.mjs";
|
|
|
14
14
|
import { forkMessage, forkRoutes, routeWrite } from "./forks.mjs";
|
|
15
15
|
import { easelDir, rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
|
|
16
16
|
import { inspect, outline } from "./html.mjs";
|
|
17
|
+
import { contentHash, livePatch } from "./livePatch.mjs";
|
|
17
18
|
import { readBody, safeJoin, sendJson } from "./index.mjs";
|
|
19
|
+
import { requestRoutes, undoState } from "./requests.mjs";
|
|
18
20
|
import { watchDesign } from "./watch.mjs";
|
|
19
21
|
|
|
20
22
|
const OUTER_LIMIT = 4096;
|
|
@@ -51,38 +53,63 @@ async function writeComments(ctx, comments) {
|
|
|
51
53
|
|
|
52
54
|
/* ---------- Screenshots (when playwright is available) ---------- */
|
|
53
55
|
// The shared Chromium lives in browser.mjs (export uses it too); re-exported here for existing callers
|
|
54
|
-
export { cachedBrowser, closeBrowser, newPage } from "./browser.mjs";
|
|
56
|
+
export { cachedBrowser, closeBrowser, newPage, withPage } from "./browser.mjs";
|
|
55
57
|
|
|
56
58
|
/** Thumbnail sizes (long side, device px) the client may ask for; anything else snaps to the next one up. Matches THUMB_SIZES in Canvas.tsx */
|
|
57
59
|
const THUMB_PX = [600, 1200, 2400];
|
|
58
60
|
export const thumbPx = (v) => THUMB_PX.find((s) => s >= Number(v)) ?? (Number(v) > 0 ? THUMB_PX[THUMB_PX.length - 1] : THUMB_PX[0]);
|
|
59
61
|
|
|
60
|
-
/**
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
62
|
+
/**
|
|
63
|
+
* Thumbnail jobs, at most two at a time. The newest request goes first (the boards the user is looking at now asked last),
|
|
64
|
+
* and a job still waiting when its request closes (board scrolled away, tab closed) is dropped. A job that has started
|
|
65
|
+
* always finishes, so its thumbnail is cached for the next request.
|
|
66
|
+
*/
|
|
67
|
+
export function createThumbQueue(limit = 2) {
|
|
68
|
+
let running = 0;
|
|
69
|
+
const waiting = [];
|
|
70
|
+
const next = () => {
|
|
71
|
+
while (running < limit && waiting.length) {
|
|
72
|
+
const job = waiting.pop();
|
|
73
|
+
if (job.gone()) job.reject(Object.assign(new Error("Thumbnail request closed before its turn"), { dropped: true }));
|
|
74
|
+
else void job.run();
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
/** gone(): true once nobody waits for the result */
|
|
79
|
+
push(fn, gone = () => false) {
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
const run = async () => {
|
|
82
|
+
running++;
|
|
83
|
+
try {
|
|
84
|
+
resolve(await fn());
|
|
85
|
+
} catch (e) {
|
|
86
|
+
reject(e);
|
|
87
|
+
} finally {
|
|
88
|
+
running--;
|
|
89
|
+
next();
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
waiting.push({ run, gone, reject });
|
|
93
|
+
next();
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
stats: () => ({ running, waiting: waiting.length }),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
const thumbQueue = createThumbQueue(2);
|
|
100
|
+
|
|
101
|
+
/** The newest thumbnail of a board on disk (any version, this size first), for when a new one cannot be made */
|
|
102
|
+
async function previousThumb(dir, base, px) {
|
|
103
|
+
const names = (await fs.readdir(dir).catch(() => [])).filter((n) => n.startsWith(base + ".") && n.endsWith(".jpg"));
|
|
104
|
+
const dated = await Promise.all(names.map(async (n) => ({ n, t: (await fs.stat(path.join(dir, n)).catch(() => null))?.mtimeMs ?? 0, same: n.endsWith(`.${px}.jpg`) })));
|
|
105
|
+
dated.sort((a, b) => b.same - a.same || b.t - a.t);
|
|
106
|
+
return dated.length ? fs.readFile(path.join(dir, dated[0].n)).catch(() => null) : null;
|
|
79
107
|
}
|
|
80
108
|
|
|
81
109
|
export async function screenshot(ctx, port, file, elPath) {
|
|
82
110
|
const board = (await ctx.store.readBoard()).boards[file];
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(file)}`, { waitUntil: "networkidle" });
|
|
111
|
+
return withPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 }, async (page) => {
|
|
112
|
+
await gotoSettled(page, `http://127.0.0.1:${port}/screens/${encodeURI(file)}`);
|
|
86
113
|
const outDir = path.join(await easelDir(ctx.dir), "screenshots");
|
|
87
114
|
await fs.mkdir(outDir, { recursive: true });
|
|
88
115
|
const name = `${file.replace(/[\\/]/g, "_").replace(/\.html$/, "")}${elPath ? "--" + elPath.replace(/\//g, "-") : ""}.png`;
|
|
@@ -100,9 +127,7 @@ export async function screenshot(ctx, port, file, elPath) {
|
|
|
100
127
|
await page.screenshot({ path: out, fullPage: true });
|
|
101
128
|
}
|
|
102
129
|
return out;
|
|
103
|
-
}
|
|
104
|
-
await page.close();
|
|
105
|
-
}
|
|
130
|
+
});
|
|
106
131
|
}
|
|
107
132
|
|
|
108
133
|
export const extraRoutes = [
|
|
@@ -126,9 +151,14 @@ export const extraRoutes = [
|
|
|
126
151
|
}
|
|
127
152
|
if (next === html) return sendJson(res, 200, { ok: true, changed: false, ...fork });
|
|
128
153
|
await writeScreen(ctx, p, next);
|
|
129
|
-
|
|
154
|
+
// What a style step changed (its human name says "colour", "fill", "radius"…): the property, or a batch's when they agree
|
|
155
|
+
const props = b.op === "setStyle" ? [b.prop] : b.op === "batch" && Array.isArray(b.ops) ? [...new Set(b.ops.filter((o) => o.op === "setStyle").map((o) => o.prop))] : [];
|
|
156
|
+
ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }], props.length === 1 && props[0] ? { prop: props[0] } : {});
|
|
130
157
|
ctx.broadcast({ type: "history-changed" });
|
|
131
|
-
|
|
158
|
+
// base/hash: the file's content hash before and after; live: the DOM change that turns a board showing base into one showing
|
|
159
|
+
// hash, when that is proven (server/livePatch.mjs). Never for a fork: the caller's board is not the file written
|
|
160
|
+
const live = to.forked ? null : livePatch(html, next, b);
|
|
161
|
+
sendJson(res, 200, { ok: true, changed: true, base: contentHash(html), hash: contentHash(next), ...(live ? { live } : {}), ...fork });
|
|
132
162
|
},
|
|
133
163
|
],
|
|
134
164
|
// Legacy route: forwards to the chronological history
|
|
@@ -145,8 +175,11 @@ export const extraRoutes = [
|
|
|
145
175
|
...forkRoutes(),
|
|
146
176
|
...activityRoutes(),
|
|
147
177
|
...chat.routes,
|
|
178
|
+
...requestRoutes({ chatState: chat.state, getSelection: () => selection }),
|
|
148
179
|
...tokenRoutes(),
|
|
149
|
-
// Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per
|
|
180
|
+
// Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per render stamp (server/stamps.mjs: the
|
|
181
|
+
// board's HTML and every local file it loads) in docs/design/.thumbs/ (gitignored). The app asks with the stamp it was told
|
|
182
|
+
// (s=), so that URL is cached for good; without it, or with a stamp that is no longer current, the answer is revalidated
|
|
150
183
|
[
|
|
151
184
|
"GET",
|
|
152
185
|
"/api/thumb",
|
|
@@ -154,36 +187,48 @@ export const extraRoutes = [
|
|
|
154
187
|
const f = url.searchParams.get("f") ?? "";
|
|
155
188
|
const src = safeJoin(ctx.store.screensDir, f);
|
|
156
189
|
const st = src && (await fs.stat(src).catch(() => null));
|
|
157
|
-
if (!st) return sendJson(res, 404, { error: "File not found" });
|
|
190
|
+
if (!st?.isFile()) return sendJson(res, 404, { error: "File not found" });
|
|
158
191
|
const px = thumbPx(url.searchParams.get("px"));
|
|
159
192
|
const dir = path.join(ctx.dir, ".thumbs");
|
|
160
193
|
const base = f.replace(/[\\/]/g, "_");
|
|
161
|
-
const
|
|
194
|
+
const cur = (await ctx.stamps.stamp(f)) ?? `m${Math.round(st.mtimeMs)}`;
|
|
195
|
+
const stamp = `${base}.${cur}.`;
|
|
162
196
|
const out = path.join(dir, `${stamp}${px}.jpg`);
|
|
197
|
+
// Read the port now: a job that waits in the queue runs after its request may have closed, and a closed socket has no localPort
|
|
198
|
+
const port = req.socket.localPort;
|
|
199
|
+
let gone = false;
|
|
200
|
+
res.on("close", () => (gone = true));
|
|
163
201
|
let buf = await fs.readFile(out).catch(() => null);
|
|
202
|
+
let fresh = true;
|
|
164
203
|
if (!buf) {
|
|
165
|
-
buf = await thumbQueue(async () => {
|
|
204
|
+
buf = await thumbQueue.push(async () => {
|
|
166
205
|
await fs.mkdir(dir, { recursive: true });
|
|
167
206
|
await fs.writeFile(path.join(dir, ".gitignore"), "*\n").catch(() => {});
|
|
168
207
|
const board = (await ctx.store.readBoard()).boards[f];
|
|
169
208
|
const w = board?.w ?? 390;
|
|
170
209
|
const h = board?.h ?? 844;
|
|
171
210
|
// Long side ≈ px device pixels, so large boards stay sharp when zoomed out on a 2× display
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
await page.goto(`http://127.0.0.1:${req.socket.localPort}/screens/${encodeURI(f)}`, { waitUntil: "load", timeout: 15000 });
|
|
211
|
+
return withPage({ viewport: { width: w, height: h }, deviceScaleFactor: Math.min(2, px / Math.max(w, h)) }, async (page) => {
|
|
212
|
+
await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(f)}`, { waitUntil: "load", timeout: 15000 });
|
|
175
213
|
await page.waitForTimeout(150);
|
|
176
214
|
const b = await page.screenshot({ type: "jpeg", quality: 80 });
|
|
177
|
-
// Remove thumbnails of older versions (other sizes of this version stay)
|
|
215
|
+
// Remove thumbnails of older versions (other sizes of this version stay); only once the new one is made
|
|
178
216
|
for (const n of await fs.readdir(dir)) if (n.startsWith(base + ".") && !n.startsWith(stamp)) await fs.rm(path.join(dir, n), { force: true });
|
|
179
217
|
await fs.writeFile(out, b);
|
|
180
218
|
return b;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
|
|
219
|
+
});
|
|
220
|
+
}, () => gone).catch(async (e) => {
|
|
221
|
+
if (e.dropped) return null;
|
|
222
|
+
// The render failed: the last picture of this board, if there is one, beats no picture (and is asked for again next time)
|
|
223
|
+
const old = await previousThumb(dir, base, px);
|
|
224
|
+
if (!old) throw e;
|
|
225
|
+
fresh = false;
|
|
226
|
+
return old;
|
|
184
227
|
});
|
|
228
|
+
if (!buf) return; // nobody is waiting for it any more
|
|
185
229
|
}
|
|
186
|
-
|
|
230
|
+
const cache = fresh && url.searchParams.get("s") === cur ? "max-age=31536000, immutable" : "no-cache";
|
|
231
|
+
res.writeHead(200, { "Content-Type": "image/jpeg", "Content-Length": buf.length, "Cache-Control": cache });
|
|
187
232
|
res.end(buf);
|
|
188
233
|
},
|
|
189
234
|
],
|
|
@@ -229,7 +274,17 @@ export const extraRoutes = [
|
|
|
229
274
|
const { html } = await readScreen(ctx, url.searchParams.get("f"));
|
|
230
275
|
const info = inspect(html, url.searchParams.get("path") ?? "");
|
|
231
276
|
if (!info) return sendJson(res, 404, { error: "Element not found (the file changed, select again)" });
|
|
232
|
-
|
|
277
|
+
// fileHash: the whole file now, so a board patched in place can check that it still shows the file
|
|
278
|
+
sendJson(res, 200, { hash: info.hash, fileHash: contentHash(html), tag: info.tag, text: info.text.slice(0, 200), source: url.searchParams.get("full") ? info.source : info.source.slice(0, OUTER_LIMIT) });
|
|
279
|
+
},
|
|
280
|
+
],
|
|
281
|
+
// The content hash of a board file now (a board patched in place asks after an echo of an older version of its own edits)
|
|
282
|
+
[
|
|
283
|
+
"GET",
|
|
284
|
+
"/api/file-hash",
|
|
285
|
+
async (req, res, url, ctx) => {
|
|
286
|
+
const { html } = await readScreen(ctx, url.searchParams.get("f"));
|
|
287
|
+
sendJson(res, 200, { hash: contentHash(html) });
|
|
233
288
|
},
|
|
234
289
|
],
|
|
235
290
|
[
|
|
@@ -300,6 +355,10 @@ export const extraRoutes = [
|
|
|
300
355
|
const f = url.searchParams.get("file");
|
|
301
356
|
if (f) list = list.filter((c) => c.file === f);
|
|
302
357
|
if (url.searchParams.get("unresolved") === "1") list = list.filter((c) => !c.resolved);
|
|
358
|
+
// for_agent=1: only comments marked For AI (requests for the agent the person is talking to)
|
|
359
|
+
if (url.searchParams.get("for_agent") === "1") list = list.filter((c) => c.forAgent);
|
|
360
|
+
// A done request says whether its own undo steps can still be undone (not stored: read from this server's history)
|
|
361
|
+
list = list.map((c) => (c.request?.state === "done" && c.request.steps?.length ? { ...c, request: { ...c.request, undo: undoState(ctx.history, c.request.steps) } } : c));
|
|
303
362
|
sendJson(res, 200, { comments: list });
|
|
304
363
|
},
|
|
305
364
|
],
|
|
@@ -320,6 +379,23 @@ export const extraRoutes = [
|
|
|
320
379
|
ctx.broadcast({ type: "comments-changed" });
|
|
321
380
|
return sendJson(res, 200, { comment: c, reply: r });
|
|
322
381
|
}
|
|
382
|
+
if (b.action === "edit") {
|
|
383
|
+
const c = list.find((x) => x.id === b.id);
|
|
384
|
+
if (!c) return sendJson(res, 404, { error: "Comment not found" });
|
|
385
|
+
if (!String(b.text ?? "").trim()) return sendJson(res, 400, { error: "text is required" });
|
|
386
|
+
c.text = String(b.text).trim();
|
|
387
|
+
await writeComments(ctx, list);
|
|
388
|
+
ctx.broadcast({ type: "comments-changed" });
|
|
389
|
+
return sendJson(res, 200, { comment: c });
|
|
390
|
+
}
|
|
391
|
+
if (b.action === "delete") {
|
|
392
|
+
const i = list.findIndex((x) => x.id === b.id);
|
|
393
|
+
if (i < 0) return sendJson(res, 404, { error: "Comment not found" });
|
|
394
|
+
const [c] = list.splice(i, 1);
|
|
395
|
+
await writeComments(ctx, list);
|
|
396
|
+
ctx.broadcast({ type: "comments-changed" });
|
|
397
|
+
return sendJson(res, 200, { comment: c });
|
|
398
|
+
}
|
|
323
399
|
if (b.action === "resolve") {
|
|
324
400
|
const c = list.find((x) => x.id === b.id);
|
|
325
401
|
if (!c) return sendJson(res, 404, { error: "Comment not found" });
|
|
@@ -350,6 +426,11 @@ export const extraRoutes = [
|
|
|
350
426
|
await readScreen(ctx, b.file);
|
|
351
427
|
const port = Number(req.socket.localPort);
|
|
352
428
|
const out = await screenshot(ctx, port, b.file, b.path || "");
|
|
429
|
+
// inline: the PNG itself, for the board menu's Export PNG to download (the copy in .easel/screenshots stays as for MCP)
|
|
430
|
+
if (b.inline) {
|
|
431
|
+
res.writeHead(200, { "Content-Type": "image/png", "Cache-Control": "no-store" });
|
|
432
|
+
return res.end(await fs.readFile(out));
|
|
433
|
+
}
|
|
353
434
|
sendJson(res, 200, { path: out, relPath: toPosix(path.relative(rootOf(ctx.dir), out)) });
|
|
354
435
|
},
|
|
355
436
|
],
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-29
|
|
2
|
+
// A board's render stamp: a short hash of the modification time and size of its HTML and of every local file the page loads
|
|
3
|
+
// (stylesheets and what they import, scripts, images, fonts, media, embedded boards and what those load). It changes whenever
|
|
4
|
+
// the rendered board can change, so the zoomed-out thumbnail is keyed by it on disk and in its URL (cached for a year by the
|
|
5
|
+
// browser). Not followed: what scripts fetch at run time, and remote URLs (both rarely change what a board looks like).
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import fs from "node:fs/promises";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
/** Tags whose attributes load something into the page (an <a href> only links, so it is not one) */
|
|
11
|
+
const LOADING_TAG = /<(link|script|img|source|video|audio|track|iframe|frame|object|embed|image|use|feimage|input)\b([^>]*)>/gi;
|
|
12
|
+
const LOADING_ATTR = /(?:^|\s)(src|href|srcset|poster|data|xlink:href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
|
|
13
|
+
const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)/gi;
|
|
14
|
+
const CSS_IMPORT = /@import\s+(?:"([^"]*)"|'([^']*)')/gi;
|
|
15
|
+
/** A board's page loads at most this many local files that count (a runaway page still gets a stamp) */
|
|
16
|
+
const MAX_FILES = 400;
|
|
17
|
+
|
|
18
|
+
const kindOf = (p) => (/\.html?$/i.test(p) ? "html" : /\.css$/i.test(p) ? "css" : "leaf");
|
|
19
|
+
|
|
20
|
+
/** The local references in an HTML page or a stylesheet, as written */
|
|
21
|
+
export function refsIn(text, kind) {
|
|
22
|
+
const out = [];
|
|
23
|
+
const css = (s) => {
|
|
24
|
+
for (const m of s.matchAll(CSS_URL)) out.push(m[1] ?? m[2] ?? m[3]);
|
|
25
|
+
for (const m of s.matchAll(CSS_IMPORT)) out.push(m[1] ?? m[2]);
|
|
26
|
+
};
|
|
27
|
+
if (kind === "css") {
|
|
28
|
+
css(text);
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
for (const t of text.matchAll(LOADING_TAG)) {
|
|
32
|
+
for (const a of t[2].matchAll(LOADING_ATTR)) {
|
|
33
|
+
const v = a[2] ?? a[3] ?? a[4] ?? "";
|
|
34
|
+
if (a[1].toLowerCase() === "srcset") for (const part of v.split(",")) out.push(part.trim().split(/\s+/)[0]);
|
|
35
|
+
else out.push(v);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Inline <style> blocks and style="" attributes (a url() inside a script only adds a needless dependency)
|
|
39
|
+
css(text);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createStamps(dir) {
|
|
44
|
+
const root = path.resolve(dir);
|
|
45
|
+
const screensDir = path.join(root, "screens");
|
|
46
|
+
const parsed = new Map(); // abs → { key, refs: abs[] }
|
|
47
|
+
const depsOf = new Map(); // board file → Set(abs) its last stamp covered
|
|
48
|
+
|
|
49
|
+
/** Where the server finds what a page at `fromAbs` asks for with `ref` (the same mapping as the static routes), or null */
|
|
50
|
+
async function resolve(fromAbs, ref) {
|
|
51
|
+
ref = String(ref ?? "").trim();
|
|
52
|
+
if (!ref || ref.startsWith("#") || ref.startsWith("//") || /^[a-z][\w+.-]*:/i.test(ref)) return null;
|
|
53
|
+
let pathname;
|
|
54
|
+
try {
|
|
55
|
+
const base = new URL("http://x/" + path.relative(root, fromAbs).split(path.sep).map(encodeURIComponent).join("/"));
|
|
56
|
+
pathname = decodeURIComponent(new URL(ref, base).pathname);
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
const inside = (p) => (p === root || p.startsWith(root + path.sep) ? p : null);
|
|
61
|
+
if (pathname.startsWith("/screens/") || pathname.startsWith("/assets/")) return inside(path.join(root, pathname));
|
|
62
|
+
// Other root paths: the server sends them to screens/ when the file is there, else serves them from the design folder
|
|
63
|
+
const inScreens = inside(path.join(screensDir, pathname));
|
|
64
|
+
if (inScreens && (await fs.stat(inScreens).catch(() => null))) return inScreens;
|
|
65
|
+
return inside(path.join(root, pathname));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function refsOf(abs, key) {
|
|
69
|
+
const hit = parsed.get(abs);
|
|
70
|
+
if (hit?.key === key) return hit.refs;
|
|
71
|
+
const kind = kindOf(abs);
|
|
72
|
+
let refs = [];
|
|
73
|
+
if (kind !== "leaf") {
|
|
74
|
+
const text = await fs.readFile(abs, "utf8").catch(() => "");
|
|
75
|
+
refs = (await Promise.all(refsIn(text, kind).map((r) => resolve(abs, r)))).filter((p) => p && p !== abs);
|
|
76
|
+
}
|
|
77
|
+
parsed.set(abs, { key, refs });
|
|
78
|
+
return refs;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The stamp of a board (path under screens/), or null when its file is missing. memo: stats shared by several stamps made
|
|
83
|
+
* together (a hundred boards using the same fonts stat them once)
|
|
84
|
+
*/
|
|
85
|
+
async function stamp(file, memo = new Map()) {
|
|
86
|
+
const start = path.join(screensDir, file);
|
|
87
|
+
const statOf = (p) => {
|
|
88
|
+
if (!memo.has(p)) memo.set(p, fs.stat(p).then((s) => (s.isFile() ? `${Math.round(s.mtimeMs)}:${s.size}` : "-"), () => "-"));
|
|
89
|
+
return memo.get(p);
|
|
90
|
+
};
|
|
91
|
+
const first = await statOf(start);
|
|
92
|
+
if (first === "-") {
|
|
93
|
+
depsOf.delete(file);
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const seen = new Map([[start, first]]);
|
|
97
|
+
let level = [start];
|
|
98
|
+
while (level.length && seen.size < MAX_FILES) {
|
|
99
|
+
const next = [];
|
|
100
|
+
for (const refs of await Promise.all(level.map(async (p) => (kindOf(p) === "leaf" || seen.get(p) === "-" ? [] : refsOf(p, seen.get(p)))))) {
|
|
101
|
+
for (const r of refs) if (!seen.has(r) && seen.size < MAX_FILES) {
|
|
102
|
+
seen.set(r, null);
|
|
103
|
+
next.push(r);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
await Promise.all(next.map(async (p) => seen.set(p, await statOf(p))));
|
|
107
|
+
level = next;
|
|
108
|
+
}
|
|
109
|
+
depsOf.set(file, new Set(seen.keys()));
|
|
110
|
+
const h = createHash("sha1");
|
|
111
|
+
for (const [p, s] of [...seen].sort((a, b) => (a[0] < b[0] ? -1 : 1))) h.update(`${path.relative(root, p)}\0${s}\n`);
|
|
112
|
+
return h.digest("hex").slice(0, 12);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Stamps of many boards at once */
|
|
116
|
+
async function stampAll(files) {
|
|
117
|
+
const memo = new Map();
|
|
118
|
+
const out = {};
|
|
119
|
+
await Promise.all(files.map(async (f) => {
|
|
120
|
+
const s = await stamp(f, memo);
|
|
121
|
+
if (s) out[f] = s;
|
|
122
|
+
}));
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Boards whose last stamp covered abs (a file they load, directly or through a stylesheet or an embedded board) */
|
|
127
|
+
function users(abs) {
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const [f, set] of depsOf) if (set.has(abs)) out.push(f);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return { stamp, stampAll, users, forget: (file) => depsOf.delete(file) };
|
|
134
|
+
}
|
package/server/up.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-27, reviewed by Hyun Park
|
|
2
|
+
// `easel-canvas up` / `status`: is a canvas running for this project, and if not (up), start one in the background.
|
|
3
|
+
// Used by agents (the Easel skill and plugin commands) so asking twice never starts a second server for the same folder.
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
import { TOOL_ROOT } from "./args.mjs";
|
|
10
|
+
import { projectName } from "./fsutil.mjs";
|
|
11
|
+
import { easelHome, isAlive, readEntries, real, within } from "./registry.mjs";
|
|
12
|
+
|
|
13
|
+
const view = (e) => ({ running: true, url: `http://localhost:${e.port}`, port: e.port, pid: e.pid, dir: e.dir, root: e.root });
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The live canvas for this project: one serving exactly `dir`; without an explicit --dir also one whose project root
|
|
17
|
+
* contains cwd (longest root wins), so `up` from a subfolder or with the screens in another folder finds it. Never
|
|
18
|
+
* another project's canvas. Returns null when there is none.
|
|
19
|
+
*/
|
|
20
|
+
export async function findCanvas({ dir, dirGiven = false, cwd = process.cwd(), home = easelHome() }) {
|
|
21
|
+
const live = [];
|
|
22
|
+
for (const e of readEntries(home)) if (await isAlive(e)) live.push(e);
|
|
23
|
+
const exact = live.find((e) => real(e.dir) === real(dir));
|
|
24
|
+
if (exact) return view(exact);
|
|
25
|
+
if (dirGiven) return null;
|
|
26
|
+
const here = real(cwd);
|
|
27
|
+
const around = live.filter((e) => within(here, real(e.root))).sort((a, b) => real(b.root).length - real(a.root).length);
|
|
28
|
+
return around.length ? view(around[0]) : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const tail = (file, n = 20) => {
|
|
32
|
+
try {
|
|
33
|
+
return readFileSync(file, "utf8").trimEnd().split("\n").slice(-n).join("\n");
|
|
34
|
+
} catch {
|
|
35
|
+
return "";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Starts `easel-canvas` detached (it outlives this process and the agent's shell), its output in
|
|
41
|
+
* <EASEL_HOME>/logs/<folder>-<hash>.log, and waits until it has registered itself. Rejects with the log's end when it exits first.
|
|
42
|
+
*/
|
|
43
|
+
export async function startCanvas({ dir, port = null, init = false, open = true, prod = false, home = easelHome(), timeoutMs = 30000, env = process.env }) {
|
|
44
|
+
const logs = path.join(home, "logs");
|
|
45
|
+
mkdirSync(logs, { recursive: true });
|
|
46
|
+
const log = path.join(logs, `${projectName(dir)}-${crypto.createHash("sha1").update(real(dir)).digest("hex").slice(0, 8)}.log`);
|
|
47
|
+
const fd = openSync(log, "w");
|
|
48
|
+
const args = [path.join(TOOL_ROOT, "bin/server.mjs"), "--dir", dir, ...(port ? ["--port", String(port)] : []), ...(init ? ["--init"] : []), open ? "--open" : "--no-open", ...(prod ? ["--prod"] : [])];
|
|
49
|
+
const child = spawn(process.execPath, args, { detached: true, stdio: ["ignore", fd, fd], env: { ...env, EASEL_HOME: home }, windowsHide: true });
|
|
50
|
+
closeSync(fd);
|
|
51
|
+
let exited = null;
|
|
52
|
+
child.on("exit", (code, signal) => (exited = { code, signal }));
|
|
53
|
+
child.on("error", (e) => (exited = { error: e }));
|
|
54
|
+
const until = Date.now() + timeoutMs;
|
|
55
|
+
try {
|
|
56
|
+
while (Date.now() < until) {
|
|
57
|
+
if (exited) {
|
|
58
|
+
const why = exited.error ? exited.error.message : `exited with ${exited.signal ?? exited.code}`;
|
|
59
|
+
throw Object.assign(new Error(`Easel did not start (${why}).${tail(log) ? `\n${tail(log)}` : ""}`), { log });
|
|
60
|
+
}
|
|
61
|
+
const e = readEntries(home).find((x) => x.pid === child.pid);
|
|
62
|
+
if (e && (await isAlive(e))) return { ...view(e), started: true, log };
|
|
63
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
64
|
+
}
|
|
65
|
+
child.kill();
|
|
66
|
+
throw Object.assign(new Error(`Easel did not start within ${Math.round(timeoutMs / 1000)} s; see ${log}`), { log });
|
|
67
|
+
} finally {
|
|
68
|
+
child.unref();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `up`: the running canvas for this project, or a newly started one. A missing design folder is an error unless init */
|
|
73
|
+
export async function up({ dir, dirGiven = false, port = null, init = false, open = true, prod = false, cwd, home = easelHome(), timeoutMs }) {
|
|
74
|
+
const found = await findCanvas({ dir, dirGiven, cwd, home });
|
|
75
|
+
if (found) return { ...found, started: false };
|
|
76
|
+
if (!init && !existsSync(dir))
|
|
77
|
+
throw Object.assign(new Error(`No design folder at ${dir}. Run again with --init to create it with a starter screen, or pass --dir <folder of screens/*.html>.`), { code: "NO_DESIGN_FOLDER" });
|
|
78
|
+
return startCanvas({ dir, port, init, open, prod, home, timeoutMs });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One line for people (and agents reading the output) */
|
|
82
|
+
export function describe(r, dir) {
|
|
83
|
+
if (!r) return `No Easel canvas is running for ${dir}. Start one with: npx easel-canvas up`;
|
|
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
|
+
}
|
package/server/watch.mjs
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
// AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
|
|
2
2
|
// Design folder watcher: when HTML changes, notify so only that board is redrawn; new files are auto-placed in board.json. PLAN.md ch. 7 M2.
|
|
3
3
|
// Changes the app did not make (agents' own file tools, editors) are handed to the undo history, which records them as steps.
|
|
4
|
-
import crypto from "node:crypto";
|
|
5
4
|
import fs from "node:fs/promises";
|
|
6
5
|
import path from "node:path";
|
|
7
6
|
|
|
8
7
|
import chokidar from "chokidar";
|
|
9
8
|
|
|
10
9
|
import { createDeps } from "./deps.mjs";
|
|
10
|
+
import { createStamps } from "./stamps.mjs";
|
|
11
11
|
import { toPosix } from "./fsutil.mjs";
|
|
12
|
+
import { contentHash } from "./livePatch.mjs";
|
|
12
13
|
|
|
13
|
-
export function watchDesign({ dir, store, broadcast, history }) {
|
|
14
|
+
export function watchDesign({ dir, store, broadcast, history, stamps = createStamps(dir) }) {
|
|
14
15
|
const screensDir = store.screensDir;
|
|
15
|
-
|
|
16
|
+
// The whole design folder: a stylesheet, image or font a board loads may sit anywhere in it (assets/ mostly)
|
|
17
|
+
const watcher = chokidar.watch([dir, screensDir, store.boardPath], {
|
|
16
18
|
ignoreInitial: true,
|
|
17
19
|
// Ignore iCloud placeholders (.icloud) and hidden files (PLAN.md ch. 9)
|
|
18
20
|
ignored: (p) => {
|
|
@@ -26,11 +28,13 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
26
28
|
// On an outside rename (same content deleted then created), move the board position/title to the new name
|
|
27
29
|
const hashes = new Map(); // file → content sha1
|
|
28
30
|
const removed = []; // { file, hash, at }
|
|
29
|
-
const sha =
|
|
31
|
+
const sha = contentHash;
|
|
30
32
|
store.listScreenFiles().then(async (files) => {
|
|
31
33
|
for (const f of files) hashes.set(f, sha(await fs.readFile(path.join(screensDir, f), "utf8").catch(() => "")));
|
|
32
34
|
});
|
|
33
35
|
store.listScreenFiles().then((files) => deps.init(files));
|
|
36
|
+
// Which files each board loads, so a change to a shared one finds its boards
|
|
37
|
+
store.listScreenFiles().then((files) => stamps.stampAll(files)).catch(() => {});
|
|
34
38
|
let syncTimer = null;
|
|
35
39
|
const scheduleSync = () => {
|
|
36
40
|
clearTimeout(syncTimer);
|
|
@@ -79,18 +83,29 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
79
83
|
broadcast({ type: "board-changed", source: "server:external" });
|
|
80
84
|
return;
|
|
81
85
|
}
|
|
82
|
-
|
|
86
|
+
const inScreens = abs.startsWith(screensDir + path.sep);
|
|
87
|
+
if (!abs.endsWith(".html") || !inScreens) {
|
|
88
|
+
// A file boards load (a stylesheet, an image, a font, a page outside screens/): redraw those boards and their thumbnails
|
|
89
|
+
for (const host of stamps.users(abs)) {
|
|
90
|
+
const stamp = await stamps.stamp(host);
|
|
91
|
+
broadcast({ type: "file-changed", file: host, kind: "change", via: toPosix(path.relative(dir, abs)), ...(stamp ? { stamp } : {}) });
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
83
95
|
const file = toPosix(path.relative(screensDir, abs));
|
|
84
96
|
const kind = event === "add" ? "add" : event === "unlink" ? "unlink" : "change";
|
|
85
97
|
void track(path.join(screensDir, file));
|
|
98
|
+
let hash;
|
|
86
99
|
if (kind === "unlink") {
|
|
87
100
|
deps.remove(file);
|
|
88
101
|
if (hashes.has(file)) removed.push({ file, hash: hashes.get(file), at: Date.now() });
|
|
89
102
|
hashes.delete(file);
|
|
90
103
|
} else {
|
|
91
104
|
await deps.update(file);
|
|
92
|
-
const
|
|
105
|
+
const text = await fs.readFile(abs, "utf8").catch(() => null);
|
|
106
|
+
const h = sha(text ?? "");
|
|
93
107
|
hashes.set(file, h);
|
|
108
|
+
if (text != null) hash = h;
|
|
94
109
|
if (kind === "add") {
|
|
95
110
|
const i = removed.findIndex((r) => r.hash === h && Date.now() - r.at < 5000);
|
|
96
111
|
if (i >= 0) {
|
|
@@ -99,9 +114,16 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
99
114
|
}
|
|
100
115
|
}
|
|
101
116
|
}
|
|
102
|
-
|
|
103
|
-
//
|
|
104
|
-
|
|
117
|
+
// hash: the content read now. A tab whose board already shows exactly this content (it patched its own edit in place) keeps it.
|
|
118
|
+
// stamp: the board's render stamp now, the version of its thumbnail
|
|
119
|
+
const stamp = kind === "unlink" ? (stamps.forget(file), null) : await stamps.stamp(file);
|
|
120
|
+
broadcast({ type: "file-changed", file, kind, ...(hash ? { hash } : {}), ...(stamp ? { stamp } : {}) });
|
|
121
|
+
// Also redraw boards that embed this screen (flow diagrams etc.), or load it some other way
|
|
122
|
+
for (const host of new Set([...deps.dependents(file), ...stamps.users(abs)])) {
|
|
123
|
+
if (host === file) continue;
|
|
124
|
+
const s = await stamps.stamp(host);
|
|
125
|
+
broadcast({ type: "file-changed", file: host, kind: "change", via: file, ...(s ? { stamp: s } : {}) });
|
|
126
|
+
}
|
|
105
127
|
if (kind !== "change") scheduleSync();
|
|
106
128
|
});
|
|
107
129
|
|