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
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easel-canvas",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Easel: an HTML design canvas for AI agents. Shows screens/*.html as boards and edits the source directly, with Claude Code / Codex via MCP",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Hyun Park",
|
|
@@ -22,11 +22,17 @@
|
|
|
22
22
|
"demo": "node bin/server.mjs --dir examples/demo --open",
|
|
23
23
|
"build": "vite build app --config vite.config.mjs && vite build app --config vite.config.mjs --mode viewer",
|
|
24
24
|
"prepack": "npm run build",
|
|
25
|
+
"version": "node tools/plugin-sync.mjs && git add plugin",
|
|
25
26
|
"mcp": "node bin/mcp.mjs",
|
|
26
27
|
"typecheck": "tsc --noEmit",
|
|
27
28
|
"test": "node --test test/*.test.mjs",
|
|
28
29
|
"test:e2e": "node --test --test-concurrency=1 test/e2e/*.e2e.mjs",
|
|
29
|
-
"design:css": "node tools/mkcss.mjs"
|
|
30
|
+
"design:css": "node tools/mkcss.mjs",
|
|
31
|
+
"verify:agents": "node tools/verify-agents.mjs",
|
|
32
|
+
"perf": "node tools/perf/measure.mjs",
|
|
33
|
+
"perf:phases": "node tools/perf/phases.mjs",
|
|
34
|
+
"site": "node site/build.mjs",
|
|
35
|
+
"icons": "node tools/icons/build.mjs"
|
|
30
36
|
},
|
|
31
37
|
"engines": {
|
|
32
38
|
"node": ">=20"
|
package/server/activity.mjs
CHANGED
|
@@ -128,7 +128,9 @@ export function boardEntries(beforeText, afterText) {
|
|
|
128
128
|
}
|
|
129
129
|
|
|
130
130
|
/* ---------- Step names ---------- */
|
|
131
|
-
const EDIT_OPS = { setText: "Change text on", setStyle: "Change style on", setAttr: "Change attribute on", delete: "Delete element on", duplicate: "Duplicate element on", move: "Move element on", insert: "Add element on", setTweaks: "Change tweaks on", batch: "Edit", wrap: "Group elements on" };
|
|
131
|
+
const EDIT_OPS = { setText: "Change text on", setStyle: "Change style on", setStyleText: "Change style on", setAttr: "Change attribute on", delete: "Delete element on", duplicate: "Duplicate element on", move: "Move element on", insert: "Add element on", setTweaks: "Change tweaks on", batch: "Edit", wrap: "Group elements on" };
|
|
132
|
+
/** What a style property is called in a step name (the app's own words; the client says them in the person's language) */
|
|
133
|
+
const STYLE_NOUNS = { color: "colour", "background-color": "fill", background: "fill", "font-size": "text size", "font-weight": "weight", "font-style": "italic", "text-decoration-line": "underline", "text-align": "alignment", "border-radius": "radius", padding: "padding", gap: "gap", opacity: "opacity", "letter-spacing": "letter spacing", width: "size", height: "size", left: "position", top: "position", "box-shadow": "shadow", border: "border" };
|
|
132
134
|
/** App labels for board.json steps that are about some boards: named after them */
|
|
133
135
|
const BOARD_LABELS = new Set(["Move board", "Resize board", "Board options", "Bring to front", "Send to back", "Move to page", "Set launch screen"]);
|
|
134
136
|
/** What the text of an element is called in a step name */
|
|
@@ -159,7 +161,10 @@ export function stepName(step, env, describe = describeChange) {
|
|
|
159
161
|
let m = /^(.+\.html) (\w+)$/.exec(label);
|
|
160
162
|
if (m && EDIT_OPS[m[2]]) {
|
|
161
163
|
const t = html.length === 1 ? textOf1(html[0]) : null;
|
|
162
|
-
|
|
164
|
+
if (t) return `Change ${copyNoun(t.tag)} on ${title(m[1])}`;
|
|
165
|
+
// A style step that changed one known property is named after it ("Change colour on Ticket")
|
|
166
|
+
if (/^(setStyle|batch)$/.test(m[2]) && step.prop && STYLE_NOUNS[step.prop]) return `Change ${STYLE_NOUNS[step.prop]} on ${title(m[1])}`;
|
|
167
|
+
return `${EDIT_OPS[m[2]]} ${title(m[1])}`;
|
|
163
168
|
}
|
|
164
169
|
if ((m = /^Create board (.+)$/.exec(label))) return `Add board ${title(m[1])}`;
|
|
165
170
|
// One writer per board, and picking a version (server/forks.mjs)
|
|
@@ -285,6 +290,16 @@ function stepInfo(ctx, step, env) {
|
|
|
285
290
|
};
|
|
286
291
|
}
|
|
287
292
|
|
|
293
|
+
/** The history's state with each step's human name in place of its internal label (undo / redo tooltips, the toast after ⌘Z) */
|
|
294
|
+
export async function namedState(ctx) {
|
|
295
|
+
const env = await envOf(ctx);
|
|
296
|
+
const { undo, redo } = ctx.history.entries();
|
|
297
|
+
return { ...ctx.history.state(), undo: undo.slice(-20).map((s) => stepName(s, env)), redo: redo.slice(-20).map((s) => stepName(s, env)) };
|
|
298
|
+
}
|
|
299
|
+
export async function stepNameOf(ctx, step) {
|
|
300
|
+
return step ? stepName(step, await envOf(ctx)) : null;
|
|
301
|
+
}
|
|
302
|
+
|
|
288
303
|
/** What step names need: where the screens and board.json are, and the board titles now */
|
|
289
304
|
async function envOf(ctx) {
|
|
290
305
|
const board = await ctx.store.readBoard();
|
package/server/args.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
|
|
2
|
-
// Command-line args: [connect] [--dir <design folder>] [--port 4317] [--open] [--demo] [--init] [--help] [--version],
|
|
3
|
-
// plus --agents a,b and --dry-run for connect, --out, --page, --boards a,b, --single-file, --pdf, --png for export,
|
|
2
|
+
// Command-line args: [connect|export|up|status] [--dir <design folder>] [--port 4317] [--open] [--demo] [--init] [--help] [--version],
|
|
3
|
+
// plus --agents a,b and --dry-run for connect, --json for up and status, --out, --page, --boards a,b, --single-file, --pdf, --png for export,
|
|
4
4
|
// and --chat / --permission for easel-mcp (the server of an in-app chat run: canvas tools and its permission tool / that tool only).
|
|
5
5
|
// Default design folder: <repo>/docs/design when Easel lives in <repo>/tools/<name> (submodule); otherwise
|
|
6
6
|
// ./docs/design or the current folder if it has screens/ (npx).
|
|
@@ -25,7 +25,7 @@ export const DEFAULT_DIR = defaultDir();
|
|
|
25
25
|
const expand = (p) => path.resolve(p.replace(/^~(?=\/)/, process.env.HOME ?? "~"));
|
|
26
26
|
|
|
27
27
|
export function parseArgs(argv = process.argv.slice(2)) {
|
|
28
|
-
const out = { command: null, dir: null, port: DEFAULT_PORT, portGiven: false, dirGiven: false, agents: null, dryRun: false, out: null, page: null, boards: null, singleFile: false, pdf: false, png: false, permission: false, chat: false, open: false, noOpen: false, demo: false, init: false, help: false, version: false, prod: false };
|
|
28
|
+
const out = { command: null, dir: null, port: DEFAULT_PORT, portGiven: false, dirGiven: false, agents: null, dryRun: false, json: false, out: null, page: null, boards: null, singleFile: false, pdf: false, png: false, permission: false, chat: false, open: false, noOpen: false, demo: false, init: false, help: false, version: false, prod: false };
|
|
29
29
|
for (let i = 0; i < argv.length; i++) {
|
|
30
30
|
const a = argv[i];
|
|
31
31
|
const next = () => argv[++i];
|
|
@@ -36,6 +36,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
|
|
|
36
36
|
else if (a === "--agents") out.agents = next();
|
|
37
37
|
else if (a.startsWith("--agents=")) out.agents = a.slice(9);
|
|
38
38
|
else if (a === "--dry-run") out.dryRun = true;
|
|
39
|
+
else if (a === "--json") out.json = true;
|
|
39
40
|
else if (a === "--out") out.out = argv[i + 1] ? expand(next()) : null;
|
|
40
41
|
else if (a.startsWith("--out=")) out.out = expand(a.slice(6));
|
|
41
42
|
else if (a === "--page") out.page = next();
|
|
@@ -45,7 +46,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
|
|
|
45
46
|
else if (a === "--single-file") out.singleFile = true;
|
|
46
47
|
else if (a === "--pdf") out.pdf = true;
|
|
47
48
|
else if (a === "--png") out.png = true;
|
|
48
|
-
else if (i === 0 &&
|
|
49
|
+
else if (i === 0 && ["connect", "export", "up", "status"].includes(a)) out.command = a;
|
|
49
50
|
else if (a === "--open") out.open = true;
|
|
50
51
|
else if (a === "--no-open") out.noOpen = true;
|
|
51
52
|
else if (a === "--demo") out.demo = true;
|
package/server/boards.mjs
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
|
|
6
|
+
import { namedState, stepNameOf } from "./activity.mjs";
|
|
6
7
|
import { formatBoard } from "./boardFormat.mjs";
|
|
7
8
|
import { writeAtomic } from "./fsutil.mjs";
|
|
8
9
|
import { readBody, safeJoin, sendJson } from "./index.mjs";
|
|
9
|
-
import {
|
|
10
|
+
import { besideOf, besideSpot, nearSpot, placeNew } from "./place.mjs";
|
|
10
11
|
import { SYSTEM_FONT } from "./tokens.mjs";
|
|
11
12
|
|
|
12
13
|
const read = (p) => fs.readFile(p, "utf8").catch(() => null);
|
|
@@ -21,6 +22,9 @@ export const TEMPLATES = {
|
|
|
21
22
|
mobile: { label: "Mobile screen", w: 390, h: 844 },
|
|
22
23
|
desktop: { label: "Desktop screen", w: 1440, h: 900 },
|
|
23
24
|
doc: { label: "Document", w: 800, h: 1000 },
|
|
25
|
+
tablet: { label: "Tablet screen", w: 834, h: 1194 },
|
|
26
|
+
watch: { label: "Watch screen", w: 198, h: 242 },
|
|
27
|
+
email: { label: "Email", w: 600, h: 1200 },
|
|
24
28
|
};
|
|
25
29
|
|
|
26
30
|
export function newBoardHtml({ title, w, h, template = "blank", brand = "" }) {
|
|
@@ -53,6 +57,52 @@ export function newBoardHtml({ title, w, h, template = "blank", brand = "" }) {
|
|
|
53
57
|
doc: `<div style="width:${w}px;min-height:${h}px;box-sizing:border-box;padding:48px;display:flex;flex-direction:column;gap:16px;background:#FFFFFF">
|
|
54
58
|
<h1 style="margin:0;font-size:34px;font-weight:700;letter-spacing:-0.02em">${t}</h1>
|
|
55
59
|
<p style="margin:0;font-size:17px;line-height:1.6;color:#111111">Body text</p>
|
|
60
|
+
</div>`,
|
|
61
|
+
// Two cards side by side under the heading, one action at the bottom: the shape of a tablet screen with room to spare
|
|
62
|
+
tablet: `<div style="width:${w}px;height:${h}px;box-sizing:border-box;background:#FFFFFF;display:flex;flex-direction:column;overflow:hidden">
|
|
63
|
+
<header style="height:64px;display:flex;align-items:center;padding:0 32px;border-bottom:1px solid #E8E8E6;flex:none">
|
|
64
|
+
<span style="font-size:17px;font-weight:700">${t}</span>
|
|
65
|
+
</header>
|
|
66
|
+
<main style="flex:1;padding:32px;display:flex;flex-direction:column;gap:24px">
|
|
67
|
+
<h1 style="margin:0;font-size:34px;font-weight:700;letter-spacing:-0.02em;line-height:1.15">Title</h1>
|
|
68
|
+
<p style="margin:0;font-size:17px;line-height:1.5;color:#6B6B6B">Description</p>
|
|
69
|
+
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
|
|
70
|
+
<section style="padding:24px;border-radius:16px;background:#F5F5F3;display:flex;flex-direction:column;gap:8px">
|
|
71
|
+
<h2 style="margin:0;font-size:22px;font-weight:600">Section</h2>
|
|
72
|
+
<p style="margin:0;font-size:16px;line-height:1.5;color:#6B6B6B">Supporting text</p>
|
|
73
|
+
</section>
|
|
74
|
+
<section style="padding:24px;border-radius:16px;background:#F5F5F3;display:flex;flex-direction:column;gap:8px">
|
|
75
|
+
<h2 style="margin:0;font-size:22px;font-weight:600">Section</h2>
|
|
76
|
+
<p style="margin:0;font-size:16px;line-height:1.5;color:#6B6B6B">Supporting text</p>
|
|
77
|
+
</section>
|
|
78
|
+
</div>
|
|
79
|
+
</main>
|
|
80
|
+
<footer style="padding:16px 32px 32px;flex:none;display:flex;justify-content:flex-end">
|
|
81
|
+
<a href="#" style="display:flex;align-items:center;justify-content:center;height:56px;padding:0 32px;border-radius:16px;background:#C94F0C;color:#FFFFFF;font-size:17px;font-weight:700;text-decoration:none">Next</a>
|
|
82
|
+
</footer>
|
|
83
|
+
</div>`,
|
|
84
|
+
// A glance and one action: a short label, a large value, a full-width button that is still a 48px target
|
|
85
|
+
watch: `<div style="width:${w}px;height:${h}px;box-sizing:border-box;padding:12px;background:#FFFFFF;display:flex;flex-direction:column;gap:4px;overflow:hidden">
|
|
86
|
+
<span style="font-size:15px;font-weight:600;color:#6B6B6B">${t}</span>
|
|
87
|
+
<strong style="font-size:34px;font-weight:700;line-height:1.15">Title</strong>
|
|
88
|
+
<span style="font-size:15px;color:#6B6B6B">Description</span>
|
|
89
|
+
<a href="#" style="margin-top:auto;display:flex;align-items:center;justify-content:center;height:48px;border-radius:999px;background:#C94F0C;color:#FFFFFF;font-size:16px;font-weight:700;text-decoration:none">Next</a>
|
|
90
|
+
</div>`,
|
|
91
|
+
// One 600px column, as an email client shows it: sender, heading, text, one button, a footer with the unsubscribe link
|
|
92
|
+
email: `<div style="width:${w}px;min-height:${h}px;box-sizing:border-box;background:#FFFFFF;display:flex;flex-direction:column">
|
|
93
|
+
<header style="padding:32px 40px 24px">
|
|
94
|
+
<strong style="font-size:17px">${name}</strong>
|
|
95
|
+
</header>
|
|
96
|
+
<main style="padding:0 40px 40px;display:flex;flex-direction:column;gap:16px">
|
|
97
|
+
<h1 style="margin:0;font-size:34px;font-weight:700;letter-spacing:-0.02em;line-height:1.15">${t}</h1>
|
|
98
|
+
<p style="margin:0;font-size:17px;line-height:1.6">Hi there,</p>
|
|
99
|
+
<p style="margin:0;font-size:17px;line-height:1.6">Body text</p>
|
|
100
|
+
<a href="#" style="align-self:flex-start;display:flex;align-items:center;height:48px;padding:0 24px;margin-top:8px;border-radius:8px;background:#C94F0C;color:#FFFFFF;font-size:17px;font-weight:700;text-decoration:none">Call to action</a>
|
|
101
|
+
</main>
|
|
102
|
+
<footer style="margin-top:auto;padding:24px 40px 32px;border-top:1px solid #E8E8E6;display:flex;flex-direction:column;gap:4px">
|
|
103
|
+
<p style="margin:0;font-size:15px;line-height:1.5;color:#6B6B6B">You are receiving this email because you signed up.</p>
|
|
104
|
+
<a href="#" style="align-self:flex-start;display:flex;align-items:center;min-height:48px;font-size:15px;color:#6B6B6B">Unsubscribe</a>
|
|
105
|
+
</footer>
|
|
56
106
|
</div>`,
|
|
57
107
|
};
|
|
58
108
|
return `<!doctype html>
|
|
@@ -227,10 +277,14 @@ export function boardRoutes() {
|
|
|
227
277
|
const title = b.title || (tpl === "blank" ? wanted.replace(/\.html$/, "") : TEMPLATES[tpl].label);
|
|
228
278
|
const board0 = await ctx.store.readBoard();
|
|
229
279
|
const html = b.html ?? newBoardHtml({ title, w, h, template: tpl, brand: board0.title });
|
|
230
|
-
//
|
|
231
|
-
|
|
280
|
+
// Where it goes, never on top of a board or a note unless it was drawn there: beside a board (New board with one picked), near
|
|
281
|
+
// a point (New board: the view's centre), exactly where drawn (the board tool), or, with no position (an agent's create_board),
|
|
282
|
+
// the first free spot after the last auto-placed screen
|
|
283
|
+
const xy = Number.isFinite(b.x) && Number.isFinite(b.y);
|
|
284
|
+
const src = b.beside ? board0.boards[b.beside] : null;
|
|
285
|
+
const at = src ? besideOf(board0, src, { w, h }) : xy && b.near ? nearSpot(board0, { x: Math.round(b.x), y: Math.round(b.y), w, h }, b.page) : xy ? { x: b.x, y: b.y } : placeNew(board0, { w, h }, b.page);
|
|
232
286
|
const [file] = await createBoards(ctx, [{ file: wanted, html, x: at.x, y: at.y, w, h, title, page: b.page }], `Create board ${wanted}`);
|
|
233
|
-
sendJson(res, 200, { file });
|
|
287
|
+
sendJson(res, 200, { file, x: at.x, y: at.y, w, h });
|
|
234
288
|
},
|
|
235
289
|
],
|
|
236
290
|
["GET", "/api/boards/templates", async (req, res) => sendJson(res, 200, { templates: Object.entries(TEMPLATES).map(([id, t]) => ({ id, ...t })) })],
|
|
@@ -271,7 +325,8 @@ export function boardRoutes() {
|
|
|
271
325
|
const board0 = await ctx.store.readBoard();
|
|
272
326
|
// The copy is an ordinary board: it is not a variant or fork of anything
|
|
273
327
|
const { origin, autoPlaced, ...it } = board0.boards[b.file] ?? { x: 0, y: 0, w: 390, h: 844 };
|
|
274
|
-
|
|
328
|
+
// Beside its original: right of it when that is free, else the nearer of further right and below
|
|
329
|
+
const at = besideSpot(board0, it);
|
|
275
330
|
await commitBoard(
|
|
276
331
|
ctx,
|
|
277
332
|
`Duplicate board ${b.file}`,
|
|
@@ -350,7 +405,8 @@ export function boardRoutes() {
|
|
|
350
405
|
async (req, res, url, ctx) => {
|
|
351
406
|
const step = await ctx.history.undo();
|
|
352
407
|
ctx.broadcast({ type: "history-changed" });
|
|
353
|
-
|
|
408
|
+
// label: the step's human name ("Change colour on Ticket"), never its file and internal operation
|
|
409
|
+
sendJson(res, 200, { ok: true, label: await stepNameOf(ctx, step), ...(await namedState(ctx)) });
|
|
354
410
|
},
|
|
355
411
|
],
|
|
356
412
|
[
|
|
@@ -359,10 +415,10 @@ export function boardRoutes() {
|
|
|
359
415
|
async (req, res, url, ctx) => {
|
|
360
416
|
const step = await ctx.history.redo();
|
|
361
417
|
ctx.broadcast({ type: "history-changed" });
|
|
362
|
-
sendJson(res, 200, { ok: true, label:
|
|
418
|
+
sendJson(res, 200, { ok: true, label: await stepNameOf(ctx, step), ...(await namedState(ctx)) });
|
|
363
419
|
},
|
|
364
420
|
],
|
|
365
|
-
["GET", "/api/history", async (req, res, url, ctx) => sendJson(res, 200, ctx
|
|
421
|
+
["GET", "/api/history", async (req, res, url, ctx) => sendJson(res, 200, await namedState(ctx))],
|
|
366
422
|
// Notes (titles, sticky notes): shared by MCP and the app. All recorded in the undo history
|
|
367
423
|
[
|
|
368
424
|
"POST",
|
package/server/browser.mjs
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
// AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
|
|
2
2
|
// The one shared headless Chromium (playwright, an optional dependency) behind screenshots, thumbnails and PDF/PNG export.
|
|
3
|
+
// Launched on first use (never at server start), shared by concurrent first calls, one fresh context per render, at most
|
|
4
|
+
// MAX_PAGES renders at a time (the rest wait), closed after EASEL_BROWSER_IDLE_SECONDS without a render, and launched again
|
|
5
|
+
// after it dies or is killed (a render that hits a dead browser is tried once more on a new one). Files from other hosts
|
|
6
|
+
// (web fonts, CDN images) are cached across renders while the browser is up (createRemoteCache).
|
|
3
7
|
import { existsSync } from "node:fs";
|
|
4
8
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
/** Default seconds without a render before the browser is closed (EASEL_BROWSER_IDLE_SECONDS overrides; 0 closes right away) */
|
|
10
|
+
export const IDLE_SECONDS = 120;
|
|
11
|
+
/** Renders open at once across screenshots, thumbnails and export; more wait in line */
|
|
12
|
+
export const MAX_PAGES = 4;
|
|
13
|
+
|
|
14
|
+
export function idleMsFromEnv(env = process.env) {
|
|
15
|
+
const v = Number(env.EASEL_BROWSER_IDLE_SECONDS);
|
|
16
|
+
return (env.EASEL_BROWSER_IDLE_SECONDS != null && env.EASEL_BROWSER_IDLE_SECONDS !== "" && Number.isFinite(v) && v >= 0 ? v : IDLE_SECONDS) * 1000;
|
|
11
17
|
}
|
|
12
18
|
|
|
13
19
|
const loadPlaywright = () =>
|
|
@@ -15,41 +21,265 @@ const loadPlaywright = () =>
|
|
|
15
21
|
throw Object.assign(new Error("Screenshots are unavailable because playwright is not installed (npm run design:install)"), { status: 501 });
|
|
16
22
|
});
|
|
17
23
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
async function launchChromium() {
|
|
25
|
+
const { chromium } = await loadPlaywright();
|
|
26
|
+
// Fall back to the installed Chrome if no downloaded Chromium exists
|
|
27
|
+
return chromium.launch().catch(() => chromium.launch({ channel: "chrome" }));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
|
|
31
|
+
const maxAgeOf = (cc) => {
|
|
32
|
+
if (/(^|,)\s*(no-store|no-cache|private)\b/i.test(cc)) return 0;
|
|
33
|
+
const m = /(?:^|,)\s*(?:s-maxage|max-age)\s*=\s*(\d+)/i.exec(cc);
|
|
34
|
+
return m ? Number(m[1]) : 0;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* HTTP cache for files boards load from other hosts (web fonts, font CSS, CDN images), shared by every render while the
|
|
39
|
+
* browser is up. Each render has a fresh context, and a fresh context starts with an empty HTTP cache, so without this a
|
|
40
|
+
* board using a 2 MB CDN font downloaded it again for every thumbnail. Only GETs from non-loopback hosts are routed (the
|
|
41
|
+
* canvas's own files are no-store and stay direct). Kept: 200 responses with a positive max-age, no no-store/no-cache/
|
|
42
|
+
* private, no Set-Cookie, no Vary beyond Accept-Encoding/Origin, at most maxEntryBytes, maxBytes in all (oldest out first),
|
|
43
|
+
* keyed by URL and Origin (the CORS answer depends on it). Requests with cookies or Authorization go straight through.
|
|
44
|
+
*/
|
|
45
|
+
export const isRemoteUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && !LOOPBACK.has(u.hostname);
|
|
46
|
+
|
|
47
|
+
export function createRemoteCache({ maxBytes = 64 * 1048576, maxEntryBytes = 8 * 1048576, now = () => Date.now(), routes = isRemoteUrl } = {}) {
|
|
48
|
+
const entries = new Map(); // key -> { status, headers, body, expires }; Map order = age
|
|
49
|
+
const inflight = new Map();
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
const drop = (k) => {
|
|
52
|
+
const e = entries.get(k);
|
|
53
|
+
if (e) (bytes -= e.body.length), entries.delete(k);
|
|
54
|
+
};
|
|
55
|
+
const cacheable = (res, body) => {
|
|
56
|
+
if (res.status !== 200 || body.length > maxEntryBytes) return 0;
|
|
57
|
+
const h = res.headers;
|
|
58
|
+
if (h["set-cookie"]) return 0;
|
|
59
|
+
if (h.vary && h.vary.split(",").some((v) => !/^\s*(accept-encoding|origin)\s*$/i.test(v))) return 0;
|
|
60
|
+
return maxAgeOf(h["cache-control"] ?? "");
|
|
61
|
+
};
|
|
62
|
+
async function fetchVia(route, key) {
|
|
63
|
+
const r = await route.fetch();
|
|
64
|
+
const res = { status: r.status(), headers: r.headers(), body: await r.body() };
|
|
65
|
+
const age = cacheable(res, res.body);
|
|
66
|
+
if (age > 0) {
|
|
67
|
+
const { "set-cookie": _, ...headers } = res.headers;
|
|
68
|
+
drop(key);
|
|
69
|
+
entries.set(key, { ...res, headers, expires: now() + age * 1000 });
|
|
70
|
+
bytes += res.body.length;
|
|
71
|
+
for (const k of entries.keys()) {
|
|
72
|
+
if (bytes <= maxBytes) break;
|
|
73
|
+
drop(k);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return res;
|
|
77
|
+
}
|
|
78
|
+
/** The page.route handler */
|
|
79
|
+
async function handle(route) {
|
|
80
|
+
const req = route.request();
|
|
81
|
+
const h = req.headers();
|
|
82
|
+
if (req.method() !== "GET" || h.cookie || h.authorization) return route.continue().catch(() => {});
|
|
83
|
+
const key = `${req.url()}\n${h.origin ?? ""}`;
|
|
84
|
+
try {
|
|
85
|
+
let hit = entries.get(key);
|
|
86
|
+
if (hit && hit.expires <= now()) drop(key), (hit = null);
|
|
87
|
+
if (hit) {
|
|
88
|
+
entries.delete(key), entries.set(key, hit); // most recently used goes last
|
|
89
|
+
} else {
|
|
90
|
+
// Two renders asking for the same font at once share one download
|
|
91
|
+
let p = inflight.get(key);
|
|
92
|
+
if (!p) {
|
|
93
|
+
p = fetchVia(route, key).finally(() => inflight.delete(key));
|
|
94
|
+
inflight.set(key, p);
|
|
95
|
+
}
|
|
96
|
+
hit = await p;
|
|
97
|
+
}
|
|
98
|
+
await route.fulfill({ status: hit.status, headers: hit.headers, body: hit.body });
|
|
99
|
+
} catch {
|
|
100
|
+
await route.continue().catch(() => {}); // a failed fetch or a closed page: let the browser deal with it
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
handle,
|
|
105
|
+
/** Routed URLs: http(s) on a host other than this machine */
|
|
106
|
+
routes,
|
|
107
|
+
clear() {
|
|
108
|
+
entries.clear();
|
|
109
|
+
bytes = 0;
|
|
110
|
+
},
|
|
111
|
+
stats: () => ({ entries: entries.size, bytes }),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The pool. launch() returns a playwright-like Browser (isConnected, on("disconnected"), newPage(opts), close).
|
|
117
|
+
* timers is injectable so tests drive the idle close without waiting.
|
|
118
|
+
*/
|
|
119
|
+
export function createBrowserPool({ launch = launchChromium, idleMs = idleMsFromEnv(), maxPages = MAX_PAGES, timers = globalThis, remoteCache = createRemoteCache() } = {}) {
|
|
120
|
+
let browserPromise = null;
|
|
121
|
+
let idleTimer = null;
|
|
122
|
+
let active = 0; // pages open (each holds a slot)
|
|
123
|
+
const waiting = [];
|
|
124
|
+
|
|
125
|
+
const clearIdle = () => {
|
|
126
|
+
if (idleTimer) timers.clearTimeout(idleTimer);
|
|
127
|
+
idleTimer = null;
|
|
128
|
+
};
|
|
129
|
+
// Armed whenever nothing is rendering and a browser is up; must not keep the Node process alive
|
|
130
|
+
const armIdle = () => {
|
|
131
|
+
clearIdle();
|
|
132
|
+
if (active > 0 || waiting.length || !browserPromise) return;
|
|
133
|
+
const p = browserPromise;
|
|
134
|
+
idleTimer = timers.setTimeout(() => {
|
|
135
|
+
idleTimer = null;
|
|
136
|
+
if (active === 0 && !waiting.length && browserPromise === p) void close();
|
|
137
|
+
}, idleMs);
|
|
138
|
+
idleTimer?.unref?.();
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
async function getBrowser() {
|
|
142
|
+
clearIdle();
|
|
143
|
+
// A browser that exited behind our back (crash, killed, sleep) must not stay cached, or every render fails until a restart
|
|
144
|
+
const pending = browserPromise;
|
|
145
|
+
const cached = pending && (await pending.catch(() => null));
|
|
146
|
+
if (cached && !cached.isConnected() && browserPromise === pending) browserPromise = null;
|
|
147
|
+
if (!browserPromise) {
|
|
148
|
+
const p = (browserPromise = (async () => {
|
|
149
|
+
const b = await launch();
|
|
150
|
+
b.on("disconnected", () => {
|
|
151
|
+
if (browserPromise === p) browserPromise = null;
|
|
152
|
+
});
|
|
153
|
+
return b;
|
|
154
|
+
})());
|
|
155
|
+
// A failed launch is not kept: installing a browser later works without a restart
|
|
156
|
+
p.catch(() => {
|
|
29
157
|
if (browserPromise === p) browserPromise = null;
|
|
30
158
|
});
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
159
|
+
}
|
|
160
|
+
const b = await browserPromise;
|
|
161
|
+
armIdle(); // browserStatus() launches without a render: still closed when idle
|
|
162
|
+
return b;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function close() {
|
|
166
|
+
clearIdle();
|
|
167
|
+
remoteCache?.clear(); // the cache lives as long as the browser
|
|
168
|
+
const b = await browserPromise?.catch(() => null);
|
|
169
|
+
browserPromise = null;
|
|
170
|
+
await b?.close().catch(() => {});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const acquire = () =>
|
|
174
|
+
new Promise((resolve) => {
|
|
175
|
+
clearIdle();
|
|
176
|
+
if (active < maxPages) {
|
|
177
|
+
active++;
|
|
178
|
+
resolve();
|
|
179
|
+
} else waiting.push(resolve);
|
|
35
180
|
});
|
|
181
|
+
const release = () => {
|
|
182
|
+
const next = waiting.shift();
|
|
183
|
+
if (next) next(); // hand the slot over
|
|
184
|
+
else {
|
|
185
|
+
active--;
|
|
186
|
+
armIdle();
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/** A page in its own fresh context (cookies, storage, viewport, color scheme, scale never leak between renders). Holds a slot until the page or its context closes */
|
|
191
|
+
async function newPage(opts) {
|
|
192
|
+
await acquire();
|
|
193
|
+
let released = false;
|
|
194
|
+
const free = () => {
|
|
195
|
+
if (!released) (released = true), release();
|
|
196
|
+
};
|
|
197
|
+
try {
|
|
198
|
+
let browser = await getBrowser();
|
|
199
|
+
let page;
|
|
200
|
+
try {
|
|
201
|
+
page = await browser.newPage(opts);
|
|
202
|
+
} catch (e) {
|
|
203
|
+
if (browser.isConnected()) throw e;
|
|
204
|
+
browser = await getBrowser(); // drops the dead one and launches again
|
|
205
|
+
page = await browser.newPage(opts);
|
|
206
|
+
}
|
|
207
|
+
if (remoteCache && page.route) await page.route(remoteCache.routes, remoteCache.handle).catch((e) => page.close().catch(() => {}).then(() => Promise.reject(e)));
|
|
208
|
+
// browser.newPage owns its context: closing the page closes it; the context also closes when the browser goes away
|
|
209
|
+
const ctx = page.context?.();
|
|
210
|
+
if (ctx?.once) ctx.once("close", free);
|
|
211
|
+
page.once?.("close", free);
|
|
212
|
+
return page;
|
|
213
|
+
} catch (e) {
|
|
214
|
+
free();
|
|
215
|
+
throw Object.assign(e, { opening: true });
|
|
216
|
+
}
|
|
36
217
|
}
|
|
37
|
-
return browserPromise;
|
|
38
|
-
}
|
|
39
218
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
219
|
+
/** Runs fn(page) on a fresh page and closes it. If the browser died during the render, tries once more on a new one */
|
|
220
|
+
async function withPage(opts, fn) {
|
|
221
|
+
for (let attempt = 0; ; attempt++) {
|
|
222
|
+
const page = await newPage(opts);
|
|
223
|
+
const browser = page.context?.().browser?.();
|
|
224
|
+
try {
|
|
225
|
+
return await fn(page);
|
|
226
|
+
} catch (e) {
|
|
227
|
+
if (attempt === 0 && browser && !browser.isConnected()) continue;
|
|
228
|
+
throw e;
|
|
229
|
+
} finally {
|
|
230
|
+
await page.close().catch(() => {});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
48
233
|
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
getBrowser,
|
|
237
|
+
newPage,
|
|
238
|
+
withPage,
|
|
239
|
+
close,
|
|
240
|
+
/** For tests: the browser currently cached, if any */
|
|
241
|
+
cached: () => browserPromise?.catch(() => null) ?? Promise.resolve(null),
|
|
242
|
+
stats: () => ({ active, waiting: waiting.length, idleArmed: !!idleTimer }),
|
|
243
|
+
};
|
|
49
244
|
}
|
|
50
245
|
|
|
246
|
+
const pool = createBrowserPool();
|
|
247
|
+
export const getBrowser = pool.getBrowser;
|
|
248
|
+
export const newPage = pool.newPage;
|
|
249
|
+
export const withPage = pool.withPage;
|
|
250
|
+
/** Close the Chromium used for screenshots/thumbnails/export when the server stops (otherwise it becomes an orphan process) */
|
|
251
|
+
export const closeBrowser = pool.close;
|
|
51
252
|
/** For tests: the browser currently cached for screenshots, if any */
|
|
52
|
-
export const cachedBrowser =
|
|
253
|
+
export const cachedBrowser = pool.cached;
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Goes to url and waits until the board has settled: the load event, web fonts, then no request in flight for quietMs.
|
|
257
|
+
* Replaces waitUntil "networkidle", whose fixed 500 ms quiet window was most of every screenshot. A page that never goes
|
|
258
|
+
* quiet (polling) is captured after maxWaitMs instead of failing.
|
|
259
|
+
*/
|
|
260
|
+
export async function gotoSettled(page, url, { timeout = 30000, quietMs = 100, maxWaitMs = 5000 } = {}) {
|
|
261
|
+
const inflight = new Set();
|
|
262
|
+
const on = (r) => inflight.add(r);
|
|
263
|
+
const off = (r) => inflight.delete(r);
|
|
264
|
+
page.on("request", on);
|
|
265
|
+
page.on("requestfinished", off);
|
|
266
|
+
page.on("requestfailed", off);
|
|
267
|
+
try {
|
|
268
|
+
await page.goto(url, { waitUntil: "load", timeout });
|
|
269
|
+
await page.evaluate(() => document.fonts?.ready.then(() => undefined)).catch(() => {});
|
|
270
|
+
const end = Date.now() + maxWaitMs;
|
|
271
|
+
let quietSince = Date.now();
|
|
272
|
+
while (Date.now() < end) {
|
|
273
|
+
if (inflight.size) quietSince = Date.now();
|
|
274
|
+
else if (Date.now() - quietSince >= quietMs) break;
|
|
275
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
276
|
+
}
|
|
277
|
+
} finally {
|
|
278
|
+
page.off("request", on);
|
|
279
|
+
page.off("requestfinished", off);
|
|
280
|
+
page.off("requestfailed", off);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
53
283
|
|
|
54
284
|
/** Can PDF/PNG export run here? { ok } or { ok: false, reason } in one line, without launching when the downloaded Chromium is on disk */
|
|
55
285
|
export async function browserStatus() {
|
package/server/edit.mjs
CHANGED
|
@@ -160,6 +160,33 @@ export function applyEdit(html, req) {
|
|
|
160
160
|
}
|
|
161
161
|
return setAttrRaw(html, node, "style", next);
|
|
162
162
|
}
|
|
163
|
+
if (op === "setStyleText") {
|
|
164
|
+
// The Code tab (2026-12-01): the element's whole inline style, as typed. Only the style attribute's range changes, its quotes kept;
|
|
165
|
+
// an empty text removes the attribute
|
|
166
|
+
const { node } = target(html, path, hash);
|
|
167
|
+
const next = String(req.text ?? "")
|
|
168
|
+
.split(/;|\n/)
|
|
169
|
+
.map((d) => d.trim())
|
|
170
|
+
.filter(Boolean)
|
|
171
|
+
.join(";");
|
|
172
|
+
const cur = node.attrs?.find((a) => a.name === "style")?.value ?? "";
|
|
173
|
+
if (next === cur.trim().replace(/;$/, "")) return html;
|
|
174
|
+
const loc = node.sourceCodeLocation?.attrs?.style;
|
|
175
|
+
if (loc) {
|
|
176
|
+
const raw = html.slice(loc.startOffset, loc.endOffset);
|
|
177
|
+
const m = raw.match(/^(style\s*=\s*)(["']?)([\s\S]*?)\2$/i);
|
|
178
|
+
if (!m) throw new EditError(422, "Could not read the style attribute");
|
|
179
|
+
const q = m[2] || '"';
|
|
180
|
+
if (!next) {
|
|
181
|
+
let s = loc.startOffset;
|
|
182
|
+
while (s > 0 && /\s/.test(html[s - 1])) s--;
|
|
183
|
+
return splice(html, s, loc.endOffset, "");
|
|
184
|
+
}
|
|
185
|
+
const val = q === '"' ? next.replace(/"/g, """) : next.replace(/'/g, "'");
|
|
186
|
+
return splice(html, loc.startOffset, loc.endOffset, `${m[1]}${q}${val}${q}`);
|
|
187
|
+
}
|
|
188
|
+
return next ? setAttrRaw(html, node, "style", next) : html;
|
|
189
|
+
}
|
|
163
190
|
if (op === "setAttr") {
|
|
164
191
|
const { node } = target(html, path, hash);
|
|
165
192
|
if (!/^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/.test(String(req.name ?? ""))) throw new EditError(400, "Invalid attribute name");
|