easel-canvas 0.2.2 → 0.3.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 +34 -6
- package/bin/mcp.mjs +21 -5
- package/bin/server.mjs +22 -1
- package/dist/assets/index-B7XvZ2rQ.js +70 -0
- package/dist/assets/index-CLVWE3wq.css +1 -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 +6 -2
- package/server/args.mjs +5 -4
- package/server/boards.mjs +49 -0
- package/server/browser.mjs +262 -32
- package/server/export.mjs +17 -22
- package/server/index.mjs +5 -2
- package/server/livePatch.mjs +109 -0
- package/server/registry.mjs +1 -1
- package/server/routes.mjs +75 -36
- package/server/up.mjs +85 -0
- package/server/watch.mjs +8 -4
- package/dist/assets/index-CjyXUlEx.css +0 -1
- package/dist/assets/index-DFCSLJXY.js +0 -66
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-27
|
|
2
|
+
// Live patches: for an edit the app made, the exact DOM change that turns the board as it was loaded (before) into what a reload of
|
|
3
|
+
// the new source (after) would show, or null when that cannot be proven. The tab that made the edit applies it to the live board and
|
|
4
|
+
// skips the reload when the watcher's echo carries the same content hash (see app/src/livePatch.ts).
|
|
5
|
+
// Proof: the patch is replayed on parse5's tree of before (attributes set as setAttribute does, inner HTML parsed as innerHTML does,
|
|
6
|
+
// i.e. HTML fragment parsing in the element's context) and the result must serialize exactly like parse5's tree of after.
|
|
7
|
+
import crypto from "node:crypto";
|
|
8
|
+
|
|
9
|
+
import { parse, parseFragment, serialize } from "parse5";
|
|
10
|
+
|
|
11
|
+
import { elementChildren, findBody, isElement } from "./html.mjs";
|
|
12
|
+
|
|
13
|
+
/** Content hash of a whole board file: sent with file-changed, written into the served page (data-dc-src) and returned by /api/edit */
|
|
14
|
+
export const contentHash = (text) => crypto.createHash("sha1").update(text).digest("hex");
|
|
15
|
+
|
|
16
|
+
const HTML_NS = "http://www.w3.org/1999/xhtml";
|
|
17
|
+
/** Ops whose result can be patched in place; everything else (move, delete, insert, wrap, duplicate, tweaks) reloads */
|
|
18
|
+
const LIVE_OPS = new Set(["setText", "setStyle", "setAttr"]);
|
|
19
|
+
/** Inner HTML set by innerHTML differs from a page parse here (leading newline dropped by the parser, raw text, foster parenting) */
|
|
20
|
+
const NO_INNER = new Set("pre listing textarea title style script xmp iframe noembed noframes noscript plaintext template table tbody thead tfoot tr colgroup select option optgroup frameset head html body".split(" "));
|
|
21
|
+
/** Attributes that act only while the page loads, or that the person may have changed by using the board: a reload shows them anew */
|
|
22
|
+
const NO_ATTR = /^(on|autofocus$|value$|checked$|selected$|is$|xmlns)/i;
|
|
23
|
+
/** Script types that never run (data blocks) */
|
|
24
|
+
const DATA_SCRIPT = /^(application\/(ld\+)?json|text\/(template|plain|markdown|x-template))$/i;
|
|
25
|
+
|
|
26
|
+
/** A page whose own scripts or load-time handlers run could have changed its DOM since it loaded: only a reload shows it right */
|
|
27
|
+
function runsScripts(node) {
|
|
28
|
+
if (isElement(node)) {
|
|
29
|
+
if (node.tagName === "script") {
|
|
30
|
+
const type = node.attrs.find((a) => a.name === "type")?.value?.trim() ?? "";
|
|
31
|
+
if (!DATA_SCRIPT.test(type)) return true;
|
|
32
|
+
}
|
|
33
|
+
if (node.attrs.some((a) => /^on/i.test(a.name))) return true;
|
|
34
|
+
}
|
|
35
|
+
for (const c of node.childNodes ?? []) if (runsScripts(c)) return true;
|
|
36
|
+
if (node.content && runsScripts(node.content)) return true;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The element at path, the way the browser's children walk finds it (never through <template> content), or null */
|
|
41
|
+
function at(doc, path) {
|
|
42
|
+
let node = findBody(doc);
|
|
43
|
+
if (!node) return null;
|
|
44
|
+
if (path === "" || path == null) return null; // body itself: its attributes reach the page's scripts and the probe; keep the reload
|
|
45
|
+
for (const part of String(path).split("/")) {
|
|
46
|
+
if (node.tagName === "template") return null;
|
|
47
|
+
node = elementChildren(node)[Number(part)];
|
|
48
|
+
if (!node) return null;
|
|
49
|
+
}
|
|
50
|
+
return node;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Ops of one request, flattened (batch → its ops) */
|
|
54
|
+
const opsOf = (req) => (req.op === "batch" ? (Array.isArray(req.ops) ? req.ops : []) : [req]);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* before, after: the board source before and after the edit; req: the /api/edit body.
|
|
58
|
+
* → [{ path, tag, attrs?: [[name, value | null]], inner?: string }] or null (reload instead)
|
|
59
|
+
*/
|
|
60
|
+
export function livePatch(before, after, req) {
|
|
61
|
+
const ops = opsOf(req);
|
|
62
|
+
if (!ops.length || ops.some((o) => !LIVE_OPS.has(o?.op))) return null;
|
|
63
|
+
const a = parse(after, { sourceCodeLocationInfo: true });
|
|
64
|
+
const b = parse(before);
|
|
65
|
+
if (runsScripts(a) || runsScripts(b)) return null;
|
|
66
|
+
const paths = [...new Set(ops.map((o) => String(o.path ?? "")))];
|
|
67
|
+
const patch = [];
|
|
68
|
+
for (const p of paths) {
|
|
69
|
+
const na = at(a, p);
|
|
70
|
+
const nb = at(b, p);
|
|
71
|
+
if (!na || !nb || na.tagName !== nb.tagName || na.namespaceURI !== HTML_NS) return null;
|
|
72
|
+
const item = { path: p, tag: na.tagName };
|
|
73
|
+
// Attributes: new values in after's order, then removals
|
|
74
|
+
const attrs = [];
|
|
75
|
+
for (const x of na.attrs) {
|
|
76
|
+
const old = nb.attrs.find((y) => y.name === x.name && !y.namespace);
|
|
77
|
+
if (old?.value !== x.value) attrs.push([x.name, x.value]);
|
|
78
|
+
}
|
|
79
|
+
for (const y of nb.attrs) if (!na.attrs.some((x) => x.name === y.name)) attrs.push([y.name, null]);
|
|
80
|
+
if ([...na.attrs, ...nb.attrs].some((x) => x.namespace || x.prefix) && attrs.length) return null;
|
|
81
|
+
if (attrs.some(([n]) => NO_ATTR.test(n))) return null;
|
|
82
|
+
if (attrs.length) item.attrs = attrs;
|
|
83
|
+
if (ops.some((o) => o.op === "setText" && String(o.path ?? "") === p)) {
|
|
84
|
+
const st = na.sourceCodeLocation?.startTag;
|
|
85
|
+
const et = na.sourceCodeLocation?.endTag;
|
|
86
|
+
if (!st || !et || NO_INNER.has(na.tagName)) return null;
|
|
87
|
+
item.inner = after.slice(st.endOffset, et.startOffset);
|
|
88
|
+
}
|
|
89
|
+
if (item.attrs || item.inner != null) patch.push(item);
|
|
90
|
+
}
|
|
91
|
+
if (!patch.length) return null;
|
|
92
|
+
// Replay on before's tree and compare with after's: anything else that changed (or a parse difference) means reload
|
|
93
|
+
for (const item of patch) {
|
|
94
|
+
const node = at(b, item.path);
|
|
95
|
+
for (const [name, value] of item.attrs ?? []) {
|
|
96
|
+
const i = node.attrs.findIndex((x) => x.name === name);
|
|
97
|
+
if (value == null) {
|
|
98
|
+
if (i >= 0) node.attrs.splice(i, 1);
|
|
99
|
+
} else if (i >= 0) node.attrs[i] = { ...node.attrs[i], value };
|
|
100
|
+
else node.attrs.push({ name, value });
|
|
101
|
+
}
|
|
102
|
+
if (item.inner != null) {
|
|
103
|
+
const frag = parseFragment(node, item.inner);
|
|
104
|
+
node.childNodes = frag.childNodes;
|
|
105
|
+
for (const c of node.childNodes) c.parentNode = node;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return serialize(b) === serialize(parse(after)) ? patch : null;
|
|
109
|
+
}
|
package/server/registry.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { DEFAULT_PORT } from "./args.mjs";
|
|
|
10
10
|
export const easelHome = (env = process.env) => env.EASEL_HOME || path.join(os.homedir(), ".easel");
|
|
11
11
|
const serversDir = (home) => path.join(home, "servers");
|
|
12
12
|
/** Resolved path (links like /var → /private/var), also for a folder that does not exist yet: its nearest existing parent */
|
|
13
|
-
const real = (p) => {
|
|
13
|
+
export const real = (p) => {
|
|
14
14
|
const abs = path.resolve(p);
|
|
15
15
|
try {
|
|
16
16
|
return realpathSync(abs);
|
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,6 +14,7 @@ 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";
|
|
18
19
|
import { watchDesign } from "./watch.mjs";
|
|
19
20
|
|
|
@@ -51,38 +52,55 @@ async function writeComments(ctx, comments) {
|
|
|
51
52
|
|
|
52
53
|
/* ---------- Screenshots (when playwright is available) ---------- */
|
|
53
54
|
// 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";
|
|
55
|
+
export { cachedBrowser, closeBrowser, newPage, withPage } from "./browser.mjs";
|
|
55
56
|
|
|
56
57
|
/** 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
58
|
const THUMB_PX = [600, 1200, 2400];
|
|
58
59
|
export const thumbPx = (v) => THUMB_PX.find((s) => s >= Number(v)) ?? (Number(v) > 0 ? THUMB_PX[THUMB_PX.length - 1] : THUMB_PX[0]);
|
|
59
60
|
|
|
60
|
-
/**
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Thumbnail jobs, at most two at a time. The newest request goes first (the boards the user is looking at now asked last),
|
|
63
|
+
* and a job still waiting when its request closes (board scrolled away, tab closed) is dropped. A job that has started
|
|
64
|
+
* always finishes, so its thumbnail is cached for the next request.
|
|
65
|
+
*/
|
|
66
|
+
export function createThumbQueue(limit = 2) {
|
|
67
|
+
let running = 0;
|
|
68
|
+
const waiting = [];
|
|
69
|
+
const next = () => {
|
|
70
|
+
while (running < limit && waiting.length) {
|
|
71
|
+
const job = waiting.pop();
|
|
72
|
+
if (job.gone()) job.reject(Object.assign(new Error("Thumbnail request closed before its turn"), { dropped: true }));
|
|
73
|
+
else void job.run();
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
/** gone(): true once nobody waits for the result */
|
|
78
|
+
push(fn, gone = () => false) {
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
const run = async () => {
|
|
81
|
+
running++;
|
|
82
|
+
try {
|
|
83
|
+
resolve(await fn());
|
|
84
|
+
} catch (e) {
|
|
85
|
+
reject(e);
|
|
86
|
+
} finally {
|
|
87
|
+
running--;
|
|
88
|
+
next();
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
waiting.push({ run, gone, reject });
|
|
92
|
+
next();
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
stats: () => ({ running, waiting: waiting.length }),
|
|
96
|
+
};
|
|
79
97
|
}
|
|
98
|
+
const thumbQueue = createThumbQueue(2);
|
|
80
99
|
|
|
81
100
|
export async function screenshot(ctx, port, file, elPath) {
|
|
82
101
|
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" });
|
|
102
|
+
return withPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 }, async (page) => {
|
|
103
|
+
await gotoSettled(page, `http://127.0.0.1:${port}/screens/${encodeURI(file)}`);
|
|
86
104
|
const outDir = path.join(await easelDir(ctx.dir), "screenshots");
|
|
87
105
|
await fs.mkdir(outDir, { recursive: true });
|
|
88
106
|
const name = `${file.replace(/[\\/]/g, "_").replace(/\.html$/, "")}${elPath ? "--" + elPath.replace(/\//g, "-") : ""}.png`;
|
|
@@ -100,9 +118,7 @@ export async function screenshot(ctx, port, file, elPath) {
|
|
|
100
118
|
await page.screenshot({ path: out, fullPage: true });
|
|
101
119
|
}
|
|
102
120
|
return out;
|
|
103
|
-
}
|
|
104
|
-
await page.close();
|
|
105
|
-
}
|
|
121
|
+
});
|
|
106
122
|
}
|
|
107
123
|
|
|
108
124
|
export const extraRoutes = [
|
|
@@ -128,7 +144,10 @@ export const extraRoutes = [
|
|
|
128
144
|
await writeScreen(ctx, p, next);
|
|
129
145
|
ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }]);
|
|
130
146
|
ctx.broadcast({ type: "history-changed" });
|
|
131
|
-
|
|
147
|
+
// base/hash: the file's content hash before and after; live: the DOM change that turns a board showing base into one showing
|
|
148
|
+
// hash, when that is proven (server/livePatch.mjs). Never for a fork: the caller's board is not the file written
|
|
149
|
+
const live = to.forked ? null : livePatch(html, next, b);
|
|
150
|
+
sendJson(res, 200, { ok: true, changed: true, base: contentHash(html), hash: contentHash(next), ...(live ? { live } : {}), ...fork });
|
|
132
151
|
},
|
|
133
152
|
],
|
|
134
153
|
// Legacy route: forwards to the chronological history
|
|
@@ -160,28 +179,33 @@ export const extraRoutes = [
|
|
|
160
179
|
const base = f.replace(/[\\/]/g, "_");
|
|
161
180
|
const stamp = `${base}.${Math.round(st.mtimeMs)}.`;
|
|
162
181
|
const out = path.join(dir, `${stamp}${px}.jpg`);
|
|
182
|
+
// 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
|
|
183
|
+
const port = req.socket.localPort;
|
|
184
|
+
let gone = false;
|
|
185
|
+
res.on("close", () => (gone = true));
|
|
163
186
|
let buf = await fs.readFile(out).catch(() => null);
|
|
164
187
|
if (!buf) {
|
|
165
|
-
buf = await thumbQueue(async () => {
|
|
188
|
+
buf = await thumbQueue.push(async () => {
|
|
166
189
|
await fs.mkdir(dir, { recursive: true });
|
|
167
190
|
await fs.writeFile(path.join(dir, ".gitignore"), "*\n").catch(() => {});
|
|
168
191
|
const board = (await ctx.store.readBoard()).boards[f];
|
|
169
192
|
const w = board?.w ?? 390;
|
|
170
193
|
const h = board?.h ?? 844;
|
|
171
194
|
// 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 });
|
|
195
|
+
return withPage({ viewport: { width: w, height: h }, deviceScaleFactor: Math.min(2, px / Math.max(w, h)) }, async (page) => {
|
|
196
|
+
await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(f)}`, { waitUntil: "load", timeout: 15000 });
|
|
175
197
|
await page.waitForTimeout(150);
|
|
176
198
|
const b = await page.screenshot({ type: "jpeg", quality: 80 });
|
|
177
199
|
// Remove thumbnails of older versions (other sizes of this version stay)
|
|
178
200
|
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
201
|
await fs.writeFile(out, b);
|
|
180
202
|
return b;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
|
|
203
|
+
});
|
|
204
|
+
}, () => gone).catch((e) => {
|
|
205
|
+
if (e.dropped) return null;
|
|
206
|
+
throw e;
|
|
184
207
|
});
|
|
208
|
+
if (!buf) return; // nobody is waiting for it any more
|
|
185
209
|
}
|
|
186
210
|
res.writeHead(200, { "Content-Type": "image/jpeg", "Content-Length": buf.length, "Cache-Control": "max-age=31536000, immutable" });
|
|
187
211
|
res.end(buf);
|
|
@@ -229,7 +253,17 @@ export const extraRoutes = [
|
|
|
229
253
|
const { html } = await readScreen(ctx, url.searchParams.get("f"));
|
|
230
254
|
const info = inspect(html, url.searchParams.get("path") ?? "");
|
|
231
255
|
if (!info) return sendJson(res, 404, { error: "Element not found (the file changed, select again)" });
|
|
232
|
-
|
|
256
|
+
// fileHash: the whole file now, so a board patched in place can check that it still shows the file
|
|
257
|
+
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) });
|
|
258
|
+
},
|
|
259
|
+
],
|
|
260
|
+
// 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)
|
|
261
|
+
[
|
|
262
|
+
"GET",
|
|
263
|
+
"/api/file-hash",
|
|
264
|
+
async (req, res, url, ctx) => {
|
|
265
|
+
const { html } = await readScreen(ctx, url.searchParams.get("f"));
|
|
266
|
+
sendJson(res, 200, { hash: contentHash(html) });
|
|
233
267
|
},
|
|
234
268
|
],
|
|
235
269
|
[
|
|
@@ -350,6 +384,11 @@ export const extraRoutes = [
|
|
|
350
384
|
await readScreen(ctx, b.file);
|
|
351
385
|
const port = Number(req.socket.localPort);
|
|
352
386
|
const out = await screenshot(ctx, port, b.file, b.path || "");
|
|
387
|
+
// inline: the PNG itself, for the board menu's Export PNG to download (the copy in .easel/screenshots stays as for MCP)
|
|
388
|
+
if (b.inline) {
|
|
389
|
+
res.writeHead(200, { "Content-Type": "image/png", "Cache-Control": "no-store" });
|
|
390
|
+
return res.end(await fs.readFile(out));
|
|
391
|
+
}
|
|
353
392
|
sendJson(res, 200, { path: out, relPath: toPosix(path.relative(rootOf(ctx.dir), out)) });
|
|
354
393
|
},
|
|
355
394
|
],
|
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,7 +1,6 @@
|
|
|
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
|
|
|
@@ -9,6 +8,7 @@ import chokidar from "chokidar";
|
|
|
9
8
|
|
|
10
9
|
import { createDeps } from "./deps.mjs";
|
|
11
10
|
import { toPosix } from "./fsutil.mjs";
|
|
11
|
+
import { contentHash } from "./livePatch.mjs";
|
|
12
12
|
|
|
13
13
|
export function watchDesign({ dir, store, broadcast, history }) {
|
|
14
14
|
const screensDir = store.screensDir;
|
|
@@ -26,7 +26,7 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
26
26
|
// On an outside rename (same content deleted then created), move the board position/title to the new name
|
|
27
27
|
const hashes = new Map(); // file → content sha1
|
|
28
28
|
const removed = []; // { file, hash, at }
|
|
29
|
-
const sha =
|
|
29
|
+
const sha = contentHash;
|
|
30
30
|
store.listScreenFiles().then(async (files) => {
|
|
31
31
|
for (const f of files) hashes.set(f, sha(await fs.readFile(path.join(screensDir, f), "utf8").catch(() => "")));
|
|
32
32
|
});
|
|
@@ -83,14 +83,17 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
83
83
|
const file = toPosix(path.relative(screensDir, abs));
|
|
84
84
|
const kind = event === "add" ? "add" : event === "unlink" ? "unlink" : "change";
|
|
85
85
|
void track(path.join(screensDir, file));
|
|
86
|
+
let hash;
|
|
86
87
|
if (kind === "unlink") {
|
|
87
88
|
deps.remove(file);
|
|
88
89
|
if (hashes.has(file)) removed.push({ file, hash: hashes.get(file), at: Date.now() });
|
|
89
90
|
hashes.delete(file);
|
|
90
91
|
} else {
|
|
91
92
|
await deps.update(file);
|
|
92
|
-
const
|
|
93
|
+
const text = await fs.readFile(abs, "utf8").catch(() => null);
|
|
94
|
+
const h = sha(text ?? "");
|
|
93
95
|
hashes.set(file, h);
|
|
96
|
+
if (text != null) hash = h;
|
|
94
97
|
if (kind === "add") {
|
|
95
98
|
const i = removed.findIndex((r) => r.hash === h && Date.now() - r.at < 5000);
|
|
96
99
|
if (i >= 0) {
|
|
@@ -99,7 +102,8 @@ export function watchDesign({ dir, store, broadcast, history }) {
|
|
|
99
102
|
}
|
|
100
103
|
}
|
|
101
104
|
}
|
|
102
|
-
|
|
105
|
+
// hash: the content read now. A tab whose board already shows exactly this content (it patched its own edit in place) keeps it
|
|
106
|
+
broadcast({ type: "file-changed", file, kind, ...(hash ? { hash } : {}) });
|
|
103
107
|
// Also redraw boards that embed this screen (flow diagrams etc.)
|
|
104
108
|
for (const host of deps.dependents(file)) broadcast({ type: "file-changed", file: host, kind: "change", via: file });
|
|
105
109
|
if (kind !== "change") scheduleSync();
|