frameboard 0.13.0 → 0.14.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/dist/cli.js CHANGED
@@ -3037,12 +3037,15 @@ const EXIT_CODES = {
3037
3037
  "stale-layout": 11,
3038
3038
  "asset-type-refused": 2,
3039
3039
  "asset-too-large": 2,
3040
+ "image-type-refused": 2,
3040
3041
  "undo-overtaken": 12,
3041
3042
  "nothing-to-undo": 12,
3042
3043
  "frame-claimed": 4,
3043
3044
  "claims-invalid": 5,
3044
3045
  "client-not-built": 3,
3045
- "tokens-exist": 4
3046
+ "tokens-exist": 4,
3047
+ "dispatch-unavailable": 3,
3048
+ "dispatch-failed": 13
3046
3049
  };
3047
3050
  var FrameboardError = class extends Error {
3048
3051
  code;
@@ -9330,7 +9333,7 @@ async function isDirectory(path) {
9330
9333
  }
9331
9334
  }
9332
9335
  // package.json
9333
- var version$1 = "0.13.0";
9336
+ var version$1 = "0.14.0";
9334
9337
  var dependencies = { "playwright-core": "1.64.1" };
9335
9338
  // src/shared/version.ts
9336
9339
  const version = version$1;
@@ -26771,6 +26774,16 @@ function serializeDocumentTypeNode(node, { treeAdapter }) {
26771
26774
  function parse$3(html, options) {
26772
26775
  return Parser.parse(html, options);
26773
26776
  }
26777
+ function parseFragment(fragmentContext, html, options) {
26778
+ if (typeof fragmentContext === "string") {
26779
+ options = html;
26780
+ html = fragmentContext;
26781
+ fragmentContext = null;
26782
+ }
26783
+ const parser = Parser.getFragmentParser(fragmentContext, options);
26784
+ parser.tokenizer.write(html, true);
26785
+ return parser.getFragment();
26786
+ }
26774
26787
  // node_modules/domelementtype/dist/index.js
26775
26788
  /** Types of elements found in htmlparser2's DOM */
26776
26789
  var ElementType;
@@ -28935,14 +28948,80 @@ function applyEdit(source, address, change) {
28935
28948
  span
28936
28949
  };
28937
28950
  }
28951
+ // src/shared/starter-tokens.ts
28952
+ /**
28953
+ * The looks a new project can start from, each accent paired by hand with a
28954
+ * dark value, so both themes hold without a derived color. The keys are the
28955
+ * values `project tokens --accent` and the route take.
28956
+ */
28957
+ const STARTER_ACCENTS = {
28958
+ blue: {
28959
+ light: "#2f7bf0",
28960
+ dark: "#4e92f6"
28961
+ },
28962
+ red: {
28963
+ light: "#e5484d",
28964
+ dark: "#ff6369"
28965
+ },
28966
+ green: {
28967
+ light: "#30a46c",
28968
+ dark: "#3dd68c"
28969
+ },
28970
+ orange: {
28971
+ light: "#f76b15",
28972
+ dark: "#ff801f"
28973
+ },
28974
+ purple: {
28975
+ light: "#8e4ec6",
28976
+ dark: "#9a5cd0"
28977
+ }
28978
+ };
28979
+ /** The served faces a starter sheet may name, keyed by their face folder. */
28980
+ const STARTER_FONTS = {
28981
+ geist: {
28982
+ family: "Geist",
28983
+ stack: "Geist, sans-serif"
28984
+ },
28985
+ "geist-mono": {
28986
+ family: "Geist Mono",
28987
+ stack: "'Geist Mono', monospace"
28988
+ }
28989
+ };
28990
+ const DEFAULT_LOOK = {
28991
+ accent: "blue",
28992
+ font: "geist"
28993
+ };
28994
+ /** A project token sheet setting the names the fixture sheets use, light then dark. */
28995
+ function starterSheet({ accent, font }) {
28996
+ const pair = STARTER_ACCENTS[accent];
28997
+ return `:root {
28998
+ --accent: ${pair.light};
28999
+ --surface: #ffffff;
29000
+ --text: #111111;
29001
+ --muted: #6b7280;
29002
+ --border: #e5e7eb;
29003
+ --radius: 10px;
29004
+ --font-text: ${STARTER_FONTS[font].stack};
29005
+ }
29006
+
29007
+ [data-theme='dark'] {
29008
+ --accent: ${pair.dark};
29009
+ --surface: #111111;
29010
+ --text: #ededed;
29011
+ --muted: #9ca3af;
29012
+ --border: #2e2e2e;
29013
+ }
29014
+ `;
29015
+ }
28938
29016
  // src/server/edit/insert.ts
28939
- const SHAPE_SIZE = "100px";
29017
+ const SHAPE_SIZE = 100;
28940
29018
  const FILL_TOKENS = [
28941
29019
  "--muted",
28942
29020
  "--secondary",
28943
29021
  "--accent"
28944
29022
  ];
28945
29023
  const LINE_TOKEN = "--border";
29024
+ const TEXT_FONT_TOKEN = "--font-text";
28946
29025
  /** Raw on purpose, so the check names it once the project sets no color token. */
28947
29026
  const RAW_GREY = "#d9d9d9";
28948
29027
  const PAINT_VALUE = /^(?:var\(--[\w-]+\)|#[0-9a-f]{6})$/i;
@@ -28986,15 +29065,25 @@ function shapePaint(tokens) {
28986
29065
  line: paint(names.has(LINE_TOKEN) ? LINE_TOKEN : firstColor)
28987
29066
  };
28988
29067
  }
28989
- /** Every byte an insert of `element` writes, with its `data-name` and default size. */
28990
- function elementMarkup(element, paint) {
29068
+ /**
29069
+ * The family placed text sets, being the project's text font token, else
29070
+ * Geist, so a frame with no font of its own still passes `default-font`.
29071
+ */
29072
+ function textFont(tokens) {
29073
+ return tokens.some((row) => row.name === TEXT_FONT_TOKEN) ? `var(${TEXT_FONT_TOKEN})` : STARTER_FONTS.geist.stack;
29074
+ }
29075
+ /** Every byte an insert of `element` writes, with its `data-name` and size. */
29076
+ function elementMarkup(element, paint, font) {
28991
29077
  const { fill, line } = paint;
28992
29078
  if (!PAINT_VALUE.test(fill) || !PAINT_VALUE.test(line)) throw new Error(`Unexpected shape paint ${fill} ${line}`);
28993
- const box = `width: ${SHAPE_SIZE}; height: ${SHAPE_SIZE}; background: ${fill}`;
29079
+ const box = ({ width = SHAPE_SIZE, height = SHAPE_SIZE }) => {
29080
+ if (!Number.isInteger(width) || !Number.isInteger(height)) throw new Error(`Unexpected shape size ${width} ${height}`);
29081
+ return `width: ${width}px; height: ${height}px; background: ${fill}`;
29082
+ };
28994
29083
  switch (element.kind) {
28995
- case "text": return "<p data-name=\"Text\">Text</p>";
28996
- case "rectangle": return `<div data-name="Rectangle" style="${box}"></div>`;
28997
- case "ellipse": return `<div data-name="Ellipse" style="${box}; border-radius: 50%"></div>`;
29084
+ case "text": return `<p data-name="Text" style="font-family: ${font}">Text</p>`;
29085
+ case "rectangle": return `<div data-name="Rectangle" style="${box(element)}"></div>`;
29086
+ case "ellipse": return `<div data-name="Ellipse" style="${box(element)}; border-radius: 50%"></div>`;
28998
29087
  case "divider": return `<hr data-name="Divider" style="align-self: stretch; margin: 0; border: 0; ${element.vertical ? "border-left" : "border-top"}: 1px solid ${line}">`;
28999
29088
  }
29000
29089
  }
@@ -29038,18 +29127,24 @@ function gapOffset(tree, placement) {
29038
29127
  * the input's with that one element added under the parent, so a tag the
29039
29128
  * parser would move, as a `<div>` closing a `<p>`, is refused rather than
29040
29129
  * written somewhere else.
29130
+ *
29131
+ * A `lead` lands the element that many bytes ahead of the gap, once they
29132
+ * read as given, so an element put back lands where it stood and not past
29133
+ * the whitespace that followed it.
29041
29134
  */
29042
- function insertElement(source, placement, markup) {
29135
+ function insertElement(source, placement, markup, lead = "") {
29043
29136
  const before = parseFrame(source);
29044
29137
  const gap = gapOffset(before, placement);
29045
29138
  if ("ok" in gap) return gap;
29046
- const { parent, offset } = gap;
29139
+ const { parent } = gap;
29140
+ const offset = gap.offset - lead.length;
29141
+ if (offset < 0 || source.slice(offset, gap.offset) !== lead) return refuse$1("address-mismatch", `the bytes ahead of the gap in the <${parent.tagName}> at ${placement.parent} changed`);
29047
29142
  const written = source.slice(0, offset) + markup + source.slice(offset);
29048
29143
  const after = parseFrame(written);
29049
29144
  const index = after.elements.findIndex((element) => element.sourceCodeLocation?.startOffset === offset);
29050
29145
  const added = after.elements[index];
29051
- if (!added || after.elements.length !== before.elements.length + 1 || added.parentNode !== after.elements[placement.parent] || spanText(written, added, "element") !== markup || !addsOnly(before, after, added)) return refuse$1("verify-failed", `a <${added?.tagName ?? "new element"}> there would change more than the <${parent.tagName}> it goes in, so nothing was written`);
29052
- const next = children(parent).find((child) => child.sourceCodeLocation?.startOffset === offset);
29146
+ if (!added || after.elements.length !== before.elements.length + 1 + descendants(added) || added.parentNode !== after.elements[placement.parent] || spanText(written, added, "element") !== markup || !addsOnly(before, after, added)) return refuse$1("verify-failed", `a <${added?.tagName ?? "new element"}> there would change more than the <${parent.tagName}> it goes in, so nothing was written`);
29147
+ const next = children(parent).find((child) => child.sourceCodeLocation?.startOffset === gap.offset);
29053
29148
  return {
29054
29149
  ok: true,
29055
29150
  html: written,
@@ -29063,10 +29158,15 @@ function insertElement(source, placement, markup) {
29063
29158
  tagName: parent.tagName,
29064
29159
  tag: startTag(source, parent)
29065
29160
  },
29066
- next: next ? startTag(source, next) : null
29161
+ next: next ? startTag(source, next) : null,
29162
+ lead
29067
29163
  }
29068
29164
  };
29069
29165
  }
29166
+ /** How many elements `element` holds, at any depth. */
29167
+ function descendants(element) {
29168
+ return children(element).reduce((count, child) => count + 1 + descendants(child), 0);
29169
+ }
29070
29170
  /** Whether `after` is `before` with `added` alone added, compared once it is taken out. */
29071
29171
  function addsOnly(before, after, added) {
29072
29172
  const parent = added.parentNode;
@@ -29087,7 +29187,8 @@ function locateInserted(source, tree, span) {
29087
29187
  /** The gap the span goes back into, read off its anchors where the frame now stands. */
29088
29188
  function locateGap(source, tree, span) {
29089
29189
  const reads = (element) => element !== void 0 && element.tagName === span.parent.tagName && startTag(source, element) === span.parent.tag;
29090
- const candidates = tree.elements.length === span.count - 1 && reads(tree.elements[span.placement.parent]) ? [span.placement.parent] : tree.elements.flatMap((element, index) => reads(element) ? [index] : []);
29190
+ const held = tree.elements.length === span.count - markupSize(span.markup);
29191
+ const candidates = held && reads(tree.elements[span.placement.parent]) ? [span.placement.parent] : tree.elements.flatMap((element, index) => reads(element) ? [index] : []);
29091
29192
  const parentIndex = candidates.length === 1 ? candidates[0] : void 0;
29092
29193
  const parent = parentIndex === void 0 ? void 0 : tree.elements[parentIndex];
29093
29194
  if (parentIndex === void 0 || !parent) return void 0;
@@ -29095,6 +29196,11 @@ function locateGap(source, tree, span) {
29095
29196
  parent: parentIndex,
29096
29197
  before: null
29097
29198
  };
29199
+ const recorded = span.placement.before === null ? void 0 : tree.elements[span.placement.before];
29200
+ if (held && recorded && recorded.parentNode === parent && startTag(source, recorded) === span.next) return {
29201
+ parent: parentIndex,
29202
+ before: span.placement.before
29203
+ };
29098
29204
  const next = children(parent).filter((child) => startTag(source, child) === span.next);
29099
29205
  const [sibling] = next;
29100
29206
  return next.length === 1 && sibling ? {
@@ -29102,6 +29208,11 @@ function locateGap(source, tree, span) {
29102
29208
  before: tree.elements.indexOf(sibling)
29103
29209
  } : void 0;
29104
29210
  }
29211
+ /** How many elements `markup` holds, itself and everything inside it. */
29212
+ function markupSize(markup) {
29213
+ const count = (node) => node.childNodes.reduce((total, child) => total + (hasTag(child) ? 1 + count(child) : 0), 0);
29214
+ return count(parseFragment(markup));
29215
+ }
29105
29216
  /** Whether the frame stands as `side` of the insert left it, with the element or with its gap. */
29106
29217
  function holdsInserted(source, span, side) {
29107
29218
  const tree = parseFrame(source);
@@ -29115,16 +29226,29 @@ function holdsInserted(source, span, side) {
29115
29226
  function removeInserted(source, span) {
29116
29227
  const tree = parseFrame(source);
29117
29228
  const index = locateInserted(source, tree, span);
29118
- const element = index === void 0 ? void 0 : tree.elements[index];
29229
+ return index === void 0 ? void 0 : takeOut$1(source, tree, index);
29230
+ }
29231
+ /**
29232
+ * Takes the element at `index` out with its descendants and answers the span
29233
+ * that puts it back, holding the bytes that stood between it and its gap.
29234
+ * Answers undefined when the element is not stated, or when putting it back
29235
+ * would not give `source` again, since the removal then reached past it.
29236
+ */
29237
+ function takeOut$1(source, tree, index) {
29238
+ const element = tree.elements[index];
29119
29239
  const at = element?.sourceCodeLocation;
29120
29240
  const parent = element?.parentNode;
29121
- if (index === void 0 || !at || !parent || !hasTag(parent)) return void 0;
29241
+ if (!element || !at?.startTag || !parent || !hasTag(parent)) return void 0;
29122
29242
  const removed = source.slice(0, at.startOffset) + source.slice(at.endOffset);
29123
29243
  const next = children(parent)[children(parent).indexOf(element) + 1];
29124
- const back = insertElement(removed, {
29244
+ const placement = {
29125
29245
  parent: tree.elements.indexOf(parent),
29126
29246
  before: next ? index : null
29127
- }, span.markup);
29247
+ };
29248
+ const gap = gapOffset(parseFrame(removed), placement);
29249
+ if ("ok" in gap || gap.offset < at.startOffset) return void 0;
29250
+ const lead = removed.slice(at.startOffset, gap.offset);
29251
+ const back = insertElement(removed, placement, source.slice(at.startOffset, at.endOffset), lead);
29128
29252
  if (!back.ok || back.html !== source) return void 0;
29129
29253
  return {
29130
29254
  html: removed,
@@ -29132,6 +29256,44 @@ function removeInserted(source, span) {
29132
29256
  };
29133
29257
  }
29134
29258
  /**
29259
+ * Takes out the element at `index`, with everything it holds, and answers
29260
+ * the span `restoreInserted` puts it back by, so a delete is an insert run
29261
+ * backwards. Only an element under `body` is taken, and the removal is
29262
+ * refused as `verify-failed` unless the result parses as the source with
29263
+ * that element alone gone, and its bytes go back as that one element.
29264
+ * Putting it back lands it
29265
+ * before the same sibling, so the whitespace around it may sit on its other
29266
+ * side.
29267
+ */
29268
+ function removeElement$1(source, index) {
29269
+ const tree = parseFrame(source);
29270
+ if (tree.unstated) return refuse$1("address-mismatch", `the browser builds a <${tree.unstated.tagName}> the file does not state, so indices after it disagree`);
29271
+ const element = tree.elements[index];
29272
+ if (!element || !underBody(element)) return refuse$1("invalid-address", `${index} names no element under the frame's body`);
29273
+ const at = element.sourceCodeLocation;
29274
+ const parent = element.parentNode;
29275
+ if (!at || !parent || !hasTag(parent)) return refuse$1("address-mismatch", `the <${element.tagName}> at ${index} is not stated in the file`);
29276
+ const removed = source.slice(0, at.startOffset) + source.slice(at.endOffset);
29277
+ const next = children(parent)[children(parent).indexOf(element) + 1];
29278
+ const back = insertElement(removed, {
29279
+ parent: tree.elements.indexOf(parent),
29280
+ before: next ? index : null
29281
+ }, source.slice(at.startOffset, at.endOffset));
29282
+ parent.childNodes = parent.childNodes.filter((node) => node !== element);
29283
+ const removesOnly = serialize(tree.document) === serialize(parseFrame(removed).document);
29284
+ if (!back.ok || !removesOnly) return refuse$1("verify-failed", `taking out the <${element.tagName}> at ${index} would change more than it, so nothing was written`);
29285
+ if (!holdsInserted(removed, back.span, "before")) return refuse$1("verify-failed", `the <${element.tagName}> at ${index} could not be put back once taken out, so nothing was written`);
29286
+ return {
29287
+ ok: true,
29288
+ html: removed,
29289
+ span: back.span
29290
+ };
29291
+ }
29292
+ function underBody(element) {
29293
+ for (let node = element.parentNode; node && hasTag(node); node = node.parentNode) if (node.tagName === "body") return true;
29294
+ return false;
29295
+ }
29296
+ /**
29135
29297
  * Writes the element back into its gap, found by the parent's and the next
29136
29298
  * sibling's start tags, and answers the span as it now stands. Answers
29137
29299
  * undefined when the gap is not found or the write is refused.
@@ -29139,12 +29301,68 @@ function removeInserted(source, span) {
29139
29301
  function restoreInserted(source, span) {
29140
29302
  const placement = locateGap(source, parseFrame(source), span);
29141
29303
  if (!placement) return void 0;
29142
- const inserted = insertElement(source, placement, span.markup);
29304
+ const inserted = insertElement(source, placement, span.markup, span.lead);
29143
29305
  return inserted.ok ? {
29144
29306
  html: inserted.html,
29145
29307
  span: inserted.span
29146
29308
  } : void 0;
29147
29309
  }
29310
+ /**
29311
+ * Takes the element at `index` out by its bytes and writes them into the gap
29312
+ * `placement` names, both read in the frame as it stands, leaving every other
29313
+ * byte. A gap in the element or under it is refused as `invalid-container`,
29314
+ * since the element would be written inside itself, and the gap it already
29315
+ * sits in as `invalid-address`. Each half is checked as `insertElement`
29316
+ * checks a placement, so a move the parser would rebuild is refused whole.
29317
+ */
29318
+ function moveElement(source, index, placement) {
29319
+ const tree = parseFrame(source);
29320
+ const element = Number.isInteger(index) ? tree.elements[index] : void 0;
29321
+ if (!element?.sourceCodeLocation?.startTag) return refuse$1("invalid-address", `${index} names no element the file states`);
29322
+ const end = index + 1 + descendants(element);
29323
+ const shift = (at) => at < end ? at : at - (end - index);
29324
+ if (placement.parent >= index && placement.parent < end) return refuse$1("invalid-container", `the <${element.tagName}> at ${index} cannot go inside itself`);
29325
+ const taken = takeOut$1(source, tree, index);
29326
+ if (!taken) return refuse$1("verify-failed", `taking the <${element.tagName}> at ${index} out would change more than it, so nothing was written`);
29327
+ const target = {
29328
+ parent: shift(placement.parent),
29329
+ before: placement.before === null ? null : shift(placement.before)
29330
+ };
29331
+ if (target.parent === taken.span.placement.parent && target.before === taken.span.placement.before) return refuse$1("invalid-address", `the <${element.tagName}> at ${index} already sits in that gap`);
29332
+ const moved = insertElement(taken.html, target, taken.span.markup);
29333
+ if (!moved.ok) return moved;
29334
+ return {
29335
+ ok: true,
29336
+ html: moved.html,
29337
+ index: moved.index,
29338
+ span: {
29339
+ from: taken.span,
29340
+ to: moved.span
29341
+ }
29342
+ };
29343
+ }
29344
+ /**
29345
+ * Writes the moved element back to `side` of the move, taking it out of the
29346
+ * other gap by its bytes and into this one by its anchors, and answers the
29347
+ * span as the frame then stands. Answers undefined when either half is not
29348
+ * found, so a step the frame no longer allows is refused rather than guessed.
29349
+ */
29350
+ function relocateMoved(source, span, side) {
29351
+ const [leave, land] = side === "before" ? [span.to, span.from] : [span.from, span.to];
29352
+ const removed = removeInserted(source, leave);
29353
+ const written = removed && restoreInserted(removed.html, land);
29354
+ if (!removed || !written) return void 0;
29355
+ return {
29356
+ html: written.html,
29357
+ span: side === "before" ? {
29358
+ from: written.span,
29359
+ to: removed.span
29360
+ } : {
29361
+ from: removed.span,
29362
+ to: written.span
29363
+ }
29364
+ };
29365
+ }
29148
29366
  // src/server/edit/frame-file.ts
29149
29367
  function stale(path) {
29150
29368
  return refuse$1("stale-address", `${basename(path)} changed after this edit was made, so nothing was written`);
@@ -29214,6 +29432,43 @@ function insertFrameFile(path, hash, placement, markup) {
29214
29432
  };
29215
29433
  }
29216
29434
  /**
29435
+ * Takes one element out of a frame file the way `insertFrameFile` writes one
29436
+ * in, refusing a hash the file no longer has as stale, so a retried delete
29437
+ * takes out at most one element.
29438
+ */
29439
+ function removeFrameFile(path, hash, index) {
29440
+ const read = readSource(path);
29441
+ if (!read.ok) return read;
29442
+ if (read.hash !== hash) return stale(path);
29443
+ const removed = removeElement$1(read.source, index);
29444
+ if (!removed.ok) return removed;
29445
+ if (!replaceFile(path, hash, removed.html)) return stale(path);
29446
+ return {
29447
+ ok: true,
29448
+ hash: contentHash(removed.html),
29449
+ span: removed.span
29450
+ };
29451
+ }
29452
+ /**
29453
+ * Moves one element of a frame file into another gap, written as
29454
+ * `insertFrameFile` writes, and refused as stale on a hash the file no longer
29455
+ * has, since both indices name nothing once the file moved.
29456
+ */
29457
+ function moveFrameFile(path, hash, index, placement) {
29458
+ const read = readSource(path);
29459
+ if (!read.ok) return read;
29460
+ if (read.hash !== hash) return stale(path);
29461
+ const moved = moveElement(read.source, index, placement);
29462
+ if (!moved.ok) return moved;
29463
+ if (!replaceFile(path, hash, moved.html)) return stale(path);
29464
+ return {
29465
+ ok: true,
29466
+ hash: contentHash(moved.html),
29467
+ index: moved.index,
29468
+ span: moved.span
29469
+ };
29470
+ }
29471
+ /**
29217
29472
  * A frame file's text and hash. Bytes that do not survive a UTF-8 round trip
29218
29473
  * are refused, since decoding would rewrite every invalid byte.
29219
29474
  */
@@ -29288,6 +29543,8 @@ async function parseBody$1(request, schema) {
29288
29543
  // src/server/routes/edit.ts
29289
29544
  const value = string$1().max(1e4);
29290
29545
  const name$1 = string$1().min(1).max(256);
29546
+ /** A dragged shape's side in CSS pixels. */
29547
+ const side = int$1().min(1).max(1e4);
29291
29548
  const editSchema = object$1({
29292
29549
  ref: string$1().min(1).max(1024),
29293
29550
  index: int$1().min(0),
@@ -29316,16 +29573,36 @@ const insertSchema = object$1({
29316
29573
  before: int$1().min(0).nullable(),
29317
29574
  element: discriminatedUnion("kind", [
29318
29575
  object$1({ kind: literal("text") }),
29319
- object$1({ kind: literal("rectangle") }),
29320
- object$1({ kind: literal("ellipse") }),
29576
+ object$1({
29577
+ kind: literal("rectangle"),
29578
+ width: side.optional(),
29579
+ height: side.optional()
29580
+ }),
29581
+ object$1({
29582
+ kind: literal("ellipse"),
29583
+ width: side.optional(),
29584
+ height: side.optional()
29585
+ }),
29321
29586
  object$1({
29322
29587
  kind: literal("divider"),
29323
29588
  vertical: boolean$1()
29324
29589
  })
29325
29590
  ])
29326
29591
  });
29592
+ const removeSchema = object$1({
29593
+ ref: string$1().min(1).max(1024),
29594
+ index: int$1().min(0),
29595
+ hash: string$1().regex(/^[0-9a-f]{64}$/)
29596
+ });
29597
+ const moveSchema$1 = object$1({
29598
+ ref: string$1().min(1).max(1024),
29599
+ hash: string$1().regex(/^[0-9a-f]{64}$/),
29600
+ index: int$1().min(0),
29601
+ parent: int$1().min(0),
29602
+ before: int$1().min(0).nullable()
29603
+ });
29327
29604
  /**
29328
- * A hand edit of one element and a placed element, each behind
29605
+ * A hand edit of one element, a placed element, and a deleted one, each behind
29329
29606
  * `requireWriter` and refused on a frame another session holds.
29330
29607
  *
29331
29608
  * The edit's body mirrors
@@ -29342,6 +29619,18 @@ const insertSchema = object$1({
29342
29619
  * the new element's index, and the hash written. A hash the file no longer
29343
29620
  * has answers 409 `stale-address` with nothing written, since the gap's
29344
29621
  * indices name nothing past an agent's write, and a retried insert lands once.
29622
+ * A rectangle or an ellipse takes an optional width and height a drag drew.
29623
+ *
29624
+ * The remove takes out the element at `index`, with what it holds, from the
29625
+ * bytes `hash` names, and records it as one step whose undo puts it back
29626
+ * under its parent. It answers the frame and the hash written, and refuses a
29627
+ * moved file as `stale-address` the way the insert does.
29628
+ *
29629
+ * The move takes one element by index and the gap it goes into, both read
29630
+ * in the frame as the hash names it, and records it as one step an undo
29631
+ * puts back byte for byte. It answers the element's new index and the hash
29632
+ * written, and refuses as the insert does, with `invalid-container` for a
29633
+ * gap inside the element itself.
29345
29634
  */
29346
29635
  function editRoutes(root, access, history, version, sheets) {
29347
29636
  const app = new Hono();
@@ -29397,7 +29686,7 @@ function editRoutes(root, access, history, version, sheets) {
29397
29686
  const result = insertFrameFile(frame.path, body.hash, {
29398
29687
  parent: body.parent,
29399
29688
  before: body.before
29400
- }, elementMarkup(body.element, shapePaint(tokens)));
29689
+ }, elementMarkup(body.element, shapePaint(tokens), textFont(tokens)));
29401
29690
  if (!result.ok) return c.json({
29402
29691
  ok: false,
29403
29692
  error: {
@@ -29427,6 +29716,79 @@ function editRoutes(root, access, history, version, sheets) {
29427
29716
  data
29428
29717
  });
29429
29718
  });
29719
+ app.post("/api/frames/remove", requireWriter(access), async (c) => {
29720
+ const body = await parseBody$1(c.req.raw, removeSchema);
29721
+ const frame = await resolveFrameRef(root, body.ref, { cwd: root });
29722
+ const ref = `${frame.project}/${frame.page}/${frame.name}`;
29723
+ await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
29724
+ const result = removeFrameFile(frame.path, body.hash, body.index);
29725
+ if (!result.ok) return c.json({
29726
+ ok: false,
29727
+ error: {
29728
+ code: result.reason,
29729
+ message: result.detail,
29730
+ details: {
29731
+ ref,
29732
+ index: body.index
29733
+ }
29734
+ }
29735
+ }, 409);
29736
+ const journal = history.journal();
29737
+ journal.deletedElement(frame.path, ref, result.span);
29738
+ history.record({
29739
+ id: journal.id,
29740
+ changes: journal.changes,
29741
+ page: null,
29742
+ frames: [ref]
29743
+ });
29744
+ const data = {
29745
+ ref,
29746
+ hash: result.hash
29747
+ };
29748
+ return c.json({
29749
+ ok: true,
29750
+ data
29751
+ });
29752
+ });
29753
+ app.post("/api/frames/move", requireWriter(access), async (c) => {
29754
+ const body = await parseBody$1(c.req.raw, moveSchema$1);
29755
+ const frame = await resolveFrameRef(root, body.ref, { cwd: root });
29756
+ const ref = `${frame.project}/${frame.page}/${frame.name}`;
29757
+ await refuseClaimed(root, [ref], /* @__PURE__ */ new Date());
29758
+ const result = moveFrameFile(frame.path, body.hash, body.index, {
29759
+ parent: body.parent,
29760
+ before: body.before
29761
+ });
29762
+ if (!result.ok) return c.json({
29763
+ ok: false,
29764
+ error: {
29765
+ code: result.reason,
29766
+ message: result.detail,
29767
+ details: {
29768
+ ref,
29769
+ index: body.index,
29770
+ parent: body.parent
29771
+ }
29772
+ }
29773
+ }, 409);
29774
+ const journal = history.journal();
29775
+ journal.relocated(frame.path, ref, result.span);
29776
+ history.record({
29777
+ id: journal.id,
29778
+ changes: journal.changes,
29779
+ page: null,
29780
+ frames: [ref]
29781
+ });
29782
+ const data = {
29783
+ ref,
29784
+ index: result.index,
29785
+ hash: result.hash
29786
+ };
29787
+ return c.json({
29788
+ ok: true,
29789
+ data
29790
+ });
29791
+ });
29430
29792
  app.onError(answerRefusal);
29431
29793
  return app;
29432
29794
  }
@@ -34489,7 +34851,7 @@ function inlineDeclarations(element, reads) {
34489
34851
  0,
34490
34852
  0
34491
34853
  ],
34492
- order: Number.MAX_SAFE_INTEGER
34854
+ order: declarations.length
34493
34855
  });
34494
34856
  });
34495
34857
  return declarations;
@@ -34568,15 +34930,17 @@ const LAYOUT_PROPERTIES = /* @__PURE__ */ new Set([
34568
34930
  "flex-direction",
34569
34931
  "flex-flow"
34570
34932
  ]);
34933
+ const ROUND_PROPERTIES = /* @__PURE__ */ new Set(["border-radius"]);
34571
34934
  /**
34572
34935
  * A frame's elements under `body` in index order, each with its parent and
34573
34936
  * name, read from the same parse and the same index `edit` addresses. A
34574
34937
  * frame where the browser builds an element the file does not state is
34575
34938
  * refused, since every index after it would name another element.
34576
34939
  * `layouts` is `elementLayouts`'s read by the same index, and an element it
34577
- * does not reach reads as `block`.
34940
+ * does not reach reads as `block`. `rounds` is `elementRounds`'s read, which
34941
+ * marks an element round only while it holds nothing.
34578
34942
  */
34579
- function elementTree(source, layouts = []) {
34943
+ function elementTree(source, layouts = [], rounds = []) {
34580
34944
  const tree = parseFrame(source);
34581
34945
  if (tree.unstated) return refuse$1("address-mismatch", `the browser builds a <${tree.unstated.tagName}> the file does not state, so indices after it disagree`);
34582
34946
  const index = new Map(tree.elements.map((element, at) => [element, at]));
@@ -34594,7 +34958,8 @@ function elementTree(source, layouts = []) {
34594
34958
  tag: element.tagName,
34595
34959
  name: elementName(element),
34596
34960
  textOnly: ownText$2(element) !== null,
34597
- layout: layouts[at] ?? "block"
34961
+ layout: layouts[at] ?? "block",
34962
+ round: (rounds[at] ?? false) && isEmpty(element)
34598
34963
  });
34599
34964
  }
34600
34965
  return listed;
@@ -34610,6 +34975,17 @@ function elementLayouts(source, tokens) {
34610
34975
  const cascade = buildCascade(source, tokens, { properties: LAYOUT_PROPERTIES });
34611
34976
  return source.elements.map((element) => layoutOf(cascade, element));
34612
34977
  }
34978
+ /**
34979
+ * Whether each element's corners round by half its size or more, read from
34980
+ * the same static cascade by the edit index, as a placed ellipse sets them.
34981
+ */
34982
+ function elementRounds(source, tokens) {
34983
+ const cascade = buildCascade(source, tokens, { properties: ROUND_PROPERTIES });
34984
+ return source.elements.map((element) => {
34985
+ const percent = (cascade.specified(element, "border-radius")?.value.trim())?.match(/^(\d+(?:\.\d+)?)%$/)?.[1];
34986
+ return percent !== void 0 && Number(percent) >= 50;
34987
+ });
34988
+ }
34613
34989
  function layoutOf(cascade, element) {
34614
34990
  const display = words(cascade.specified(element, "display")?.value);
34615
34991
  if (display.includes("grid") || display.includes("inline-grid")) return "grid";
@@ -34639,6 +35015,10 @@ function ownText$2(element) {
34639
35015
  const text = texts.map((node) => node.value).join("").replace(/\s+/g, " ").trim();
34640
35016
  return text === "" ? null : text;
34641
35017
  }
35018
+ /** True when the element holds no element and no text past whitespace. */
35019
+ function isEmpty(element) {
35020
+ return element.childNodes.every((node) => isText(node) && node.value.trim() === "");
35021
+ }
34642
35022
  function isText(node) {
34643
35023
  return node.nodeName === "#text";
34644
35024
  }
@@ -34858,8 +35238,9 @@ function elementsRoutes(root, access, selection, tokens = null) {
34858
35238
  const readTree = async (ref) => {
34859
35239
  const frame = await resolveFrameRef(root, ref, { cwd: root });
34860
35240
  const bytes = await readFile(frame.path);
34861
- const layouts = elementLayouts(readFrame(frame), tokenSheets(root, frame.project, tokens));
34862
- const elements = elementTree(bytes.toString("utf8"), layouts);
35241
+ const source = readFrame(frame);
35242
+ const sheets = tokenSheets(root, frame.project, tokens);
35243
+ const elements = elementTree(bytes.toString("utf8"), elementLayouts(source, sheets), elementRounds(source, sheets));
34863
35244
  if (!Array.isArray(elements)) throw new FrameboardError(elements.reason, elements.detail, { ref });
34864
35245
  return {
34865
35246
  ref: `${frame.project}/${frame.page}/${frame.name}`,
@@ -35451,6 +35832,141 @@ async function hashOf(path) {
35451
35832
  throw error;
35452
35833
  }
35453
35834
  }
35835
+ // src/server/notes/dispatch.ts
35836
+ /** The `serve` environment variable holding the command a dispatched note runs. */
35837
+ const DISPATCH_ENV = "FRAMEBOARD_DISPATCH";
35838
+ const DISPATCH_LOG = "dispatch.log";
35839
+ /**
35840
+ * How long a command has to fail before it counts as started. A command that
35841
+ * backgrounds its session and exits 0, as `claude --bg` does, counts at once.
35842
+ * `claude --bg` refusing an untrusted folder exits 1 near 700 ms, so the
35843
+ * window sits well past that.
35844
+ */
35845
+ const START_WINDOW_MS = 2e3;
35846
+ /**
35847
+ * Starts a session for a note by running the developer's command detached,
35848
+ * its output appended to `.run/dispatch.log`. The note reaches the command as
35849
+ * environment variables alone, never spliced into the command string, so its
35850
+ * text is data to the shell. Resolves once the command exits 0 or outlives
35851
+ * the window, and refuses `dispatch-failed` when it exits otherwise inside it.
35852
+ */
35853
+ function createDispatcher({ command, cwd, root, env, windowMs = START_WINDOW_MS }) {
35854
+ return async ({ session, id, line }) => {
35855
+ const log = await open(join(await ensureRunFolder(root), DISPATCH_LOG), "a");
35856
+ try {
35857
+ await started(spawn("sh", ["-c", command], {
35858
+ cwd,
35859
+ detached: true,
35860
+ stdio: [
35861
+ "ignore",
35862
+ log.fd,
35863
+ log.fd
35864
+ ],
35865
+ env: {
35866
+ ...env,
35867
+ FRAMEBOARD_SESSION: session,
35868
+ FRAMEBOARD_NOTE: line,
35869
+ FRAMEBOARD_NOTE_ID: id,
35870
+ FRAMEBOARD_ROOT: root
35871
+ }
35872
+ }), windowMs);
35873
+ } finally {
35874
+ await log.close();
35875
+ }
35876
+ };
35877
+ }
35878
+ function started(child, windowMs) {
35879
+ return new Promise((resolve, reject) => {
35880
+ const timer = setTimeout(() => {
35881
+ child.unref();
35882
+ resolve();
35883
+ }, windowMs);
35884
+ child.once("error", (error) => {
35885
+ clearTimeout(timer);
35886
+ reject(new FrameboardError("dispatch-failed", `The ${DISPATCH_ENV} command did not start: ${error.message}`, {}, { cause: error }));
35887
+ });
35888
+ child.once("exit", (code, signal) => {
35889
+ clearTimeout(timer);
35890
+ if (code === 0) {
35891
+ resolve();
35892
+ return;
35893
+ }
35894
+ reject(new FrameboardError("dispatch-failed", `The ${DISPATCH_ENV} command exited ${code ?? signal} within ${windowMs} ms. Its output is in .run/${DISPATCH_LOG}.`, {
35895
+ code,
35896
+ signal
35897
+ }));
35898
+ });
35899
+ });
35900
+ }
35901
+ // src/server/notes/images.ts
35902
+ /** A page's folder of note images, dot-named so the board never reads it as content. */
35903
+ const NOTES_FOLDER = ".notes";
35904
+ /** A stored image as a note records it, relative to its page. */
35905
+ const STORED = /^\.notes\/[0-9a-f]{12}\.(png|jpg|gif|webp)$/;
35906
+ const IMAGE_CONTENT_TYPES = {
35907
+ png: "image/png",
35908
+ jpg: "image/jpeg",
35909
+ gif: "image/gif",
35910
+ webp: "image/webp"
35911
+ };
35912
+ /**
35913
+ * The extension an image's bytes declare, or null for anything but PNG,
35914
+ * JPEG, GIF, and WebP. SVG is left out on purpose, since it can carry script
35915
+ * and the thumbnails render in the board's own page.
35916
+ */
35917
+ function imageExtension(bytes) {
35918
+ const ascii = (from, to) => String.fromCharCode(...bytes.subarray(from, to));
35919
+ if (bytes[0] === 137 && ascii(1, 4) === "PNG") return "png";
35920
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpg";
35921
+ if (ascii(0, 4) === "GIF8") return "gif";
35922
+ if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "webp";
35923
+ return null;
35924
+ }
35925
+ /**
35926
+ * Saves each image to `<page>/.notes/` under a fresh random name and answers
35927
+ * the page-relative paths in order. Every image is checked before any is
35928
+ * written, so a refusal leaves the folder as it was.
35929
+ */
35930
+ async function saveImages(pageDir, images) {
35931
+ const typed = images.map((bytes, index) => {
35932
+ const extension = imageExtension(bytes);
35933
+ if (extension === null) throw new FrameboardError("image-type-refused", "A note takes PNG, JPEG, GIF, or WebP images. Nothing was saved.", { index });
35934
+ return {
35935
+ bytes,
35936
+ extension
35937
+ };
35938
+ });
35939
+ const folder = join(pageDir, NOTES_FOLDER);
35940
+ await mkdir(folder, { recursive: true });
35941
+ return Promise.all(typed.map(async ({ bytes, extension }) => {
35942
+ const name = `${randomBytes(6).toString("hex")}.${extension}`;
35943
+ await writeFile(join(folder, name), bytes, { flag: "wx" });
35944
+ return `${NOTES_FOLDER}/${name}`;
35945
+ }));
35946
+ }
35947
+ /**
35948
+ * The absolute path of a stored image in a page, or null when the path is
35949
+ * not one `saveImages` writes, the file is gone, or its real path leaves the
35950
+ * page's `.notes/`.
35951
+ */
35952
+ async function storedImage(pageDir, stored) {
35953
+ if (!STORED.test(stored)) return null;
35954
+ try {
35955
+ const folder = await realpath(join(pageDir, NOTES_FOLDER));
35956
+ const file = await realpath(join(pageDir, stored));
35957
+ if (!file.startsWith(folder + sep)) return null;
35958
+ return (await stat(file)).isFile() ? file : null;
35959
+ } catch (error) {
35960
+ if (isCode(error, "ENOENT") || isCode(error, "ENOTDIR")) return null;
35961
+ throw error;
35962
+ }
35963
+ }
35964
+ /** Refuses a note naming an image its page does not hold, before anything is written. */
35965
+ async function assertStored(pageDir, images) {
35966
+ const found = await Promise.all(images.map((image) => storedImage(pageDir, image)));
35967
+ const missing = images.filter((_, index) => found[index] === null);
35968
+ if (missing.length > 0) throw new FrameboardError("usage", `The note names images its page does not hold: ${missing.join(", ")}. Upload each one first.`, { missing });
35969
+ }
35454
35970
  // src/shared/records/notes.ts
35455
35971
  /** Where a note on one element points, in the edit address's terms. */
35456
35972
  const noteAnchorSchema = looseObject({
@@ -35469,6 +35985,8 @@ const noteSchema = looseObject({
35469
35985
  /** Null for a note on the whole frame. */
35470
35986
  anchor: noteAnchorSchema.nullable(),
35471
35987
  text: string$1(),
35988
+ /** Images saved with the message, relative to its page, as `.notes/<file>`. Absent on a note with none. */
35989
+ images: array$1(string$1()).optional(),
35472
35990
  from: _enum$1(["developer", "agent"]),
35473
35991
  /** Who signed it, as git names them, stamped by the server. */
35474
35992
  author: string$1().nullable(),
@@ -35504,15 +36022,21 @@ const listenerSchema = object$1({
35504
36022
  * The one line a follower prints per note. It opens with `frameboard note`,
35505
36023
  * which the skill tells the agent to act on, and names the verbs that answer
35506
36024
  * it. Text is collapsed onto one line, stripped of control characters so it
35507
- * cannot drive the terminal, and cut at 200 characters.
36025
+ * cannot drive the terminal, and cut at 200 characters. Image paths sit
36026
+ * between the text and the hints, so the prefix and the hints never move.
35508
36027
  */
35509
- function noteLine({ id, ref, element, text }) {
35510
- return `frameboard note ${id} on ${element === null ? ref : `${ref} element ${element}`}: ${collapse(text)} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
36028
+ function noteLine({ id, ref, element, text, images = [] }) {
36029
+ const where = element === null ? ref : `${ref} element ${element}`;
36030
+ const attached = images.length === 0 ? "" : ` (images: ${images.map(flatten).join(", ")})`;
36031
+ return `frameboard note ${id} on ${where}: ${collapse(text)}${attached} (reply: frameboard notes reply ${id} "<text>", close: frameboard notes done ${id})`;
35511
36032
  }
35512
36033
  function collapse(text) {
35513
- const flat = text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
36034
+ const flat = flatten(text);
35514
36035
  return flat.length > 200 ? `${flat.slice(0, 200)}...` : flat;
35515
36036
  }
36037
+ function flatten(text) {
36038
+ return text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
36039
+ }
35516
36040
  // src/server/notes/store.ts
35517
36041
  const NOTES_FILE$1 = "notes.json";
35518
36042
  const notesSpec = {
@@ -35589,6 +36113,7 @@ function addRoot(file, fields, { now, id }) {
35589
36113
  frame: fields.frame,
35590
36114
  anchor: fields.anchor,
35591
36115
  text: fields.text,
36116
+ ...withImages(fields.images),
35592
36117
  from: "developer",
35593
36118
  author: fields.author,
35594
36119
  session: null,
@@ -35613,6 +36138,7 @@ function addReply(file, replyTo, fields, { now, id }) {
35613
36138
  frame: root.frame,
35614
36139
  anchor: root.anchor,
35615
36140
  text: fields.text,
36141
+ ...withImages(fields.images),
35616
36142
  from: fields.from,
35617
36143
  author: fields.author,
35618
36144
  session: fields.session,
@@ -35633,6 +36159,10 @@ function addReply(file, replyTo, fields, { now, id }) {
35633
36159
  notes: [...notes, reply]
35634
36160
  };
35635
36161
  }
36162
+ /** A note with no images carries no key, so it reads as one written before images. */
36163
+ function withImages(images) {
36164
+ return images === void 0 || images.length === 0 ? {} : { images };
36165
+ }
35636
36166
  /** Sets the state of the thread `id` belongs to, and its addressee when one is given. */
35637
36167
  function setState(file, id, state, now, to) {
35638
36168
  const root = rootOf(file, id);
@@ -35646,6 +36176,13 @@ function setState(file, id, state, now, to) {
35646
36176
  } : note)
35647
36177
  };
35648
36178
  }
36179
+ /** Takes one message out, for a write whose send failed after it landed. */
36180
+ function removeNote(file, id) {
36181
+ return {
36182
+ ...file,
36183
+ notes: file.notes.filter((note) => note.id !== id)
36184
+ };
36185
+ }
35649
36186
  /** A page's notes as the board draws them, an unreadable file reading as none. */
35650
36187
  async function pageView(root, place) {
35651
36188
  let file;
@@ -35677,23 +36214,36 @@ async function queuedFor(root, session) {
35677
36214
  for (const note of notes) {
35678
36215
  if (note.thread !== null || note.state !== "queued") continue;
35679
36216
  if (note.to !== session) continue;
35680
- const ref = `${place.project}/${place.page}/${note.frame}`;
35681
- const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
35682
- const { element, ...stored } = note;
35683
- deliveries.push({
35684
- note: stored,
35685
- ref,
35686
- line: noteLine({
35687
- id: note.id,
35688
- ref,
35689
- element,
35690
- text: (newest ?? note).text
35691
- })
35692
- });
36217
+ deliveries.push(toDelivery(place, notes, note));
35693
36218
  }
35694
36219
  }
35695
36220
  return deliveries;
35696
36221
  }
36222
+ /** A root note as a follower would receive it, read from its page whatever its state. */
36223
+ async function deliveryOf(root, place, rootId) {
36224
+ const notes = await pageView(root, place);
36225
+ const note = notes.find((each) => each.id === rootId && each.thread === null);
36226
+ if (!note) throw new FrameboardError("note-not-found", `No note ${rootId} in this page.`, { id: rootId });
36227
+ return toDelivery(place, notes, note);
36228
+ }
36229
+ function toDelivery(place, notes, note) {
36230
+ const ref = `${place.project}/${place.page}/${note.frame}`;
36231
+ const newest = notes.filter((each) => (each.id === note.id || each.thread === note.id) && each.from === "developer").at(-1);
36232
+ const { element, ...stored } = note;
36233
+ const message = newest ?? note;
36234
+ const pageDir = dirname(place.path);
36235
+ return {
36236
+ note: stored,
36237
+ ref,
36238
+ line: noteLine({
36239
+ id: note.id,
36240
+ ref,
36241
+ element,
36242
+ text: message.text,
36243
+ images: message.images?.map((image) => join(pageDir, image))
36244
+ })
36245
+ };
36246
+ }
35697
36247
  /** Marks a root note delivered, while it is still queued to that session. */
35698
36248
  async function markDelivered(root, id, session, now) {
35699
36249
  await updateNotes((await findNote(root, id)).path, (file) => {
@@ -35710,33 +36260,64 @@ const STATUS$1 = {
35710
36260
  "frame-not-found": 404,
35711
36261
  "note-not-found": 404,
35712
36262
  "stale-address": 409,
36263
+ "dispatch-unavailable": 409,
35713
36264
  "notes-invalid": 422,
36265
+ "image-type-refused": 415,
36266
+ "dispatch-failed": 502,
35714
36267
  "lock-timeout": 503
35715
36268
  };
35716
36269
  const text = string$1().trim().min(1).max(1e5);
35717
36270
  const session = string$1().min(1).max(256);
36271
+ /** Page-relative paths an upload answered, each checked against the page on write. */
36272
+ const images = array$1(string$1().max(256)).max(32).optional();
36273
+ /** Asks for a new session in place of `to`. */
36274
+ const dispatch = literal(true).optional();
36275
+ const oneAddressee = {
36276
+ check: (body) => body.to === void 0 || body.dispatch === void 0,
36277
+ message: { message: "names a session or asks to start one, never both" }
36278
+ };
35718
36279
  const pinSchema = object$1({
35719
36280
  /** The frame ref, `<project>/<page>/<frame>`. */
35720
36281
  frame: string$1().min(1).max(1024),
35721
36282
  text,
36283
+ images,
35722
36284
  /** The element's index, given with the `modifiedAt` the board rendered it at. */
35723
36285
  element: int$1().min(0).optional(),
35724
36286
  renderedAt: string$1().optional(),
35725
- to: session.optional()
35726
- });
36287
+ to: session.optional(),
36288
+ dispatch
36289
+ }).refine(oneAddressee.check, oneAddressee.message);
35727
36290
  const replySchema = object$1({
35728
36291
  text,
35729
- to: session.optional()
35730
- });
35731
- const sendSchema = object$1({ to: session });
36292
+ images,
36293
+ to: session.optional(),
36294
+ dispatch
36295
+ }).refine(oneAddressee.check, oneAddressee.message);
36296
+ const sendSchema = object$1({
36297
+ to: session.optional(),
36298
+ dispatch
36299
+ }).refine((body) => body.to === void 0 !== (body.dispatch === void 0), { message: "names a session to send to or asks to start one" });
35732
36300
  /**
35733
36301
  * The board's note writes, each behind `requireWriter`: pin a note, reply in
35734
36302
  * its thread, send it to a listening session, and mark it done. Each answers
35735
36303
  * the CLI's `{ ok, data }` envelope with the note it wrote, and a refusal its
35736
36304
  * `{ ok, error }`. A write offers the queue to delivery at once rather than
35737
36305
  * waiting on the watcher.
35738
- */
35739
- function notesRoutes(root, access, delivery) {
36306
+ *
36307
+ * Pin, reply, and send take `dispatch: true` in place of `to`, which starts a
36308
+ * session through `dispatch` under an id minted here and marks the thread's
36309
+ * root delivered to it, so the started session's inbox never prints it a
36310
+ * second time. A failed start takes back the message the request added, and
36311
+ * no `dispatch` refuses before anything is written.
36312
+ *
36313
+ * A note's images go up first, as multipart `files` with the `page` ref, to
36314
+ * `/api/notes/images`, which saves them to the page's `.notes/` and answers
36315
+ * their page-relative paths for pin and reply to carry. A write naming an
36316
+ * image its page does not hold is refused. `/api/note-images/...` reads one
36317
+ * back with no writer check, as the frames route reads a page's files, since
36318
+ * an `<img>` sends no `Origin`.
36319
+ */
36320
+ function notesRoutes(root, access, delivery, dispatch, imageLimit = ASSET_BODY_LIMIT) {
35740
36321
  const app = new Hono();
35741
36322
  app.use("/api/notes", requireWriter(access));
35742
36323
  app.use("/api/notes/*", requireWriter(access));
@@ -35745,35 +36326,106 @@ function notesRoutes(root, access, delivery) {
35745
36326
  delivery?.offer().catch(() => {});
35746
36327
  return file.notes.find((note) => note.id === id);
35747
36328
  };
36329
+ const dispatcher = (asked) => {
36330
+ if (asked === void 0) return void 0;
36331
+ if (!dispatch) throw new FrameboardError("dispatch-unavailable", `No session can be started, since serve was started without ${DISPATCH_ENV}.`);
36332
+ return dispatch;
36333
+ };
36334
+ /**
36335
+ * Starts a session on a thread already on disk, then hands the root to it
36336
+ * as delivered, answering the note `answer` names.
36337
+ */
36338
+ const startSession = async (run, place, rootId, added, answer) => {
36339
+ const minted = randomUUID();
36340
+ try {
36341
+ const { line } = await deliveryOf(root, place, rootId);
36342
+ await run({
36343
+ session: minted,
36344
+ id: rootId,
36345
+ line
36346
+ });
36347
+ } catch (error) {
36348
+ if (added !== null) await updateNotes(place.path, (file) => removeNote(file, added));
36349
+ throw error;
36350
+ }
36351
+ return write(place.path, (file) => setState(file, rootId, "delivered", /* @__PURE__ */ new Date(), minted), answer);
36352
+ };
36353
+ app.post("/api/notes/images", bodyLimit({
36354
+ maxSize: imageLimit,
36355
+ onError: (c) => c.json({
36356
+ ok: false,
36357
+ error: {
36358
+ code: "asset-too-large",
36359
+ message: `A note's images may carry ${imageLimit / 1024 / 1024} MiB at most. Nothing was saved.`
36360
+ }
36361
+ }, 413)
36362
+ }), async (c) => {
36363
+ const form = await c.req.parseBody({ all: true }).catch(() => ({}));
36364
+ const sent = [form.files].flat().filter((v) => v instanceof File);
36365
+ if (typeof form.page !== "string" || sent.length === 0) throw new FrameboardError("usage", "Send multipart/form-data with the page ref in \"page\" and images in \"files\".");
36366
+ const page = await resolvePageRef(root, form.page, { cwd: root });
36367
+ const bytes = await Promise.all(sent.map(async (file) => new Uint8Array(await file.arrayBuffer())));
36368
+ return c.json({
36369
+ ok: true,
36370
+ data: { images: await saveImages(page.path, bytes) }
36371
+ });
36372
+ });
36373
+ app.get("/api/note-images/:project/:page/:name", async (c) => {
36374
+ const { project, page, name } = c.req.param();
36375
+ const found = await resolvePageRef(root, `${project}/${page}`, { cwd: root }).catch(() => null);
36376
+ const file = found && await storedImage(found.path, `.notes/${name}`);
36377
+ if (!file) return c.notFound();
36378
+ return c.body(new Uint8Array(await readFile(file)), 200, {
36379
+ "Content-Type": IMAGE_CONTENT_TYPES[extname(file).slice(1)] ?? "application/octet-stream",
36380
+ "Cache-Control": "no-store"
36381
+ });
36382
+ });
35748
36383
  app.post("/api/notes", async (c) => {
35749
36384
  const body = await parseBody(c.req.raw, pinSchema);
36385
+ const run = dispatcher(body.dispatch);
35750
36386
  const frame = await resolveFrameRef(root, body.frame, { cwd: root });
36387
+ await assertStored(dirname(frame.path), body.images ?? []);
35751
36388
  if (body.element !== void 0 && body.renderedAt === void 0) throw new FrameboardError("usage", "An element note needs the renderedAt the board showed it at.");
35752
36389
  const anchor = body.element === void 0 ? null : await anchorFor(frame.path, body.element, body.renderedAt ?? "");
35753
36390
  const id = newNoteId();
35754
36391
  const author = await readAuthor(root);
35755
- const note = await write(notesPath(root, frame.project, frame.page), (file) => addRoot(file, {
36392
+ const place = {
36393
+ project: frame.project,
36394
+ page: frame.page,
36395
+ path: notesPath(root, frame.project, frame.page)
36396
+ };
36397
+ const note = await write(place.path, (file) => addRoot(file, {
35756
36398
  frame: frame.name,
35757
36399
  anchor,
35758
36400
  text: body.text,
36401
+ images: body.images,
35759
36402
  author,
35760
36403
  to: body.to ?? null
35761
36404
  }, {
35762
36405
  now: /* @__PURE__ */ new Date(),
35763
36406
  id
35764
36407
  }), id);
35765
- return c.json({
36408
+ if (!run) return c.json({
35766
36409
  ok: true,
35767
36410
  data: { note }
35768
36411
  });
36412
+ const started = await startSession(run, place, id, id, id);
36413
+ return c.json({
36414
+ ok: true,
36415
+ data: { note: started }
36416
+ });
35769
36417
  });
35770
36418
  app.post("/api/notes/:id/replies", async (c) => {
35771
36419
  const body = await parseBody(c.req.raw, replySchema);
36420
+ const run = dispatcher(body.dispatch);
35772
36421
  const found = await findNote(root, c.req.param("id"));
36422
+ await assertStored(dirname(found.path), body.images ?? []);
36423
+ const rootId = found.note.thread ?? found.note.id;
35773
36424
  const id = newNoteId();
35774
36425
  const author = await readAuthor(root);
35775
36426
  const note = await write(found.path, (file) => addReply(file, found.note.id, {
35776
36427
  text: body.text,
36428
+ images: body.images,
35777
36429
  from: "developer",
35778
36430
  author,
35779
36431
  session: null,
@@ -35782,15 +36434,28 @@ function notesRoutes(root, access, delivery) {
35782
36434
  now: /* @__PURE__ */ new Date(),
35783
36435
  id
35784
36436
  }), id);
35785
- return c.json({
36437
+ if (!run) return c.json({
35786
36438
  ok: true,
35787
36439
  data: { note }
35788
36440
  });
36441
+ const started = await startSession(run, found, rootId, id, id);
36442
+ return c.json({
36443
+ ok: true,
36444
+ data: { note: started }
36445
+ });
35789
36446
  });
35790
36447
  app.post("/api/notes/:id/send", async (c) => {
35791
36448
  const body = await parseBody(c.req.raw, sendSchema);
36449
+ const run = dispatcher(body.dispatch);
35792
36450
  const found = await findNote(root, c.req.param("id"));
35793
36451
  const rootId = found.note.thread ?? found.note.id;
36452
+ if (run) {
36453
+ const note = await startSession(run, found, rootId, null, rootId);
36454
+ return c.json({
36455
+ ok: true,
36456
+ data: { note }
36457
+ });
36458
+ }
35794
36459
  const note = await write(found.path, (file) => setState(file, rootId, "queued", /* @__PURE__ */ new Date(), body.to), rootId);
35795
36460
  return c.json({
35796
36461
  ok: true,
@@ -35873,8 +36538,8 @@ function isTheme(value) {
35873
36538
  return value === "light" || value === "dark";
35874
36539
  }
35875
36540
  // src/server/board/pages.ts
35876
- /** Notes belong to the page they were pinned on, so a copy starts without them. */
35877
- const NOT_COPIED = /* @__PURE__ */ new Set(["notes.json"]);
36541
+ /** Notes and their images belong to the page they were pinned on, so a copy starts without them. */
36542
+ const NOT_COPIED = /* @__PURE__ */ new Set(["notes.json", ".notes"]);
35878
36543
  async function addPage(root, ref, { index, ...options }) {
35879
36544
  const page = await resolvePageRef(root, ref, {
35880
36545
  ...options,
@@ -36130,71 +36795,6 @@ async function assertFree(root, name, self) {
36130
36795
  taken
36131
36796
  });
36132
36797
  }
36133
- // src/shared/starter-tokens.ts
36134
- /**
36135
- * The looks a new project can start from, each accent paired by hand with a
36136
- * dark value, so both themes hold without a derived color. The keys are the
36137
- * values `project tokens --accent` and the route take.
36138
- */
36139
- const STARTER_ACCENTS = {
36140
- blue: {
36141
- light: "#2f7bf0",
36142
- dark: "#4e92f6"
36143
- },
36144
- red: {
36145
- light: "#e5484d",
36146
- dark: "#ff6369"
36147
- },
36148
- green: {
36149
- light: "#30a46c",
36150
- dark: "#3dd68c"
36151
- },
36152
- orange: {
36153
- light: "#f76b15",
36154
- dark: "#ff801f"
36155
- },
36156
- purple: {
36157
- light: "#8e4ec6",
36158
- dark: "#9a5cd0"
36159
- }
36160
- };
36161
- /** The served faces a starter sheet may name, keyed by their face folder. */
36162
- const STARTER_FONTS = {
36163
- geist: {
36164
- family: "Geist",
36165
- stack: "Geist, sans-serif"
36166
- },
36167
- "geist-mono": {
36168
- family: "Geist Mono",
36169
- stack: "'Geist Mono', monospace"
36170
- }
36171
- };
36172
- const DEFAULT_LOOK = {
36173
- accent: "blue",
36174
- font: "geist"
36175
- };
36176
- /** A project token sheet setting the names the fixture sheets use, light then dark. */
36177
- function starterSheet({ accent, font }) {
36178
- const pair = STARTER_ACCENTS[accent];
36179
- return `:root {
36180
- --accent: ${pair.light};
36181
- --surface: #ffffff;
36182
- --text: #111111;
36183
- --muted: #6b7280;
36184
- --border: #e5e7eb;
36185
- --radius: 10px;
36186
- --font-text: ${STARTER_FONTS[font].stack};
36187
- }
36188
-
36189
- [data-theme='dark'] {
36190
- --accent: ${pair.dark};
36191
- --surface: #111111;
36192
- --text: #ededed;
36193
- --muted: #9ca3af;
36194
- --border: #2e2e2e;
36195
- }
36196
- `;
36197
- }
36198
36798
  // src/server/look/starter.ts
36199
36799
  /**
36200
36800
  * Writes a starter `tokens.css` into a project that renders with no token
@@ -36254,6 +36854,8 @@ const coordinate = int$1();
36254
36854
  const frameAddSchema = object$1({
36255
36855
  ref,
36256
36856
  size: _enum$1(Object.keys(FRAME_SIZES)).optional(),
36857
+ width: int$1().min(1).optional(),
36858
+ height: int$1().min(1).optional(),
36257
36859
  x: coordinate.optional(),
36258
36860
  y: coordinate.optional()
36259
36861
  });
@@ -36380,7 +36982,11 @@ function structureRoutes(root, access, history, measure, tokens = null) {
36380
36982
  before: `${source.project}/${source.name}`,
36381
36983
  after: renamed.ref
36382
36984
  },
36383
- frames: []
36985
+ frames: [],
36986
+ renamed: {
36987
+ before: `${source.project}/${source.name}`,
36988
+ after: renamed.ref
36989
+ }
36384
36990
  }));
36385
36991
  return c.json({
36386
36992
  ok: true,
@@ -36596,8 +37202,15 @@ function structureRoutes(root, access, history, measure, tokens = null) {
36596
37202
  });
36597
37203
  app.post("/api/project/rename", async (c) => {
36598
37204
  const body = await parseBody$1(c.req.raw, renameSchema);
36599
- await refuseHeld([(await resolveProject(root, body.ref)).name]);
36600
- const project = await recorded((journal) => renameProject(root, body.ref, body.name, { journal }), onHome);
37205
+ const source = await resolveProject(root, body.ref);
37206
+ await refuseHeld([source.name]);
37207
+ const project = await recorded((journal) => renameProject(root, body.ref, body.name, { journal }), async (renamed) => ({
37208
+ ...await onHome(),
37209
+ renamed: {
37210
+ before: source.name,
37211
+ after: renamed.name
37212
+ }
37213
+ }));
36601
37214
  return c.json({
36602
37215
  ok: true,
36603
37216
  data: project
@@ -36722,7 +37335,7 @@ function boardHostGuard(port) {
36722
37335
  await next();
36723
37336
  };
36724
37337
  }
36725
- function createApp({ clientDir, root, port, actions, tickets, renderFrame, facesDir, tokens, delivery, history, selection, checks, thumbnails, measure, frameVersion, settledVersion }) {
37338
+ function createApp({ clientDir, root, port, actions, tickets, renderFrame, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion }) {
36726
37339
  const app = new Hono();
36727
37340
  const given = tokens ?? null;
36728
37341
  app.use("*", async (c, next) => {
@@ -36744,7 +37357,7 @@ function createApp({ clientDir, root, port, actions, tickets, renderFrame, faces
36744
37357
  app.route("/", apiRoutes(root, actions, frames.look, history));
36745
37358
  app.route("/", structureRoutes(root, actions.access, history, measure, given));
36746
37359
  app.route("/", historyRoutes(actions.access, history));
36747
- app.route("/", notesRoutes(root, actions.access, delivery));
37360
+ app.route("/", notesRoutes(root, actions.access, delivery, dispatch));
36748
37361
  app.route("/", assetsRoutes(root, actions.access));
36749
37362
  app.route("/", elementsRoutes(root, actions.access, selection, given));
36750
37363
  app.route("/", findRoutes(root));
@@ -38793,6 +39406,15 @@ object$1({
38793
39406
  index: int$1().min(0),
38794
39407
  hash
38795
39408
  });
39409
+ object$1({
39410
+ ref: string$1(),
39411
+ hash
39412
+ });
39413
+ object$1({
39414
+ ref: string$1(),
39415
+ index: int$1().min(0),
39416
+ hash
39417
+ });
38796
39418
  // src/shared/records/elements.ts
38797
39419
  /**
38798
39420
  * How an element lays out what it holds, read from the frame's static
@@ -38816,7 +39438,9 @@ const treeElementSchema = object$1({
38816
39438
  /** True when the element holds text and nothing else. */
38817
39439
  textOnly: boolean$1(),
38818
39440
  /** Its layout, which a culled frame's Layers rows draw from without an iframe. */
38819
- layout: layoutSchema
39441
+ layout: layoutSchema,
39442
+ /** True when it holds nothing and its corners round by half or more, so it draws as an ellipse. */
39443
+ round: boolean$1()
38820
39444
  });
38821
39445
  /** What `GET /api/frames/elements` answers: a frame's elements under `body` in index order, and the hash they were read from. */
38822
39446
  const elementTreeSchema = object$1({
@@ -38970,7 +39594,7 @@ function contentFormat() {
38970
39594
  `A project is any folder in the board whose name does not open with a dot. Its ${PROJECT_FILE} lists page names in display order, and pages it does not list follow by name.`,
38971
39595
  `A page is any folder in a project except ${ASSETS_FOLDER}/ and dot-named ones. Its ${LAYOUT_FILE} holds each frame's box, stacking order, and flags.`,
38972
39596
  `A frame is any *${FRAME_EXTENSION} file directly in a page, named by its stem.`,
38973
- `A page's notes sit in its ${NOTES_FILE$1}, never in a frame. A note pins to a frame or to one element by index and the frame file's hash, and reads at the frame once the file changes. Read them with notes, answer with notes reply, and close them with notes done.`,
39597
+ `A page's notes sit in its ${NOTES_FILE$1}, never in a frame. A note pins to a frame or to one element by index and the frame file's hash, and reads at the frame once the file changes. Read them with notes, answer with notes reply, and close them with notes done. A note's images sit in its page's ${NOTES_FOLDER}/ folder, and its images field lists them relative to the page.`,
38974
39598
  `serve reuses a board the walk finds, and otherwise creates ${DEFAULT_BOARD_FOLDER}/ in the working folder with project ${START_PROJECT} and empty page ${START_PAGE}, and records its address in ${RUN_FOLDER}/${ADDRESS_FILE}.`,
38975
39599
  `Dot-named folders, *${LOCK_SUFFIX} files, and *${TEMP_SUFFIX} files belong to Frameboard and are never content.`
38976
39600
  ],
@@ -39242,7 +39866,7 @@ function registerFrame(program, context) {
39242
39866
  data: record,
39243
39867
  human: `${what} ${record.ref}`
39244
39868
  });
39245
- act(withPosition(withSize(verb("add", "Place a frame past every frame, writing a skeleton file when none exists. Each axis no size names hugs its content, so a preset or --width fixes the width and the height hugs."))), context, async ([ref = ""], options) => done(await addFrame(await boardOf(options, io), ref, {
39869
+ act(withPosition(withSize(verb("add", "Place a frame past every frame, as written when its file exists and with a skeleton file only when none does, so write the file first to show no empty box. Each axis no size names hugs its content, so a preset or --width fixes the width and the height hugs."))), context, async ([ref = ""], options) => done(await addFrame(await boardOf(options, io), ref, {
39246
39870
  ...options,
39247
39871
  cwd: io.cwd
39248
39872
  }), "Added"));
@@ -43148,11 +43772,13 @@ function registerNotes(program, context) {
43148
43772
  const file = await readNotes(place.path);
43149
43773
  const done = new Set(file.notes.filter((n) => n.state === "done").map((n) => n.id));
43150
43774
  const kept = byThread(file.notes).filter((note) => (options.all || !done.has(note.thread ?? note.id)) && (!frame || note.frame === frame.name));
43151
- const elements = await resolveAnchors(join(root, place.project, place.page), kept);
43775
+ const pageDir = join(root, place.project, place.page);
43776
+ const elements = await resolveAnchors(pageDir, kept);
43152
43777
  listed.push(...kept.map((note) => ({
43153
43778
  ...note,
43154
43779
  ref: `${place.project}/${place.page}/${note.frame}`,
43155
- element: elements[note.id] ?? null
43780
+ element: elements[note.id] ?? null,
43781
+ ...note.images?.length ? { imagePaths: note.images.map((image) => join(pageDir, image)) } : {}
43156
43782
  })));
43157
43783
  }
43158
43784
  return {
@@ -43220,7 +43846,7 @@ function byThread(notes) {
43220
43846
  function describe$1(notes) {
43221
43847
  if (notes.length === 0) return "No open notes";
43222
43848
  return notes.map((note) => {
43223
- const text = note.text.replace(/\s+/g, " ").trim();
43849
+ const text = `${note.text.replace(/\s+/g, " ").trim()}${(note.imagePaths ?? []).map((path) => `\n image: ${path}`).join("")}`;
43224
43850
  if (note.thread) return ` ${note.from === "agent" ? "agent" : note.author ?? "developer"}: ${text}`;
43225
43851
  const where = note.element === null ? note.ref : `${note.ref} element ${note.element}`;
43226
43852
  return `${note.id} Note ${note.number} on ${where} ${note.state}${note.to ? ` to ${note.to}` : ""}\n ${note.author ?? "developer"}: ${text}`;
@@ -43727,7 +44353,7 @@ function versionKey(ref, hash) {
43727
44353
  /** The files and folders a step wrote, being every rewrite, creation, removal, and move. */
43728
44354
  function writtenPaths(step) {
43729
44355
  return step.changes.flatMap((change) => {
43730
- if (change.kind === "element" || change.kind === "inserted" || change.kind === "path") return [change.path];
44356
+ if (change.kind === "element" || change.kind === "inserted" || change.kind === "relocated" || change.kind === "path") return [change.path];
43731
44357
  if (change.kind === "moved") return [change.from, change.to];
43732
44358
  return [];
43733
44359
  });
@@ -43923,7 +44549,8 @@ async function reads(change, side) {
43923
44549
  }
43924
44550
  case "path": return change.present === side ? await exists(change.path) && await hashPath(change.path) === change.hash : !await exists(change.path) && await exists(change.slot);
43925
44551
  case "element": return await exists(change.path) && holdsSpan(await readFile(change.path, "utf8"), change.span, side);
43926
- case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side);
44552
+ case "inserted": return await exists(change.path) && holdsInserted(await readFile(change.path, "utf8"), change.span, side === change.present ? "after" : "before");
44553
+ case "relocated": return await exists(change.path) && relocateMoved(await readFile(change.path, "utf8"), change.span, OTHER[side]) !== void 0;
43927
44554
  }
43928
44555
  }
43929
44556
  /**
@@ -43992,7 +44619,16 @@ async function restore(change, side) {
43992
44619
  };
43993
44620
  });
43994
44621
  case "inserted": return rewriteFrame(change, (source) => {
43995
- const written = side === "before" ? removeInserted(source, change.span) : restoreInserted(source, change.span);
44622
+ const written = side === change.present ? restoreInserted(source, change.span) : removeInserted(source, change.span);
44623
+ return written && {
44624
+ html: written.html,
44625
+ keep: () => {
44626
+ change.span = written.span;
44627
+ }
44628
+ };
44629
+ });
44630
+ case "relocated": return rewriteFrame(change, (source) => {
44631
+ const written = relocateMoved(source, change.span, side);
43996
44632
  return written && {
43997
44633
  html: written.html,
43998
44634
  keep: () => {
@@ -44089,6 +44725,26 @@ var StepJournal = class {
44089
44725
  kind: "inserted",
44090
44726
  path,
44091
44727
  ref,
44728
+ span,
44729
+ present: "after"
44730
+ });
44731
+ }
44732
+ /** The element a hand delete took out of a frame file, which this journal does not write. */
44733
+ deletedElement(path, ref, span) {
44734
+ this.changes.push({
44735
+ kind: "inserted",
44736
+ path,
44737
+ ref,
44738
+ span,
44739
+ present: "before"
44740
+ });
44741
+ }
44742
+ /** The element a hand move took to another gap of a frame file, which this journal does not write. */
44743
+ relocated(path, ref, span) {
44744
+ this.changes.push({
44745
+ kind: "relocated",
44746
+ path,
44747
+ ref,
44092
44748
  span
44093
44749
  });
44094
44750
  }
@@ -44192,7 +44848,7 @@ var History = class {
44192
44848
  if (this.#undo.length > 100) this.#undo.shift();
44193
44849
  this.#redo = [];
44194
44850
  this.onChange(this.counts());
44195
- this.onWrite(step);
44851
+ this.onWrite(step, "after");
44196
44852
  }
44197
44853
  /**
44198
44854
  * The refs the top undo or redo step would write, without popping it, so a
@@ -44253,7 +44909,7 @@ var History = class {
44253
44909
  }
44254
44910
  onto.push(step);
44255
44911
  this.onChange(this.counts());
44256
- this.onWrite(step);
44912
+ this.onWrite(step, to);
44257
44913
  const answer = {
44258
44914
  page: step.page?.[to] ?? null,
44259
44915
  frames: step.frames
@@ -47561,6 +48217,24 @@ function reloadRefs(root, paths, board, tokens = null) {
47561
48217
  return named;
47562
48218
  }
47563
48219
  /**
48220
+ * `refs` less each frame that only moved with a folder the board renamed,
48221
+ * being one under a moved folder whose file carries the stamp `last`, the
48222
+ * board sent before the move, showed at its old path. It renders what the
48223
+ * tab already shows, so a reload would restart it for nothing, while a file
48224
+ * written before or after the move that `last` never showed still reloads.
48225
+ */
48226
+ function unmovedRefs(refs, board, moved, last) {
48227
+ if (moved.length === 0 || !last) return refs;
48228
+ const shown = new Map(last.projects.flatMap((project) => project.pages.flatMap((page) => page.frames.map((frame) => [frame.path, frame.modifiedAt]))));
48229
+ const onlyMoved = /* @__PURE__ */ new Set();
48230
+ for (const project of board.projects) for (const page of project.pages) for (const frame of page.frames) {
48231
+ const folder = moved.find(({ path }) => frame.path.startsWith(`${path}${sep}`));
48232
+ const before = folder && `${folder.from}${frame.path.slice(folder.path.length)}`;
48233
+ if (before && shown.get(before) === frame.modifiedAt) onlyMoved.add(frame.ref);
48234
+ }
48235
+ return refs.filter((ref) => !onlyMoved.has(ref));
48236
+ }
48237
+ /**
47564
48238
  * The frame a page-folder file belongs to: `hero.html` itself, or a temp file
47565
48239
  * an editor or atomic writer saves it through, such as `hero.html.swap`.
47566
48240
  */
@@ -47659,7 +48333,7 @@ function checkOne(root, frame, context) {
47659
48333
  * it never counts as a tab, and taken only from a socket upgraded with the
47660
48334
  * address token as a bearer, since a browser page must never register one.
47661
48335
  */
47662
- function createHub({ tabs, port, access, snapshot, findings, notes, delivery, history, claims, changes, closeTab }) {
48336
+ function createHub({ tabs, port, access, snapshot, findings, notes, delivery, history, claims, changes, closeTab, dispatch = false }) {
47663
48337
  const server = new import_websocket_server.default({ noServer: true });
47664
48338
  const boards = /* @__PURE__ */ new Map();
47665
48339
  const inboxes = /* @__PURE__ */ new Map();
@@ -47701,7 +48375,8 @@ function createHub({ tabs, port, access, snapshot, findings, notes, delivery, hi
47701
48375
  });
47702
48376
  send(socket, {
47703
48377
  type: "access",
47704
- write: writer
48378
+ write: writer,
48379
+ dispatch: writer && dispatch
47705
48380
  });
47706
48381
  if (history) send(socket, {
47707
48382
  type: "history",
@@ -48089,6 +48764,11 @@ const HOSTNAME = "127.0.0.1";
48089
48764
  */
48090
48765
  const OWN_GRACE_MS = 1e3;
48091
48766
  /**
48767
+ * How long a folder the board's own rename moved keeps its unchanged frames
48768
+ * from reloading, well past the watcher reporting the move under load.
48769
+ */
48770
+ const MOVED_MS = 1e4;
48771
+ /**
48092
48772
  * The board tabs holding a live connection to this server, counting apart the
48093
48773
  * ones that can write. The route a tab connects through calls `open` and
48094
48774
  * `close`, and `serve` waits on a writer before deciding to open a tab of its
@@ -48141,7 +48821,7 @@ async function startServer({ strictPort = true, port, ...options }) {
48141
48821
  });
48142
48822
  }
48143
48823
  }
48144
- async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch }) {
48824
+ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch, dispatch }) {
48145
48825
  const tabs = new BoardTabs();
48146
48826
  const tickets = createTickets();
48147
48827
  let bound = 0;
@@ -48170,6 +48850,10 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48170
48850
  }),
48171
48851
  now: () => /* @__PURE__ */ new Date()
48172
48852
  });
48853
+ const dispatcher = dispatch ? createDispatcher({
48854
+ ...dispatch,
48855
+ root
48856
+ }) : void 0;
48173
48857
  await emptyTrash(root);
48174
48858
  const tracker = createChangeTracker(root);
48175
48859
  const settling = /* @__PURE__ */ new Set();
@@ -48186,23 +48870,51 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48186
48870
  }, OWN_GRACE_MS);
48187
48871
  settling.add(timer);
48188
48872
  };
48873
+ const shown = { board: null };
48874
+ let moved = [];
48875
+ const recentlyMoved = () => {
48876
+ moved = moved.filter(({ at }) => Date.now() - at < MOVED_MS);
48877
+ return moved;
48878
+ };
48189
48879
  const history = new History(root, (counts) => hub.broadcast({
48190
48880
  type: "history",
48191
48881
  ...counts
48192
- }), (step) => void inTurn(() => tracker.own(step)));
48882
+ }), (step, side) => {
48883
+ if (step.renamed) {
48884
+ for (const change of step.changes) {
48885
+ if (change.kind !== "moved") continue;
48886
+ moved = [...recentlyMoved(), {
48887
+ from: side === "after" ? change.from : change.to,
48888
+ path: side === "after" ? change.to : change.from,
48889
+ at: Date.now()
48890
+ }];
48891
+ }
48892
+ const from = side === "after" ? "before" : "after";
48893
+ hub.broadcast({
48894
+ type: "renamed",
48895
+ before: step.renamed[from],
48896
+ after: step.renamed[side]
48897
+ });
48898
+ }
48899
+ inTurn(() => tracker.own(step));
48900
+ });
48193
48901
  const selection = createSelectionHolder(() => tabs.writers);
48194
48902
  const hub = createHub({
48195
48903
  tabs,
48196
48904
  port: boundPort,
48197
48905
  access,
48198
- snapshot: () => inTurn(() => scanBoard(root)),
48906
+ snapshot: () => inTurn(async () => {
48907
+ shown.board = await scanBoard(root);
48908
+ return shown.board;
48909
+ }),
48199
48910
  findings: () => inTurn(async () => findings.all()),
48200
48911
  notes: () => inTurn(() => boardView(root)),
48201
48912
  delivery,
48202
48913
  history: () => history.counts(),
48203
48914
  claims: () => inTurn(() => claims.read()),
48204
48915
  changes: () => inTurn(async () => tracker.log()),
48205
- closeTab: selection.closeTab
48916
+ closeTab: selection.closeTab,
48917
+ dispatch: dispatcher !== void 0
48206
48918
  });
48207
48919
  const claims = createClaimsPush(root, {
48208
48920
  broadcast: (list) => hub.broadcast({
@@ -48282,6 +48994,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48282
48994
  port: boundPort,
48283
48995
  tickets,
48284
48996
  delivery,
48997
+ dispatch: dispatcher,
48285
48998
  history,
48286
48999
  selection,
48287
49000
  renderFrame,
@@ -48352,7 +49065,9 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48352
49065
  claims,
48353
49066
  thumbnails,
48354
49067
  hug,
48355
- settleLater
49068
+ settleLater,
49069
+ moved: recentlyMoved,
49070
+ shown
48356
49071
  }));
48357
49072
  });
48358
49073
  return {
@@ -48390,7 +49105,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
48390
49105
  * notes or frames it touched, whose queue it offers to delivery. The frames
48391
49106
  * an agent changed wait out the grace before the board hears of them.
48392
49107
  */
48393
- async function pushBatch(root, tokens, paths, { hub, findings, rendered, delivery, tracker, claims, thumbnails, hug, settleLater }) {
49108
+ async function pushBatch(root, tokens, paths, { hub, findings, rendered, delivery, tracker, claims, thumbnails, hug, settleLater, moved, shown }) {
48394
49109
  let board;
48395
49110
  let own;
48396
49111
  try {
@@ -48404,12 +49119,15 @@ async function pushBatch(root, tokens, paths, { hub, findings, rendered, deliver
48404
49119
  type: "board",
48405
49120
  data: board
48406
49121
  });
49122
+ const last = shown.board;
49123
+ shown.board = board;
48407
49124
  const refs = reloadRefs(root, paths, board, tokens);
48408
49125
  hug.later(board, refs.filter((ref) => !own.includes(ref)));
48409
49126
  if (refs.length > 0) {
48410
- hub.broadcast({
49127
+ const reloads = unmovedRefs(refs, board, moved(), last);
49128
+ if (reloads.length > 0) hub.broadcast({
48411
49129
  type: "reload",
48412
- refs
49130
+ refs: reloads
48413
49131
  });
48414
49132
  thumbnails.invalidate(refs);
48415
49133
  const stale = Object.fromEntries(refs.map((ref) => [ref, null]));
@@ -48478,7 +49196,7 @@ const DEFAULT_PORT = 4173;
48478
49196
  const RECONNECT_WAIT_MS = 1e3;
48479
49197
  function registerServe(program, context) {
48480
49198
  const { io } = context;
48481
- act(addVerb(program, "serve", "Serve the board in a local browser").option("-p, --port <port>", "port to listen on, falling back to a free one when the default is taken", parsePort, DEFAULT_PORT).option("--no-open", "leave the browser alone").option("--tokens <path>", "a token sheet another tool manages, standing in for the board's tokens.css"), context, async (_args, options, self) => {
49199
+ act(addVerb(program, "serve", `Serve the board in a local browser. A note sent to a new session runs the shell command in ${DISPATCH_ENV}, read once at start, with the note in FRAMEBOARD_NOTE, FRAMEBOARD_NOTE_ID, FRAMEBOARD_SESSION, and FRAMEBOARD_ROOT`).option("-p, --port <port>", "port to listen on, falling back to a free one when the default is taken", parsePort, DEFAULT_PORT).option("--no-open", "leave the browser alone").option("--tokens <path>", "a token sheet another tool manages, standing in for the board's tokens.css"), context, async (_args, options, self) => {
48482
49200
  const tokens = options.tokens === void 0 ? void 0 : resolve(io.cwd, options.tokens);
48483
49201
  if (tokens !== void 0 && !isFile(tokens)) throw new FrameboardError("tokens-not-found", `No token sheet at ${tokens}.`, { tokens });
48484
49202
  const existing = await resolveBoard({
@@ -48514,7 +49232,8 @@ function registerServe(program, context) {
48514
49232
  tokens,
48515
49233
  port: options.port,
48516
49234
  strictPort: self.getOptionValueSource("port") !== "default",
48517
- openUrl: io.openUrl
49235
+ openUrl: io.openUrl,
49236
+ dispatch: dispatchCommand(io.cwd)
48518
49237
  });
48519
49238
  const address = newAddress({
48520
49239
  root,
@@ -48546,6 +49265,19 @@ function registerServe(program, context) {
48546
49265
  };
48547
49266
  });
48548
49267
  }
49268
+ /**
49269
+ * The developer's dispatch command, read from this process's environment
49270
+ * alone, never from a file a repository carries, so a cloned board cannot
49271
+ * make Send run anything.
49272
+ */
49273
+ function dispatchCommand(cwd) {
49274
+ const command = process.env[DISPATCH_ENV]?.trim();
49275
+ return command ? {
49276
+ command,
49277
+ cwd,
49278
+ env: process.env
49279
+ } : void 0;
49280
+ }
48549
49281
  /** True for a file, and false for a folder or a path that does not exist. */
48550
49282
  function isFile(path) {
48551
49283
  return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false;