pica-mcp 0.1.0 → 0.1.1

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 CHANGED
@@ -8,7 +8,7 @@ Every canvas is a standard, standalone `.pica.svg` file. Agents mutate it cleanl
8
8
 
9
9
  ## Demo
10
10
 
11
- ![pica demo](assets/demo.webp)
11
+ ![pica demo](https://raw.githubusercontent.com/nadeeshafdo/pica/main/assets/demo.webp)
12
12
 
13
13
  Opening hook from the pica launch ad, a 64 second spot authored as `.pica.svg` and exported with `pica_export`.
14
14
 
@@ -38,7 +38,7 @@ Coding Agent (OpenCode / Claude Code / MCP Client)
38
38
 
39
39
  - **Zero heavy JS media deps:** No Playwright, Puppeteer, Sharp, Canvas, React, or Vite.
40
40
  - **Pure stdio protocol:** All logs route to `stderr` so `stdout` stays clean JSON-RPC.
41
- - **Deterministic animation capture:** Headless Chromium pauses `document.getAnimations()`, steps exact integer frame timestamps, and pipes raw PNG frames straight into `ffmpeg` stdin.
41
+ - **Deterministic animation capture:** Headless Chromium pauses `document.getAnimations()`, steps exact frame timestamps, and pipes raw PNG frames straight into `ffmpeg` stdin.
42
42
 
43
43
  ## Prerequisites
44
44
 
@@ -162,6 +162,16 @@ Adds, updates, or removes `@keyframes` and `#id` animation rules inside `<style
162
162
  - `animations` (array, optional): Target bindings `{ id, durationMs?, delayMs?, easing?, iterations?, direction?, fill?, transformOrigin? }`.
163
163
  - `remove` (boolean, default `false`): Delete the `@keyframes` block and surgically remove only matching entries from comma-separated `animation:` declarations.
164
164
 
165
+ ### `pica_configure`
166
+ Updates canvas-level properties on an existing `.pica.svg` file and notifies live preview clients.
167
+
168
+ - `path` (string, required): Target `.pica.svg` file path.
169
+ - `width` (int, optional): Canvas width in pixels.
170
+ - `height` (int, optional): Canvas height in pixels.
171
+ - `background` (string, optional): Canvas background CSS color (syncs `#pica-bg` and `#pica-meta`).
172
+ - `fps` (number, optional): Frames per second for animated exports.
173
+ - `durationMs` (int, optional): Timeline duration in milliseconds. Sets `baseDurationMs` and recalculates `durationMs`.
174
+
165
175
  ### `pica_inspect`
166
176
  Renders a PNG preview and returns an MCP image block plus a short text summary for visual verification.
167
177
 
@@ -205,7 +215,7 @@ All disk writes are atomic (`.tmp` write followed by rename). Because the source
205
215
  When the MCP server starts, it opens an optional local preview server at `http://127.0.0.1:4173` (port failures log to `stderr` and never crash the MCP transport). If `PICA_PORT` is busy, it automatically falls back to an OS-assigned ephemeral port on `127.0.0.1` and logs the actual URL.
206
216
 
207
217
  - Checkerboard artboard with wheel zoom, drag pan, and fit-to-screen.
208
- - Live WebSocket reload on every `pica_create`, `pica_patch`, and `pica_animate` while preserving your current zoom and pan across patches. `/ws` upgrades require same-origin (`127.0.0.1` / `localhost`) or missing `Origin`.
218
+ - Live WebSocket reload on every `pica_create`, `pica_patch`, `pica_animate`, and `pica_configure` while preserving your current zoom and pan across patches. `/ws` upgrades require same-origin (`127.0.0.1` / `localhost`) or missing `Origin`.
209
219
  - Bottom timeline scrubber (Play/Pause + time slider) synced with `document.getAnimations()`.
210
220
 
211
221
  ## Environment Variables
@@ -215,6 +225,7 @@ When the MCP server starts, it opens an optional local preview server at `http:/
215
225
  | `PICA_PORT` | `4173` | Port for the local Hono live preview server (`127.0.0.1`). Falls back to ephemeral `0` when busy. |
216
226
  | `PICA_ROOT` | Unset | When set, all `path` / `outPath` inputs must resolve inside this directory tree. |
217
227
  | `CHROME_PATH` / `CHROMIUM_PATH` | Auto-detected | Explicit path to a Chromium or Google Chrome executable. |
228
+ | `PICA_CHROME_NO_SANDBOX` | Unset | Set to `1` to launch Chromium with `--no-sandbox`. By default the sandbox is kept and only retried without it when the first launch does not start. |
218
229
 
219
230
  ## Development
220
231
 
package/SECURITY.md CHANGED
@@ -56,12 +56,13 @@ Out of scope (but still welcome as regular bugs):
56
56
 
57
57
  Hardening already in place:
58
58
 
59
- - DOM-based SVG sanitization via `linkedom`: rejects `<script>`, `<foreignObject>`, `<iframe>`, `<object>`, `<embed>`, and `<applet>`; `on*` handlers including no-space bypasses; entity-decoded `javascript:`, `vbscript:`, and `data:text/html` URLs; and dangerous `<style>` CSS (`@import`, `javascript:`, `expression(`).
59
+ - DOM-based SVG sanitization via `linkedom`: rejects `<script>`, `<foreignObject>`, `<iframe>`, `<object>`, `<embed>`, and `<applet>`; `on*` handlers including no-space forms; entity-decoded `javascript:`, `vbscript:`, and limited `data:` URLs (allowlist: `data:image/png`, `data:image/jpeg`, `data:image/webp`, `data:image/gif`, `data:font/`, `data:application/font-woff`, `data:application/font-woff2`); and `<style>` CSS with `@import`, `javascript:`, `expression(`, or `url(` after comment and hex-escape normalization. Only `<style id="pica-anim">` is accepted.
60
60
  - Skeleton element protection: `pica-meta`, `pica-defs`, `pica-anim`, and `pica-root` are blocked from `update`, `remove`, and `reorder`; `pica-bg` is restricted to `fill`, `opacity`, and `fill-opacity`; `id` mutation is blocked on all elements.
61
- - `pica_animate` CSS injection guards on keyframe names, keyframe bodies (including `url(`), and target properties (`easing`, `transformOrigin`, `direction`, `fill`, string `iterations`).
62
- - Path safety via `resolveSafePath` (null-byte rejection and optional `PICA_ROOT` sandbox jail) plus `ffmpeg` flag (`-...`) and protocol (`://`) rejection on the raw `outPath`.
63
- - Headless Chromium CDP `Fetch.enable` request blocking: external `http://`, `https://`, `file://`, and `ws://` requests are blocked, allowing only `about:blank` and non-HTML `data:` URLs.
64
- - Preview server bound to `127.0.0.1`, `/ws` `Origin` header validation (`403` on cross-origin), strict `DOMParser` SVG parsing with no `innerHTML` fallback, and `Content-Security-Policy` headers on `/` and `/svg`.
61
+ - `pica_animate` CSS checks on keyframe names, keyframe bodies (including `url(`, balanced-brace validation, comment and hex-escape normalization), and target properties (`easing`, `transformOrigin`, `direction`, `fill`, string `iterations`).
62
+ - `pica_configure` updates `width`, `height`, `viewBox`, `#pica-bg` fill, and `#pica-meta` (`fps`, `background`, `baseDurationMs`, recalculated `durationMs`) atomically; `pica_patch` keeps `#pica-meta.background` in sync when `#pica-bg` fill changes.
63
+ - Path handling via `resolveSafePath` (null-byte rejection and optional `PICA_ROOT` check with `realpathSync` canonicalization, walking to the nearest existing ancestor for new files) plus `ffmpeg` flag (`-...`) and protocol (`://`) rejection on the raw `outPath`.
64
+ - Headless Chromium CDP `Fetch.enable` request handling: external `http://`, `https://`, `file://`, and `ws://` requests are not allowed, allowing only `about:blank` and the same `data:` allowlist as above. Chromium launches with the sandbox by default; set `PICA_CHROME_NO_SANDBOX=1` to include `--no-sandbox`, with a single retry without it when the first launch does not start.
65
+ - Preview server bound to `127.0.0.1`, `/ws` `Origin` header validation (`403` on cross-origin), `DOMParser` SVG parsing for metadata with canvas rendering isolated in a sandboxed `<iframe sandbox="allow-same-origin" srcdoc>`, and `Content-Security-Policy` headers on `/` (`frame-src 'self'`, `font-src`) and `/svg`.
65
66
  - Atomic `.tmp` plus `rename` writes with failed-write `.tmp` cleanup, so interrupted writes never leave partial files.
66
67
  - Exports strip debug overlays (`showGrid`, `showIds` never persist).
67
68
  - No cloud calls, no telemetry, no bundled secrets.
package/dist/index.js CHANGED
@@ -29,7 +29,8 @@ import { z } from "zod";
29
29
 
30
30
  // src/pica-file.ts
31
31
  import { DOMParser } from "linkedom";
32
- import { isAbsolute, relative, resolve, sep } from "path";
32
+ import { existsSync, lstatSync, readlinkSync, realpathSync } from "fs";
33
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
33
34
 
34
35
  // src/bbox.ts
35
36
  function num(v, fallback = 0) {
@@ -249,9 +250,24 @@ function pathBbox(d) {
249
250
  cy = y;
250
251
  push(x, y);
251
252
  } else if (C === "A") {
253
+ const rx = Math.abs(args[0]);
254
+ const ry = Math.abs(args[1]);
252
255
  const x = args[5] + (rel ? cx : 0);
253
256
  const y = args[6] + (rel ? cy : 0);
257
+ push(cx, cy);
254
258
  push(x, y);
259
+ if (rx > 0 && ry > 0) {
260
+ const mx = (cx + x) / 2;
261
+ const my = (cy + y) / 2;
262
+ if (Math.abs(y - cy) < ry * 2) {
263
+ push(mx, Math.min(cy, y) - ry);
264
+ push(mx, Math.max(cy, y) + ry);
265
+ }
266
+ if (Math.abs(x - cx) < rx * 2) {
267
+ push(Math.min(cx, x) - rx, my);
268
+ push(Math.max(cx, x) + rx, my);
269
+ }
270
+ }
255
271
  cx = x;
256
272
  cy = y;
257
273
  }
@@ -340,9 +356,9 @@ function buildPicaSvg(opts) {
340
356
  return `<svg xmlns="${SVG_NS}" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` + `<metadata id="pica-meta">${escapeAttr(metaJson)}</metadata>` + `<defs id="pica-defs"></defs>` + `<style id="pica-anim"></style>` + `<rect id="pica-bg" width="100%" height="100%" fill="${escapeAttr(background)}"/>` + `<g id="pica-root"></g>` + `</svg>`;
341
357
  }
342
358
  async function atomicWriteFile(path, content) {
343
- const { dirname } = await import("path");
359
+ const { dirname: dirname2 } = await import("path");
344
360
  const { rename, unlink } = await import("fs/promises");
345
- const dir = dirname(path);
361
+ const dir = dirname2(path);
346
362
  if (dir && dir !== "." && dir !== "") {
347
363
  const { mkdir } = await import("fs/promises");
348
364
  await mkdir(dir, { recursive: true });
@@ -468,17 +484,48 @@ function resolveSafePath(inputPath) {
468
484
  }
469
485
  const resolved = resolve(inputPath);
470
486
  const rootRaw = process.env["PICA_ROOT"];
471
- if (rootRaw && rootRaw.length > 0) {
472
- if (rootRaw.includes("\x00")) {
473
- throw new Error("Rejected: PICA_ROOT contains null bytes.");
474
- }
475
- const root = resolve(rootRaw);
476
- const rel = relative(root, resolved);
477
- if (rel === ".." || rel.startsWith(`..${sep}`) || rel.startsWith("../") || isAbsolute(rel)) {
478
- throw new Error(`Rejected: path escapes PICA_ROOT (${root}).`);
479
- }
487
+ if (!rootRaw || rootRaw.length === 0)
488
+ return resolved;
489
+ if (rootRaw.includes("\x00")) {
490
+ throw new Error("Rejected: PICA_ROOT contains null bytes.");
480
491
  }
481
- return resolved;
492
+ let canonicalRoot;
493
+ try {
494
+ canonicalRoot = realpathSync(resolve(rootRaw));
495
+ } catch {
496
+ throw new Error(`Rejected: path escapes PICA_ROOT (${resolve(rootRaw)}).`);
497
+ }
498
+ let ancestor = resolved;
499
+ const rest = [];
500
+ const seenLinks = new Set;
501
+ while (!existsSync(ancestor)) {
502
+ try {
503
+ const st = lstatSync(ancestor);
504
+ if (st.isSymbolicLink() && !seenLinks.has(ancestor)) {
505
+ seenLinks.add(ancestor);
506
+ const target = readlinkSync(ancestor);
507
+ ancestor = resolve(dirname(ancestor), target);
508
+ continue;
509
+ }
510
+ } catch {}
511
+ const parent = dirname(ancestor);
512
+ if (parent === ancestor)
513
+ break;
514
+ rest.unshift(basename(ancestor));
515
+ ancestor = parent;
516
+ }
517
+ let canonicalAncestor;
518
+ try {
519
+ canonicalAncestor = realpathSync(ancestor);
520
+ } catch {
521
+ throw new Error(`Rejected: path escapes PICA_ROOT (${canonicalRoot}).`);
522
+ }
523
+ const canonicalTarget = rest.length > 0 ? join(canonicalAncestor, ...rest) : canonicalAncestor;
524
+ const rel = relative(canonicalRoot, canonicalTarget);
525
+ if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || rel.startsWith("../") || isAbsolute(rel)) {
526
+ throw new Error(`Rejected: path escapes PICA_ROOT (${canonicalRoot}).`);
527
+ }
528
+ return canonicalTarget;
482
529
  }
483
530
  var FORBIDDEN_TAG_SET = new Set(["script", "foreignobject", "iframe", "object", "embed", "applet"]);
484
531
  function localTagName(tagName) {
@@ -497,11 +544,96 @@ function isForbiddenTag(tagName) {
497
544
  function cleanUrlValue(value) {
498
545
  return value.replace(/[\x00-\x20\x7F]+/g, "").toLowerCase();
499
546
  }
547
+ var SAFE_DATA_PREFIXES = [
548
+ "data:image/png",
549
+ "data:image/jpeg",
550
+ "data:image/webp",
551
+ "data:image/gif",
552
+ "data:font/",
553
+ "data:application/font-woff",
554
+ "data:application/font-woff2"
555
+ ];
556
+ function isSafeDataUrl(cleanedLower) {
557
+ return SAFE_DATA_PREFIXES.some((p) => cleanedLower.startsWith(p));
558
+ }
559
+ function normalizeCssForCheck(css) {
560
+ let out = css.replace(/\/\*[\s\S]*?\*\//g, "");
561
+ out = out.replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_m, hex) => {
562
+ const code = Number.parseInt(hex, 16);
563
+ if (!Number.isFinite(code))
564
+ return "";
565
+ try {
566
+ return String.fromCodePoint(code);
567
+ } catch {
568
+ return "";
569
+ }
570
+ });
571
+ out = out.replace(/\\(.)/gs, "$1");
572
+ return out;
573
+ }
574
+ function assertBalancedBraces(body) {
575
+ const withoutComments = body.replace(/\/\*[\s\S]*?\*\//g, "");
576
+ if (withoutComments.includes("/*") || withoutComments.includes("*/")) {
577
+ throw new Error("Rejected: unclosed comment in keyframes.");
578
+ }
579
+ const stripped = withoutComments;
580
+ let depth = 0;
581
+ let inSingle = false;
582
+ let inDouble = false;
583
+ for (let i = 0;i < stripped.length; i++) {
584
+ const ch = stripped[i];
585
+ if (inSingle) {
586
+ if (ch === "\\") {
587
+ i++;
588
+ continue;
589
+ }
590
+ if (ch === "'")
591
+ inSingle = false;
592
+ continue;
593
+ }
594
+ if (inDouble) {
595
+ if (ch === "\\") {
596
+ i++;
597
+ continue;
598
+ }
599
+ if (ch === '"')
600
+ inDouble = false;
601
+ continue;
602
+ }
603
+ if (ch === "'") {
604
+ inSingle = true;
605
+ continue;
606
+ }
607
+ if (ch === '"') {
608
+ inDouble = true;
609
+ continue;
610
+ }
611
+ if (ch === "{")
612
+ depth++;
613
+ else if (ch === "}") {
614
+ depth--;
615
+ if (depth < 0)
616
+ throw new Error("Rejected: unbalanced braces in keyframes.");
617
+ }
618
+ }
619
+ if (inSingle || inDouble)
620
+ throw new Error("Rejected: unbalanced braces in keyframes.");
621
+ if (depth !== 0)
622
+ throw new Error("Rejected: unbalanced braces in keyframes.");
623
+ }
500
624
  function assertSafeAttrValue(_attrName, value) {
501
625
  const cleaned = cleanUrlValue(value);
502
- if (cleaned.includes("javascript:") || cleaned.includes("vbscript:") || cleaned.includes("data:text/html")) {
626
+ if (cleaned.includes("javascript:") || cleaned.includes("vbscript:")) {
503
627
  throw new Error(`Rejected: dangerous URL in attribute '${_attrName}'.`);
504
628
  }
629
+ const dataUrls = cleaned.match(/data:[^)\s"'<>]*/g);
630
+ if (dataUrls) {
631
+ for (const m of dataUrls) {
632
+ if (!isSafeDataUrl(m)) {
633
+ throw new Error(`Rejected: unsupported data: URL in attribute '${_attrName}'.`);
634
+ }
635
+ }
636
+ }
505
637
  }
506
638
  function assertSafeAttributesRecord(attrs) {
507
639
  for (const [k, v] of Object.entries(attrs)) {
@@ -537,9 +669,13 @@ function assertSafeSvgTree(doc) {
537
669
  }
538
670
  }
539
671
  if (localTagName(String(tag)) === "style") {
540
- const css = (el.textContent ?? "").toLowerCase();
541
- if (css.includes("javascript:") || css.includes("expression(") || css.includes("@import")) {
542
- throw new Error("Rejected: dangerous CSS in <style>.");
672
+ const sid = el.getAttribute?.("id") ?? null;
673
+ if (sid !== "pica-anim") {
674
+ throw new Error('Rejected: only <style id="pica-anim"> is allowed.');
675
+ }
676
+ const css = normalizeCssForCheck(el.textContent ?? "").toLowerCase();
677
+ if (css.includes("javascript:") || css.includes("expression(") || css.includes("@import") || css.includes("url(")) {
678
+ throw new Error("Rejected: unsupported CSS in <style>.");
543
679
  }
544
680
  }
545
681
  }
@@ -706,7 +842,7 @@ function normalizeFontAliases(svgText) {
706
842
  }
707
843
  function buildResvg(svgText, scale) {
708
844
  const s = scale <= 0 || !Number.isFinite(scale) ? 1 : scale;
709
- const withText = svgText.includes("<text");
845
+ const withText = /<(?:[A-Za-z_][\w.-]*:)?text\b/i.test(svgText);
710
846
  const input = withText ? normalizeFontAliases(svgText) : svgText;
711
847
  if (!withText) {
712
848
  return new Resvg(input, {
@@ -732,7 +868,7 @@ function renderPngBuffer(svgText, scale = 1) {
732
868
  }
733
869
 
734
870
  // src/chromium.ts
735
- import { join } from "path";
871
+ import { join as join2 } from "path";
736
872
  import { tmpdir } from "os";
737
873
  import { mkdtemp, rm } from "fs/promises";
738
874
  import { rmSync } from "fs";
@@ -1002,16 +1138,23 @@ async function readBrowserEndpoint(proc) {
1002
1138
  reader.releaseLock();
1003
1139
  } catch {}
1004
1140
  }
1005
- throw new Error("Timed out waiting for Chromium DevTools endpoint. Is chromium installed and runnable with --no-sandbox?");
1006
- }
1141
+ throw new Error("Timed out waiting for Chromium DevTools endpoint. Is chromium installed and runnable? If the sandbox is restricted, set PICA_CHROME_NO_SANDBOX=1.");
1142
+ }
1143
+ var SAFE_DATA_PREFIXES2 = [
1144
+ "data:image/png",
1145
+ "data:image/jpeg",
1146
+ "data:image/webp",
1147
+ "data:image/gif",
1148
+ "data:font/",
1149
+ "data:application/font-woff",
1150
+ "data:application/font-woff2"
1151
+ ];
1007
1152
  function isAllowedRequestUrl(url) {
1008
1153
  if (url === "about:blank")
1009
1154
  return true;
1010
- const lower = url.toLowerCase();
1155
+ const lower = url.toLowerCase().replace(/[\x00-\x20\x7F]+/g, "");
1011
1156
  if (lower.startsWith("data:")) {
1012
- if (lower.startsWith("data:text/html"))
1013
- return false;
1014
- return true;
1157
+ return SAFE_DATA_PREFIXES2.some((p) => lower.startsWith(p));
1015
1158
  }
1016
1159
  return false;
1017
1160
  }
@@ -1064,11 +1207,10 @@ async function startBrowser() {
1064
1207
  const bin = findChromeBinary();
1065
1208
  if (!bin)
1066
1209
  throw new Error(chromeMissingMessage());
1067
- const userDir = await mkdtemp(join(tmpdir(), "pica-chrome-"));
1210
+ const userDir = await mkdtemp(join2(tmpdir(), "pica-chrome-"));
1068
1211
  browserUserDir = userDir;
1069
- const args = [
1212
+ const baseArgs = [
1070
1213
  "--headless",
1071
- "--no-sandbox",
1072
1214
  "--disable-gpu",
1073
1215
  "--disable-dev-shm-usage",
1074
1216
  "--hide-scrollbars",
@@ -1077,35 +1219,65 @@ async function startBrowser() {
1077
1219
  `--user-data-dir=${userDir}`,
1078
1220
  "about:blank"
1079
1221
  ];
1080
- browserProc = Bun.spawn([bin, ...args], {
1081
- stdout: "ignore",
1082
- stderr: "pipe",
1083
- stdin: "ignore"
1084
- });
1085
- try {
1086
- const endpoint = await readBrowserEndpoint(browserProc);
1087
- browserConn = await CdpConn.connect(endpoint);
1088
- const created = await browserConn.send("Target.createTarget", { url: "about:blank" });
1089
- if (!created?.targetId)
1090
- throw new Error("Chromium Target.createTarget did not return a targetId.");
1091
- pageTargetId = created.targetId;
1092
- const attached = await browserConn.send("Target.attachToTarget", {
1093
- targetId: pageTargetId,
1094
- flatten: true
1222
+ const envNoSandbox = process.env["PICA_CHROME_NO_SANDBOX"] === "1";
1223
+ const withSandboxArgs = baseArgs;
1224
+ const noSandboxArgs = ["--headless", "--no-sandbox", ...baseArgs.slice(1)];
1225
+ const attempts = envNoSandbox ? [noSandboxArgs] : [withSandboxArgs, noSandboxArgs];
1226
+ let lastError = null;
1227
+ for (let attempt = 0;attempt < attempts.length; attempt++) {
1228
+ const args = attempts[attempt];
1229
+ browserProc = Bun.spawn([bin, ...args], {
1230
+ stdout: "ignore",
1231
+ stderr: "pipe",
1232
+ stdin: "ignore"
1095
1233
  });
1096
- if (!attached?.sessionId)
1097
- throw new Error("Chromium Target.attachToTarget did not return a sessionId.");
1098
- pageSessionId = attached.sessionId;
1099
- await browserConn.send("Page.enable", {}, pageSessionId);
1100
- await browserConn.send("Runtime.enable", {}, pageSessionId);
1101
- await enableFetchBlocking();
1102
- touchIdle();
1103
- } catch (e) {
1104
- await closeBrowser().catch(() => {
1234
+ try {
1235
+ const endpoint = await readBrowserEndpoint(browserProc);
1236
+ browserConn = await CdpConn.connect(endpoint);
1237
+ const created = await browserConn.send("Target.createTarget", { url: "about:blank" });
1238
+ if (!created?.targetId)
1239
+ throw new Error("Chromium Target.createTarget did not return a targetId.");
1240
+ pageTargetId = created.targetId;
1241
+ const attached = await browserConn.send("Target.attachToTarget", {
1242
+ targetId: pageTargetId,
1243
+ flatten: true
1244
+ });
1245
+ if (!attached?.sessionId)
1246
+ throw new Error("Chromium Target.attachToTarget did not return a sessionId.");
1247
+ pageSessionId = attached.sessionId;
1248
+ await browserConn.send("Page.enable", {}, pageSessionId);
1249
+ await browserConn.send("Runtime.enable", {}, pageSessionId);
1250
+ await enableFetchBlocking();
1251
+ touchIdle();
1105
1252
  return;
1106
- });
1107
- throw e;
1253
+ } catch (e) {
1254
+ lastError = e;
1255
+ try {
1256
+ browserConn?.close();
1257
+ } catch {}
1258
+ browserConn = null;
1259
+ pageSessionId = null;
1260
+ pageTargetId = null;
1261
+ if (browserProc) {
1262
+ try {
1263
+ browserProc.kill();
1264
+ } catch {}
1265
+ browserProc = null;
1266
+ }
1267
+ if (attempt === 0 && !envNoSandbox) {
1268
+ console.error(`[pica] Chromium launch failed, retrying with --no-sandbox: ${String(e)}`);
1269
+ continue;
1270
+ }
1271
+ await closeBrowser().catch(() => {
1272
+ return;
1273
+ });
1274
+ throw e;
1275
+ }
1108
1276
  }
1277
+ await closeBrowser().catch(() => {
1278
+ return;
1279
+ });
1280
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
1109
1281
  })();
1110
1282
  try {
1111
1283
  await starting;
@@ -1177,12 +1349,12 @@ async function getExactBboxes(svgText, width, height) {
1177
1349
  return Array.isArray(out) ? out : [];
1178
1350
  });
1179
1351
  }
1180
- async function getRenderedBboxesAtTime(svgText, width, height, timeMs) {
1352
+ async function screenshotAtTime(svgText, width, height, timeMs, scale) {
1181
1353
  return withCdpLock(async () => {
1182
1354
  await ensureBrowser();
1183
1355
  if (!browserConn || !pageSessionId)
1184
1356
  throw new Error("Browser not started.");
1185
- const { w, h } = scaledSize(width, height, 1);
1357
+ const { w, h } = scaledSize(width, height, scale);
1186
1358
  await applyViewport(w, h, pageSessionId);
1187
1359
  await setDocumentHtml(htmlWrapper(svgText, w, h));
1188
1360
  await runtimeEval(`(async () => {
@@ -1191,27 +1363,14 @@ async function getRenderedBboxesAtTime(svgText, width, height, timeMs) {
1191
1363
  document.getAnimations().forEach((a) => { try { a.pause(); a.currentTime = ${Math.max(0, timeMs)}; } catch (e) {} });
1192
1364
  return 'ok';
1193
1365
  })()`, true);
1194
- const out = await runtimeEval(`(() => {
1195
- const svg = document.querySelector('svg');
1196
- if (!svg) return [];
1197
- const svgRect = svg.getBoundingClientRect();
1198
- const root = document.querySelector('#pica-root');
1199
- if (!root) return [];
1200
- const els = Array.from(root.querySelectorAll('[id]'));
1201
- return els.map((el) => {
1202
- try {
1203
- const r = el.getBoundingClientRect();
1204
- return { id: el.id, bbox: { x: r.left - svgRect.left, y: r.top - svgRect.top, w: r.width, h: r.height } };
1205
- } catch (e) {
1206
- return { id: el.id, bbox: { x: 0, y: 0, w: 0, h: 0 } };
1207
- }
1208
- });
1209
- })()`);
1366
+ const res = await browserConn.send("Page.captureScreenshot", { format: "png", fromSurface: true }, pageSessionId);
1210
1367
  touchIdle();
1211
- return Array.isArray(out) ? out : [];
1368
+ if (!res?.data)
1369
+ throw new Error("Chromium Page.captureScreenshot returned no data.");
1370
+ return Buffer.from(res.data, "base64");
1212
1371
  });
1213
1372
  }
1214
- async function screenshotAtTime(svgText, width, height, timeMs, scale) {
1373
+ async function screenshotInspectSinglePass(svgText, width, height, timeMs, scale, showGrid, showIds) {
1215
1374
  return withCdpLock(async () => {
1216
1375
  await ensureBrowser();
1217
1376
  if (!browserConn || !pageSessionId)
@@ -1219,12 +1378,102 @@ async function screenshotAtTime(svgText, width, height, timeMs, scale) {
1219
1378
  const { w, h } = scaledSize(width, height, scale);
1220
1379
  await applyViewport(w, h, pageSessionId);
1221
1380
  await setDocumentHtml(htmlWrapper(svgText, w, h));
1381
+ const t = Math.max(0, timeMs);
1222
1382
  await runtimeEval(`(async () => {
1223
- document.getAnimations().forEach((a) => { try { a.pause(); a.currentTime = ${Math.max(0, timeMs)}; } catch (e) {} });
1383
+ document.getAnimations().forEach((a) => { try { a.pause(); a.currentTime = ${t}; } catch (e) {} });
1224
1384
  await new Promise((r) => requestAnimationFrame(() => r(1)));
1225
- document.getAnimations().forEach((a) => { try { a.pause(); a.currentTime = ${Math.max(0, timeMs)}; } catch (e) {} });
1385
+ document.getAnimations().forEach((a) => { try { a.pause(); a.currentTime = ${t}; } catch (e) {} });
1226
1386
  return 'ok';
1227
1387
  })()`, true);
1388
+ await runtimeEval(`(() => {
1389
+ const svg = document.querySelector('svg');
1390
+ if (!svg) return 'no-svg';
1391
+ const W = ${width};
1392
+ const H = ${height};
1393
+ const showGrid = ${showGrid ? "true" : "false"};
1394
+ const showIds = ${showIds ? "true" : "false"};
1395
+ const NS = 'http://www.w3.org/2000/svg';
1396
+ let overlay = document.getElementById('pica-debug-overlay');
1397
+ if (overlay) overlay.remove();
1398
+ overlay = document.createElementNS(NS, 'g');
1399
+ overlay.setAttribute('id', 'pica-debug-overlay');
1400
+ overlay.setAttribute('pointer-events', 'none');
1401
+ if (showGrid) {
1402
+ for (let x = 100; x < W; x += 100) {
1403
+ const ln = document.createElementNS(NS, 'line');
1404
+ ln.setAttribute('x1', String(x));
1405
+ ln.setAttribute('y1', '0');
1406
+ ln.setAttribute('x2', String(x));
1407
+ ln.setAttribute('y2', String(H));
1408
+ ln.setAttribute('stroke', '#d4d4d8');
1409
+ ln.setAttribute('stroke-width', '1');
1410
+ ln.setAttribute('opacity', '0.7');
1411
+ overlay.appendChild(ln);
1412
+ }
1413
+ for (let y = 100; y < H; y += 100) {
1414
+ const ln = document.createElementNS(NS, 'line');
1415
+ ln.setAttribute('x1', '0');
1416
+ ln.setAttribute('y1', String(y));
1417
+ ln.setAttribute('x2', String(W));
1418
+ ln.setAttribute('y2', String(y));
1419
+ ln.setAttribute('stroke', '#d4d4d8');
1420
+ ln.setAttribute('stroke-width', '1');
1421
+ ln.setAttribute('opacity', '0.7');
1422
+ overlay.appendChild(ln);
1423
+ }
1424
+ const frame = document.createElementNS(NS, 'rect');
1425
+ frame.setAttribute('x', '0.5');
1426
+ frame.setAttribute('y', '0.5');
1427
+ frame.setAttribute('width', String(W - 1));
1428
+ frame.setAttribute('height', String(H - 1));
1429
+ frame.setAttribute('fill', 'none');
1430
+ frame.setAttribute('stroke', '#a1a1aa');
1431
+ frame.setAttribute('stroke-width', '1');
1432
+ overlay.appendChild(frame);
1433
+ }
1434
+ if (showIds) {
1435
+ const svgRect = svg.getBoundingClientRect();
1436
+ const root = document.querySelector('#pica-root');
1437
+ const els = root ? Array.from(root.querySelectorAll('[id]')) : [];
1438
+ for (const el of els) {
1439
+ try {
1440
+ const r = el.getBoundingClientRect();
1441
+ const bx = r.left - svgRect.left;
1442
+ const by = r.top - svgRect.top;
1443
+ const bw = r.width;
1444
+ const bh = r.height;
1445
+ if (!(bw > 0 && bh > 0)) continue;
1446
+ const id = el.id || '';
1447
+ // Scale page px back to SVG units.
1448
+ const sx = svgRect.width > 0 ? W / svgRect.width : 1;
1449
+ const sy = svgRect.height > 0 ? H / svgRect.height : 1;
1450
+ const ux = bx * sx;
1451
+ const uy = by * sy;
1452
+ const uw = bw * sx;
1453
+ const uh = bh * sy;
1454
+ const box = document.createElementNS(NS, 'rect');
1455
+ box.setAttribute('x', String(ux));
1456
+ box.setAttribute('y', String(uy));
1457
+ box.setAttribute('width', String(uw));
1458
+ box.setAttribute('height', String(uh));
1459
+ box.setAttribute('fill', 'none');
1460
+ box.setAttribute('stroke', '#2563eb');
1461
+ box.setAttribute('stroke-width', '1.5');
1462
+ overlay.appendChild(box);
1463
+ const label = document.createElementNS(NS, 'text');
1464
+ label.setAttribute('x', String(ux + 2));
1465
+ label.setAttribute('y', String(Math.max(10, uy - 4)));
1466
+ label.setAttribute('font-size', '11');
1467
+ label.setAttribute('font-family', 'monospace');
1468
+ label.setAttribute('fill', '#1d4ed8');
1469
+ label.textContent = '#' + id;
1470
+ overlay.appendChild(label);
1471
+ } catch (e) {}
1472
+ }
1473
+ }
1474
+ svg.appendChild(overlay);
1475
+ return 'ok';
1476
+ })()`);
1228
1477
  const res = await browserConn.send("Page.captureScreenshot", { format: "png", fromSurface: true }, pageSessionId);
1229
1478
  touchIdle();
1230
1479
  if (!res?.data)
@@ -1243,7 +1492,7 @@ async function captureFrames(svgText, width, height, durationMs, fps, scale, onF
1243
1492
  const safeFps = Math.max(1, fps);
1244
1493
  const totalFrames = Math.max(1, Math.round(durationMs / 1000 * safeFps));
1245
1494
  for (let i = 0;i < totalFrames; i++) {
1246
- const t = Math.round(i * 1000 / safeFps);
1495
+ const t = i * 1000 / safeFps;
1247
1496
  await runtimeEval(`(async () => {
1248
1497
  document.getAnimations().forEach((a) => { try { a.pause(); a.currentTime = ${t}; } catch (e) {} });
1249
1498
  await new Promise((r) => requestAnimationFrame(() => r(1)));
@@ -1260,14 +1509,14 @@ async function captureFrames(svgText, width, height, durationMs, fps, scale, onF
1260
1509
  }
1261
1510
 
1262
1511
  // src/export.ts
1263
- import { dirname, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
1512
+ import { dirname as dirname2, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
1264
1513
  import { mkdir } from "fs/promises";
1265
1514
  async function readSvgClean(path) {
1266
1515
  const raw = await Bun.file(path).text();
1267
1516
  return stripDebugOverlay(raw);
1268
1517
  }
1269
1518
  async function ensureParentDir(outPath) {
1270
- const dir = dirname(outPath);
1519
+ const dir = dirname2(outPath);
1271
1520
  if (dir && dir !== "." && dir !== "") {
1272
1521
  await mkdir(dir, { recursive: true });
1273
1522
  }
@@ -1320,7 +1569,7 @@ async function runFfmpegWithPngInput(args, png, outPath) {
1320
1569
  }
1321
1570
  const sink = writer;
1322
1571
  await sink.write(png);
1323
- sink.flush();
1572
+ await sink.flush();
1324
1573
  sink.end();
1325
1574
  const exit = await proc.exited;
1326
1575
  const errText = await stderrPromise;
@@ -1442,7 +1691,7 @@ async function exportAnimated(svgText, width, height, outPath, kind, fps, durati
1442
1691
  try {
1443
1692
  await captureFrames(svgText, width, height, durationMs, fps, scale, async (png) => {
1444
1693
  await writer.write(png);
1445
- writer.flush();
1694
+ await writer.flush();
1446
1695
  });
1447
1696
  writer.end();
1448
1697
  const exit = await proc.exited;
@@ -1507,11 +1756,11 @@ function startPreviewServer() {
1507
1756
  const app = new Hono;
1508
1757
  app.get("/", async (c) => {
1509
1758
  const html = await loadViewerHtml();
1510
- c.header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws://127.0.0.1:* ws://localhost:*; object-src 'none'; frame-ancestors 'none'");
1759
+ c.header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ws://127.0.0.1:* ws://localhost:*; object-src 'none'; frame-src 'self'; frame-ancestors 'none'");
1511
1760
  return c.html(html);
1512
1761
  });
1513
1762
  app.get("/svg", (c) => {
1514
- c.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox");
1763
+ c.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox");
1515
1764
  if (!lastSvgText) {
1516
1765
  return c.text("No .pica.svg written yet in this session.", 404);
1517
1766
  }
@@ -1636,6 +1885,14 @@ var AnimateSchema = z.object({
1636
1885
  animations: z.array(AnimateTargetSchema).optional().describe("Target animation rules to add/update"),
1637
1886
  remove: z.boolean().default(false).describe("Remove the keyframes and referencing rules")
1638
1887
  });
1888
+ var ConfigureSchema = z.object({
1889
+ path: z.string().min(1).describe("Target .pica.svg file path"),
1890
+ width: z.number().int().positive().max(8192).optional().describe("Canvas width in px"),
1891
+ height: z.number().int().positive().max(8192).optional().describe("Canvas height in px"),
1892
+ background: z.string().optional().describe("Canvas background CSS color"),
1893
+ fps: z.number().positive().max(120).optional().describe("Frames per second for animated exports"),
1894
+ durationMs: z.number().int().positive().max(600000).optional().describe("Timeline duration in ms")
1895
+ });
1639
1896
  var InspectSchema = z.object({
1640
1897
  path: z.string().min(1).describe("Input .pica.svg file path"),
1641
1898
  timeMs: z.number().min(0).default(0).describe("Animation timestamp in ms. Static designs render via resvg; animated designs (and any timeMs>0) capture via headless Chromium CDP when available, else static resvg fallback at timeMs=0"),
@@ -1802,6 +2059,10 @@ async function handlePatch(input) {
1802
2059
  ensurePicaSkeleton(doc);
1803
2060
  for (const op of input.ops) {
1804
2061
  if (op.op === "add") {
2062
+ const localTag = op.tag.includes(":") ? (op.tag.split(":").pop() ?? op.tag).toLowerCase() : op.tag.toLowerCase();
2063
+ if (localTag === "style") {
2064
+ throw new Error("pica_patch add failed: <style> elements are managed by pica_animate.");
2065
+ }
1805
2066
  sanitizeTag(op.tag);
1806
2067
  if (!ID_RE.test(op.id)) {
1807
2068
  throw new Error(`pica_patch add failed: invalid id '#${op.id}'. Use /^[a-zA-Z_][a-zA-Z0-9_-]*$/.`);
@@ -1871,6 +2132,18 @@ async function handlePatch(input) {
1871
2132
  else
1872
2133
  el.setAttribute(k, v);
1873
2134
  }
2135
+ if (Object.prototype.hasOwnProperty.call(attrs, "fill")) {
2136
+ const fillVal = attrs["fill"];
2137
+ if (typeof fillVal === "string") {
2138
+ const metaEl = getElById(doc, "pica-meta");
2139
+ if (metaEl?.textContent) {
2140
+ try {
2141
+ const meta = parseMeta(doc);
2142
+ metaEl.textContent = JSON.stringify({ ...meta, background: fillVal });
2143
+ } catch {}
2144
+ }
2145
+ }
2146
+ }
1874
2147
  } else {
1875
2148
  const attrs = sanitizeAttrs(op.attrs);
1876
2149
  for (const [k] of Object.entries(attrs)) {
@@ -2136,11 +2409,11 @@ function upsertIdRule(css, id, animationValue, origin) {
2136
2409
  }
2137
2410
  function assertSafeCssValue(field, value) {
2138
2411
  if (/[{};<>]/.test(value)) {
2139
- throw new Error(`Rejected: dangerous CSS in '${field}'.`);
2412
+ throw new Error(`Rejected: unsupported CSS in '${field}'.`);
2140
2413
  }
2141
- const lowered = value.toLowerCase();
2414
+ const lowered = normalizeCssForCheck(value).toLowerCase();
2142
2415
  if (lowered.includes("@import") || lowered.includes("javascript:") || lowered.includes("expression(") || lowered.includes("url(")) {
2143
- throw new Error(`Rejected: dangerous CSS in '${field}'.`);
2416
+ throw new Error(`Rejected: unsupported CSS in '${field}'.`);
2144
2417
  }
2145
2418
  }
2146
2419
  async function handleAnimate(input) {
@@ -2206,9 +2479,10 @@ async function handleAnimate(input) {
2206
2479
  }
2207
2480
  if (body) {
2208
2481
  assertNoScript(body);
2209
- const lowered = body.toLowerCase();
2482
+ assertBalancedBraces(body);
2483
+ const lowered = normalizeCssForCheck(body).toLowerCase();
2210
2484
  if (lowered.includes("javascript:") || lowered.includes("expression(") || lowered.includes("@import") || lowered.includes("url(")) {
2211
- throw new Error("Rejected: dangerous CSS in keyframes.");
2485
+ throw new Error("Rejected: unsupported CSS in keyframes.");
2212
2486
  }
2213
2487
  css = removeKeyframesBlock(css, input.name);
2214
2488
  css = `${css}
@@ -2248,6 +2522,81 @@ async function handleAnimate(input) {
2248
2522
  return errText(`pica_animate failed: ${e instanceof Error ? e.message : String(e)}`);
2249
2523
  }
2250
2524
  }
2525
+ async function handleConfigure(input) {
2526
+ let safePath;
2527
+ try {
2528
+ safePath = resolveSafePath(input.path);
2529
+ } catch (e) {
2530
+ return errText(`pica_configure failed: ${e instanceof Error ? e.message : String(e)}`);
2531
+ }
2532
+ let raw;
2533
+ try {
2534
+ raw = await Bun.file(safePath).text();
2535
+ } catch {
2536
+ return errText(`pica_configure failed: file not found: ${safePath}. Create it first with pica_create.`);
2537
+ }
2538
+ try {
2539
+ assertNoScript(raw);
2540
+ const doc = loadXmlDoc(raw);
2541
+ ensurePicaSkeleton(doc);
2542
+ const svg = doc.documentElement;
2543
+ if (!svg)
2544
+ throw new Error("pica_configure failed: missing <svg> root.");
2545
+ const current = parseDims(doc);
2546
+ const meta = parseMeta(doc);
2547
+ const styleEl = getElById(doc, "pica-anim");
2548
+ const css = (styleEl?.textContent ?? "").trim();
2549
+ const nextW = input.width ?? current.width;
2550
+ const nextH = input.height ?? current.height;
2551
+ if (input.width !== undefined)
2552
+ svg.setAttribute("width", String(nextW));
2553
+ if (input.height !== undefined)
2554
+ svg.setAttribute("height", String(nextH));
2555
+ if (input.width !== undefined || input.height !== undefined) {
2556
+ svg.setAttribute("viewBox", `0 0 ${nextW} ${nextH}`);
2557
+ }
2558
+ if (input.background !== undefined) {
2559
+ assertSafeAttrValue("fill", input.background);
2560
+ const bg = getElById(doc, "pica-bg");
2561
+ if (!bg)
2562
+ throw new Error("pica_configure failed: #pica-bg not found.");
2563
+ bg.setAttribute("fill", input.background);
2564
+ }
2565
+ const metaEl = getElById(doc, "pica-meta");
2566
+ if (!metaEl)
2567
+ throw new Error("pica_configure failed: #pica-meta not found.");
2568
+ const nextFps = input.fps ?? meta.fps;
2569
+ const nextBg = input.background ?? meta.background;
2570
+ const nextBase = input.durationMs ?? meta.baseDurationMs ?? meta.durationMs;
2571
+ const recalc = recalcDurationMs(css, nextBase);
2572
+ metaEl.textContent = JSON.stringify({
2573
+ ...meta,
2574
+ fps: nextFps,
2575
+ background: nextBg,
2576
+ baseDurationMs: nextBase,
2577
+ durationMs: recalc
2578
+ });
2579
+ const out = serializeDoc(doc);
2580
+ assertNoScript(out);
2581
+ assertWellFormedXml(out);
2582
+ assertSafeSvgTree(loadXmlDoc(out));
2583
+ await atomicWriteFile(safePath, out);
2584
+ setCurrentSvg(safePath, out);
2585
+ const parsed = parsePica(out);
2586
+ return okText({
2587
+ ok: true,
2588
+ path: safePath,
2589
+ width: parsed.width,
2590
+ height: parsed.height,
2591
+ background: parsed.meta.background,
2592
+ fps: parsed.meta.fps,
2593
+ durationMs: parsed.meta.durationMs,
2594
+ baseDurationMs: parsed.meta.baseDurationMs
2595
+ });
2596
+ } catch (e) {
2597
+ return errText(`pica_configure failed: ${e instanceof Error ? e.message : String(e)}`);
2598
+ }
2599
+ }
2251
2600
  function buildDebugOverlay(width, height, nodes, showGrid, showIds) {
2252
2601
  if (!showGrid && !showIds)
2253
2602
  return "";
@@ -2296,29 +2645,29 @@ async function handleInspect(input) {
2296
2645
  const clean = stripDebugOverlay(raw);
2297
2646
  const animated = parsed.animations.length > 0;
2298
2647
  const effScale = Math.max(0.05, Math.min(requestedScale, maxWidth / Math.max(1, parsed.width)));
2299
- let overlayNodes = parsed.nodesFlat;
2300
- if (showIds && findChromeBinary() && (animated || timeMs > 0 || /\btransform\s*[=:]/.test(clean))) {
2301
- try {
2302
- const exact = await getRenderedBboxesAtTime(clean, parsed.width, parsed.height, timeMs);
2303
- if (exact.length > 0) {
2304
- overlayNodes = exact;
2305
- }
2306
- } catch {}
2307
- }
2308
- let svgForRender = clean;
2309
- if (showGrid || showIds) {
2310
- const overlay = buildDebugOverlay(parsed.width, parsed.height, overlayNodes, showGrid, showIds);
2311
- svgForRender = clean.replace(/<\/svg\s*>\s*$/i, `${overlay}</svg>`);
2312
- }
2313
2648
  let png;
2314
2649
  let renderer = "resvg";
2315
2650
  let note = "";
2316
2651
  if (timeMs === 0 && !animated) {
2652
+ let svgForRender = clean;
2653
+ if (showGrid || showIds) {
2654
+ const overlay = buildDebugOverlay(parsed.width, parsed.height, parsed.nodesFlat, showGrid, showIds);
2655
+ svgForRender = clean.replace(/<\/svg\s*>\s*$/i, `${overlay}</svg>`);
2656
+ }
2317
2657
  png = renderPngBuffer(svgForRender, effScale);
2318
2658
  } else if (findChromeBinary()) {
2319
- png = await screenshotAtTime(svgForRender, parsed.width, parsed.height, timeMs, effScale);
2659
+ if (showGrid || showIds) {
2660
+ png = await screenshotInspectSinglePass(clean, parsed.width, parsed.height, timeMs, effScale, showGrid, showIds);
2661
+ } else {
2662
+ png = await screenshotAtTime(clean, parsed.width, parsed.height, timeMs, effScale);
2663
+ }
2320
2664
  renderer = "chromium-cdp";
2321
2665
  } else if (timeMs === 0) {
2666
+ let svgForRender = clean;
2667
+ if (showGrid || showIds) {
2668
+ const overlay = buildDebugOverlay(parsed.width, parsed.height, parsed.nodesFlat, showGrid, showIds);
2669
+ svgForRender = clean.replace(/<\/svg\s*>\s*$/i, `${overlay}</svg>`);
2670
+ }
2322
2671
  png = renderPngBuffer(svgForRender, effScale);
2323
2672
  note = " (static fallback: CSS animations not evaluated, Chromium missing)";
2324
2673
  } else {
@@ -2439,7 +2788,7 @@ async function handleExport(input) {
2439
2788
 
2440
2789
  // src/server.ts
2441
2790
  function createServer() {
2442
- const server = new McpServer({ name: "pica", version: "0.1.0" });
2791
+ const server = new McpServer({ name: "pica", version: "0.1.1" });
2443
2792
  server.registerTool("pica_create", {
2444
2793
  title: "Create canvas",
2445
2794
  description: "Initialize a .pica.svg canvas with metadata, defs, style, background, and root. Notifies live preview.",
@@ -2460,6 +2809,11 @@ function createServer() {
2460
2809
  description: "Add, update, or remove @keyframes and #id animation rules in <style id='pica-anim'>. Multiple animations stack as comma-separated entries per #id; durationMs is recalculated automatically.",
2461
2810
  inputSchema: AnimateSchema
2462
2811
  }, async (args) => handleAnimate(args));
2812
+ server.registerTool("pica_configure", {
2813
+ title: "Configure canvas",
2814
+ description: "Update canvas-level properties (width, height, background, fps, durationMs) on an existing .pica.svg. Updates svg dimensions, background fill, and metadata atomically.",
2815
+ inputSchema: ConfigureSchema
2816
+ }, async (args) => handleConfigure(args));
2463
2817
  server.registerTool("pica_inspect", {
2464
2818
  title: "Inspect preview",
2465
2819
  description: "Render a preview PNG. Static designs at timeMs=0 use resvg; animated designs (and any timeMs>0) capture via headless Chromium CDP when available, else static resvg fallback at timeMs=0. Optional grid/id overlays.",
package/dist/viewer.html CHANGED
@@ -43,6 +43,7 @@
43
43
  left: 0; top: 0;
44
44
  }
45
45
  #artboard svg { display: block; }
46
+ #canvasframe { display: block; border: 0; pointer-events: none; background: transparent; }
46
47
  .checker {
47
48
  background-image:
48
49
  linear-gradient(45deg, #ececee 25%, transparent 25%),
@@ -75,7 +76,7 @@
75
76
  </header>
76
77
  <div id="stage">
77
78
  <div id="viewport">
78
- <div id="artboard" class="checker"></div>
79
+ <div id="artboard" class="checker"><iframe id="canvasframe" sandbox="allow-same-origin" scrolling="no" style="border:0;display:block;pointer-events:none"></iframe></div>
79
80
  </div>
80
81
  </div>
81
82
  <footer>
@@ -142,9 +143,20 @@
142
143
  viewport.addEventListener('pointerup', () => { drag = null; viewport.classList.remove('dragging'); });
143
144
  fitBtn.addEventListener('click', fit);
144
145
 
146
+ function frameDoc() {
147
+ try {
148
+ const f = document.getElementById('canvasframe');
149
+ if (f && f.contentDocument) return f.contentDocument;
150
+ } catch (e) {}
151
+ return null;
152
+ }
145
153
  function allAnims() {
146
- try { return document.getAnimations({ subtree: true }); }
147
- catch (e) { return document.getAnimations(); }
154
+ const d = frameDoc();
155
+ if (!d) return [];
156
+ try { return d.getAnimations({ subtree: true }); }
157
+ catch (e) {
158
+ try { return d.getAnimations(); } catch (e2) { return []; }
159
+ }
148
160
  }
149
161
  playpause.addEventListener('click', () => {
150
162
  const anims = allAnims();
@@ -215,15 +227,11 @@
215
227
  currentPath = nextPath;
216
228
  filepathEl.textContent = currentPath || 'live svg';
217
229
  const dims = parseSvgDims(parsed.svg);
218
- const pathChanged = parsed.svg && nextPath !== filepathEl.dataset.path;
230
+ const pathChanged = nextPath !== filepathEl.dataset.path;
219
231
  const dimsChanged = dims.w !== lastW || dims.h !== lastH;
220
232
  filepathEl.dataset.path = nextPath || '';
221
- // Adopt the parsed node into the live document.
222
- const svg = parsed.owned ? document.importNode(parsed.svg, true) : parsed.svg;
223
- artboard.innerHTML = '';
224
- artboard.appendChild(svg);
225
233
  try {
226
- const meta = svg.querySelector('#pica-meta');
234
+ const meta = parsed.svg.querySelector('#pica-meta');
227
235
  if (meta && meta.textContent) {
228
236
  const j = JSON.parse(meta.textContent.trim());
229
237
  if (typeof j.durationMs === 'number') {
@@ -233,6 +241,14 @@
233
241
  }
234
242
  }
235
243
  } catch (e) {}
244
+ const frame = document.getElementById('canvasframe');
245
+ artboard.style.width = dims.w + 'px';
246
+ artboard.style.height = dims.h + 'px';
247
+ frame.setAttribute('width', String(dims.w));
248
+ frame.setAttribute('height', String(dims.h));
249
+ frame.style.width = dims.w + 'px';
250
+ frame.style.height = dims.h + 'px';
251
+ frame.srcdoc = '<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}svg{display:block}</style></head><body>' + text + '</body></html>';
236
252
  playing = true;
237
253
  playpause.textContent = 'Pause';
238
254
  // Only reset the camera on first load, path switch, or canvas resize.
@@ -241,7 +257,8 @@
241
257
  lastW = dims.w;
242
258
  lastH = dims.h;
243
259
  fittedOnce = true;
244
- fit();
260
+ // Wait a tick so the iframe has layout before fitting.
261
+ requestAnimationFrame(fit);
245
262
  }
246
263
  statusEl.textContent = '';
247
264
  } catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pica-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Ultra-lightweight headless-first 2D vector design and animation MCP server",
5
5
  "license": "MIT",
6
6
  "publishConfig": {