frameboard 0.39.0 → 0.40.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
@@ -3061,7 +3061,11 @@ const EXIT_CODES = {
3061
3061
  "motion-unbounded": 10,
3062
3062
  "no-network-address": 3,
3063
3063
  "kit-not-found": 3,
3064
- "kit-invalid": 5
3064
+ "kit-invalid": 5,
3065
+ "result-not-found": 3,
3066
+ "no-provider": 3,
3067
+ "source-failed": 13,
3068
+ "provider-failed": 13
3065
3069
  };
3066
3070
  var FrameboardError = class extends Error {
3067
3071
  code;
@@ -3121,7 +3125,7 @@ async function readRecord(path, spec) {
3121
3125
  try {
3122
3126
  raw = JSON.parse(text);
3123
3127
  } catch (error) {
3124
- throw invalid(spec, path, `does not parse: ${messageOf(error)}`, error);
3128
+ throw invalid(spec, path, `does not parse: ${messageOf$1(error)}`, error);
3125
3129
  }
3126
3130
  const result = spec.schema.safeParse(raw);
3127
3131
  if (!result.success) throw invalid(spec, path, `fails its schema: ${result.error.message}`);
@@ -3292,7 +3296,7 @@ function invalid(spec, path, reason, cause) {
3292
3296
  function isCode(error, code) {
3293
3297
  return error instanceof Error && error.code === code;
3294
3298
  }
3295
- function messageOf(error) {
3299
+ function messageOf$1(error) {
3296
3300
  return error instanceof Error ? error.message : String(error);
3297
3301
  }
3298
3302
  // node_modules/zod/v4/core/util.js
@@ -4322,7 +4326,7 @@ function datetime$1(args) {
4322
4326
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
4323
4327
  }
4324
4328
  const anyString = /^[\s\S]{0,}$/;
4325
- const integer = /^-?\d+$/;
4329
+ const integer$1 = /^-?\d+$/;
4326
4330
  const number$1 = /^-?\d+(?:\.\d+)?$/;
4327
4331
  const boolean$2 = /^(?:true|false)$/i;
4328
4332
  const lowercase = /^[^A-Z]*$/;
@@ -7882,7 +7886,7 @@ function stringifyKeyNames(bySchema, json, visited) {
7882
7886
  else if (typeof rest.const === "number") rest.const = String(rest.const);
7883
7887
  if (!numericType) return rest;
7884
7888
  rest.type = "string";
7885
- if (!values) rest.pattern = (types.includes("number") ? number$1 : integer).source;
7889
+ if (!values) rest.pattern = (types.includes("number") ? number$1 : integer$1).source;
7886
7890
  return rest;
7887
7891
  }
7888
7892
  /** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
@@ -9119,6 +9123,15 @@ const BEZELS = {
9119
9123
  }
9120
9124
  };
9121
9125
  /**
9126
+ * A device's screen corners as a CSS `border-radius`, which the body and every
9127
+ * box drawn on its screen share. A laptop's screen meets its chin, so only
9128
+ * its top corners round.
9129
+ */
9130
+ function screenCorners(device) {
9131
+ const { screenRadius } = BEZELS[device];
9132
+ return device === "laptop" ? `${screenRadius}px ${screenRadius}px 0 0` : `${screenRadius}px`;
9133
+ }
9134
+ /**
9122
9135
  * The narrowest width each device draws around, widest first, so a frame
9123
9136
  * takes the first one it reaches. Under the phone's width no device fits.
9124
9137
  */
@@ -9635,8 +9648,15 @@ const layoutEntrySchema = looseObject({
9635
9648
  })), unknown()]).optional(),
9636
9649
  showDevice: unknown().optional(),
9637
9650
  device: unknown().optional(),
9638
- transition: unknown().optional()
9651
+ transition: unknown().optional(),
9652
+ speakerNotes: unknown().optional()
9639
9653
  });
9654
+ /** The longest speaker note a write accepts, in characters. */
9655
+ const SPEAKER_NOTES_MAX = 1e4;
9656
+ /** The note a layout entry's `speakerNotes` holds, null for none or a value of another type. */
9657
+ function speakerNotesOf(value) {
9658
+ return typeof value === "string" && value.trim() !== "" ? value : null;
9659
+ }
9640
9660
  /** A named box grouping the frames whose center it holds, which it never lists. */
9641
9661
  const sectionEntrySchema = looseObject({
9642
9662
  x: int$1(),
@@ -24431,6 +24451,7 @@ function placeFrames(frames, names, readTransition = storedTransitionOf) {
24431
24451
  const shown = showsDevice(entry);
24432
24452
  const device = shown ? deviceForWidth(box.width) : null;
24433
24453
  const transition = readTransition(entry.transition);
24454
+ const speakerNotes = speakerNotesOf(entry.speakerNotes);
24434
24455
  placements.set(name, {
24435
24456
  box,
24436
24457
  order: entry.order,
@@ -24443,6 +24464,7 @@ function placeFrames(frames, names, readTransition = storedTransitionOf) {
24443
24464
  ...shown ? { showDevice: true } : {},
24444
24465
  ...device ? { device } : {},
24445
24466
  ...transition ? { transition } : {},
24467
+ ...speakerNotes ? { speakerNotes } : {},
24446
24468
  placed: true
24447
24469
  });
24448
24470
  }
@@ -24670,7 +24692,7 @@ async function isDirectory(path) {
24670
24692
  }
24671
24693
  }
24672
24694
  // package.json
24673
- var version$1 = "0.39.0";
24695
+ var version$1 = "0.40.0";
24674
24696
  var dependencies = { "playwright-core": "1.65.0" };
24675
24697
  var peerDependencies = { "oxfmt": "0.78.0" };
24676
24698
  // src/shared/version.ts
@@ -25651,6 +25673,30 @@ async function setFrameTransition(root, ref, transition, options) {
25651
25673
  } : rest;
25652
25674
  });
25653
25675
  }
25676
+ /**
25677
+ * Sets a frame's speaker note on its layout entry, null or blank clearing it.
25678
+ * Refuses `usage` past `SPEAKER_NOTES_MAX` rather than cutting, and
25679
+ * `stale-layout` once `expected`, the note the edit began from, is gone.
25680
+ */
25681
+ async function setFrameSpeakerNotes(root, ref, text, { expected, ...options }) {
25682
+ if (text !== null && text.length > 1e4) throw new FrameboardError("usage", `A speaker note holds at most ${SPEAKER_NOTES_MAX} characters, and this one has ${text.length}.`, {
25683
+ max: SPEAKER_NOTES_MAX,
25684
+ length: text.length
25685
+ });
25686
+ const speakerNotes = speakerNotesOf(text);
25687
+ return updatePlacement(root, ref, options, (placement, frameRef) => {
25688
+ const { speakerNotes: held, ...rest } = placement;
25689
+ if (expected !== void 0 && (speakerNotesOf(expected) ?? "") !== (held ?? "")) throw new FrameboardError("stale-layout", `The speaker notes on ${frameRef} changed since this edit began, so nothing was written.`, {
25690
+ ref: frameRef,
25691
+ stored: held ?? "",
25692
+ expected
25693
+ });
25694
+ return speakerNotes ? {
25695
+ ...rest,
25696
+ speakerNotes
25697
+ } : rest;
25698
+ });
25699
+ }
25654
25700
  async function deleteFrame(root, ref, options) {
25655
25701
  const { journal } = options;
25656
25702
  const frame = await resolveFrameRef(root, ref, options);
@@ -25740,7 +25786,7 @@ var PageLayout = class {
25740
25786
  * Writes the fixed keys after the entry's own, so unknown keys survive, and a
25741
25787
  * flag only once on or already held, so an older entry gains no key.
25742
25788
  */
25743
- set(name, { box, order, hidden, locked, scroll, widths, showDevice, transition, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
25789
+ set(name, { box, order, hidden, locked, scroll, widths, showDevice, transition, speakerNotes, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
25744
25790
  const hugWidth = hugsWidth && !scroll;
25745
25791
  const hugHeight = hugsHeight && !scroll;
25746
25792
  const held = this.file.frames[name];
@@ -25761,12 +25807,14 @@ var PageLayout = class {
25761
25807
  height
25762
25808
  })) } : {},
25763
25809
  ...showDevice ? { showDevice } : {},
25764
- ...transition ? { transition: { ...transition } } : {}
25810
+ ...transition ? { transition: { ...transition } } : {},
25811
+ ...speakerNotes ? { speakerNotes } : {}
25765
25812
  };
25766
25813
  if (widths.length === 0 && widthsOf(held?.widths).length > 0) delete entry.widths;
25767
25814
  if (!showDevice && held?.showDevice === true) delete entry.showDevice;
25768
25815
  if (typeof held?.device === "string") delete entry.device;
25769
25816
  if (!transition && storedTransitionOf(held?.transition)) delete entry.transition;
25817
+ if (!speakerNotes && speakerNotesOf(held?.speakerNotes)) delete entry.speakerNotes;
25770
25818
  this.file.frames[name] = entry;
25771
25819
  this.changed = true;
25772
25820
  }
@@ -30333,7 +30381,7 @@ const boxesBodySchema = object$1({
30333
30381
  sections: boxesSchema.optional(),
30334
30382
  expectedSections: boxesSchema.optional()
30335
30383
  });
30336
- const STATUS$5 = {
30384
+ const STATUS$6 = {
30337
30385
  usage: 400,
30338
30386
  "invalid-name": 400,
30339
30387
  "project-required": 400,
@@ -30396,7 +30444,7 @@ function apiRoutes(root, actions, look, history) {
30396
30444
  code: error.code,
30397
30445
  message: error.message
30398
30446
  }
30399
- }, STATUS$5[error.code] ?? 500);
30447
+ }, STATUS$6[error.code] ?? 500);
30400
30448
  }
30401
30449
  return c.json({
30402
30450
  ok: true,
@@ -30467,7 +30515,7 @@ function apiRoutes(root, actions, look, history) {
30467
30515
  message: error.message,
30468
30516
  details: error.details
30469
30517
  }
30470
- }, STATUS$5[error.code] ?? 500);
30518
+ }, STATUS$6[error.code] ?? 500);
30471
30519
  }
30472
30520
  });
30473
30521
  return app;
@@ -30595,11 +30643,134 @@ function assetKind(name) {
30595
30643
  function isAcceptedUpload(name) {
30596
30644
  return extensionOf(name) in ACCEPTED;
30597
30645
  }
30646
+ // src/shared/records/sourcing.ts
30647
+ /** So `house.jpg` carries its license in `house.jpg.license.json` beside it. */
30648
+ const LICENSE_FILE_SUFFIX = ".license.json";
30649
+ const IMAGE_PROVIDERS = ["fal", "google"];
30650
+ /** One image a search found, numbered from 1 in the order the source ranked it. */
30651
+ const imageResultSchema = object$1({
30652
+ number: int$1().min(1),
30653
+ /** The source's own id, which `--save` takes in place of the number. */
30654
+ id: string$1(),
30655
+ title: string$1().nullable(),
30656
+ creator: string$1().nullable(),
30657
+ creatorUrl: string$1().nullable(),
30658
+ license: string$1(),
30659
+ licenseVersion: string$1().nullable(),
30660
+ licenseUrl: string$1().nullable(),
30661
+ attribution: string$1().nullable(),
30662
+ landingUrl: string$1().nullable(),
30663
+ url: string$1(),
30664
+ thumbnail: string$1().nullable(),
30665
+ width: int$1().nullable(),
30666
+ height: int$1().nullable()
30667
+ });
30668
+ /** What `image find` answers without `--save`, writing nothing. */
30669
+ const imageFindSchema = object$1({
30670
+ version: literal(1),
30671
+ query: string$1(),
30672
+ licenses: array$1(string$1()),
30673
+ results: array$1(imageResultSchema)
30674
+ });
30675
+ /** The `<file>.license.json` beside every saved image, saying where it came from. */
30676
+ const licenseFileSchema = discriminatedUnion("origin", [object$1({
30677
+ version: literal(1),
30678
+ origin: literal("found"),
30679
+ source: literal("openverse"),
30680
+ id: string$1(),
30681
+ /** The search that found it, null when it was saved by id. */
30682
+ query: string$1().nullable(),
30683
+ title: string$1().nullable(),
30684
+ creator: string$1().nullable(),
30685
+ creatorUrl: string$1().nullable(),
30686
+ license: string$1(),
30687
+ licenseVersion: string$1().nullable(),
30688
+ licenseUrl: string$1().nullable(),
30689
+ attribution: string$1().nullable(),
30690
+ landingUrl: string$1().nullable(),
30691
+ url: string$1(),
30692
+ /** ISO 8601. */
30693
+ savedAt: string$1()
30694
+ }), object$1({
30695
+ version: literal(1),
30696
+ origin: literal("generated"),
30697
+ provider: _enum$1(IMAGE_PROVIDERS),
30698
+ model: string$1(),
30699
+ prompt: string$1(),
30700
+ width: int$1(),
30701
+ height: int$1(),
30702
+ /** The price estimated before the call, in US dollars. */
30703
+ priceUsd: number(),
30704
+ savedAt: string$1()
30705
+ })]);
30706
+ /** An image saved into a project's `assets/`, with the license file written beside it. */
30707
+ const savedImageSchema = object$1({
30708
+ version: literal(1),
30709
+ project: string$1(),
30710
+ /** Relative to the project's `assets/`, the name the image landed under. */
30711
+ path: string$1(),
30712
+ licensePath: string$1(),
30713
+ license: licenseFileSchema
30714
+ });
30715
+ /** What `image generate` answers, with `saved` null on a dry run. */
30716
+ const imageGenerateSchema = object$1({
30717
+ version: literal(1),
30718
+ provider: _enum$1(IMAGE_PROVIDERS),
30719
+ model: string$1(),
30720
+ prompt: string$1(),
30721
+ /** The size the provider produces, which may round the size asked for. */
30722
+ width: int$1(),
30723
+ height: int$1(),
30724
+ priceUsd: number(),
30725
+ dryRun: boolean$1(),
30726
+ saved: savedImageSchema.nullable()
30727
+ });
30728
+ object$1({
30729
+ version: literal(1),
30730
+ /** Whether the board may generate at all, false while generating from a tab is switched off. */
30731
+ enabled: boolean$1(),
30732
+ /** The first provider whose key is set, null when none is. */
30733
+ provider: object$1({
30734
+ name: _enum$1(IMAGE_PROVIDERS),
30735
+ model: string$1(),
30736
+ /** The environment variable its key is read from. */
30737
+ key: string$1(),
30738
+ width: int$1(),
30739
+ height: int$1(),
30740
+ priceUsd: number()
30741
+ }).nullable(),
30742
+ /** Every provider's key variable, in the order generation tries them. */
30743
+ keys: array$1(string$1())
30744
+ });
30745
+ /** What `image doctor` answers, naming each key as set or unset and never its value. */
30746
+ const imageDoctorSchema = object$1({
30747
+ version: literal(1),
30748
+ /** The first GPU `nvidia-smi` reports, null when it is absent or fails. */
30749
+ gpu: object$1({
30750
+ name: string$1(),
30751
+ memoryMiB: int$1()
30752
+ }).nullable(),
30753
+ /** The ComfyUI server at `FRAMEBOARD_COMFYUI_URL`, or the default address. */
30754
+ local: object$1({
30755
+ url: string$1(),
30756
+ running: boolean$1()
30757
+ }),
30758
+ /** Each provider key by its environment variable, true when set and not empty. */
30759
+ keys: record(string$1(), boolean$1()),
30760
+ providers: array$1(object$1({
30761
+ provider: _enum$1(IMAGE_PROVIDERS),
30762
+ model: string$1(),
30763
+ key: string$1(),
30764
+ ready: boolean$1()
30765
+ })),
30766
+ /** The provider `image generate` would run on now, null when none is ready. */
30767
+ provider: _enum$1(IMAGE_PROVIDERS).nullable()
30768
+ });
30598
30769
  // src/server/board/assets.ts
30599
30770
  /**
30600
30771
  * Every file under a project's `assets/` by relative path, skipping dot-named
30601
- * paths, lock and temp files, and any file whose real path leaves the folder.
30602
- * A folder that does not exist lists as empty.
30772
+ * paths, lock, temp, and license files, and any file whose real path leaves
30773
+ * the folder. A folder that does not exist lists as empty.
30603
30774
  */
30604
30775
  async function listAssets(projectDir) {
30605
30776
  const folder = join(projectDir, ASSETS_FOLDER);
@@ -30629,6 +30800,7 @@ async function walk(folder, prefix, real, into) {
30629
30800
  await walk(path, `${prefix}${name}/`, real, into);
30630
30801
  continue;
30631
30802
  }
30803
+ if (name.endsWith(".license.json")) continue;
30632
30804
  let target;
30633
30805
  let size;
30634
30806
  try {
@@ -30866,7 +31038,7 @@ function checkRoutes(access, checks) {
30866
31038
  }
30867
31039
  // src/server/routes/envelope.ts
30868
31040
  /** The status each refusal of a structure or history write answers with. */
30869
- const STATUS$4 = {
31041
+ const STATUS$5 = {
30870
31042
  usage: 400,
30871
31043
  "invalid-name": 400,
30872
31044
  "project-required": 400,
@@ -30904,7 +31076,7 @@ function answerRefusal(error, c) {
30904
31076
  message: error.message,
30905
31077
  details: error.details
30906
31078
  }
30907
- }, STATUS$4[error.code] ?? 500);
31079
+ }, STATUS$5[error.code] ?? 500);
30908
31080
  }
30909
31081
  /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
30910
31082
  async function parseBody$1(request, schema) {
@@ -31019,7 +31191,7 @@ function processHost() {
31019
31191
  };
31020
31192
  }
31021
31193
  // src/server/routes/clipboard.ts
31022
- const STATUS$3 = {
31194
+ const STATUS$4 = {
31023
31195
  usage: 400,
31024
31196
  "project-required": 400,
31025
31197
  "project-not-found": 404,
@@ -31053,7 +31225,7 @@ function clipboardRoutes(root, access, render, clipboard) {
31053
31225
  message: error.message,
31054
31226
  details: error.details
31055
31227
  }
31056
- }, STATUS$3[error.code] ?? 500);
31228
+ }, STATUS$4[error.code] ?? 500);
31057
31229
  });
31058
31230
  app.use("/api/frames/clipboard", requireWriter(access));
31059
31231
  app.post("/api/frames/clipboard", async (c) => {
@@ -36896,10 +37068,11 @@ function escapeText(value) {
36896
37068
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
36897
37069
  }
36898
37070
  /**
36899
- * Replaces a text-only element's text, refusing unless its source is exactly
36900
- * one text node, since misnesting can put its end tag past another's markup.
37071
+ * Replaces a text-only element's text, or only the text node `run` names,
37072
+ * refusing source that does not tile, since misnesting can put an end tag
37073
+ * past another's markup.
36901
37074
  */
36902
- function setText(source, element, value) {
37075
+ function setText(source, element, value, run) {
36903
37076
  const tag = element.tagName;
36904
37077
  const location = element.sourceCodeLocation;
36905
37078
  if (RAW_TEXT.has(tag)) return {
@@ -36916,15 +37089,46 @@ function setText(source, element, value) {
36916
37089
  };
36917
37090
  const from = location.startTag.endOffset;
36918
37091
  const to = location.endTag.startOffset;
37092
+ if (run !== void 0) return setRun(source, element, value, run, from, to);
36919
37093
  const [only, ...rest] = element.childNodes;
36920
37094
  if (!(only === void 0 ? from === to : rest.length === 0 && only.nodeName === "#text" && only.sourceCodeLocation?.startOffset === from && only.sourceCodeLocation.endOffset === to)) return {
36921
37095
  ok: false,
36922
37096
  detail: `<${tag}> holds more than one text node`
36923
37097
  };
36924
- const written = LEADING_NEWLINE_DROPPED.has(tag) && value.startsWith("\n") ? `\n${value}` : value;
36925
37098
  return {
36926
37099
  ok: true,
36927
- html: source.slice(0, from) + escapeText(written) + source.slice(to)
37100
+ html: source.slice(0, from) + escapeText(guarded(tag, value)) + source.slice(to)
37101
+ };
37102
+ }
37103
+ /** A value starting right after the start tag, its leading newline doubled where the parser drops one. */
37104
+ function guarded(tag, value) {
37105
+ return LEADING_NEWLINE_DROPPED.has(tag) && value.startsWith("\n") ? `\n${value}` : value;
37106
+ }
37107
+ /**
37108
+ * Splices one text node's source span, refusing one whose span leaves the
37109
+ * element's content or overlaps a sibling, since its bytes would not tile.
37110
+ */
37111
+ function setRun(source, element, value, run, from, to) {
37112
+ const tag = element.tagName;
37113
+ const nodes = element.childNodes;
37114
+ const at = nodes.filter((node) => node.nodeName === "#text")[run];
37115
+ if (!at) return {
37116
+ ok: false,
37117
+ detail: `<${tag}> holds no text run ${run}`
37118
+ };
37119
+ const position = nodes.indexOf(at);
37120
+ const start = at.sourceCodeLocation?.startOffset;
37121
+ const end = at.sourceCodeLocation?.endOffset;
37122
+ const previous = nodes[position - 1]?.sourceCodeLocation?.endOffset ?? from;
37123
+ const next = nodes[position + 1]?.sourceCodeLocation?.startOffset ?? to;
37124
+ if (start === void 0 || end === void 0 || start < previous || end > next || start < from || end > to) return {
37125
+ ok: false,
37126
+ detail: `<${tag}>'s text run ${run} does not tile its source`
37127
+ };
37128
+ const written = start === from ? guarded(tag, value) : value;
37129
+ return {
37130
+ ok: true,
37131
+ html: source.slice(0, start) + escapeText(written) + source.slice(end)
36928
37132
  };
36929
37133
  }
36930
37134
  // src/server/edit/apply.ts
@@ -36966,6 +37170,7 @@ function checkChange(change) {
36966
37170
  const invalid = checkValue(change.value);
36967
37171
  if (invalid) return invalid;
36968
37172
  }
37173
+ if (change.kind === "text" && change.run !== void 0 && !(Number.isInteger(change.run) && change.run >= 0)) return refuse$2("invalid-edit", `${change.run} names no text run`);
36969
37174
  if (change.kind === "attribute") {
36970
37175
  if (!ATTRIBUTE_NAME.test(change.name)) return refuse$2("invalid-edit", `${change.name} is not an attribute name`);
36971
37176
  if (change.name.toLowerCase() === "style") return refuse$2("invalid-edit", "style is edited one declaration at a time, as a style edit");
@@ -36989,7 +37194,7 @@ function editedAttribute(change) {
36989
37194
  }
36990
37195
  function write(source, element, change) {
36991
37196
  if (change.kind === "text") {
36992
- const written = setText(source, element, change.value);
37197
+ const written = setText(source, element, change.value, change.run);
36993
37198
  return written.ok ? written : refuse$2("not-text-only", written.detail);
36994
37199
  }
36995
37200
  if (change.kind === "attribute") {
@@ -37032,7 +37237,12 @@ function changesOnlyTarget(before, after, index, change) {
37032
37237
  const now = after.elements[index];
37033
37238
  if (!was || !now || was.tagName !== now.tagName) return false;
37034
37239
  const name = editedAttribute(change);
37035
- if (name === void 0) was.childNodes = now.childNodes;
37240
+ if (change.kind === "text" && change.run !== void 0) {
37241
+ const run = textNodes(was)[change.run];
37242
+ const written = textNodes(now)[change.run];
37243
+ if (!run) return false;
37244
+ was.childNodes = change.value === "" ? was.childNodes.filter((node) => node !== run) : was.childNodes.map((node) => node === run && written ? written : node);
37245
+ } else if (name === void 0) was.childNodes = now.childNodes;
37036
37246
  else {
37037
37247
  const written = now.attrs.find((attribute) => isNamed(attribute, name));
37038
37248
  const others = was.attrs.filter((attribute) => !isNamed(attribute, name));
@@ -37041,11 +37251,15 @@ function changesOnlyTarget(before, after, index, change) {
37041
37251
  }
37042
37252
  return serialize$1(before.document) === serialize$1(after.document);
37043
37253
  }
37254
+ function textNodes(element) {
37255
+ return element.childNodes.filter((node) => node.nodeName === "#text");
37256
+ }
37044
37257
  function textOf(element) {
37045
- return element.childNodes.map((node) => "value" in node && node.nodeName === "#text" ? node.value : "").join("");
37258
+ return textNodes(element).map((node) => node.value).join("");
37046
37259
  }
37047
37260
  /** Whether the target holds the value the change asked for. */
37048
37261
  function holdsValue(element, change) {
37262
+ if (change.kind === "text" && change.run !== void 0) return change.value === "" || textNodes(element)[change.run]?.value === change.value;
37049
37263
  if (change.kind === "text") return textOf(element) === change.value;
37050
37264
  if (change.kind === "attribute") {
37051
37265
  const stated = element.attrs.find((attribute) => isNamed(attribute, change.name));
@@ -39016,7 +39230,7 @@ function filed(file, filing) {
39016
39230
  }
39017
39231
  /** The hand-written keys a project file holds, leaving out the ones it lacks. */
39018
39232
  function filingOf(file) {
39019
- const off = isRecord$3(file.checks) ? file.checks.off : void 0;
39233
+ const off = isRecord$5(file.checks) ? file.checks.off : void 0;
39020
39234
  return {
39021
39235
  ...file.group === void 0 ? {} : { group: file.group },
39022
39236
  ...file.archived === void 0 ? {} : { archived: file.archived },
@@ -39039,7 +39253,7 @@ async function setProjectRule(root, name, rule, off, { journal } = {}) {
39039
39253
  ...projectSpec,
39040
39254
  empty: emptyProject
39041
39255
  });
39042
- if (file.checks !== void 0 && !isRecord$3(file.checks)) throw new FrameboardError("project-file-invalid", `${project.name}/${PROJECT_FILE} holds a checks value that is not an object. Make it an object and turn the rule off again.`, { project: project.name });
39256
+ if (file.checks !== void 0 && !isRecord$5(file.checks)) throw new FrameboardError("project-file-invalid", `${project.name}/${PROJECT_FILE} holds a checks value that is not an object. Make it an object and turn the rule off again.`, { project: project.name });
39043
39257
  const stored = filingOf(file).off;
39044
39258
  const list = isRuleList(stored) ? stored : [];
39045
39259
  const next = off ? list.includes(rule) ? list : [...list, rule] : list.filter((each) => each !== rule);
@@ -39060,8 +39274,8 @@ async function setProjectRule(root, name, rule, off, { journal } = {}) {
39060
39274
  * off and on leaves no empty object.
39061
39275
  */
39062
39276
  function withOff(file, off) {
39063
- if (off === void 0 && !(isRecord$3(file.checks) && file.checks.off !== void 0)) return file;
39064
- const { off: _off, ...kept } = isRecord$3(file.checks) ? file.checks : {};
39277
+ if (off === void 0 && !(isRecord$5(file.checks) && file.checks.off !== void 0)) return file;
39278
+ const { off: _off, ...kept } = isRecord$5(file.checks) ? file.checks : {};
39065
39279
  const checks = off === void 0 ? kept : {
39066
39280
  ...kept,
39067
39281
  off
@@ -39076,7 +39290,7 @@ function withOff(file, off) {
39076
39290
  function isRuleList(value) {
39077
39291
  return Array.isArray(value) && value.every((each) => typeof each === "string");
39078
39292
  }
39079
- function isRecord$3(value) {
39293
+ function isRecord$5(value) {
39080
39294
  return typeof value === "object" && value !== null && !Array.isArray(value);
39081
39295
  }
39082
39296
  /**
@@ -40336,7 +40550,8 @@ const changeSchema = union([
40336
40550
  }),
40337
40551
  object$1({
40338
40552
  kind: literal("text"),
40339
- value
40553
+ value,
40554
+ run: int$1().min(0).optional()
40340
40555
  }),
40341
40556
  object$1({
40342
40557
  kind: literal("styles"),
@@ -41028,7 +41243,7 @@ const selectionResultSchema = object$1({
41028
41243
  tabs: int$1().min(0)
41029
41244
  });
41030
41245
  // src/server/routes/elements.ts
41031
- const STATUS$2 = {
41246
+ const STATUS$3 = {
41032
41247
  usage: 400,
41033
41248
  "project-required": 400,
41034
41249
  "project-not-found": 404,
@@ -41129,7 +41344,7 @@ function elementsRoutes(root, access, selection, tokens = null) {
41129
41344
  message: error.message,
41130
41345
  details: error.details
41131
41346
  }
41132
- }, STATUS$2[error.code] ?? 500);
41347
+ }, STATUS$3[error.code] ?? 500);
41133
41348
  });
41134
41349
  return app;
41135
41350
  }
@@ -41632,13 +41847,17 @@ const BOM = [
41632
41847
  * itself, so the one injected element a live frame keeps is the stylesheet.
41633
41848
  */
41634
41849
  const THEME_SCRIPT = `(function(s,t){if(t==='light'||t==='dark')(${setFrameTheme.toString()})(document.documentElement,t);s.remove()})(document.currentScript,new URLSearchParams(location.search).get(${JSON.stringify(THEME_QUERY)}))`;
41850
+ /** Where the look route serves the frame bridge's script, under the running release. */
41851
+ const BRIDGE_URL = `/frameboard/bridge/v${version}/frame-bridge.js`;
41635
41852
  /**
41636
41853
  * The frame route's injected `head`, one stylesheet carrying `hash` as its one
41637
- * other attribute, since another element would shift every live index.
41854
+ * other attribute, since another element would shift every live index. Given
41855
+ * no `bridge`, as a kit preview's policy allows none, it loads no bridge.
41638
41856
  */
41639
- function frameHead(sheets, hash) {
41857
+ function frameHead(sheets, hash, bridge) {
41640
41858
  const imports = sheets.map((url) => `@import url(${JSON.stringify(url)});`);
41641
- return `<style ${LOOK_MARKER} ${RENDERED_HASH}="${hash}">${imports.join("")}</style><script ${LOOK_MARKER}>${THEME_SCRIPT}<\/script>`;
41859
+ const script = bridge === void 0 ? "" : `<script ${LOOK_MARKER} src=${JSON.stringify(bridge)}><\/script>`;
41860
+ return `<style ${LOOK_MARKER} ${RENDERED_HASH}="${hash}">${imports.join("")}</style><script ${LOOK_MARKER}>${THEME_SCRIPT}<\/script>${script}`;
41642
41861
  }
41643
41862
  /**
41644
41863
  * Splices `head` where the browser starts its `head`, keeping every byte of
@@ -41760,7 +41979,7 @@ function frameRoutes(root, look, version, base = "") {
41760
41979
  if (held === null) return c.notFound();
41761
41980
  bytes = new TextEncoder().encode(held);
41762
41981
  }
41763
- const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project), hasKit(root, project)).map((url) => `${base}${url}`), contentHash(bytes)));
41982
+ const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project), hasKit(root, project)).map((url) => `${base}${url}`), contentHash(bytes), `${base}${BRIDGE_URL}`));
41764
41983
  return c.body(body, 200, {
41765
41984
  "Content-Type": contentType,
41766
41985
  "Cache-Control": "no-store"
@@ -41847,7 +42066,7 @@ async function resolveFile(root, [project, page, ...rest]) {
41847
42066
  if (!project || !page) return null;
41848
42067
  const projectSheet = rest.length === 0 && page === "tokens.css";
41849
42068
  if (rest.length === 0 && !projectSheet) return null;
41850
- if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$2(rest[0] ?? ""))) return null;
42069
+ if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$4(rest[0] ?? ""))) return null;
41851
42070
  try {
41852
42071
  const projectDir = await realpath(join(root, project));
41853
42072
  if (!projectDir.startsWith(root + sep)) return null;
@@ -41867,9 +42086,9 @@ function servableInProject(segments) {
41867
42086
  if (segments.some((segment) => segment.startsWith("."))) return false;
41868
42087
  const [first = "", name = ""] = segments;
41869
42088
  if (segments.length === 1) return first === TOKEN_FILE;
41870
- return first === "assets" || !isRecord$2(name);
42089
+ return first === "assets" || !isRecord$4(name);
41871
42090
  }
41872
- function isRecord$2(name) {
42091
+ function isRecord$4(name) {
41873
42092
  return name === "layout.json" || name === NOTES_FILE$1;
41874
42093
  }
41875
42094
  // src/server/routes/kits.ts
@@ -41995,6 +42214,7 @@ const IMMUTABLE = "public, max-age=31536000, immutable";
41995
42214
  const RELEASE_SEGMENT = /^v\d+\.\d+\.\d+/;
41996
42215
  const CONTENT_TYPES = {
41997
42216
  ".css": "text/css; charset=utf-8",
42217
+ ".js": "text/javascript; charset=utf-8",
41998
42218
  ".woff2": "font/woff2"
41999
42219
  };
42000
42220
  /**
@@ -42030,6 +42250,14 @@ function lookRoutes({ facesDir, boardSheet }) {
42030
42250
  "Cache-Control": "no-store"
42031
42251
  });
42032
42252
  });
42253
+ app.get(BRIDGE_URL, async (c) => {
42254
+ const script = await bridgeScript();
42255
+ if (script === null) return c.notFound();
42256
+ return c.body(script, 200, {
42257
+ "Content-Type": CONTENT_TYPES[".js"] ?? "",
42258
+ "Cache-Control": fromSource ? "no-store" : IMMUTABLE
42259
+ });
42260
+ });
42033
42261
  app.get(`${FACES_URL}/*`, async (c) => {
42034
42262
  const segments = new URL(c.req.url).pathname.slice(18).split("/");
42035
42263
  const release = RELEASE_SEGMENT.test(segments[0] ?? "");
@@ -42058,6 +42286,34 @@ async function resolveFace(facesDir, segments) {
42058
42286
  return null;
42059
42287
  }
42060
42288
  }
42289
+ /** Whether this module runs from source, where no bundle sits beside it. */
42290
+ const fromSource = import.meta.url.endsWith(".ts");
42291
+ let bridge;
42292
+ /**
42293
+ * The frame bridge's script, read once from beside the bundle, or built from
42294
+ * source on a source run, so a dev server or a test serves the code as it
42295
+ * stands. A missing bundle answers null, and a failed build is tried again.
42296
+ */
42297
+ function bridgeScript() {
42298
+ bridge ??= fromSource ? buildBridge().catch((error) => {
42299
+ bridge = void 0;
42300
+ throw error;
42301
+ }) : readFile(fileURLToPath(new URL("./frame-bridge.js", import.meta.url)), "utf8").catch(() => null);
42302
+ return bridge;
42303
+ }
42304
+ /** Bundles the bridge the way `rolldown.config.ts` does, in memory. */
42305
+ async function buildBridge() {
42306
+ const { build } = await import("rolldown");
42307
+ const src = fileURLToPath(new URL("../..", import.meta.url));
42308
+ const { output } = await build({
42309
+ input: join(src, "frame-bridge", "main.ts"),
42310
+ platform: "browser",
42311
+ resolve: { alias: { "@": src } },
42312
+ write: false,
42313
+ output: { format: "iife" }
42314
+ });
42315
+ return output[0].code;
42316
+ }
42061
42317
  async function readOrNull(path) {
42062
42318
  try {
42063
42319
  return new Uint8Array(await readFile(path));
@@ -42142,7 +42398,7 @@ const IMAGE_CONTENT_TYPES = {
42142
42398
  * JPEG, GIF, and WebP. SVG is left out on purpose, since it can carry script
42143
42399
  * and the thumbnails render in the board's own page.
42144
42400
  */
42145
- function imageExtension(bytes) {
42401
+ function imageExtension$1(bytes) {
42146
42402
  const ascii = (from, to) => String.fromCharCode(...bytes.subarray(from, to));
42147
42403
  if (bytes[0] === 137 && ascii(1, 4) === "PNG") return "png";
42148
42404
  if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpg";
@@ -42157,7 +42413,7 @@ function imageExtension(bytes) {
42157
42413
  */
42158
42414
  async function saveImages(pageDir, images) {
42159
42415
  const typed = images.map((bytes, index) => {
42160
- const extension = imageExtension(bytes);
42416
+ const extension = imageExtension$1(bytes);
42161
42417
  if (extension === null) throw new FrameboardError("image-type-refused", "A note takes PNG, JPEG, GIF, or WebP images. Nothing was saved.", { index });
42162
42418
  return {
42163
42419
  bytes,
@@ -42196,7 +42452,7 @@ async function assertStored(pageDir, images) {
42196
42452
  if (missing.length > 0) throw new FrameboardError("usage", `The note names images its page does not hold: ${missing.join(", ")}. Upload each one first.`, { missing });
42197
42453
  }
42198
42454
  // src/server/routes/notes.ts
42199
- const STATUS$1 = {
42455
+ const STATUS$2 = {
42200
42456
  usage: 400,
42201
42457
  "project-required": 400,
42202
42458
  "project-not-found": 404,
@@ -42210,7 +42466,7 @@ const STATUS$1 = {
42210
42466
  "dispatch-failed": 502,
42211
42467
  "lock-timeout": 503
42212
42468
  };
42213
- const text = string$1().trim().min(1).max(1e5);
42469
+ const text$1 = string$1().trim().min(1).max(1e5);
42214
42470
  const session = string$1().min(1).max(256);
42215
42471
  /** Page-relative paths an upload answered, each checked against the page on write. */
42216
42472
  const images = array$1(string$1().max(256)).max(32).optional();
@@ -42223,7 +42479,7 @@ const oneAddressee = {
42223
42479
  const pinSchema = object$1({
42224
42480
  /** The frame ref, `<project>/<page>/<frame>`. */
42225
42481
  frame: string$1().min(1).max(1024),
42226
- text,
42482
+ text: text$1,
42227
42483
  images,
42228
42484
  /** The element's index, given with the `modifiedAt` the board rendered it at. */
42229
42485
  element: int$1().min(0).optional(),
@@ -42232,7 +42488,7 @@ const pinSchema = object$1({
42232
42488
  dispatch
42233
42489
  }).refine(oneAddressee.check, oneAddressee.message);
42234
42490
  const replySchema = object$1({
42235
- text,
42491
+ text: text$1,
42236
42492
  images,
42237
42493
  to: session.optional(),
42238
42494
  dispatch
@@ -42404,7 +42660,7 @@ function notesRoutes(root, access, delivery, dispatch, imageLimit = ASSET_BODY_L
42404
42660
  message: error.message,
42405
42661
  details: error.details
42406
42662
  }
42407
- }, STATUS$1[error.code] ?? 500);
42663
+ }, STATUS$2[error.code] ?? 500);
42408
42664
  });
42409
42665
  return app;
42410
42666
  }
@@ -42414,7 +42670,7 @@ async function parseBody(request, schema) {
42414
42670
  return parsed.data;
42415
42671
  }
42416
42672
  // src/server/routes/png.ts
42417
- const STATUS = {
42673
+ const STATUS$1 = {
42418
42674
  usage: 400,
42419
42675
  "project-required": 400,
42420
42676
  "project-not-found": 404,
@@ -42482,7 +42738,7 @@ function pngRoutes(root, render, renderFilmstrip) {
42482
42738
  message: error.message,
42483
42739
  details: error.details
42484
42740
  }
42485
- }, STATUS[error.code] ?? 500);
42741
+ }, STATUS$1[error.code] ?? 500);
42486
42742
  }
42487
42743
  });
42488
42744
  return app;
@@ -42612,6 +42868,711 @@ function previewRoutes(root, access, slot, { address = networkAddress } = {}) {
42612
42868
  });
42613
42869
  return app;
42614
42870
  }
42871
+ // src/server/sourcing/save.ts
42872
+ /** The most bytes one download takes, so a runaway response never fills memory. */
42873
+ const DOWNLOAD_LIMIT = 67108864;
42874
+ const IMAGE_TYPES = {
42875
+ "image/jpeg": "jpg",
42876
+ "image/png": "png",
42877
+ "image/webp": "webp",
42878
+ "image/avif": "avif",
42879
+ "image/gif": "gif",
42880
+ "image/svg+xml": "svg"
42881
+ };
42882
+ /**
42883
+ * The extension an image's media type names, else the one its URL ends in,
42884
+ * null when neither names an image a frame shows.
42885
+ */
42886
+ function imageExtension(mediaType, url) {
42887
+ const type = mediaType?.split(";")[0]?.trim().toLowerCase() ?? "";
42888
+ const fromType = IMAGE_TYPES[type];
42889
+ if (fromType !== void 0) return fromType;
42890
+ if (url === null) return null;
42891
+ const name = new URL(url).pathname.split("/").at(-1) ?? "";
42892
+ const kind = assetKind(name);
42893
+ return kind === "image" || kind === "gif" || kind === "svg" ? name.slice(name.lastIndexOf(".") + 1).toLowerCase() : null;
42894
+ }
42895
+ /**
42896
+ * Downloads a whole image into memory before anything is written, so a
42897
+ * download failing partway leaves no file. Refuses `source-failed` on a
42898
+ * failed request, a body past `limit`, or a file that is no image.
42899
+ */
42900
+ async function downloadImage(url, send, limit = DOWNLOAD_LIMIT) {
42901
+ const failed = (message, status) => new FrameboardError("source-failed", message, {
42902
+ url,
42903
+ status
42904
+ });
42905
+ let response;
42906
+ try {
42907
+ response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
42908
+ } catch (error) {
42909
+ throw failed(`The image did not download: ${error instanceof Error ? error.message : String(error)}`, null);
42910
+ }
42911
+ if (!response.ok) throw failed(`The image host answered ${response.status}.`, response.status);
42912
+ const extension = imageExtension(response.headers.get("content-type"), url);
42913
+ if (extension === null) throw failed("The download is not an image a frame shows.", response.status);
42914
+ let bytes;
42915
+ try {
42916
+ bytes = await readCapped(response, limit);
42917
+ } catch (error) {
42918
+ if (error instanceof FrameboardError) throw error;
42919
+ throw failed(`The image stopped downloading: ${error instanceof Error ? error.message : String(error)}`, response.status);
42920
+ }
42921
+ return {
42922
+ bytes,
42923
+ extension
42924
+ };
42925
+ }
42926
+ /** Reads the body chunk by chunk and stops once it passes `limit`, whatever length the host declared. */
42927
+ async function readCapped(response, limit) {
42928
+ if (Number(response.headers.get("content-length") ?? NaN) > limit) throw tooLarge(limit);
42929
+ const chunks = [];
42930
+ let total = 0;
42931
+ const reader = response.body?.getReader();
42932
+ for (let chunk = await reader?.read(); chunk && !chunk.done;) {
42933
+ total += chunk.value.byteLength;
42934
+ if (total > limit) {
42935
+ await reader?.cancel();
42936
+ throw tooLarge(limit);
42937
+ }
42938
+ chunks.push(chunk.value);
42939
+ chunk = await reader?.read();
42940
+ }
42941
+ const bytes = new Uint8Array(total);
42942
+ let offset = 0;
42943
+ for (const chunk of chunks) {
42944
+ bytes.set(chunk, offset);
42945
+ offset += chunk.byteLength;
42946
+ }
42947
+ return bytes;
42948
+ }
42949
+ function tooLarge(limit) {
42950
+ return new FrameboardError("source-failed", `The image is past ${limit / 1024 / 1024} MiB.`, { limit });
42951
+ }
42952
+ /**
42953
+ * The stem a saved file takes: `--name` when given, else the query or prompt
42954
+ * as a lowercase dashed name, else `image`. Refuses `invalid-name` for a
42955
+ * `--name` breaking the board name rule.
42956
+ */
42957
+ function savedStem(name, text) {
42958
+ if (name === void 0) return folderName(text) || "image";
42959
+ if (!isValidName(name)) throw new FrameboardError("invalid-name", `--name ${name} breaks the board's name rule, ${NAME_PATTERN.source}.`, { name });
42960
+ return name;
42961
+ }
42962
+ /**
42963
+ * Writes the image into the project's `assets/` under the first free name
42964
+ * from the stem, then its license file as `<landed name>.license.json`. A
42965
+ * license file that fails to land takes the image back out.
42966
+ */
42967
+ async function saveImage(project, stem, image, license) {
42968
+ const { added, refused } = await addAssets(project.path, [{
42969
+ name: `${stem}.${image.extension}`,
42970
+ bytes: image.bytes
42971
+ }]);
42972
+ const landed = added[0];
42973
+ if (landed === void 0) throw new FrameboardError("asset-type-refused", refused[0]?.message ?? "The image was refused.");
42974
+ const folder = join(project.path, ASSETS_FOLDER);
42975
+ const licensePath = `${landed.path}${LICENSE_FILE_SUFFIX}`;
42976
+ const temp = join(folder, `${randomBytes(6).toString("hex")}${TEMP_SUFFIX}`);
42977
+ try {
42978
+ await writeFile(temp, `${JSON.stringify(license, null, 2)}\n`, { flag: "wx" });
42979
+ await rename(temp, join(folder, licensePath));
42980
+ } catch (error) {
42981
+ await Promise.all([rm(temp, { force: true }), rm(join(folder, landed.path), { force: true })]);
42982
+ throw error;
42983
+ }
42984
+ return {
42985
+ version: 1,
42986
+ project: project.name,
42987
+ path: landed.path,
42988
+ licensePath,
42989
+ license
42990
+ };
42991
+ }
42992
+ // src/server/sourcing/providers/provider.ts
42993
+ /**
42994
+ * The refusal a provider's failure answers, with its status and its own
42995
+ * message, the key scrubbed from that message should the provider echo it.
42996
+ */
42997
+ function providerFailed(provider, status, reason, key) {
42998
+ const scrubbed = reason.split(key).join("***").slice(0, 300);
42999
+ return new FrameboardError("provider-failed", `${provider} ${status === null ? "did not answer" : `answered ${status}`}: ${scrubbed}`, {
43000
+ provider,
43001
+ status
43002
+ });
43003
+ }
43004
+ /** A dollar amount rounded up to a hundredth of a cent, so an estimate never reads low. */
43005
+ function roundPrice(usd) {
43006
+ return Math.ceil(usd * 1e4 - 1e-9) / 1e4;
43007
+ }
43008
+ // src/server/sourcing/providers/fal.ts
43009
+ /** fal's synchronous run endpoint for FLUX.1 schnell. */
43010
+ const FAL_ENDPOINT = "https://fal.run/fal-ai/flux/schnell";
43011
+ /** fal's published price for FLUX.1 schnell, per megapixel of output. */
43012
+ const FAL_PRICE_PER_MEGAPIXEL = .003;
43013
+ /** FLUX.1 schnell on fal, which takes any width and height as asked. */
43014
+ const fal = {
43015
+ name: "fal",
43016
+ model: "fal-ai/flux/schnell",
43017
+ keyEnv: "FAL_KEY",
43018
+ sizeFor: (asked) => asked,
43019
+ priceFor: ({ width, height }) => roundPrice(width * height / 1e6 * FAL_PRICE_PER_MEGAPIXEL),
43020
+ async generate({ prompt, size, key }, send) {
43021
+ let response;
43022
+ try {
43023
+ response = await send(FAL_ENDPOINT, {
43024
+ method: "POST",
43025
+ headers: {
43026
+ Authorization: `Key ${key}`,
43027
+ "Content-Type": "application/json"
43028
+ },
43029
+ body: JSON.stringify({
43030
+ prompt,
43031
+ image_size: size,
43032
+ num_images: 1,
43033
+ output_format: "jpeg",
43034
+ sync_mode: true
43035
+ })
43036
+ });
43037
+ } catch (error) {
43038
+ throw providerFailed("fal", null, String(error), key);
43039
+ }
43040
+ const body = await response.json().catch(() => null);
43041
+ if (!response.ok) throw providerFailed("fal", response.status, detailOf(body), key);
43042
+ const url = firstImageUrl(body);
43043
+ const image = url === null ? null : await fetchImage(url, send);
43044
+ if (image === null) throw providerFailed("fal", response.status, "no image came back", key);
43045
+ return image;
43046
+ }
43047
+ };
43048
+ function firstImageUrl(body) {
43049
+ if (typeof body !== "object" || body === null || !("images" in body)) return null;
43050
+ const [first] = Array.isArray(body.images) ? body.images : [];
43051
+ return typeof first === "object" && first !== null && "url" in first && typeof first.url === "string" ? first.url : null;
43052
+ }
43053
+ /** The image a data URI holds, or the one a hosted URL serves, null when neither is an image. */
43054
+ async function fetchImage(url, send) {
43055
+ const data = /^data:([^;,]+)(;base64)?,(.*)$/s.exec(url);
43056
+ if (data) {
43057
+ const extension = imageExtension(data[1] ?? null, null);
43058
+ if (extension === null || data[2] === void 0) return null;
43059
+ return {
43060
+ bytes: new Uint8Array(Buffer.from(data[3] ?? "", "base64")),
43061
+ extension
43062
+ };
43063
+ }
43064
+ const response = await send(url).catch(() => null);
43065
+ if (!response?.ok) return null;
43066
+ const extension = imageExtension(response.headers.get("content-type"), url);
43067
+ if (extension === null) return null;
43068
+ return {
43069
+ bytes: new Uint8Array(await response.arrayBuffer()),
43070
+ extension
43071
+ };
43072
+ }
43073
+ function detailOf(body) {
43074
+ if (typeof body === "object" && body !== null && "detail" in body) return typeof body.detail === "string" ? body.detail : JSON.stringify(body.detail);
43075
+ return "the request was refused";
43076
+ }
43077
+ // src/server/sourcing/providers/google.ts
43078
+ /** The Gemini API's Interactions endpoint, the one its image guide calls. */
43079
+ const GOOGLE_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/interactions";
43080
+ /** The API revision the request shape below was written against. */
43081
+ const GOOGLE_API_REVISION = "2026-05-20";
43082
+ /** Google's published price for one 1K image from Nano Banana 2.1. */
43083
+ const GOOGLE_PRICE_1K = .0336;
43084
+ /** Each aspect ratio Nano Banana 2.1 takes, with the size it draws at 1K. */
43085
+ const ASPECT_RATIOS = {
43086
+ "1:1": {
43087
+ width: 1024,
43088
+ height: 1024
43089
+ },
43090
+ "1:4": {
43091
+ width: 512,
43092
+ height: 2048
43093
+ },
43094
+ "1:8": {
43095
+ width: 384,
43096
+ height: 3072
43097
+ },
43098
+ "2:3": {
43099
+ width: 848,
43100
+ height: 1264
43101
+ },
43102
+ "3:2": {
43103
+ width: 1264,
43104
+ height: 848
43105
+ },
43106
+ "3:4": {
43107
+ width: 896,
43108
+ height: 1200
43109
+ },
43110
+ "4:1": {
43111
+ width: 2048,
43112
+ height: 512
43113
+ },
43114
+ "4:3": {
43115
+ width: 1200,
43116
+ height: 896
43117
+ },
43118
+ "4:5": {
43119
+ width: 928,
43120
+ height: 1152
43121
+ },
43122
+ "5:4": {
43123
+ width: 1152,
43124
+ height: 928
43125
+ },
43126
+ "8:1": {
43127
+ width: 3072,
43128
+ height: 384
43129
+ },
43130
+ "9:16": {
43131
+ width: 768,
43132
+ height: 1376
43133
+ },
43134
+ "16:9": {
43135
+ width: 1376,
43136
+ height: 768
43137
+ },
43138
+ "21:9": {
43139
+ width: 1584,
43140
+ height: 672
43141
+ }
43142
+ };
43143
+ /** The aspect ratio nearest the size asked, compared on a log scale so tall and wide weigh alike. */
43144
+ function aspectRatioFor({ width, height }) {
43145
+ const asked = Math.log(width / height);
43146
+ let best = "1:1";
43147
+ let distance = Number.POSITIVE_INFINITY;
43148
+ for (const [ratio, size] of Object.entries(ASPECT_RATIOS)) {
43149
+ const gap = Math.abs(Math.log(size.width / size.height) - asked);
43150
+ if (gap < distance) {
43151
+ best = ratio;
43152
+ distance = gap;
43153
+ }
43154
+ }
43155
+ return best;
43156
+ }
43157
+ /** Nano Banana 2.1 at 1K, at the aspect ratio nearest the size asked. */
43158
+ const google = {
43159
+ name: "google",
43160
+ model: "gemini-nano-banana-2.1",
43161
+ keyEnv: "GEMINI_API_KEY",
43162
+ sizeFor: (asked) => ASPECT_RATIOS[aspectRatioFor(asked)] ?? asked,
43163
+ priceFor: () => GOOGLE_PRICE_1K,
43164
+ async generate({ prompt, size, key }, send) {
43165
+ let response;
43166
+ try {
43167
+ response = await send(GOOGLE_ENDPOINT, {
43168
+ method: "POST",
43169
+ headers: {
43170
+ "x-goog-api-key": key,
43171
+ "Content-Type": "application/json",
43172
+ "Api-Revision": GOOGLE_API_REVISION
43173
+ },
43174
+ body: JSON.stringify({
43175
+ model: google.model,
43176
+ input: [{
43177
+ type: "text",
43178
+ text: prompt
43179
+ }],
43180
+ response_format: {
43181
+ type: "image",
43182
+ mime_type: "image/jpeg",
43183
+ aspect_ratio: aspectRatioFor(size),
43184
+ image_size: "1K"
43185
+ }
43186
+ })
43187
+ });
43188
+ } catch (error) {
43189
+ throw providerFailed("google", null, String(error), key);
43190
+ }
43191
+ const body = await response.json().catch(() => null);
43192
+ if (!response.ok) throw providerFailed("google", response.status, messageOf(body), key);
43193
+ const image = imageOf(body);
43194
+ const extension = imageExtension(image?.mimeType ?? "image/jpeg", null);
43195
+ if (image === null || extension === null) throw providerFailed("google", response.status, "no image came back", key);
43196
+ return {
43197
+ bytes: new Uint8Array(Buffer.from(image.data, "base64")),
43198
+ extension
43199
+ };
43200
+ }
43201
+ };
43202
+ /** The first image the interaction output, from `output_image` or else its model output steps. */
43203
+ function imageOf(body) {
43204
+ if (!isRecord$3(body)) return null;
43205
+ const blocks = [body.output_image];
43206
+ for (const step of Array.isArray(body.steps) ? body.steps : []) if (isRecord$3(step) && step.type === "model_output") blocks.push(...Array.isArray(step.content) ? step.content : []);
43207
+ for (const block of blocks) {
43208
+ if (!isRecord$3(block) || typeof block.data !== "string") continue;
43209
+ if (block.type !== void 0 && block.type !== "image") continue;
43210
+ return {
43211
+ data: block.data,
43212
+ mimeType: typeof block.mime_type === "string" ? block.mime_type : null
43213
+ };
43214
+ }
43215
+ return null;
43216
+ }
43217
+ function messageOf(body) {
43218
+ if (isRecord$3(body) && isRecord$3(body.error)) return typeof body.error.message === "string" ? body.error.message : "the request was refused";
43219
+ return "the request was refused";
43220
+ }
43221
+ function isRecord$3(value) {
43222
+ return typeof value === "object" && value !== null;
43223
+ }
43224
+ // src/server/sourcing/generate.ts
43225
+ /** Every provider in the order `image generate` tries them. */
43226
+ const PROVIDERS = [fal, google];
43227
+ /** A provider's key, null when unset or empty, so an empty string never reaches a request. */
43228
+ function keyOf(provider, env) {
43229
+ const key = env[provider.keyEnv]?.trim();
43230
+ return key === void 0 || key === "" ? null : key;
43231
+ }
43232
+ /**
43233
+ * The provider a generation runs on, the one named or else the first whose
43234
+ * key is set, with the size it produces and its price. Makes no request.
43235
+ * Refuses `no-provider` when none is ready, and `usage` for an unknown name.
43236
+ */
43237
+ function planGeneration(request, env) {
43238
+ const candidates = request.provider === void 0 ? PROVIDERS : PROVIDERS.filter((each) => each.name === request.provider);
43239
+ if (candidates.length === 0) throw new FrameboardError("usage", `--provider ${request.provider} is not one of ${IMAGE_PROVIDERS.join(", ")}.`, { providers: [...IMAGE_PROVIDERS] });
43240
+ for (const provider of candidates) {
43241
+ const key = keyOf(provider, env);
43242
+ if (key === null) continue;
43243
+ const size = provider.sizeFor(request.size);
43244
+ return {
43245
+ provider,
43246
+ prompt: request.prompt,
43247
+ size,
43248
+ priceUsd: provider.priceFor(size),
43249
+ key
43250
+ };
43251
+ }
43252
+ const keys = candidates.map((each) => each.keyEnv);
43253
+ throw new FrameboardError("no-provider", `No image provider is ready. Set ${keys.join(" or ")} in the environment.`, { keys });
43254
+ }
43255
+ /** Runs a planned call, the one point a generation spends. */
43256
+ function generateImage(plan, send) {
43257
+ return plan.provider.generate({
43258
+ prompt: plan.prompt,
43259
+ size: plan.size,
43260
+ key: plan.key
43261
+ }, send);
43262
+ }
43263
+ // src/server/sourcing/openverse.ts
43264
+ const OPENVERSE_API = "https://api.openverse.org/v1/images/";
43265
+ /** Public domain alone, so a saved image owes nobody credit. */
43266
+ const DEFAULT_LICENSES = ["cc0", "pdm"];
43267
+ /** `--credited` adds the licenses that ask only for credit, never a share-alike or non-commercial one. */
43268
+ const CREDITED_LICENSES = [...DEFAULT_LICENSES, "by"];
43269
+ function licensesFor({ credited }) {
43270
+ return [...credited ? CREDITED_LICENSES : DEFAULT_LICENSES];
43271
+ }
43272
+ /**
43273
+ * One page of Openverse results for the query, numbered from 1 in the order
43274
+ * Openverse ranked them, empty when nothing matched. A refusal or a failed
43275
+ * request throws `source-failed` with the status in the details.
43276
+ */
43277
+ async function searchImages(query, options, send) {
43278
+ const url = new URL(OPENVERSE_API);
43279
+ url.searchParams.set("q", query);
43280
+ url.searchParams.set("license", licensesFor(options).join(","));
43281
+ url.searchParams.set("page_size", String(20));
43282
+ const body = await request(url, send);
43283
+ return (isRecord$2(body) && Array.isArray(body.results) ? body.results : []).map(toImage).filter((image) => image !== null).map((image, index) => ({
43284
+ number: index + 1,
43285
+ ...image
43286
+ }));
43287
+ }
43288
+ /**
43289
+ * One image by its Openverse id, refusing `result-not-found` for an id
43290
+ * Openverse does not hold or one under a license the options do not allow.
43291
+ */
43292
+ async function imageById(id, options, send) {
43293
+ const missing = (reason) => new FrameboardError("result-not-found", reason, { id });
43294
+ const image = toImage(await request(new URL(`${encodeURIComponent(id)}/`, OPENVERSE_API), send, missing));
43295
+ if (image === null) throw missing(`Openverse holds no image ${id}.`);
43296
+ const allowed = licensesFor(options);
43297
+ if (!allowed.includes(image.license)) throw new FrameboardError("result-not-found", `Openverse image ${id} is under ${image.license}, outside ${allowed.join(", ")}. Pass --credited to allow a license that asks for credit.`, {
43298
+ id,
43299
+ license: image.license,
43300
+ licenses: allowed
43301
+ });
43302
+ return image;
43303
+ }
43304
+ /** The license file for an Openverse image, `query` null when it was saved by id. */
43305
+ function foundLicense(image, query, savedAt) {
43306
+ return {
43307
+ version: 1,
43308
+ origin: "found",
43309
+ source: "openverse",
43310
+ id: image.id,
43311
+ query,
43312
+ title: image.title,
43313
+ creator: image.creator,
43314
+ creatorUrl: image.creatorUrl,
43315
+ license: image.license,
43316
+ licenseVersion: image.licenseVersion,
43317
+ licenseUrl: image.licenseUrl,
43318
+ attribution: image.attribution,
43319
+ landingUrl: image.landingUrl,
43320
+ url: image.url,
43321
+ savedAt: savedAt.toISOString()
43322
+ };
43323
+ }
43324
+ async function request(url, send, missing) {
43325
+ let response;
43326
+ try {
43327
+ response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
43328
+ } catch (error) {
43329
+ throw new FrameboardError("source-failed", `Openverse did not answer: ${error instanceof Error ? error.message : String(error)}`, {
43330
+ source: "openverse",
43331
+ status: null
43332
+ });
43333
+ }
43334
+ if (response.status === 404 && missing) throw missing(`Openverse holds no image at ${url.pathname}.`);
43335
+ if (!response.ok) throw new FrameboardError("source-failed", `Openverse answered ${response.status}${response.status === 429 ? ", its limit for anonymous requests" : ""}.`, {
43336
+ source: "openverse",
43337
+ status: response.status
43338
+ });
43339
+ try {
43340
+ return await response.json();
43341
+ } catch {
43342
+ throw new FrameboardError("source-failed", "Openverse answered something other than JSON.", {
43343
+ source: "openverse",
43344
+ status: response.status
43345
+ });
43346
+ }
43347
+ }
43348
+ /** Openverse's snake_case result as the record's fields, null when it lacks an id, a license, or a URL. */
43349
+ function toImage(raw) {
43350
+ if (!isRecord$2(raw)) return null;
43351
+ const id = text(raw.id);
43352
+ const license = text(raw.license);
43353
+ const url = text(raw.url);
43354
+ if (id === null || license === null || url === null) return null;
43355
+ return {
43356
+ id,
43357
+ title: text(raw.title),
43358
+ creator: text(raw.creator),
43359
+ creatorUrl: text(raw.creator_url),
43360
+ license,
43361
+ licenseVersion: text(raw.license_version),
43362
+ licenseUrl: text(raw.license_url),
43363
+ attribution: text(raw.attribution),
43364
+ landingUrl: text(raw.foreign_landing_url),
43365
+ url,
43366
+ thumbnail: text(raw.thumbnail),
43367
+ width: integer(raw.width),
43368
+ height: integer(raw.height)
43369
+ };
43370
+ }
43371
+ function isRecord$2(value) {
43372
+ return typeof value === "object" && value !== null;
43373
+ }
43374
+ function text(value) {
43375
+ return typeof value === "string" && value !== "" ? value : null;
43376
+ }
43377
+ function integer(value) {
43378
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
43379
+ }
43380
+ // src/server/routes/sourcing.ts
43381
+ /** How long a search waits on Openverse before the panel says it did not answer. */
43382
+ const FIND_TIMEOUT_MS = 15e3;
43383
+ /** How long each request of a save, its lookup and its download, may take. */
43384
+ const SAVE_TIMEOUT_MS = 6e4;
43385
+ /** How long a provider may take, so a provider that never answers frees the button. */
43386
+ const GENERATE_TIMEOUT_MS = 12e4;
43387
+ /** The size the panel asks a provider for, the verb's own default. */
43388
+ const GENERATE_SIZE = {
43389
+ width: 1024,
43390
+ height: 1024
43391
+ };
43392
+ const queryLimit = string$1().trim().min(1).max(200);
43393
+ const saveBodySchema = object$1({
43394
+ id: string$1().min(1).max(200),
43395
+ query: queryLimit,
43396
+ credited: boolean$1().default(false)
43397
+ });
43398
+ const generateBodySchema = object$1({ prompt: string$1().trim().min(1).max(2e3) });
43399
+ const STATUS = {
43400
+ usage: 400,
43401
+ "invalid-name": 400,
43402
+ "project-not-found": 404,
43403
+ "result-not-found": 404,
43404
+ "no-provider": 409,
43405
+ "asset-type-refused": 422,
43406
+ "source-failed": 502,
43407
+ "provider-failed": 502
43408
+ };
43409
+ /**
43410
+ * A project's image sourcing under `/api/projects/:project/sourcing`, calling
43411
+ * the modules `frameboard image` calls. Finding and the provider's price read
43412
+ * only; saving and generating need a writer. No answer carries a key.
43413
+ */
43414
+ function sourcingRoutes(root, access, { send = (input, init) => fetch(input, init), env = process.env, generate = false } = {}) {
43415
+ const app = new Hono();
43416
+ const authorized = requireWriter(access);
43417
+ const base = "/api/projects/:project/sourcing";
43418
+ const saving = /* @__PURE__ */ new Map();
43419
+ let generating = false;
43420
+ app.onError((error, c) => answer(error, c));
43421
+ app.get(`${base}/find`, async (c) => {
43422
+ projectOf$1(root, c.req.param("project"));
43423
+ const query = queryLimit.safeParse(c.req.query("q") ?? "");
43424
+ if (!query.success) throw new FrameboardError("usage", "Send ?q=<what the image shows>, up to 200 characters.");
43425
+ const search = { credited: c.req.query("credited") === "true" };
43426
+ const record = {
43427
+ version: 1,
43428
+ query: query.data,
43429
+ licenses: licensesFor(search),
43430
+ results: await searchImages(query.data, search, timed(send, FIND_TIMEOUT_MS))
43431
+ };
43432
+ return c.json({
43433
+ ok: true,
43434
+ data: record
43435
+ });
43436
+ });
43437
+ app.post(`${base}/save`, authorized, async (c) => {
43438
+ const project = projectOf$1(root, c.req.param("project"));
43439
+ const body = await parseBody$1(c.req.raw, saveBodySchema);
43440
+ const key = JSON.stringify([
43441
+ project.name,
43442
+ body.id,
43443
+ body.credited
43444
+ ]);
43445
+ let pending = saving.get(key);
43446
+ if (pending === void 0) {
43447
+ pending = saveFound(project, body, timed(send, SAVE_TIMEOUT_MS)).finally(() => saving.delete(key));
43448
+ saving.set(key, pending);
43449
+ }
43450
+ return c.json({
43451
+ ok: true,
43452
+ data: await pending
43453
+ });
43454
+ });
43455
+ app.get(`${base}/provider`, (c) => {
43456
+ projectOf$1(root, c.req.param("project"));
43457
+ return c.json({
43458
+ ok: true,
43459
+ data: offer(env, generate)
43460
+ });
43461
+ });
43462
+ app.post(`${base}/generate`, authorized, async (c) => {
43463
+ const project = projectOf$1(root, c.req.param("project"));
43464
+ if (!generate) return c.json({
43465
+ ok: false,
43466
+ error: {
43467
+ code: "generate-off",
43468
+ message: "Generating from the board is off in this release. Run `frameboard image generate` instead."
43469
+ }
43470
+ }, 403);
43471
+ const { prompt } = await parseBody$1(c.req.raw, generateBodySchema);
43472
+ if (generating) return c.json({
43473
+ ok: false,
43474
+ error: {
43475
+ code: "generate-busy",
43476
+ message: "An image is already generating. Wait for it to land."
43477
+ }
43478
+ }, 429);
43479
+ const plan = planGeneration({
43480
+ prompt,
43481
+ size: GENERATE_SIZE
43482
+ }, env);
43483
+ generating = true;
43484
+ try {
43485
+ const bytes = await generateImage(plan, timed(send, GENERATE_TIMEOUT_MS));
43486
+ const saved = await saveImage(project, savedStem(void 0, prompt), bytes, {
43487
+ version: 1,
43488
+ origin: "generated",
43489
+ provider: plan.provider.name,
43490
+ model: plan.provider.model,
43491
+ prompt,
43492
+ ...plan.size,
43493
+ priceUsd: plan.priceUsd,
43494
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
43495
+ });
43496
+ const record = {
43497
+ version: 1,
43498
+ provider: plan.provider.name,
43499
+ model: plan.provider.model,
43500
+ prompt,
43501
+ ...plan.size,
43502
+ priceUsd: plan.priceUsd,
43503
+ dryRun: false,
43504
+ saved
43505
+ };
43506
+ return c.json({
43507
+ ok: true,
43508
+ data: record
43509
+ });
43510
+ } finally {
43511
+ generating = false;
43512
+ }
43513
+ });
43514
+ return app;
43515
+ }
43516
+ async function saveFound(project, body, send) {
43517
+ const image = await imageById(body.id, { credited: body.credited }, send);
43518
+ return saveImage(project, savedStem(void 0, body.query), await downloadImage(image.url, send), foundLicense(image, body.query, /* @__PURE__ */ new Date()));
43519
+ }
43520
+ /** The provider a generation would run on and its price, naming each key by its variable alone. */
43521
+ function offer(env, enabled) {
43522
+ const keys = PROVIDERS.map((provider) => provider.keyEnv);
43523
+ try {
43524
+ const plan = planGeneration({
43525
+ prompt: "",
43526
+ size: GENERATE_SIZE
43527
+ }, env);
43528
+ return {
43529
+ version: 1,
43530
+ enabled,
43531
+ provider: {
43532
+ name: plan.provider.name,
43533
+ model: plan.provider.model,
43534
+ key: plan.provider.keyEnv,
43535
+ ...plan.size,
43536
+ priceUsd: plan.priceUsd
43537
+ },
43538
+ keys
43539
+ };
43540
+ } catch (error) {
43541
+ if (!(error instanceof FrameboardError) || error.code !== "no-provider") throw error;
43542
+ return {
43543
+ version: 1,
43544
+ enabled,
43545
+ provider: null,
43546
+ keys
43547
+ };
43548
+ }
43549
+ }
43550
+ function projectOf$1(root, name) {
43551
+ const path = join(root, name);
43552
+ if (!isValidName(name) || !existsSync(path)) throw new FrameboardError("project-not-found", `No project named ${name} in this board.`);
43553
+ return {
43554
+ name,
43555
+ path
43556
+ };
43557
+ }
43558
+ /** `send` with every request abandoned after `ms`, which the modules report as their source not answering. */
43559
+ function timed(send, ms) {
43560
+ return ((input, init) => send(input, {
43561
+ ...init,
43562
+ signal: AbortSignal.timeout(ms)
43563
+ }));
43564
+ }
43565
+ function answer(error, c) {
43566
+ if (!(error instanceof FrameboardError)) throw error;
43567
+ return c.json({
43568
+ ok: false,
43569
+ error: {
43570
+ code: error.code,
43571
+ message: error.message,
43572
+ details: error.details
43573
+ }
43574
+ }, STATUS[error.code] ?? 500);
43575
+ }
42615
43576
  // src/server/board/paste.ts
42616
43577
  /** Reads each frame's file and placement under its page's lock, in the order given. */
42617
43578
  async function holdFrames(root, refs, options) {
@@ -43883,7 +44844,6 @@ async function shootElement(page, ref, index, scale) {
43883
44844
  * page the size of the body, so the PNG holds the body and nothing past it.
43884
44845
  */
43885
44846
  async function drawBezel(browser, shot, box, device, scale) {
43886
- const { screenRadius } = BEZELS[device];
43887
44847
  const outer = bezelBox({
43888
44848
  x: 0,
43889
44849
  y: 0,
@@ -43900,8 +44860,8 @@ async function drawBezel(browser, shot, box, device, scale) {
43900
44860
  try {
43901
44861
  const page = await context.newPage();
43902
44862
  const marks = device === "phone" ? `<span style="${pill(PHONE_ISLAND.width, PHONE_ISLAND.height, BEZEL_COLORS.island)}top:${PHONE_ISLAND.top}px"></span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>` : laptop ? laptopMarks(box) : "";
43903
- const radius = laptop ? `${screenRadius}px ${screenRadius}px 0 0` : `${screenRadius}px`;
43904
- await page.setContent(`<!doctype html><html><body style="margin:0;background:transparent"><div style="position:absolute;left:${-outer.x}px;top:${-outer.y}px;width:${box.width}px;height:${box.height}px"><img alt="" src="data:image/png;base64,${shot.toString("base64")}" style="display:block;width:100%;height:100%"><div style="position:absolute;inset:0;border-radius:${radius};box-shadow:${bezelShadow(device, { board: false })}">${marks}</div></div></body></html>`, { waitUntil: "load" });
44863
+ const radius = screenCorners(device);
44864
+ await page.setContent(`<!doctype html><html><body style="margin:0;background:transparent"><div style="position:absolute;left:${-outer.x}px;top:${-outer.y}px;width:${box.width}px;height:${box.height}px"><img alt="" src="data:image/png;base64,${shot.toString("base64")}" style="display:block;width:100%;height:100%;border-radius:${radius}"><div style="position:absolute;inset:0;border-radius:${radius};box-shadow:${bezelShadow(device, { board: false })}">${marks}</div></div></body></html>`, { waitUntil: "load" });
43905
44865
  return await page.screenshot({
43906
44866
  omitBackground: true,
43907
44867
  caret: "hide"
@@ -45516,6 +46476,15 @@ const frameTransitionSchema = object$1({
45516
46476
  refs,
45517
46477
  transition: transition.nullable()
45518
46478
  });
46479
+ /**
46480
+ * Blank text clears the note, and the setter refuses one past its limit.
46481
+ * `expected` is the note the edit began from, so one an agent set since is kept.
46482
+ */
46483
+ const frameSpeakerNotesSchema = object$1({
46484
+ ref,
46485
+ speakerNotes: string$1(),
46486
+ expected: string$1()
46487
+ });
45519
46488
  const frameFlagSchema = object$1({
45520
46489
  refs,
45521
46490
  flag: _enum$1(["hidden", "locked"]),
@@ -45887,6 +46856,20 @@ function structureRoutes(root, access, history, measure, tokens = null) {
45887
46856
  data: frames
45888
46857
  });
45889
46858
  });
46859
+ /** Sets or clears one frame's speaker note in one step, leaving its file alone. */
46860
+ app.post("/api/frame/speaker-notes", async (c) => {
46861
+ const body = await parseBody$1(c.req.raw, frameSpeakerNotesSchema);
46862
+ await refuseHeldFrames([body.ref]);
46863
+ const [frame] = await eachFrame([body.ref], (target, journal) => setFrameSpeakerNotes(root, target, body.speakerNotes, {
46864
+ cwd,
46865
+ journal,
46866
+ expected: body.expected
46867
+ }), (records) => records.map((record) => record.ref));
46868
+ return c.json({
46869
+ ok: true,
46870
+ data: frame
46871
+ });
46872
+ });
45890
46873
  app.post("/api/frame/height", async (c) => {
45891
46874
  const body = await parseBody$1(c.req.raw, frameHeightSchema);
45892
46875
  if (body.heights && body.mode !== "scroll") throw new FrameboardError("usage", `The body gives heights to a ${body.mode} write, which takes them only with scroll.`);
@@ -46148,20 +47131,23 @@ function cardFrames(project) {
46148
47131
  }
46149
47132
  // src/server/routes/thumbnails.ts
46150
47133
  /**
46151
- * The thumbnail routes, queueing stale renders so home hears each landing on
47134
+ * The thumbnail routes, answering each project's card frames or one named
47135
+ * page's visible frames, queueing stale renders so home hears each landing on
46152
47136
  * the socket, and caching a capture for good, since a change takes a new stamp.
46153
47137
  */
46154
47138
  function thumbnailRoutes(root, store) {
46155
47139
  const app = new Hono();
46156
47140
  app.get("/api/thumbnails", async (c) => {
46157
- const theme = themeOf(c.req.query("theme"), "Ask for /api/thumbnails?theme=<light|dark>.");
46158
- const frames = (await scanBoard(root)).projects.flatMap((project) => cardFrames(project).map(({ ref, box }) => ({
47141
+ const theme = themeOf(c.req.query("theme"), "Ask for /api/thumbnails?theme=<light|dark>&page=<page-ref>.");
47142
+ const board = await scanBoard(root);
47143
+ const page = c.req.query("page");
47144
+ const frames = (page === void 0 ? board.projects.flatMap((project) => cardFrames(project)) : visibleFramesOf(board, page)).map(({ ref, box }) => ({
46159
47145
  ref,
46160
47146
  box: {
46161
47147
  width: box.width,
46162
47148
  height: box.height
46163
47149
  }
46164
- })));
47150
+ }));
46165
47151
  return c.json({
46166
47152
  ok: true,
46167
47153
  data: { stamps: store.ask(theme, frames) }
@@ -46186,6 +47172,11 @@ function thumbnailRoutes(root, store) {
46186
47172
  app.onError(answerRefusal);
46187
47173
  return app;
46188
47174
  }
47175
+ function visibleFramesOf(board, ref) {
47176
+ const page = board.projects.flatMap((project) => project.pages).find((candidate) => candidate.ref === ref);
47177
+ if (!page) throw new FrameboardError("page-not-found", `No page ${ref} on the board.`, { page: ref });
47178
+ return page.frames.filter((frame) => !frame.hidden);
47179
+ }
46189
47180
  function themeOf(value, usage) {
46190
47181
  if (!isTheme$1(value)) throw new FrameboardError("usage", usage, { theme: value ?? "" });
46191
47182
  return value;
@@ -46352,6 +47343,7 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
46352
47343
  app.route("/", historyRoutes(actions.access, history));
46353
47344
  app.route("/", notesRoutes(root, actions.access, delivery, dispatch));
46354
47345
  app.route("/", assetsRoutes(root, actions.access, { usage: assetUsage }));
47346
+ app.route("/", sourcingRoutes(root, actions.access));
46355
47347
  app.route("/", elementsRoutes(root, actions.access, selection, given));
46356
47348
  app.route("/", findRoutes(root));
46357
47349
  app.route("/", claimsRoutes(root, actions.access));
@@ -47178,6 +48170,8 @@ const frameRecordSchema = object$1({
47178
48170
  device: _enum$1(DEVICES).optional(),
47179
48171
  /** The transition the frame arrives with in present mode, over its page's, absent when it holds none. */
47180
48172
  transition: transitionRecordSchema.optional(),
48173
+ /** What the presenter means to say over the slide, plain text with its line breaks, absent when it holds none. */
48174
+ speakerNotes: string$1().optional(),
47181
48175
  placed: boolean$1(),
47182
48176
  modifiedAt: string$1()
47183
48177
  });
@@ -47703,7 +48697,12 @@ const RECORDS = {
47703
48697
  referencesSync: referencesSyncSchema,
47704
48698
  referencesCheck: referencesCheckSchema,
47705
48699
  previewStart: previewStartSchema,
47706
- previewStop: previewStopSchema
48700
+ previewStop: previewStopSchema,
48701
+ imageFind: imageFindSchema,
48702
+ savedImage: savedImageSchema,
48703
+ licenseFile: licenseFileSchema,
48704
+ imageGenerate: imageGenerateSchema,
48705
+ imageDoctor: imageDoctorSchema
47707
48706
  };
47708
48707
  // src/cli/docs/content-format.ts
47709
48708
  /** The content format `docs` prints, built from the constants the verbs run on. */
@@ -47744,6 +48743,7 @@ function contentFormat() {
47744
48743
  present: [
47745
48744
  `A page's slide transition sits on the present key of its ${LAYOUT_FILE} as { transition: { name, direction, ms } }, and a frame's entry may hold its own transition, which wins as that slide arrives. name is one of ${TRANSITIONS.join(", ")}, or one of the project's own. direction is one of ${DIRECTIONS.join(", ")}, taken by ${DIRECTED.join(" and ")} alone and defaulting to left. ms runs ${TRANSITION_MS.min} to ${TRANSITION_MS.max}, a frame's taking its page's when absent and the page's defaulting to 500. Any other value reads as none and is kept on write. The board draws a transition itself and never writes it into a frame file.`,
47746
48745
  `A project adds its own transition as a stylesheet at ${ASSETS_FOLDER}/${TRANSITIONS_FOLDER}/<name>${TRANSITION_FILE_EXTENSION}, set by <name> as a built-in is. The name is lowercase kebab case and never a built-in name, none, or page. The file holds @keyframes enter, which the arriving slide plays, optionally @keyframes leave, which the leaving slide plays or else holds still, and nothing else: no other rule or at-rule, and no url(), quoted string, or backslash escape in a value. The board plays those two keyframes over the transition's ms and never loads the file itself. It takes --ms and no direction, so a second file covers a second direction. A file breaking any of this is refused whole, reported by check and the write hook as transition-file, left out of list --json's transitions on its project, and a page or frame naming it cuts. Turning transition-file off silences the finding and the file stays refused.`,
48746
+ `A frame's entry may hold speakerNotes, what the presenter means to say over the slide: plain text up to ${SPEAKER_NOTES_MAX} characters with its line breaks kept and no markup read. It lives on the entry alone and never enters the frame file, so a rewrite of the file keeps it, and a duplicate or a move to another page carries it. list --json reports it on the frame, absent when it holds none, and any value other than text reads as none and is kept on write. frame speaker-notes <frame-ref> prints it, frame speaker-notes <frame-ref> <text> sets it, refusing usage past the limit rather than cutting it, and --clear or blank text removes it. Present mode never shows it.`,
47747
48747
  "page transition <page-ref> <name> sets the page's, and none clears it so slides cut. frame transition <frame-ref> <name> sets a frame's, and page clears it so the frame takes its page's. Both take --ms and --direction, refuse usage on a name that is neither built in nor the project's own with the known names in the error's details, and write only layout.json.",
47748
48748
  `A step is an element present mode holds back until a press reveals it, marked by three attributes on that element and nothing else. ${STEP_ATTRIBUTES.step}="<n>" is a positive integer, and steps show in number order with equal numbers together and gaps closed. ${STEP_ATTRIBUTES.effect} is one of ${STEP_EFFECTS.join(", ")}, defaulting to appear. ${STEP_ATTRIBUTES.start} is one of ${STEP_STARTS.join(", ")}, defaulting to click, where with shows the step beside the one before it and after shows it once that one finishes. Set them with edit --attr. Edit, Play, capture, and an exported PNG show every step.`
47749
48749
  ],
@@ -47758,6 +48758,13 @@ function contentFormat() {
47758
48758
  `kit add copies the kit's ${TOKEN_FILE} as the project's, its kit page as the project's kit page, and every other file into ${ASSETS_FOLDER}/kit/. It refuses tokens-exist where a board, --tokens, or project sheet already reaches the project, and name-taken where the project holds a kit page or ${ASSETS_FOLDER}/kit/, unless --replace is given. kit save refuses name-taken for a name a shipped or saved kit holds, and tokens-not-found for a project no sheet reaches.`,
47759
48759
  `The server imports ${ASSETS_FOLDER}/kit/${KIT_SHEET} into each frame after the project sheet, and check reads it with the token sheets. Read ${ASSETS_FOLDER}/kit/${KIT_NOTE} and the kit page before drawing in a project that holds one.`
47760
48760
  ],
48761
+ images: [
48762
+ `image find searches Openverse under ${DEFAULT_LICENSES.join(", ")} alone, and --credited widens it to ${CREDITED_LICENSES.join(", ")}. It lists up to 20 results numbered from 1 and writes nothing. --save <number> runs the search again and saves that result, and --save <id> saves the Openverse image with that id with no search, refusing result-not-found for an id under a license the flags do not allow. Openverse allows an address 200 anonymous requests a day, so save by id.`,
48763
+ `image generate runs on the provider --provider names, else the first whose key is set, in the order ${PROVIDERS.map((each) => `${each.name} (${each.model}, ${each.keyEnv})`).join(", ")}. A key set to an empty string reads as unset. priceUsd is the estimate before the call, and --dry-run answers it with saved null and makes no request. Without --dry-run the call spends on that key at once, since no verb prompts. No ready provider refuses no-provider with the keys in the details, and a failed call refuses provider-failed with the provider's status and never the key.`,
48764
+ `A saved image lands in the project's ${ASSETS_FOLDER}/ under the --name stem, else the query or prompt as a lowercase dashed name, taking the first free -2, -3, and onward. Its license file lands beside it as <file>${LICENSE_FILE_SUFFIX}, the licenseFile record, saying where it came from. A download is held whole, at most ${DOWNLOAD_LIMIT / 1024 / 1024} MiB, before anything is written, so a failed one leaves no file, and the Assets tab never draws a license file as its own tile.`,
48765
+ "image doctor reports the GPU nvidia-smi names, whether a ComfyUI server answers at FRAMEBOARD_COMFYUI_URL or the default address, and each key as set or unset, never its value. It installs and spends nothing.",
48766
+ `A frame links a saved image as ../${ASSETS_FOLDER}/<path>, never by its web address, since a frame loads nothing over the network.`
48767
+ ],
47761
48768
  assets: `A frame links files in its own page folder or in its project's ${ASSETS_FOLDER}/ folder. frame duplicate and frame move carry the ${FRAME_EXTENSION} file alone, so keep files shared between frames or pages in ${ASSETS_FOLDER}/.`,
47762
48769
  look: [
47763
48770
  `The board's ${TOKEN_FILE} holds the design tokens every project shares, and a project's own ${TOKEN_FILE} overrides it. serve --tokens <path> stands in for the board's sheet, resolved against the working folder and recorded as tokens in ${RUN_FOLDER}/${ADDRESS_FILE} while that server runs.`,
@@ -47815,6 +48822,10 @@ function formatLines(format) {
47815
48822
  ...format.present.map((line) => `${INDENT}${line}`),
47816
48823
  "Controls",
47817
48824
  ...format.controls.map((line) => `${INDENT}${line}`),
48825
+ "Kits",
48826
+ ...format.kits.map((line) => `${INDENT}${line}`),
48827
+ "Images",
48828
+ ...format.images.map((line) => `${INDENT}${line}`),
47818
48829
  "Assets",
47819
48830
  `${INDENT}${format.assets}`,
47820
48831
  "Look",
@@ -48240,12 +49251,190 @@ function registerFrame(program, context) {
48240
49251
  });
48241
49252
  return done(record, record.transition ? `Set ${transitionLabel(record.transition.name)} on` : "Cleared the transition on");
48242
49253
  });
49254
+ act(verb("speaker-notes", `Print a slide's speaker note, set it to the text given, or remove it with --clear, writing only layout.json and never the frame file. Plain text up to ${SPEAKER_NOTES_MAX} characters with its line breaks kept, and blank text clears it.`).argument("[text]", "the note to set, in place of the one it holds").option("--clear", "remove the note"), context, async ([ref = "", text], { clear, ...options }) => {
49255
+ if (clear && text !== void 0) throw new FrameboardError("usage", "Pass the text or --clear, not both.");
49256
+ const root = await boardOf(options, io);
49257
+ const refOptions = {
49258
+ ...options,
49259
+ cwd: io.cwd
49260
+ };
49261
+ if (!clear && text === void 0) {
49262
+ const record = await readFrame(root, ref, refOptions);
49263
+ return {
49264
+ data: record,
49265
+ human: record.speakerNotes ?? `No speaker notes on ${record.ref}`
49266
+ };
49267
+ }
49268
+ const record = await setFrameSpeakerNotes(root, ref, clear ? null : text ?? null, refOptions);
49269
+ return done(record, record.speakerNotes ? "Set the speaker notes on" : "Cleared the speaker notes on");
49270
+ });
48243
49271
  for (const [name, flag] of [["hide", "hidden"], ["lock", "locked"]]) act(verb(name, `Set a frame ${flag}, or clear it with --off`).option("--off", `clear ${flag}`), context, async ([ref = ""], options) => done(await setFrameFlag(await boardOf(options, io), ref, flag, {
48244
49272
  ...options,
48245
49273
  on: !options.off,
48246
49274
  cwd: io.cwd
48247
49275
  }), options.off ? `Cleared ${flag} on` : `Set ${flag} on`));
48248
49276
  }
49277
+ /** How long a probe waits, so a machine with nothing listening answers at once. */
49278
+ const PROBE_TIMEOUT_MS = 1e3;
49279
+ function runNvidiaSmi(args) {
49280
+ return new Promise((resolve) => {
49281
+ execFile("nvidia-smi", args, { timeout: 5e3 }, (error, stdout) => resolve(error ? null : stdout));
49282
+ });
49283
+ }
49284
+ /**
49285
+ * The GPU, the local server, and which keys are set, reading each key's
49286
+ * presence and never its value. Installs and spends nothing.
49287
+ */
49288
+ async function diagnose({ env, send, queryGpu }) {
49289
+ const url = env.FRAMEBOARD_COMFYUI_URL?.trim() || "http://127.0.0.1:8188";
49290
+ const [gpu, running] = await Promise.all([readGpu(queryGpu), probe(url, send)]);
49291
+ const providers = PROVIDERS.map((provider) => ({
49292
+ provider: provider.name,
49293
+ model: provider.model,
49294
+ key: provider.keyEnv,
49295
+ ready: keyOf(provider, env) !== null
49296
+ }));
49297
+ return {
49298
+ version: 1,
49299
+ gpu,
49300
+ local: {
49301
+ url,
49302
+ running
49303
+ },
49304
+ keys: Object.fromEntries(providers.map((each) => [each.key, each.ready])),
49305
+ providers,
49306
+ provider: providers.find((each) => each.ready)?.provider ?? null
49307
+ };
49308
+ }
49309
+ async function readGpu(queryGpu) {
49310
+ const [name, memory] = ((await queryGpu(["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"]))?.split("\n")[0] ?? "").split(",").map((part) => part.trim());
49311
+ const memoryMiB = Number(memory);
49312
+ if (!name || !Number.isSafeInteger(memoryMiB)) return null;
49313
+ return {
49314
+ name,
49315
+ memoryMiB
49316
+ };
49317
+ }
49318
+ /** True when ComfyUI's `/system_stats` answers within the probe timeout. */
49319
+ async function probe(url, send) {
49320
+ try {
49321
+ return (await send(new URL("/system_stats", url), { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })).ok;
49322
+ } catch {
49323
+ return false;
49324
+ }
49325
+ }
49326
+ // src/cli/commands/image.ts
49327
+ function registerImage(program, context) {
49328
+ const { io } = context;
49329
+ const send = io.fetch ?? fetch;
49330
+ const image = program.command("image").description("Find an openly licensed image or generate one, saving it into a project's assets with its license");
49331
+ act(addVerb(image, "find", "Search Openverse for public domain images, writing nothing unless --save names a result", { project: true }).argument("<query>", "what the image shows").option("--credited", "also allow images whose license asks only for credit, CC BY").option("--save <number-or-id>", "save the result with this number, or the Openverse image with this id, into the project's assets").option("--name <stem>", "the saved file name without its extension, the query by default"), context, async ([query = ""], options) => {
49332
+ const search = { credited: options.credited ?? false };
49333
+ if (options.save === void 0) {
49334
+ if (options.name !== void 0) throw new FrameboardError("usage", "--name needs --save.");
49335
+ const results = await searchImages(query, search, send);
49336
+ const record = {
49337
+ version: 1,
49338
+ query,
49339
+ licenses: licensesFor(search),
49340
+ results
49341
+ };
49342
+ return {
49343
+ data: record,
49344
+ human: results.length === 0 ? `No image under ${record.licenses.join(", ")} matches ${query}` : results.map((each) => `${each.number}\t${each.license}\t${each.title ?? each.id}\t${each.id}`).join("\n")
49345
+ };
49346
+ }
49347
+ const stem = savedStem(options.name, query);
49348
+ const project = await resolveProject(await boardOf(options, io), options.project);
49349
+ const chosen = await pick(query, options.save, search);
49350
+ const saved = await saveImage(project, stem, await downloadImage(chosen.image.url, send), foundLicense(chosen.image, chosen.query, /* @__PURE__ */ new Date()));
49351
+ return {
49352
+ data: saved,
49353
+ human: savedLine(saved)
49354
+ };
49355
+ });
49356
+ act(addVerb(image, "generate", "Generate an image on the first provider whose key is set and save it into the project's assets, spending on that key unless --dry-run", { project: true }).argument("<prompt>", "what the image shows").option("--provider <name>", `run on this provider, one of ${IMAGE_PROVIDERS.join(", ")}, rather than the first ready`).option("--width <px>", "the width asked for", parseInteger(1), 1024).option("--height <px>", "the height asked for", parseInteger(1), 1024).option("--dry-run", "answer the provider, size, and price, and make no request").option("--name <stem>", "the saved file name without its extension, the prompt by default"), context, async ([prompt = ""], options) => {
49357
+ const plan = planGeneration({
49358
+ prompt,
49359
+ size: {
49360
+ width: options.width,
49361
+ height: options.height
49362
+ },
49363
+ provider: options.provider
49364
+ }, process.env);
49365
+ const record = {
49366
+ version: 1,
49367
+ provider: plan.provider.name,
49368
+ model: plan.provider.model,
49369
+ prompt,
49370
+ ...plan.size,
49371
+ priceUsd: plan.priceUsd,
49372
+ dryRun: options.dryRun ?? false,
49373
+ saved: null
49374
+ };
49375
+ const priced = `${record.provider} ${record.model} at ${record.width}x${record.height} for about $${record.priceUsd}`;
49376
+ if (record.dryRun) return {
49377
+ data: record,
49378
+ human: `Would generate on ${priced}`
49379
+ };
49380
+ const stem = savedStem(options.name, prompt);
49381
+ const saved = await saveImage(await resolveProject(await boardOf(options, io), options.project), stem, await generateImage(plan, send), {
49382
+ version: 1,
49383
+ origin: "generated",
49384
+ provider: record.provider,
49385
+ model: record.model,
49386
+ prompt,
49387
+ width: record.width,
49388
+ height: record.height,
49389
+ priceUsd: record.priceUsd,
49390
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
49391
+ });
49392
+ return {
49393
+ data: {
49394
+ ...record,
49395
+ saved
49396
+ },
49397
+ human: `Generated on ${priced}. ${savedLine(saved)}`
49398
+ };
49399
+ });
49400
+ act(addVerb(image, "doctor", "Report the GPU, a local ComfyUI server, and which provider keys are set, installing nothing"), context, async () => {
49401
+ const report = await diagnose({
49402
+ env: process.env,
49403
+ send,
49404
+ queryGpu: runNvidiaSmi
49405
+ });
49406
+ return {
49407
+ data: report,
49408
+ human: [
49409
+ `GPU\t${report.gpu === null ? "none found" : `${report.gpu.name}, ${report.gpu.memoryMiB} MiB`}`,
49410
+ `Local\t${report.local.url} ${report.local.running ? "answers" : "does not answer"}`,
49411
+ ...report.providers.map((each) => `${each.provider}\t${each.key} ${each.ready ? "set" : "unset"}`),
49412
+ `Generate runs on\t${report.provider ?? "nothing, since no key is set"}`
49413
+ ].join("\n")
49414
+ };
49415
+ });
49416
+ /** The result `--save` names: a number reruns the search, anything else is an id. */
49417
+ async function pick(query, save, search) {
49418
+ if (!/^\d+$/.test(save)) return {
49419
+ image: await imageById(save, search, send),
49420
+ query: null
49421
+ };
49422
+ const number = Number(save);
49423
+ const results = await searchImages(query, search, send);
49424
+ const found = results.find((each) => each.number === number);
49425
+ if (found === void 0) throw new FrameboardError("result-not-found", `The search for ${query} found ${results.length} results, so there is no result ${number}.`, {
49426
+ number,
49427
+ results: results.length
49428
+ });
49429
+ return {
49430
+ image: found,
49431
+ query
49432
+ };
49433
+ }
49434
+ }
49435
+ function savedLine(saved) {
49436
+ return `Saved assets/${saved.path} into ${saved.project}, its license in assets/${saved.licensePath}`;
49437
+ }
48249
49438
  // node_modules/ws/lib/constants.js
48250
49439
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
48251
49440
  const BINARY_TYPES = [
@@ -57531,7 +58720,7 @@ function innerPath(pathname, token, project) {
57531
58720
  const [given = "", ...rest] = pathname.slice(3).split("/");
57532
58721
  if (!sameToken(given, token)) return null;
57533
58722
  const inner = `/${rest.join("/")}`;
57534
- if (inner === "/frameboard/tokens.css" || inner.startsWith(`/frameboard/faces/`)) return inner;
58723
+ if (inner === "/frameboard/tokens.css" || inner === BRIDGE_URL || inner.startsWith(`/frameboard/faces/`)) return inner;
57535
58724
  const [area, named, ...within] = rest;
57536
58725
  if (area !== "frames" || within.length === 0) return null;
57537
58726
  let decoded;
@@ -58548,6 +59737,7 @@ function createProgram(context) {
58548
59737
  registerList(program, context);
58549
59738
  registerProject(program, context);
58550
59739
  registerKit(program, context);
59740
+ registerImage(program, context);
58551
59741
  registerPage(program, context);
58552
59742
  registerFrame(program, faced);
58553
59743
  registerEdit(program, context);