frameboard 0.39.0 → 0.41.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. */
@@ -9080,11 +9084,15 @@ function datetime(params) {
9080
9084
  return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
9081
9085
  }
9082
9086
  // src/shared/frame-device.ts
9083
- /** The devices the board can draw around a frame, the frame's width picking one. */
9087
+ /**
9088
+ * The devices the board can draw around a frame. A frame's width picks the
9089
+ * first three, and a frame names a foldable.
9090
+ */
9084
9091
  const DEVICES = [
9085
9092
  "phone",
9086
9093
  "tablet",
9087
- "laptop"
9094
+ "laptop",
9095
+ "foldable"
9088
9096
  ];
9089
9097
  /** The laptop lid's chin below the screen, past the border its sides hold. */
9090
9098
  const LAPTOP_CHIN = 28;
@@ -9095,8 +9103,9 @@ const LAPTOP_BASE = {
9095
9103
  radius: 10
9096
9104
  };
9097
9105
  /**
9098
- * Bezels measured off a current Pro phone and 13-inch tablet, the tablet's
9099
- * screen radius a guess, and the laptop scaled off the picked mock.
9106
+ * Bezels measured off a current Pro phone and 13-inch tablet, the laptop
9107
+ * scaled off the picked mock, and the foldable's body less its glass. The
9108
+ * tablet's and the foldable's screen radii are guesses no source gives.
9100
9109
  */
9101
9110
  const BEZELS = {
9102
9111
  phone: {
@@ -9116,9 +9125,24 @@ const BEZELS = {
9116
9125
  bottom: LAPTOP_CHIN + LAPTOP_BASE.height,
9117
9126
  screenRadius: 10,
9118
9127
  bodyRadius: 30
9128
+ },
9129
+ foldable: {
9130
+ border: 20,
9131
+ bottom: 20,
9132
+ screenRadius: 48,
9133
+ bodyRadius: 68
9119
9134
  }
9120
9135
  };
9121
9136
  /**
9137
+ * A device's screen corners as a CSS `border-radius`, which the body and every
9138
+ * box drawn on its screen share. A laptop's screen meets its chin, so only
9139
+ * its top corners round.
9140
+ */
9141
+ function screenCorners(device) {
9142
+ const { screenRadius } = BEZELS[device];
9143
+ return device === "laptop" ? `${screenRadius}px ${screenRadius}px 0 0` : `${screenRadius}px`;
9144
+ }
9145
+ /**
9122
9146
  * The narrowest width each device draws around, widest first, so a frame
9123
9147
  * takes the first one it reaches. Under the phone's width no device fits.
9124
9148
  */
@@ -9156,6 +9180,67 @@ const HOME_BAR = {
9156
9180
  height: 5,
9157
9181
  bottom: 8
9158
9182
  };
9183
+ /** The ways a foldable is held, each a screen the frame's box takes the size of. */
9184
+ const POSES = [
9185
+ "closed",
9186
+ "half",
9187
+ "open"
9188
+ ];
9189
+ /**
9190
+ * Each pose's screen in points, the cover display closed and the inner one
9191
+ * half open and open. The published pixel counts at three pixels to a point,
9192
+ * a scale no source states for this device.
9193
+ */
9194
+ const POSE_SIZES = {
9195
+ closed: {
9196
+ width: 466,
9197
+ height: 678
9198
+ },
9199
+ half: {
9200
+ width: 890,
9201
+ height: 626
9202
+ },
9203
+ open: {
9204
+ width: 890,
9205
+ height: 626
9206
+ }
9207
+ };
9208
+ /** A layout entry's `pose` as a pose, closed for none or a value no reader knows. */
9209
+ function poseOf(value) {
9210
+ return POSES.find((pose) => pose === value) ?? "closed";
9211
+ }
9212
+ /** The pose a frame this wide starts in, closed or open, whichever moves its box least. */
9213
+ function nearestPose(width) {
9214
+ return Math.abs(width - POSE_SIZES.closed.width) <= Math.abs(width - POSE_SIZES.open.width) ? "closed" : "open";
9215
+ }
9216
+ /**
9217
+ * The foldable's island, a generic pill, centered on the cover screen and on
9218
+ * the right half of the inner one, a place no source gives.
9219
+ */
9220
+ const FOLDABLE_ISLAND = {
9221
+ width: 100,
9222
+ height: 30,
9223
+ top: 14
9224
+ };
9225
+ /** Where the island's center sits across a pose's screen, as a share of its width. */
9226
+ function islandCenter(pose) {
9227
+ return pose === "closed" ? .5 : .75;
9228
+ }
9229
+ /**
9230
+ * The band drawn down the middle of the inner screen, a faint crease open
9231
+ * and a shaded fold half open, null on the cover screen, which has no fold.
9232
+ */
9233
+ function foldBand(pose) {
9234
+ if (pose === "closed") return null;
9235
+ if (pose === "open") return {
9236
+ width: 26,
9237
+ background: "linear-gradient(90deg, transparent, rgba(0,0,0,.05) 35%, rgba(0,0,0,.11) 50%, rgba(255,255,255,.5) 56%, transparent)"
9238
+ };
9239
+ return {
9240
+ width: 150,
9241
+ background: "linear-gradient(90deg, transparent, rgba(0,0,0,.10) 30%, rgba(0,0,0,.34) 49%, rgba(0,0,0,.34) 51%, rgba(0,0,0,.08) 70%, transparent)"
9242
+ };
9243
+ }
9159
9244
  /**
9160
9245
  * The laptop's chin and base, each a box from the frame's top left, which
9161
9246
  * the board and the PNG draw as positioned boxes, since one spread around
@@ -9412,6 +9497,13 @@ function widthsOf(value) {
9412
9497
  }
9413
9498
  return widths;
9414
9499
  }
9500
+ /**
9501
+ * The widths a layout entry draws: none for a frame naming the foldable,
9502
+ * whose poses are its sizes, whatever its `widths` lists.
9503
+ */
9504
+ function drawnWidths(entry) {
9505
+ return entry.foldable === true ? [] : widthsOf(entry.widths);
9506
+ }
9415
9507
  function isSize(value) {
9416
9508
  return typeof value === "number" && Number.isInteger(value) && value >= 1;
9417
9509
  }
@@ -9635,8 +9727,17 @@ const layoutEntrySchema = looseObject({
9635
9727
  })), unknown()]).optional(),
9636
9728
  showDevice: unknown().optional(),
9637
9729
  device: unknown().optional(),
9638
- transition: unknown().optional()
9730
+ foldable: unknown().optional(),
9731
+ pose: unknown().optional(),
9732
+ transition: unknown().optional(),
9733
+ speakerNotes: unknown().optional()
9639
9734
  });
9735
+ /** The longest speaker note a write accepts, in characters. */
9736
+ const SPEAKER_NOTES_MAX = 1e4;
9737
+ /** The note a layout entry's `speakerNotes` holds, null for none or a value of another type. */
9738
+ function speakerNotesOf(value) {
9739
+ return typeof value === "string" && value.trim() !== "" ? value : null;
9740
+ }
9640
9741
  /** A named box grouping the frames whose center it holds, which it never lists. */
9641
9742
  const sectionEntrySchema = looseObject({
9642
9743
  x: int$1(),
@@ -24429,8 +24530,12 @@ function placeFrames(frames, names, readTransition = storedTransitionOf) {
24429
24530
  height: entry.height
24430
24531
  };
24431
24532
  const shown = showsDevice(entry);
24432
- const device = shown ? deviceForWidth(box.width) : null;
24533
+ const foldable = entry.foldable === true;
24534
+ const kept = widthsOf(entry.widths);
24535
+ const named = foldable ? "foldable" : deviceForWidth(box.width);
24536
+ const device = shown ? named : null;
24433
24537
  const transition = readTransition(entry.transition);
24538
+ const speakerNotes = speakerNotesOf(entry.speakerNotes);
24434
24539
  placements.set(name, {
24435
24540
  box,
24436
24541
  order: entry.order,
@@ -24439,10 +24544,16 @@ function placeFrames(frames, names, readTransition = storedTransitionOf) {
24439
24544
  hugWidth: !scroll && (entry.hugWidth ?? false),
24440
24545
  hugHeight: !scroll && (entry.hugHeight ?? false),
24441
24546
  scroll,
24442
- widths: widthsOf(entry.widths),
24547
+ widths: drawnWidths(entry),
24443
24548
  ...shown ? { showDevice: true } : {},
24444
24549
  ...device ? { device } : {},
24550
+ ...foldable ? {
24551
+ foldable,
24552
+ pose: poseOf(entry.pose)
24553
+ } : {},
24554
+ ...foldable && kept.length > 0 ? { keptWidths: kept } : {},
24445
24555
  ...transition ? { transition } : {},
24556
+ ...speakerNotes ? { speakerNotes } : {},
24446
24557
  placed: true
24447
24558
  });
24448
24559
  }
@@ -24551,7 +24662,7 @@ async function scanPage(root, project, name, index, transitions) {
24551
24662
  const placements = placeFrames(frames, names, (value) => transitionOf(value, own));
24552
24663
  const stacked = (await Promise.all(names.map(async (frame) => {
24553
24664
  const framePath = join(path, `${frame}${FRAME_EXTENSION}`);
24554
- const placement = placements.get(frame) ?? placeNext([]);
24665
+ const { foldable: _named, keptWidths: _kept, ...placement } = placements.get(frame) ?? placeNext([]);
24555
24666
  return {
24556
24667
  ref: `${project}/${name}/${frame}`,
24557
24668
  project,
@@ -24670,7 +24781,7 @@ async function isDirectory(path) {
24670
24781
  }
24671
24782
  }
24672
24783
  // package.json
24673
- var version$1 = "0.39.0";
24784
+ var version$1 = "0.41.0";
24674
24785
  var dependencies = { "playwright-core": "1.65.0" };
24675
24786
  var peerDependencies = { "oxfmt": "0.78.0" };
24676
24787
  // src/shared/version.ts
@@ -25342,6 +25453,10 @@ async function setLinkedWidths(root, targets, widths, options) {
25342
25453
  }
25343
25454
  /** The placement `resizeFrame` writes, for the size it read off its options. */
25344
25455
  function resizedPlacement(placement, frameRef, size, options) {
25456
+ if (placement.foldable && options.widths && options.widths.length > 0) throw new FrameboardError("usage", `${frameRef} is a foldable, whose poses are its sizes, so it shows at no other width.`, {
25457
+ ref: frameRef,
25458
+ widths: options.widths
25459
+ });
25345
25460
  const scroll = options.scroll ?? placement.scroll;
25346
25461
  const width = size.width ?? placement.box.width;
25347
25462
  const drops = scroll && placement.hugHeight && size.height === void 0;
@@ -25351,8 +25466,10 @@ function resizedPlacement(placement, frameRef, size, options) {
25351
25466
  hugWidth,
25352
25467
  held: placement.widths
25353
25468
  });
25469
+ const { keptWidths, ...kept } = placement;
25354
25470
  return {
25355
- ...placement,
25471
+ ...kept,
25472
+ ...keptWidths && options.widths !== false ? { keptWidths } : {},
25356
25473
  box: {
25357
25474
  ...placement.box,
25358
25475
  ...size,
@@ -25623,17 +25740,54 @@ async function setFrameFlag(root, ref, flag, { on, ...options }) {
25623
25740
  }));
25624
25741
  }
25625
25742
  /**
25626
- * Shows or hides the device the board draws around a frame, which the
25627
- * frame's width picks. The frame's file and box are left as they stand,
25628
- * since the body wraps whatever size the frame is.
25743
+ * Shows or hides a frame's device, names or un-names the foldable, and folds
25744
+ * it, never writing the frame's file. Naming a foldable shows it and, as a
25745
+ * pose does, sets the box to that pose's screen, fixed on both axes.
25629
25746
  */
25630
- async function setFrameDevice(root, ref, show, options) {
25631
- return updatePlacement(root, ref, options, (placement) => {
25632
- const { showDevice: _held, device: _device, ...rest } = placement;
25633
- return show ? {
25747
+ async function setFrameDevice(root, ref, show, { foldable: name, pose: fold, ...options }) {
25748
+ return updatePlacement(root, ref, options, (placement, frameRef) => {
25749
+ const { showDevice: held, device: _device, foldable: named, pose: stored, keptWidths, ...rest } = placement;
25750
+ const foldable = name ?? named === true;
25751
+ if (fold && !foldable) throw new FrameboardError("usage", `${frameRef} is not a foldable, so it has no pose. Name it with --foldable first.`, {
25752
+ ref: frameRef,
25753
+ pose: fold
25754
+ });
25755
+ const shown = show ?? (name === true || held === true);
25756
+ const base = {
25634
25757
  ...rest,
25635
- showDevice: true
25636
- } : rest;
25758
+ ...shown ? { showDevice: true } : {}
25759
+ };
25760
+ if (!foldable) {
25761
+ const widths = (keptWidths ?? rest.widths).filter((linked) => linked.width !== placement.box.width);
25762
+ return {
25763
+ ...base,
25764
+ widths
25765
+ };
25766
+ }
25767
+ const undrawn = keptWidths ?? rest.widths;
25768
+ const kept = {
25769
+ widths: [],
25770
+ ...undrawn.length > 0 ? { keptWidths: undrawn } : {}
25771
+ };
25772
+ const pose = fold ?? stored ?? nearestPose(placement.box.width);
25773
+ if (!fold && named) return {
25774
+ ...base,
25775
+ ...kept,
25776
+ foldable,
25777
+ pose
25778
+ };
25779
+ return {
25780
+ ...base,
25781
+ ...kept,
25782
+ foldable,
25783
+ pose,
25784
+ box: {
25785
+ ...placement.box,
25786
+ ...POSE_SIZES[pose]
25787
+ },
25788
+ hugWidth: false,
25789
+ hugHeight: false
25790
+ };
25637
25791
  });
25638
25792
  }
25639
25793
  /**
@@ -25651,6 +25805,30 @@ async function setFrameTransition(root, ref, transition, options) {
25651
25805
  } : rest;
25652
25806
  });
25653
25807
  }
25808
+ /**
25809
+ * Sets a frame's speaker note on its layout entry, null or blank clearing it.
25810
+ * Refuses `usage` past `SPEAKER_NOTES_MAX` rather than cutting, and
25811
+ * `stale-layout` once `expected`, the note the edit began from, is gone.
25812
+ */
25813
+ async function setFrameSpeakerNotes(root, ref, text, { expected, ...options }) {
25814
+ 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}.`, {
25815
+ max: SPEAKER_NOTES_MAX,
25816
+ length: text.length
25817
+ });
25818
+ const speakerNotes = speakerNotesOf(text);
25819
+ return updatePlacement(root, ref, options, (placement, frameRef) => {
25820
+ const { speakerNotes: held, ...rest } = placement;
25821
+ 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.`, {
25822
+ ref: frameRef,
25823
+ stored: held ?? "",
25824
+ expected
25825
+ });
25826
+ return speakerNotes ? {
25827
+ ...rest,
25828
+ speakerNotes
25829
+ } : rest;
25830
+ });
25831
+ }
25654
25832
  async function deleteFrame(root, ref, options) {
25655
25833
  const { journal } = options;
25656
25834
  const frame = await resolveFrameRef(root, ref, options);
@@ -25740,10 +25918,11 @@ var PageLayout = class {
25740
25918
  * Writes the fixed keys after the entry's own, so unknown keys survive, and a
25741
25919
  * flag only once on or already held, so an older entry gains no key.
25742
25920
  */
25743
- set(name, { box, order, hidden, locked, scroll, widths, showDevice, transition, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
25921
+ set(name, { box, order, hidden, locked, scroll, widths, showDevice, foldable, pose, keptWidths, transition, speakerNotes, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
25744
25922
  const hugWidth = hugsWidth && !scroll;
25745
25923
  const hugHeight = hugsHeight && !scroll;
25746
25924
  const held = this.file.frames[name];
25925
+ const listed = foldable ? keptWidths ?? [] : widths;
25747
25926
  const entry = {
25748
25927
  ...held,
25749
25928
  x: box.x,
@@ -25756,17 +25935,25 @@ var PageLayout = class {
25756
25935
  ...!held || hugWidth || held.hugWidth !== void 0 ? { hugWidth } : {},
25757
25936
  ...!held || hugHeight || held.hugHeight !== void 0 ? { hugHeight } : {},
25758
25937
  ...scroll || held?.scroll !== void 0 ? { scroll } : {},
25759
- ...widths.length > 0 ? { widths: widths.map(({ width, height }) => ({
25938
+ ...listed.length > 0 ? { widths: listed.map(({ width, height }) => ({
25760
25939
  width,
25761
25940
  height
25762
25941
  })) } : {},
25763
25942
  ...showDevice ? { showDevice } : {},
25764
- ...transition ? { transition: { ...transition } } : {}
25943
+ ...foldable ? { foldable } : {},
25944
+ ...foldable && pose && (held?.foldable !== true || poseOf(held.pose) !== pose) ? { pose } : {},
25945
+ ...transition ? { transition: { ...transition } } : {},
25946
+ ...speakerNotes ? { speakerNotes } : {}
25765
25947
  };
25766
- if (widths.length === 0 && widthsOf(held?.widths).length > 0) delete entry.widths;
25948
+ if (listed.length === 0 && widthsOf(held?.widths).length > 0) delete entry.widths;
25949
+ if (!foldable && held?.foldable === true) {
25950
+ delete entry.foldable;
25951
+ delete entry.pose;
25952
+ }
25767
25953
  if (!showDevice && held?.showDevice === true) delete entry.showDevice;
25768
25954
  if (typeof held?.device === "string") delete entry.device;
25769
25955
  if (!transition && storedTransitionOf(held?.transition)) delete entry.transition;
25956
+ if (!speakerNotes && speakerNotesOf(held?.speakerNotes)) delete entry.speakerNotes;
25770
25957
  this.file.frames[name] = entry;
25771
25958
  this.changed = true;
25772
25959
  }
@@ -30333,7 +30520,7 @@ const boxesBodySchema = object$1({
30333
30520
  sections: boxesSchema.optional(),
30334
30521
  expectedSections: boxesSchema.optional()
30335
30522
  });
30336
- const STATUS$5 = {
30523
+ const STATUS$6 = {
30337
30524
  usage: 400,
30338
30525
  "invalid-name": 400,
30339
30526
  "project-required": 400,
@@ -30396,7 +30583,7 @@ function apiRoutes(root, actions, look, history) {
30396
30583
  code: error.code,
30397
30584
  message: error.message
30398
30585
  }
30399
- }, STATUS$5[error.code] ?? 500);
30586
+ }, STATUS$6[error.code] ?? 500);
30400
30587
  }
30401
30588
  return c.json({
30402
30589
  ok: true,
@@ -30467,7 +30654,7 @@ function apiRoutes(root, actions, look, history) {
30467
30654
  message: error.message,
30468
30655
  details: error.details
30469
30656
  }
30470
- }, STATUS$5[error.code] ?? 500);
30657
+ }, STATUS$6[error.code] ?? 500);
30471
30658
  }
30472
30659
  });
30473
30660
  return app;
@@ -30595,11 +30782,134 @@ function assetKind(name) {
30595
30782
  function isAcceptedUpload(name) {
30596
30783
  return extensionOf(name) in ACCEPTED;
30597
30784
  }
30785
+ // src/shared/records/sourcing.ts
30786
+ /** So `house.jpg` carries its license in `house.jpg.license.json` beside it. */
30787
+ const LICENSE_FILE_SUFFIX = ".license.json";
30788
+ const IMAGE_PROVIDERS = ["fal", "google"];
30789
+ /** One image a search found, numbered from 1 in the order the source ranked it. */
30790
+ const imageResultSchema = object$1({
30791
+ number: int$1().min(1),
30792
+ /** The source's own id, which `--save` takes in place of the number. */
30793
+ id: string$1(),
30794
+ title: string$1().nullable(),
30795
+ creator: string$1().nullable(),
30796
+ creatorUrl: string$1().nullable(),
30797
+ license: string$1(),
30798
+ licenseVersion: string$1().nullable(),
30799
+ licenseUrl: string$1().nullable(),
30800
+ attribution: string$1().nullable(),
30801
+ landingUrl: string$1().nullable(),
30802
+ url: string$1(),
30803
+ thumbnail: string$1().nullable(),
30804
+ width: int$1().nullable(),
30805
+ height: int$1().nullable()
30806
+ });
30807
+ /** What `image find` answers without `--save`, writing nothing. */
30808
+ const imageFindSchema = object$1({
30809
+ version: literal(1),
30810
+ query: string$1(),
30811
+ licenses: array$1(string$1()),
30812
+ results: array$1(imageResultSchema)
30813
+ });
30814
+ /** The `<file>.license.json` beside every saved image, saying where it came from. */
30815
+ const licenseFileSchema = discriminatedUnion("origin", [object$1({
30816
+ version: literal(1),
30817
+ origin: literal("found"),
30818
+ source: literal("openverse"),
30819
+ id: string$1(),
30820
+ /** The search that found it, null when it was saved by id. */
30821
+ query: string$1().nullable(),
30822
+ title: string$1().nullable(),
30823
+ creator: string$1().nullable(),
30824
+ creatorUrl: string$1().nullable(),
30825
+ license: string$1(),
30826
+ licenseVersion: string$1().nullable(),
30827
+ licenseUrl: string$1().nullable(),
30828
+ attribution: string$1().nullable(),
30829
+ landingUrl: string$1().nullable(),
30830
+ url: string$1(),
30831
+ /** ISO 8601. */
30832
+ savedAt: string$1()
30833
+ }), object$1({
30834
+ version: literal(1),
30835
+ origin: literal("generated"),
30836
+ provider: _enum$1(IMAGE_PROVIDERS),
30837
+ model: string$1(),
30838
+ prompt: string$1(),
30839
+ width: int$1(),
30840
+ height: int$1(),
30841
+ /** The price estimated before the call, in US dollars. */
30842
+ priceUsd: number(),
30843
+ savedAt: string$1()
30844
+ })]);
30845
+ /** An image saved into a project's `assets/`, with the license file written beside it. */
30846
+ const savedImageSchema = object$1({
30847
+ version: literal(1),
30848
+ project: string$1(),
30849
+ /** Relative to the project's `assets/`, the name the image landed under. */
30850
+ path: string$1(),
30851
+ licensePath: string$1(),
30852
+ license: licenseFileSchema
30853
+ });
30854
+ /** What `image generate` answers, with `saved` null on a dry run. */
30855
+ const imageGenerateSchema = object$1({
30856
+ version: literal(1),
30857
+ provider: _enum$1(IMAGE_PROVIDERS),
30858
+ model: string$1(),
30859
+ prompt: string$1(),
30860
+ /** The size the provider produces, which may round the size asked for. */
30861
+ width: int$1(),
30862
+ height: int$1(),
30863
+ priceUsd: number(),
30864
+ dryRun: boolean$1(),
30865
+ saved: savedImageSchema.nullable()
30866
+ });
30867
+ object$1({
30868
+ version: literal(1),
30869
+ /** Whether the board may generate at all, false while generating from a tab is switched off. */
30870
+ enabled: boolean$1(),
30871
+ /** The first provider whose key is set, null when none is. */
30872
+ provider: object$1({
30873
+ name: _enum$1(IMAGE_PROVIDERS),
30874
+ model: string$1(),
30875
+ /** The environment variable its key is read from. */
30876
+ key: string$1(),
30877
+ width: int$1(),
30878
+ height: int$1(),
30879
+ priceUsd: number()
30880
+ }).nullable(),
30881
+ /** Every provider's key variable, in the order generation tries them. */
30882
+ keys: array$1(string$1())
30883
+ });
30884
+ /** What `image doctor` answers, naming each key as set or unset and never its value. */
30885
+ const imageDoctorSchema = object$1({
30886
+ version: literal(1),
30887
+ /** The first GPU `nvidia-smi` reports, null when it is absent or fails. */
30888
+ gpu: object$1({
30889
+ name: string$1(),
30890
+ memoryMiB: int$1()
30891
+ }).nullable(),
30892
+ /** The ComfyUI server at `FRAMEBOARD_COMFYUI_URL`, or the default address. */
30893
+ local: object$1({
30894
+ url: string$1(),
30895
+ running: boolean$1()
30896
+ }),
30897
+ /** Each provider key by its environment variable, true when set and not empty. */
30898
+ keys: record(string$1(), boolean$1()),
30899
+ providers: array$1(object$1({
30900
+ provider: _enum$1(IMAGE_PROVIDERS),
30901
+ model: string$1(),
30902
+ key: string$1(),
30903
+ ready: boolean$1()
30904
+ })),
30905
+ /** The provider `image generate` would run on now, null when none is ready. */
30906
+ provider: _enum$1(IMAGE_PROVIDERS).nullable()
30907
+ });
30598
30908
  // src/server/board/assets.ts
30599
30909
  /**
30600
30910
  * 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.
30911
+ * paths, lock, temp, and license files, and any file whose real path leaves
30912
+ * the folder. A folder that does not exist lists as empty.
30603
30913
  */
30604
30914
  async function listAssets(projectDir) {
30605
30915
  const folder = join(projectDir, ASSETS_FOLDER);
@@ -30629,6 +30939,7 @@ async function walk(folder, prefix, real, into) {
30629
30939
  await walk(path, `${prefix}${name}/`, real, into);
30630
30940
  continue;
30631
30941
  }
30942
+ if (name.endsWith(".license.json")) continue;
30632
30943
  let target;
30633
30944
  let size;
30634
30945
  try {
@@ -30866,7 +31177,7 @@ function checkRoutes(access, checks) {
30866
31177
  }
30867
31178
  // src/server/routes/envelope.ts
30868
31179
  /** The status each refusal of a structure or history write answers with. */
30869
- const STATUS$4 = {
31180
+ const STATUS$5 = {
30870
31181
  usage: 400,
30871
31182
  "invalid-name": 400,
30872
31183
  "project-required": 400,
@@ -30904,7 +31215,7 @@ function answerRefusal(error, c) {
30904
31215
  message: error.message,
30905
31216
  details: error.details
30906
31217
  }
30907
- }, STATUS$4[error.code] ?? 500);
31218
+ }, STATUS$5[error.code] ?? 500);
30908
31219
  }
30909
31220
  /** The request's JSON body as the schema reads it, or `usage` naming what failed. */
30910
31221
  async function parseBody$1(request, schema) {
@@ -31019,7 +31330,7 @@ function processHost() {
31019
31330
  };
31020
31331
  }
31021
31332
  // src/server/routes/clipboard.ts
31022
- const STATUS$3 = {
31333
+ const STATUS$4 = {
31023
31334
  usage: 400,
31024
31335
  "project-required": 400,
31025
31336
  "project-not-found": 404,
@@ -31053,7 +31364,7 @@ function clipboardRoutes(root, access, render, clipboard) {
31053
31364
  message: error.message,
31054
31365
  details: error.details
31055
31366
  }
31056
- }, STATUS$3[error.code] ?? 500);
31367
+ }, STATUS$4[error.code] ?? 500);
31057
31368
  });
31058
31369
  app.use("/api/frames/clipboard", requireWriter(access));
31059
31370
  app.post("/api/frames/clipboard", async (c) => {
@@ -36896,10 +37207,11 @@ function escapeText(value) {
36896
37207
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
36897
37208
  }
36898
37209
  /**
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.
37210
+ * Replaces a text-only element's text, or only the text node `run` names,
37211
+ * refusing source that does not tile, since misnesting can put an end tag
37212
+ * past another's markup.
36901
37213
  */
36902
- function setText(source, element, value) {
37214
+ function setText(source, element, value, run) {
36903
37215
  const tag = element.tagName;
36904
37216
  const location = element.sourceCodeLocation;
36905
37217
  if (RAW_TEXT.has(tag)) return {
@@ -36916,15 +37228,46 @@ function setText(source, element, value) {
36916
37228
  };
36917
37229
  const from = location.startTag.endOffset;
36918
37230
  const to = location.endTag.startOffset;
37231
+ if (run !== void 0) return setRun(source, element, value, run, from, to);
36919
37232
  const [only, ...rest] = element.childNodes;
36920
37233
  if (!(only === void 0 ? from === to : rest.length === 0 && only.nodeName === "#text" && only.sourceCodeLocation?.startOffset === from && only.sourceCodeLocation.endOffset === to)) return {
36921
37234
  ok: false,
36922
37235
  detail: `<${tag}> holds more than one text node`
36923
37236
  };
36924
- const written = LEADING_NEWLINE_DROPPED.has(tag) && value.startsWith("\n") ? `\n${value}` : value;
36925
37237
  return {
36926
37238
  ok: true,
36927
- html: source.slice(0, from) + escapeText(written) + source.slice(to)
37239
+ html: source.slice(0, from) + escapeText(guarded(tag, value)) + source.slice(to)
37240
+ };
37241
+ }
37242
+ /** A value starting right after the start tag, its leading newline doubled where the parser drops one. */
37243
+ function guarded(tag, value) {
37244
+ return LEADING_NEWLINE_DROPPED.has(tag) && value.startsWith("\n") ? `\n${value}` : value;
37245
+ }
37246
+ /**
37247
+ * Splices one text node's source span, refusing one whose span leaves the
37248
+ * element's content or overlaps a sibling, since its bytes would not tile.
37249
+ */
37250
+ function setRun(source, element, value, run, from, to) {
37251
+ const tag = element.tagName;
37252
+ const nodes = element.childNodes;
37253
+ const at = nodes.filter((node) => node.nodeName === "#text")[run];
37254
+ if (!at) return {
37255
+ ok: false,
37256
+ detail: `<${tag}> holds no text run ${run}`
37257
+ };
37258
+ const position = nodes.indexOf(at);
37259
+ const start = at.sourceCodeLocation?.startOffset;
37260
+ const end = at.sourceCodeLocation?.endOffset;
37261
+ const previous = nodes[position - 1]?.sourceCodeLocation?.endOffset ?? from;
37262
+ const next = nodes[position + 1]?.sourceCodeLocation?.startOffset ?? to;
37263
+ if (start === void 0 || end === void 0 || start < previous || end > next || start < from || end > to) return {
37264
+ ok: false,
37265
+ detail: `<${tag}>'s text run ${run} does not tile its source`
37266
+ };
37267
+ const written = start === from ? guarded(tag, value) : value;
37268
+ return {
37269
+ ok: true,
37270
+ html: source.slice(0, start) + escapeText(written) + source.slice(end)
36928
37271
  };
36929
37272
  }
36930
37273
  // src/server/edit/apply.ts
@@ -36966,6 +37309,7 @@ function checkChange(change) {
36966
37309
  const invalid = checkValue(change.value);
36967
37310
  if (invalid) return invalid;
36968
37311
  }
37312
+ 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
37313
  if (change.kind === "attribute") {
36970
37314
  if (!ATTRIBUTE_NAME.test(change.name)) return refuse$2("invalid-edit", `${change.name} is not an attribute name`);
36971
37315
  if (change.name.toLowerCase() === "style") return refuse$2("invalid-edit", "style is edited one declaration at a time, as a style edit");
@@ -36989,7 +37333,7 @@ function editedAttribute(change) {
36989
37333
  }
36990
37334
  function write(source, element, change) {
36991
37335
  if (change.kind === "text") {
36992
- const written = setText(source, element, change.value);
37336
+ const written = setText(source, element, change.value, change.run);
36993
37337
  return written.ok ? written : refuse$2("not-text-only", written.detail);
36994
37338
  }
36995
37339
  if (change.kind === "attribute") {
@@ -37032,7 +37376,12 @@ function changesOnlyTarget(before, after, index, change) {
37032
37376
  const now = after.elements[index];
37033
37377
  if (!was || !now || was.tagName !== now.tagName) return false;
37034
37378
  const name = editedAttribute(change);
37035
- if (name === void 0) was.childNodes = now.childNodes;
37379
+ if (change.kind === "text" && change.run !== void 0) {
37380
+ const run = textNodes(was)[change.run];
37381
+ const written = textNodes(now)[change.run];
37382
+ if (!run) return false;
37383
+ was.childNodes = change.value === "" ? was.childNodes.filter((node) => node !== run) : was.childNodes.map((node) => node === run && written ? written : node);
37384
+ } else if (name === void 0) was.childNodes = now.childNodes;
37036
37385
  else {
37037
37386
  const written = now.attrs.find((attribute) => isNamed(attribute, name));
37038
37387
  const others = was.attrs.filter((attribute) => !isNamed(attribute, name));
@@ -37041,11 +37390,15 @@ function changesOnlyTarget(before, after, index, change) {
37041
37390
  }
37042
37391
  return serialize$1(before.document) === serialize$1(after.document);
37043
37392
  }
37393
+ function textNodes(element) {
37394
+ return element.childNodes.filter((node) => node.nodeName === "#text");
37395
+ }
37044
37396
  function textOf(element) {
37045
- return element.childNodes.map((node) => "value" in node && node.nodeName === "#text" ? node.value : "").join("");
37397
+ return textNodes(element).map((node) => node.value).join("");
37046
37398
  }
37047
37399
  /** Whether the target holds the value the change asked for. */
37048
37400
  function holdsValue(element, change) {
37401
+ if (change.kind === "text" && change.run !== void 0) return change.value === "" || textNodes(element)[change.run]?.value === change.value;
37049
37402
  if (change.kind === "text") return textOf(element) === change.value;
37050
37403
  if (change.kind === "attribute") {
37051
37404
  const stated = element.attrs.find((attribute) => isNamed(attribute, change.name));
@@ -39016,7 +39369,7 @@ function filed(file, filing) {
39016
39369
  }
39017
39370
  /** The hand-written keys a project file holds, leaving out the ones it lacks. */
39018
39371
  function filingOf(file) {
39019
- const off = isRecord$3(file.checks) ? file.checks.off : void 0;
39372
+ const off = isRecord$5(file.checks) ? file.checks.off : void 0;
39020
39373
  return {
39021
39374
  ...file.group === void 0 ? {} : { group: file.group },
39022
39375
  ...file.archived === void 0 ? {} : { archived: file.archived },
@@ -39039,7 +39392,7 @@ async function setProjectRule(root, name, rule, off, { journal } = {}) {
39039
39392
  ...projectSpec,
39040
39393
  empty: emptyProject
39041
39394
  });
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 });
39395
+ 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
39396
  const stored = filingOf(file).off;
39044
39397
  const list = isRuleList(stored) ? stored : [];
39045
39398
  const next = off ? list.includes(rule) ? list : [...list, rule] : list.filter((each) => each !== rule);
@@ -39060,8 +39413,8 @@ async function setProjectRule(root, name, rule, off, { journal } = {}) {
39060
39413
  * off and on leaves no empty object.
39061
39414
  */
39062
39415
  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 : {};
39416
+ if (off === void 0 && !(isRecord$5(file.checks) && file.checks.off !== void 0)) return file;
39417
+ const { off: _off, ...kept } = isRecord$5(file.checks) ? file.checks : {};
39065
39418
  const checks = off === void 0 ? kept : {
39066
39419
  ...kept,
39067
39420
  off
@@ -39076,7 +39429,7 @@ function withOff(file, off) {
39076
39429
  function isRuleList(value) {
39077
39430
  return Array.isArray(value) && value.every((each) => typeof each === "string");
39078
39431
  }
39079
- function isRecord$3(value) {
39432
+ function isRecord$5(value) {
39080
39433
  return typeof value === "object" && value !== null && !Array.isArray(value);
39081
39434
  }
39082
39435
  /**
@@ -40336,7 +40689,8 @@ const changeSchema = union([
40336
40689
  }),
40337
40690
  object$1({
40338
40691
  kind: literal("text"),
40339
- value
40692
+ value,
40693
+ run: int$1().min(0).optional()
40340
40694
  }),
40341
40695
  object$1({
40342
40696
  kind: literal("styles"),
@@ -41028,7 +41382,7 @@ const selectionResultSchema = object$1({
41028
41382
  tabs: int$1().min(0)
41029
41383
  });
41030
41384
  // src/server/routes/elements.ts
41031
- const STATUS$2 = {
41385
+ const STATUS$3 = {
41032
41386
  usage: 400,
41033
41387
  "project-required": 400,
41034
41388
  "project-not-found": 404,
@@ -41129,7 +41483,7 @@ function elementsRoutes(root, access, selection, tokens = null) {
41129
41483
  message: error.message,
41130
41484
  details: error.details
41131
41485
  }
41132
- }, STATUS$2[error.code] ?? 500);
41486
+ }, STATUS$3[error.code] ?? 500);
41133
41487
  });
41134
41488
  return app;
41135
41489
  }
@@ -41632,13 +41986,17 @@ const BOM = [
41632
41986
  * itself, so the one injected element a live frame keeps is the stylesheet.
41633
41987
  */
41634
41988
  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)}))`;
41989
+ /** Where the look route serves the frame bridge's script, under the running release. */
41990
+ const BRIDGE_URL = `/frameboard/bridge/v${version}/frame-bridge.js`;
41635
41991
  /**
41636
41992
  * The frame route's injected `head`, one stylesheet carrying `hash` as its one
41637
- * other attribute, since another element would shift every live index.
41993
+ * other attribute, since another element would shift every live index. Given
41994
+ * no `bridge`, as a kit preview's policy allows none, it loads no bridge.
41638
41995
  */
41639
- function frameHead(sheets, hash) {
41996
+ function frameHead(sheets, hash, bridge) {
41640
41997
  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>`;
41998
+ const script = bridge === void 0 ? "" : `<script ${LOOK_MARKER} src=${JSON.stringify(bridge)}><\/script>`;
41999
+ return `<style ${LOOK_MARKER} ${RENDERED_HASH}="${hash}">${imports.join("")}</style><script ${LOOK_MARKER}>${THEME_SCRIPT}<\/script>${script}`;
41642
42000
  }
41643
42001
  /**
41644
42002
  * Splices `head` where the browser starts its `head`, keeping every byte of
@@ -41760,7 +42118,7 @@ function frameRoutes(root, look, version, base = "") {
41760
42118
  if (held === null) return c.notFound();
41761
42119
  bytes = new TextEncoder().encode(held);
41762
42120
  }
41763
- const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project), hasKit(root, project)).map((url) => `${base}${url}`), contentHash(bytes)));
42121
+ const body = injectHead(bytes, frameHead(sheetUrls(project, look.sheets(project), hasKit(root, project)).map((url) => `${base}${url}`), contentHash(bytes), `${base}${BRIDGE_URL}`));
41764
42122
  return c.body(body, 200, {
41765
42123
  "Content-Type": contentType,
41766
42124
  "Cache-Control": "no-store"
@@ -41847,7 +42205,7 @@ async function resolveFile(root, [project, page, ...rest]) {
41847
42205
  if (!project || !page) return null;
41848
42206
  const projectSheet = rest.length === 0 && page === "tokens.css";
41849
42207
  if (rest.length === 0 && !projectSheet) return null;
41850
- if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$2(rest[0] ?? ""))) return null;
42208
+ if (page !== "assets" && !projectSheet && (rest.length > 1 || isRecord$4(rest[0] ?? ""))) return null;
41851
42209
  try {
41852
42210
  const projectDir = await realpath(join(root, project));
41853
42211
  if (!projectDir.startsWith(root + sep)) return null;
@@ -41867,9 +42225,9 @@ function servableInProject(segments) {
41867
42225
  if (segments.some((segment) => segment.startsWith("."))) return false;
41868
42226
  const [first = "", name = ""] = segments;
41869
42227
  if (segments.length === 1) return first === TOKEN_FILE;
41870
- return first === "assets" || !isRecord$2(name);
42228
+ return first === "assets" || !isRecord$4(name);
41871
42229
  }
41872
- function isRecord$2(name) {
42230
+ function isRecord$4(name) {
41873
42231
  return name === "layout.json" || name === NOTES_FILE$1;
41874
42232
  }
41875
42233
  // src/server/routes/kits.ts
@@ -41995,6 +42353,7 @@ const IMMUTABLE = "public, max-age=31536000, immutable";
41995
42353
  const RELEASE_SEGMENT = /^v\d+\.\d+\.\d+/;
41996
42354
  const CONTENT_TYPES = {
41997
42355
  ".css": "text/css; charset=utf-8",
42356
+ ".js": "text/javascript; charset=utf-8",
41998
42357
  ".woff2": "font/woff2"
41999
42358
  };
42000
42359
  /**
@@ -42030,6 +42389,14 @@ function lookRoutes({ facesDir, boardSheet }) {
42030
42389
  "Cache-Control": "no-store"
42031
42390
  });
42032
42391
  });
42392
+ app.get(BRIDGE_URL, async (c) => {
42393
+ const script = await bridgeScript();
42394
+ if (script === null) return c.notFound();
42395
+ return c.body(script, 200, {
42396
+ "Content-Type": CONTENT_TYPES[".js"] ?? "",
42397
+ "Cache-Control": fromSource ? "no-store" : IMMUTABLE
42398
+ });
42399
+ });
42033
42400
  app.get(`${FACES_URL}/*`, async (c) => {
42034
42401
  const segments = new URL(c.req.url).pathname.slice(18).split("/");
42035
42402
  const release = RELEASE_SEGMENT.test(segments[0] ?? "");
@@ -42058,6 +42425,34 @@ async function resolveFace(facesDir, segments) {
42058
42425
  return null;
42059
42426
  }
42060
42427
  }
42428
+ /** Whether this module runs from source, where no bundle sits beside it. */
42429
+ const fromSource = import.meta.url.endsWith(".ts");
42430
+ let bridge;
42431
+ /**
42432
+ * The frame bridge's script, read once from beside the bundle, or built from
42433
+ * source on a source run, so a dev server or a test serves the code as it
42434
+ * stands. A missing bundle answers null, and a failed build is tried again.
42435
+ */
42436
+ function bridgeScript() {
42437
+ bridge ??= fromSource ? buildBridge().catch((error) => {
42438
+ bridge = void 0;
42439
+ throw error;
42440
+ }) : readFile(fileURLToPath(new URL("./frame-bridge.js", import.meta.url)), "utf8").catch(() => null);
42441
+ return bridge;
42442
+ }
42443
+ /** Bundles the bridge the way `rolldown.config.ts` does, in memory. */
42444
+ async function buildBridge() {
42445
+ const { build } = await import("rolldown");
42446
+ const src = fileURLToPath(new URL("../..", import.meta.url));
42447
+ const { output } = await build({
42448
+ input: join(src, "frame-bridge", "main.ts"),
42449
+ platform: "browser",
42450
+ resolve: { alias: { "@": src } },
42451
+ write: false,
42452
+ output: { format: "iife" }
42453
+ });
42454
+ return output[0].code;
42455
+ }
42061
42456
  async function readOrNull(path) {
42062
42457
  try {
42063
42458
  return new Uint8Array(await readFile(path));
@@ -42142,7 +42537,7 @@ const IMAGE_CONTENT_TYPES = {
42142
42537
  * JPEG, GIF, and WebP. SVG is left out on purpose, since it can carry script
42143
42538
  * and the thumbnails render in the board's own page.
42144
42539
  */
42145
- function imageExtension(bytes) {
42540
+ function imageExtension$1(bytes) {
42146
42541
  const ascii = (from, to) => String.fromCharCode(...bytes.subarray(from, to));
42147
42542
  if (bytes[0] === 137 && ascii(1, 4) === "PNG") return "png";
42148
42543
  if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpg";
@@ -42157,7 +42552,7 @@ function imageExtension(bytes) {
42157
42552
  */
42158
42553
  async function saveImages(pageDir, images) {
42159
42554
  const typed = images.map((bytes, index) => {
42160
- const extension = imageExtension(bytes);
42555
+ const extension = imageExtension$1(bytes);
42161
42556
  if (extension === null) throw new FrameboardError("image-type-refused", "A note takes PNG, JPEG, GIF, or WebP images. Nothing was saved.", { index });
42162
42557
  return {
42163
42558
  bytes,
@@ -42196,7 +42591,7 @@ async function assertStored(pageDir, images) {
42196
42591
  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
42592
  }
42198
42593
  // src/server/routes/notes.ts
42199
- const STATUS$1 = {
42594
+ const STATUS$2 = {
42200
42595
  usage: 400,
42201
42596
  "project-required": 400,
42202
42597
  "project-not-found": 404,
@@ -42210,7 +42605,7 @@ const STATUS$1 = {
42210
42605
  "dispatch-failed": 502,
42211
42606
  "lock-timeout": 503
42212
42607
  };
42213
- const text = string$1().trim().min(1).max(1e5);
42608
+ const text$1 = string$1().trim().min(1).max(1e5);
42214
42609
  const session = string$1().min(1).max(256);
42215
42610
  /** Page-relative paths an upload answered, each checked against the page on write. */
42216
42611
  const images = array$1(string$1().max(256)).max(32).optional();
@@ -42223,7 +42618,7 @@ const oneAddressee = {
42223
42618
  const pinSchema = object$1({
42224
42619
  /** The frame ref, `<project>/<page>/<frame>`. */
42225
42620
  frame: string$1().min(1).max(1024),
42226
- text,
42621
+ text: text$1,
42227
42622
  images,
42228
42623
  /** The element's index, given with the `modifiedAt` the board rendered it at. */
42229
42624
  element: int$1().min(0).optional(),
@@ -42232,7 +42627,7 @@ const pinSchema = object$1({
42232
42627
  dispatch
42233
42628
  }).refine(oneAddressee.check, oneAddressee.message);
42234
42629
  const replySchema = object$1({
42235
- text,
42630
+ text: text$1,
42236
42631
  images,
42237
42632
  to: session.optional(),
42238
42633
  dispatch
@@ -42404,7 +42799,7 @@ function notesRoutes(root, access, delivery, dispatch, imageLimit = ASSET_BODY_L
42404
42799
  message: error.message,
42405
42800
  details: error.details
42406
42801
  }
42407
- }, STATUS$1[error.code] ?? 500);
42802
+ }, STATUS$2[error.code] ?? 500);
42408
42803
  });
42409
42804
  return app;
42410
42805
  }
@@ -42414,7 +42809,7 @@ async function parseBody(request, schema) {
42414
42809
  return parsed.data;
42415
42810
  }
42416
42811
  // src/server/routes/png.ts
42417
- const STATUS = {
42812
+ const STATUS$1 = {
42418
42813
  usage: 400,
42419
42814
  "project-required": 400,
42420
42815
  "project-not-found": 404,
@@ -42482,7 +42877,7 @@ function pngRoutes(root, render, renderFilmstrip) {
42482
42877
  message: error.message,
42483
42878
  details: error.details
42484
42879
  }
42485
- }, STATUS[error.code] ?? 500);
42880
+ }, STATUS$1[error.code] ?? 500);
42486
42881
  }
42487
42882
  });
42488
42883
  return app;
@@ -42612,6 +43007,711 @@ function previewRoutes(root, access, slot, { address = networkAddress } = {}) {
42612
43007
  });
42613
43008
  return app;
42614
43009
  }
43010
+ // src/server/sourcing/save.ts
43011
+ /** The most bytes one download takes, so a runaway response never fills memory. */
43012
+ const DOWNLOAD_LIMIT = 67108864;
43013
+ const IMAGE_TYPES = {
43014
+ "image/jpeg": "jpg",
43015
+ "image/png": "png",
43016
+ "image/webp": "webp",
43017
+ "image/avif": "avif",
43018
+ "image/gif": "gif",
43019
+ "image/svg+xml": "svg"
43020
+ };
43021
+ /**
43022
+ * The extension an image's media type names, else the one its URL ends in,
43023
+ * null when neither names an image a frame shows.
43024
+ */
43025
+ function imageExtension(mediaType, url) {
43026
+ const type = mediaType?.split(";")[0]?.trim().toLowerCase() ?? "";
43027
+ const fromType = IMAGE_TYPES[type];
43028
+ if (fromType !== void 0) return fromType;
43029
+ if (url === null) return null;
43030
+ const name = new URL(url).pathname.split("/").at(-1) ?? "";
43031
+ const kind = assetKind(name);
43032
+ return kind === "image" || kind === "gif" || kind === "svg" ? name.slice(name.lastIndexOf(".") + 1).toLowerCase() : null;
43033
+ }
43034
+ /**
43035
+ * Downloads a whole image into memory before anything is written, so a
43036
+ * download failing partway leaves no file. Refuses `source-failed` on a
43037
+ * failed request, a body past `limit`, or a file that is no image.
43038
+ */
43039
+ async function downloadImage(url, send, limit = DOWNLOAD_LIMIT) {
43040
+ const failed = (message, status) => new FrameboardError("source-failed", message, {
43041
+ url,
43042
+ status
43043
+ });
43044
+ let response;
43045
+ try {
43046
+ response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
43047
+ } catch (error) {
43048
+ throw failed(`The image did not download: ${error instanceof Error ? error.message : String(error)}`, null);
43049
+ }
43050
+ if (!response.ok) throw failed(`The image host answered ${response.status}.`, response.status);
43051
+ const extension = imageExtension(response.headers.get("content-type"), url);
43052
+ if (extension === null) throw failed("The download is not an image a frame shows.", response.status);
43053
+ let bytes;
43054
+ try {
43055
+ bytes = await readCapped(response, limit);
43056
+ } catch (error) {
43057
+ if (error instanceof FrameboardError) throw error;
43058
+ throw failed(`The image stopped downloading: ${error instanceof Error ? error.message : String(error)}`, response.status);
43059
+ }
43060
+ return {
43061
+ bytes,
43062
+ extension
43063
+ };
43064
+ }
43065
+ /** Reads the body chunk by chunk and stops once it passes `limit`, whatever length the host declared. */
43066
+ async function readCapped(response, limit) {
43067
+ if (Number(response.headers.get("content-length") ?? NaN) > limit) throw tooLarge(limit);
43068
+ const chunks = [];
43069
+ let total = 0;
43070
+ const reader = response.body?.getReader();
43071
+ for (let chunk = await reader?.read(); chunk && !chunk.done;) {
43072
+ total += chunk.value.byteLength;
43073
+ if (total > limit) {
43074
+ await reader?.cancel();
43075
+ throw tooLarge(limit);
43076
+ }
43077
+ chunks.push(chunk.value);
43078
+ chunk = await reader?.read();
43079
+ }
43080
+ const bytes = new Uint8Array(total);
43081
+ let offset = 0;
43082
+ for (const chunk of chunks) {
43083
+ bytes.set(chunk, offset);
43084
+ offset += chunk.byteLength;
43085
+ }
43086
+ return bytes;
43087
+ }
43088
+ function tooLarge(limit) {
43089
+ return new FrameboardError("source-failed", `The image is past ${limit / 1024 / 1024} MiB.`, { limit });
43090
+ }
43091
+ /**
43092
+ * The stem a saved file takes: `--name` when given, else the query or prompt
43093
+ * as a lowercase dashed name, else `image`. Refuses `invalid-name` for a
43094
+ * `--name` breaking the board name rule.
43095
+ */
43096
+ function savedStem(name, text) {
43097
+ if (name === void 0) return folderName(text) || "image";
43098
+ if (!isValidName(name)) throw new FrameboardError("invalid-name", `--name ${name} breaks the board's name rule, ${NAME_PATTERN.source}.`, { name });
43099
+ return name;
43100
+ }
43101
+ /**
43102
+ * Writes the image into the project's `assets/` under the first free name
43103
+ * from the stem, then its license file as `<landed name>.license.json`. A
43104
+ * license file that fails to land takes the image back out.
43105
+ */
43106
+ async function saveImage(project, stem, image, license) {
43107
+ const { added, refused } = await addAssets(project.path, [{
43108
+ name: `${stem}.${image.extension}`,
43109
+ bytes: image.bytes
43110
+ }]);
43111
+ const landed = added[0];
43112
+ if (landed === void 0) throw new FrameboardError("asset-type-refused", refused[0]?.message ?? "The image was refused.");
43113
+ const folder = join(project.path, ASSETS_FOLDER);
43114
+ const licensePath = `${landed.path}${LICENSE_FILE_SUFFIX}`;
43115
+ const temp = join(folder, `${randomBytes(6).toString("hex")}${TEMP_SUFFIX}`);
43116
+ try {
43117
+ await writeFile(temp, `${JSON.stringify(license, null, 2)}\n`, { flag: "wx" });
43118
+ await rename(temp, join(folder, licensePath));
43119
+ } catch (error) {
43120
+ await Promise.all([rm(temp, { force: true }), rm(join(folder, landed.path), { force: true })]);
43121
+ throw error;
43122
+ }
43123
+ return {
43124
+ version: 1,
43125
+ project: project.name,
43126
+ path: landed.path,
43127
+ licensePath,
43128
+ license
43129
+ };
43130
+ }
43131
+ // src/server/sourcing/providers/provider.ts
43132
+ /**
43133
+ * The refusal a provider's failure answers, with its status and its own
43134
+ * message, the key scrubbed from that message should the provider echo it.
43135
+ */
43136
+ function providerFailed(provider, status, reason, key) {
43137
+ const scrubbed = reason.split(key).join("***").slice(0, 300);
43138
+ return new FrameboardError("provider-failed", `${provider} ${status === null ? "did not answer" : `answered ${status}`}: ${scrubbed}`, {
43139
+ provider,
43140
+ status
43141
+ });
43142
+ }
43143
+ /** A dollar amount rounded up to a hundredth of a cent, so an estimate never reads low. */
43144
+ function roundPrice(usd) {
43145
+ return Math.ceil(usd * 1e4 - 1e-9) / 1e4;
43146
+ }
43147
+ // src/server/sourcing/providers/fal.ts
43148
+ /** fal's synchronous run endpoint for FLUX.1 schnell. */
43149
+ const FAL_ENDPOINT = "https://fal.run/fal-ai/flux/schnell";
43150
+ /** fal's published price for FLUX.1 schnell, per megapixel of output. */
43151
+ const FAL_PRICE_PER_MEGAPIXEL = .003;
43152
+ /** FLUX.1 schnell on fal, which takes any width and height as asked. */
43153
+ const fal = {
43154
+ name: "fal",
43155
+ model: "fal-ai/flux/schnell",
43156
+ keyEnv: "FAL_KEY",
43157
+ sizeFor: (asked) => asked,
43158
+ priceFor: ({ width, height }) => roundPrice(width * height / 1e6 * FAL_PRICE_PER_MEGAPIXEL),
43159
+ async generate({ prompt, size, key }, send) {
43160
+ let response;
43161
+ try {
43162
+ response = await send(FAL_ENDPOINT, {
43163
+ method: "POST",
43164
+ headers: {
43165
+ Authorization: `Key ${key}`,
43166
+ "Content-Type": "application/json"
43167
+ },
43168
+ body: JSON.stringify({
43169
+ prompt,
43170
+ image_size: size,
43171
+ num_images: 1,
43172
+ output_format: "jpeg",
43173
+ sync_mode: true
43174
+ })
43175
+ });
43176
+ } catch (error) {
43177
+ throw providerFailed("fal", null, String(error), key);
43178
+ }
43179
+ const body = await response.json().catch(() => null);
43180
+ if (!response.ok) throw providerFailed("fal", response.status, detailOf(body), key);
43181
+ const url = firstImageUrl(body);
43182
+ const image = url === null ? null : await fetchImage(url, send);
43183
+ if (image === null) throw providerFailed("fal", response.status, "no image came back", key);
43184
+ return image;
43185
+ }
43186
+ };
43187
+ function firstImageUrl(body) {
43188
+ if (typeof body !== "object" || body === null || !("images" in body)) return null;
43189
+ const [first] = Array.isArray(body.images) ? body.images : [];
43190
+ return typeof first === "object" && first !== null && "url" in first && typeof first.url === "string" ? first.url : null;
43191
+ }
43192
+ /** The image a data URI holds, or the one a hosted URL serves, null when neither is an image. */
43193
+ async function fetchImage(url, send) {
43194
+ const data = /^data:([^;,]+)(;base64)?,(.*)$/s.exec(url);
43195
+ if (data) {
43196
+ const extension = imageExtension(data[1] ?? null, null);
43197
+ if (extension === null || data[2] === void 0) return null;
43198
+ return {
43199
+ bytes: new Uint8Array(Buffer.from(data[3] ?? "", "base64")),
43200
+ extension
43201
+ };
43202
+ }
43203
+ const response = await send(url).catch(() => null);
43204
+ if (!response?.ok) return null;
43205
+ const extension = imageExtension(response.headers.get("content-type"), url);
43206
+ if (extension === null) return null;
43207
+ return {
43208
+ bytes: new Uint8Array(await response.arrayBuffer()),
43209
+ extension
43210
+ };
43211
+ }
43212
+ function detailOf(body) {
43213
+ if (typeof body === "object" && body !== null && "detail" in body) return typeof body.detail === "string" ? body.detail : JSON.stringify(body.detail);
43214
+ return "the request was refused";
43215
+ }
43216
+ // src/server/sourcing/providers/google.ts
43217
+ /** The Gemini API's Interactions endpoint, the one its image guide calls. */
43218
+ const GOOGLE_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/interactions";
43219
+ /** The API revision the request shape below was written against. */
43220
+ const GOOGLE_API_REVISION = "2026-05-20";
43221
+ /** Google's published price for one 1K image from Nano Banana 2.1. */
43222
+ const GOOGLE_PRICE_1K = .0336;
43223
+ /** Each aspect ratio Nano Banana 2.1 takes, with the size it draws at 1K. */
43224
+ const ASPECT_RATIOS = {
43225
+ "1:1": {
43226
+ width: 1024,
43227
+ height: 1024
43228
+ },
43229
+ "1:4": {
43230
+ width: 512,
43231
+ height: 2048
43232
+ },
43233
+ "1:8": {
43234
+ width: 384,
43235
+ height: 3072
43236
+ },
43237
+ "2:3": {
43238
+ width: 848,
43239
+ height: 1264
43240
+ },
43241
+ "3:2": {
43242
+ width: 1264,
43243
+ height: 848
43244
+ },
43245
+ "3:4": {
43246
+ width: 896,
43247
+ height: 1200
43248
+ },
43249
+ "4:1": {
43250
+ width: 2048,
43251
+ height: 512
43252
+ },
43253
+ "4:3": {
43254
+ width: 1200,
43255
+ height: 896
43256
+ },
43257
+ "4:5": {
43258
+ width: 928,
43259
+ height: 1152
43260
+ },
43261
+ "5:4": {
43262
+ width: 1152,
43263
+ height: 928
43264
+ },
43265
+ "8:1": {
43266
+ width: 3072,
43267
+ height: 384
43268
+ },
43269
+ "9:16": {
43270
+ width: 768,
43271
+ height: 1376
43272
+ },
43273
+ "16:9": {
43274
+ width: 1376,
43275
+ height: 768
43276
+ },
43277
+ "21:9": {
43278
+ width: 1584,
43279
+ height: 672
43280
+ }
43281
+ };
43282
+ /** The aspect ratio nearest the size asked, compared on a log scale so tall and wide weigh alike. */
43283
+ function aspectRatioFor({ width, height }) {
43284
+ const asked = Math.log(width / height);
43285
+ let best = "1:1";
43286
+ let distance = Number.POSITIVE_INFINITY;
43287
+ for (const [ratio, size] of Object.entries(ASPECT_RATIOS)) {
43288
+ const gap = Math.abs(Math.log(size.width / size.height) - asked);
43289
+ if (gap < distance) {
43290
+ best = ratio;
43291
+ distance = gap;
43292
+ }
43293
+ }
43294
+ return best;
43295
+ }
43296
+ /** Nano Banana 2.1 at 1K, at the aspect ratio nearest the size asked. */
43297
+ const google = {
43298
+ name: "google",
43299
+ model: "gemini-nano-banana-2.1",
43300
+ keyEnv: "GEMINI_API_KEY",
43301
+ sizeFor: (asked) => ASPECT_RATIOS[aspectRatioFor(asked)] ?? asked,
43302
+ priceFor: () => GOOGLE_PRICE_1K,
43303
+ async generate({ prompt, size, key }, send) {
43304
+ let response;
43305
+ try {
43306
+ response = await send(GOOGLE_ENDPOINT, {
43307
+ method: "POST",
43308
+ headers: {
43309
+ "x-goog-api-key": key,
43310
+ "Content-Type": "application/json",
43311
+ "Api-Revision": GOOGLE_API_REVISION
43312
+ },
43313
+ body: JSON.stringify({
43314
+ model: google.model,
43315
+ input: [{
43316
+ type: "text",
43317
+ text: prompt
43318
+ }],
43319
+ response_format: {
43320
+ type: "image",
43321
+ mime_type: "image/jpeg",
43322
+ aspect_ratio: aspectRatioFor(size),
43323
+ image_size: "1K"
43324
+ }
43325
+ })
43326
+ });
43327
+ } catch (error) {
43328
+ throw providerFailed("google", null, String(error), key);
43329
+ }
43330
+ const body = await response.json().catch(() => null);
43331
+ if (!response.ok) throw providerFailed("google", response.status, messageOf(body), key);
43332
+ const image = imageOf(body);
43333
+ const extension = imageExtension(image?.mimeType ?? "image/jpeg", null);
43334
+ if (image === null || extension === null) throw providerFailed("google", response.status, "no image came back", key);
43335
+ return {
43336
+ bytes: new Uint8Array(Buffer.from(image.data, "base64")),
43337
+ extension
43338
+ };
43339
+ }
43340
+ };
43341
+ /** The first image the interaction output, from `output_image` or else its model output steps. */
43342
+ function imageOf(body) {
43343
+ if (!isRecord$3(body)) return null;
43344
+ const blocks = [body.output_image];
43345
+ 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 : []);
43346
+ for (const block of blocks) {
43347
+ if (!isRecord$3(block) || typeof block.data !== "string") continue;
43348
+ if (block.type !== void 0 && block.type !== "image") continue;
43349
+ return {
43350
+ data: block.data,
43351
+ mimeType: typeof block.mime_type === "string" ? block.mime_type : null
43352
+ };
43353
+ }
43354
+ return null;
43355
+ }
43356
+ function messageOf(body) {
43357
+ if (isRecord$3(body) && isRecord$3(body.error)) return typeof body.error.message === "string" ? body.error.message : "the request was refused";
43358
+ return "the request was refused";
43359
+ }
43360
+ function isRecord$3(value) {
43361
+ return typeof value === "object" && value !== null;
43362
+ }
43363
+ // src/server/sourcing/generate.ts
43364
+ /** Every provider in the order `image generate` tries them. */
43365
+ const PROVIDERS = [fal, google];
43366
+ /** A provider's key, null when unset or empty, so an empty string never reaches a request. */
43367
+ function keyOf(provider, env) {
43368
+ const key = env[provider.keyEnv]?.trim();
43369
+ return key === void 0 || key === "" ? null : key;
43370
+ }
43371
+ /**
43372
+ * The provider a generation runs on, the one named or else the first whose
43373
+ * key is set, with the size it produces and its price. Makes no request.
43374
+ * Refuses `no-provider` when none is ready, and `usage` for an unknown name.
43375
+ */
43376
+ function planGeneration(request, env) {
43377
+ const candidates = request.provider === void 0 ? PROVIDERS : PROVIDERS.filter((each) => each.name === request.provider);
43378
+ if (candidates.length === 0) throw new FrameboardError("usage", `--provider ${request.provider} is not one of ${IMAGE_PROVIDERS.join(", ")}.`, { providers: [...IMAGE_PROVIDERS] });
43379
+ for (const provider of candidates) {
43380
+ const key = keyOf(provider, env);
43381
+ if (key === null) continue;
43382
+ const size = provider.sizeFor(request.size);
43383
+ return {
43384
+ provider,
43385
+ prompt: request.prompt,
43386
+ size,
43387
+ priceUsd: provider.priceFor(size),
43388
+ key
43389
+ };
43390
+ }
43391
+ const keys = candidates.map((each) => each.keyEnv);
43392
+ throw new FrameboardError("no-provider", `No image provider is ready. Set ${keys.join(" or ")} in the environment.`, { keys });
43393
+ }
43394
+ /** Runs a planned call, the one point a generation spends. */
43395
+ function generateImage(plan, send) {
43396
+ return plan.provider.generate({
43397
+ prompt: plan.prompt,
43398
+ size: plan.size,
43399
+ key: plan.key
43400
+ }, send);
43401
+ }
43402
+ // src/server/sourcing/openverse.ts
43403
+ const OPENVERSE_API = "https://api.openverse.org/v1/images/";
43404
+ /** Public domain alone, so a saved image owes nobody credit. */
43405
+ const DEFAULT_LICENSES = ["cc0", "pdm"];
43406
+ /** `--credited` adds the licenses that ask only for credit, never a share-alike or non-commercial one. */
43407
+ const CREDITED_LICENSES = [...DEFAULT_LICENSES, "by"];
43408
+ function licensesFor({ credited }) {
43409
+ return [...credited ? CREDITED_LICENSES : DEFAULT_LICENSES];
43410
+ }
43411
+ /**
43412
+ * One page of Openverse results for the query, numbered from 1 in the order
43413
+ * Openverse ranked them, empty when nothing matched. A refusal or a failed
43414
+ * request throws `source-failed` with the status in the details.
43415
+ */
43416
+ async function searchImages(query, options, send) {
43417
+ const url = new URL(OPENVERSE_API);
43418
+ url.searchParams.set("q", query);
43419
+ url.searchParams.set("license", licensesFor(options).join(","));
43420
+ url.searchParams.set("page_size", String(20));
43421
+ const body = await request(url, send);
43422
+ return (isRecord$2(body) && Array.isArray(body.results) ? body.results : []).map(toImage).filter((image) => image !== null).map((image, index) => ({
43423
+ number: index + 1,
43424
+ ...image
43425
+ }));
43426
+ }
43427
+ /**
43428
+ * One image by its Openverse id, refusing `result-not-found` for an id
43429
+ * Openverse does not hold or one under a license the options do not allow.
43430
+ */
43431
+ async function imageById(id, options, send) {
43432
+ const missing = (reason) => new FrameboardError("result-not-found", reason, { id });
43433
+ const image = toImage(await request(new URL(`${encodeURIComponent(id)}/`, OPENVERSE_API), send, missing));
43434
+ if (image === null) throw missing(`Openverse holds no image ${id}.`);
43435
+ const allowed = licensesFor(options);
43436
+ 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.`, {
43437
+ id,
43438
+ license: image.license,
43439
+ licenses: allowed
43440
+ });
43441
+ return image;
43442
+ }
43443
+ /** The license file for an Openverse image, `query` null when it was saved by id. */
43444
+ function foundLicense(image, query, savedAt) {
43445
+ return {
43446
+ version: 1,
43447
+ origin: "found",
43448
+ source: "openverse",
43449
+ id: image.id,
43450
+ query,
43451
+ title: image.title,
43452
+ creator: image.creator,
43453
+ creatorUrl: image.creatorUrl,
43454
+ license: image.license,
43455
+ licenseVersion: image.licenseVersion,
43456
+ licenseUrl: image.licenseUrl,
43457
+ attribution: image.attribution,
43458
+ landingUrl: image.landingUrl,
43459
+ url: image.url,
43460
+ savedAt: savedAt.toISOString()
43461
+ };
43462
+ }
43463
+ async function request(url, send, missing) {
43464
+ let response;
43465
+ try {
43466
+ response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
43467
+ } catch (error) {
43468
+ throw new FrameboardError("source-failed", `Openverse did not answer: ${error instanceof Error ? error.message : String(error)}`, {
43469
+ source: "openverse",
43470
+ status: null
43471
+ });
43472
+ }
43473
+ if (response.status === 404 && missing) throw missing(`Openverse holds no image at ${url.pathname}.`);
43474
+ if (!response.ok) throw new FrameboardError("source-failed", `Openverse answered ${response.status}${response.status === 429 ? ", its limit for anonymous requests" : ""}.`, {
43475
+ source: "openverse",
43476
+ status: response.status
43477
+ });
43478
+ try {
43479
+ return await response.json();
43480
+ } catch {
43481
+ throw new FrameboardError("source-failed", "Openverse answered something other than JSON.", {
43482
+ source: "openverse",
43483
+ status: response.status
43484
+ });
43485
+ }
43486
+ }
43487
+ /** Openverse's snake_case result as the record's fields, null when it lacks an id, a license, or a URL. */
43488
+ function toImage(raw) {
43489
+ if (!isRecord$2(raw)) return null;
43490
+ const id = text(raw.id);
43491
+ const license = text(raw.license);
43492
+ const url = text(raw.url);
43493
+ if (id === null || license === null || url === null) return null;
43494
+ return {
43495
+ id,
43496
+ title: text(raw.title),
43497
+ creator: text(raw.creator),
43498
+ creatorUrl: text(raw.creator_url),
43499
+ license,
43500
+ licenseVersion: text(raw.license_version),
43501
+ licenseUrl: text(raw.license_url),
43502
+ attribution: text(raw.attribution),
43503
+ landingUrl: text(raw.foreign_landing_url),
43504
+ url,
43505
+ thumbnail: text(raw.thumbnail),
43506
+ width: integer(raw.width),
43507
+ height: integer(raw.height)
43508
+ };
43509
+ }
43510
+ function isRecord$2(value) {
43511
+ return typeof value === "object" && value !== null;
43512
+ }
43513
+ function text(value) {
43514
+ return typeof value === "string" && value !== "" ? value : null;
43515
+ }
43516
+ function integer(value) {
43517
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
43518
+ }
43519
+ // src/server/routes/sourcing.ts
43520
+ /** How long a search waits on Openverse before the panel says it did not answer. */
43521
+ const FIND_TIMEOUT_MS = 15e3;
43522
+ /** How long each request of a save, its lookup and its download, may take. */
43523
+ const SAVE_TIMEOUT_MS = 6e4;
43524
+ /** How long a provider may take, so a provider that never answers frees the button. */
43525
+ const GENERATE_TIMEOUT_MS = 12e4;
43526
+ /** The size the panel asks a provider for, the verb's own default. */
43527
+ const GENERATE_SIZE = {
43528
+ width: 1024,
43529
+ height: 1024
43530
+ };
43531
+ const queryLimit = string$1().trim().min(1).max(200);
43532
+ const saveBodySchema = object$1({
43533
+ id: string$1().min(1).max(200),
43534
+ query: queryLimit,
43535
+ credited: boolean$1().default(false)
43536
+ });
43537
+ const generateBodySchema = object$1({ prompt: string$1().trim().min(1).max(2e3) });
43538
+ const STATUS = {
43539
+ usage: 400,
43540
+ "invalid-name": 400,
43541
+ "project-not-found": 404,
43542
+ "result-not-found": 404,
43543
+ "no-provider": 409,
43544
+ "asset-type-refused": 422,
43545
+ "source-failed": 502,
43546
+ "provider-failed": 502
43547
+ };
43548
+ /**
43549
+ * A project's image sourcing under `/api/projects/:project/sourcing`, calling
43550
+ * the modules `frameboard image` calls. Finding and the provider's price read
43551
+ * only; saving and generating need a writer. No answer carries a key.
43552
+ */
43553
+ function sourcingRoutes(root, access, { send = (input, init) => fetch(input, init), env = process.env, generate = false } = {}) {
43554
+ const app = new Hono();
43555
+ const authorized = requireWriter(access);
43556
+ const base = "/api/projects/:project/sourcing";
43557
+ const saving = /* @__PURE__ */ new Map();
43558
+ let generating = false;
43559
+ app.onError((error, c) => answer(error, c));
43560
+ app.get(`${base}/find`, async (c) => {
43561
+ projectOf$1(root, c.req.param("project"));
43562
+ const query = queryLimit.safeParse(c.req.query("q") ?? "");
43563
+ if (!query.success) throw new FrameboardError("usage", "Send ?q=<what the image shows>, up to 200 characters.");
43564
+ const search = { credited: c.req.query("credited") === "true" };
43565
+ const record = {
43566
+ version: 1,
43567
+ query: query.data,
43568
+ licenses: licensesFor(search),
43569
+ results: await searchImages(query.data, search, timed(send, FIND_TIMEOUT_MS))
43570
+ };
43571
+ return c.json({
43572
+ ok: true,
43573
+ data: record
43574
+ });
43575
+ });
43576
+ app.post(`${base}/save`, authorized, async (c) => {
43577
+ const project = projectOf$1(root, c.req.param("project"));
43578
+ const body = await parseBody$1(c.req.raw, saveBodySchema);
43579
+ const key = JSON.stringify([
43580
+ project.name,
43581
+ body.id,
43582
+ body.credited
43583
+ ]);
43584
+ let pending = saving.get(key);
43585
+ if (pending === void 0) {
43586
+ pending = saveFound(project, body, timed(send, SAVE_TIMEOUT_MS)).finally(() => saving.delete(key));
43587
+ saving.set(key, pending);
43588
+ }
43589
+ return c.json({
43590
+ ok: true,
43591
+ data: await pending
43592
+ });
43593
+ });
43594
+ app.get(`${base}/provider`, (c) => {
43595
+ projectOf$1(root, c.req.param("project"));
43596
+ return c.json({
43597
+ ok: true,
43598
+ data: offer(env, generate)
43599
+ });
43600
+ });
43601
+ app.post(`${base}/generate`, authorized, async (c) => {
43602
+ const project = projectOf$1(root, c.req.param("project"));
43603
+ if (!generate) return c.json({
43604
+ ok: false,
43605
+ error: {
43606
+ code: "generate-off",
43607
+ message: "Generating from the board is off in this release. Run `frameboard image generate` instead."
43608
+ }
43609
+ }, 403);
43610
+ const { prompt } = await parseBody$1(c.req.raw, generateBodySchema);
43611
+ if (generating) return c.json({
43612
+ ok: false,
43613
+ error: {
43614
+ code: "generate-busy",
43615
+ message: "An image is already generating. Wait for it to land."
43616
+ }
43617
+ }, 429);
43618
+ const plan = planGeneration({
43619
+ prompt,
43620
+ size: GENERATE_SIZE
43621
+ }, env);
43622
+ generating = true;
43623
+ try {
43624
+ const bytes = await generateImage(plan, timed(send, GENERATE_TIMEOUT_MS));
43625
+ const saved = await saveImage(project, savedStem(void 0, prompt), bytes, {
43626
+ version: 1,
43627
+ origin: "generated",
43628
+ provider: plan.provider.name,
43629
+ model: plan.provider.model,
43630
+ prompt,
43631
+ ...plan.size,
43632
+ priceUsd: plan.priceUsd,
43633
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
43634
+ });
43635
+ const record = {
43636
+ version: 1,
43637
+ provider: plan.provider.name,
43638
+ model: plan.provider.model,
43639
+ prompt,
43640
+ ...plan.size,
43641
+ priceUsd: plan.priceUsd,
43642
+ dryRun: false,
43643
+ saved
43644
+ };
43645
+ return c.json({
43646
+ ok: true,
43647
+ data: record
43648
+ });
43649
+ } finally {
43650
+ generating = false;
43651
+ }
43652
+ });
43653
+ return app;
43654
+ }
43655
+ async function saveFound(project, body, send) {
43656
+ const image = await imageById(body.id, { credited: body.credited }, send);
43657
+ return saveImage(project, savedStem(void 0, body.query), await downloadImage(image.url, send), foundLicense(image, body.query, /* @__PURE__ */ new Date()));
43658
+ }
43659
+ /** The provider a generation would run on and its price, naming each key by its variable alone. */
43660
+ function offer(env, enabled) {
43661
+ const keys = PROVIDERS.map((provider) => provider.keyEnv);
43662
+ try {
43663
+ const plan = planGeneration({
43664
+ prompt: "",
43665
+ size: GENERATE_SIZE
43666
+ }, env);
43667
+ return {
43668
+ version: 1,
43669
+ enabled,
43670
+ provider: {
43671
+ name: plan.provider.name,
43672
+ model: plan.provider.model,
43673
+ key: plan.provider.keyEnv,
43674
+ ...plan.size,
43675
+ priceUsd: plan.priceUsd
43676
+ },
43677
+ keys
43678
+ };
43679
+ } catch (error) {
43680
+ if (!(error instanceof FrameboardError) || error.code !== "no-provider") throw error;
43681
+ return {
43682
+ version: 1,
43683
+ enabled,
43684
+ provider: null,
43685
+ keys
43686
+ };
43687
+ }
43688
+ }
43689
+ function projectOf$1(root, name) {
43690
+ const path = join(root, name);
43691
+ if (!isValidName(name) || !existsSync(path)) throw new FrameboardError("project-not-found", `No project named ${name} in this board.`);
43692
+ return {
43693
+ name,
43694
+ path
43695
+ };
43696
+ }
43697
+ /** `send` with every request abandoned after `ms`, which the modules report as their source not answering. */
43698
+ function timed(send, ms) {
43699
+ return ((input, init) => send(input, {
43700
+ ...init,
43701
+ signal: AbortSignal.timeout(ms)
43702
+ }));
43703
+ }
43704
+ function answer(error, c) {
43705
+ if (!(error instanceof FrameboardError)) throw error;
43706
+ return c.json({
43707
+ ok: false,
43708
+ error: {
43709
+ code: error.code,
43710
+ message: error.message,
43711
+ details: error.details
43712
+ }
43713
+ }, STATUS[error.code] ?? 500);
43714
+ }
42615
43715
  // src/server/board/paste.ts
42616
43716
  /** Reads each frame's file and placement under its page's lock, in the order given. */
42617
43717
  async function holdFrames(root, refs, options) {
@@ -43844,7 +44944,10 @@ function createWarmRenderer({ baseUrl, browser, scale: defaultScale }) {
43844
44944
  } finally {
43845
44945
  await opened.close();
43846
44946
  }
43847
- return device ? drawBezel(open, shot, frame.box, device, scale) : shot;
44947
+ return device ? drawBezel(open, shot, frame.box, {
44948
+ device,
44949
+ pose: frame.pose
44950
+ }, scale) : shot;
43848
44951
  });
43849
44952
  queue = run.catch(() => {});
43850
44953
  return run;
@@ -43882,8 +44985,7 @@ async function shootElement(page, ref, index, scale) {
43882
44985
  * A frame's shot drawn inside a device's body, as the board draws it, on a
43883
44986
  * page the size of the body, so the PNG holds the body and nothing past it.
43884
44987
  */
43885
- async function drawBezel(browser, shot, box, device, scale) {
43886
- const { screenRadius } = BEZELS[device];
44988
+ async function drawBezel(browser, shot, box, { device, pose = "closed" }, scale) {
43887
44989
  const outer = bezelBox({
43888
44990
  x: 0,
43889
44991
  y: 0,
@@ -43899,9 +45001,9 @@ async function drawBezel(browser, shot, box, device, scale) {
43899
45001
  });
43900
45002
  try {
43901
45003
  const page = await context.newPage();
43902
- 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" });
45004
+ 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) : device === "foldable" ? foldableMarks(pose) : "";
45005
+ const radius = screenCorners(device);
45006
+ 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
45007
  return await page.screenshot({
43906
45008
  omitBackground: true,
43907
45009
  caret: "hide"
@@ -43919,8 +45021,15 @@ function laptopMarks(box) {
43919
45021
  const edge = `1px solid ${BEZEL_COLORS.edge}`;
43920
45022
  return `<span style="position:absolute;box-sizing:border-box;left:${chin.x}px;top:${chin.y}px;width:${chin.width}px;height:${chin.height}px;background:${BEZEL_COLORS.body};border-left:${edge};border-right:${edge}"></span><span style="position:absolute;box-sizing:border-box;left:${base.x}px;top:${base.y}px;width:${base.width}px;height:${base.height}px;background:${BEZEL_COLORS.base};border:${edge};border-radius:0 0 ${LAPTOP_BASE.radius}px ${LAPTOP_BASE.radius}px"></span>`;
43921
45023
  }
43922
- function pill(width, height, color) {
43923
- return `position:absolute;left:50%;transform:translateX(-50%);width:${width}px;height:${height}px;border-radius:${height / 2}px;background:${color};`;
45024
+ /** The foldable's fold band, island, and home bar as the board draws them for a pose. */
45025
+ function foldableMarks(pose) {
45026
+ const band = foldBand(pose);
45027
+ const reach = pose === "half" ? -BEZELS.foldable.border : 0;
45028
+ const island = pill(FOLDABLE_ISLAND.width, FOLDABLE_ISLAND.height, BEZEL_COLORS.island, islandCenter(pose));
45029
+ return (band ? `<span style="position:absolute;left:50%;transform:translateX(-50%);top:${reach}px;bottom:${reach}px;width:${band.width}px;background:${band.background}"></span>` : "") + `<span style="${island}top:${FOLDABLE_ISLAND.top}px"></span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>`;
45030
+ }
45031
+ function pill(width, height, color, center = .5) {
45032
+ return `position:absolute;left:${center * 100}%;transform:translateX(-50%);width:${width}px;height:${height}px;border-radius:${height / 2}px;background:${color};`;
43924
45033
  }
43925
45034
  // src/server/capture/fit.ts
43926
45035
  /** The widest a hugging width grows, past which the layout check reports the content clipped. */
@@ -45486,7 +46595,10 @@ const pasteSchema = object$1({
45486
46595
  });
45487
46596
  const frameDeviceSchema = object$1({
45488
46597
  refs,
45489
- show: boolean$1()
46598
+ /** Absent leaves the device as it stands, but for naming a foldable, which shows it. */
46599
+ show: boolean$1().optional(),
46600
+ foldable: boolean$1().optional(),
46601
+ pose: _enum$1(POSES).optional()
45490
46602
  });
45491
46603
  /** More widths than any device list offers, so a body cannot grow without bound. */
45492
46604
  const widthList = array$1(int$1().min(1)).max(64);
@@ -45516,6 +46628,15 @@ const frameTransitionSchema = object$1({
45516
46628
  refs,
45517
46629
  transition: transition.nullable()
45518
46630
  });
46631
+ /**
46632
+ * Blank text clears the note, and the setter refuses one past its limit.
46633
+ * `expected` is the note the edit began from, so one an agent set since is kept.
46634
+ */
46635
+ const frameSpeakerNotesSchema = object$1({
46636
+ ref,
46637
+ speakerNotes: string$1(),
46638
+ expected: string$1()
46639
+ });
45519
46640
  const frameFlagSchema = object$1({
45520
46641
  refs,
45521
46642
  flag: _enum$1(["hidden", "locked"]),
@@ -45843,12 +46964,14 @@ function structureRoutes(root, access, history, measure, tokens = null) {
45843
46964
  data: frames
45844
46965
  });
45845
46966
  });
45846
- /** Shows or hides the device each frame's width names, in one step, leaving every frame file alone. */
46967
+ /** Shows or hides each frame's device, names the foldable, or folds it, in one step, leaving every frame file alone. */
45847
46968
  app.post("/api/frame/device", async (c) => {
45848
46969
  const body = await parseBody$1(c.req.raw, frameDeviceSchema);
45849
46970
  const frames = await eachFrame(body.refs, (frame, journal) => setFrameDevice(root, frame, body.show, {
45850
46971
  cwd,
45851
- journal
46972
+ journal,
46973
+ foldable: body.foldable,
46974
+ pose: body.pose
45852
46975
  }), (records) => records.map((record) => record.ref));
45853
46976
  return c.json({
45854
46977
  ok: true,
@@ -45887,6 +47010,20 @@ function structureRoutes(root, access, history, measure, tokens = null) {
45887
47010
  data: frames
45888
47011
  });
45889
47012
  });
47013
+ /** Sets or clears one frame's speaker note in one step, leaving its file alone. */
47014
+ app.post("/api/frame/speaker-notes", async (c) => {
47015
+ const body = await parseBody$1(c.req.raw, frameSpeakerNotesSchema);
47016
+ await refuseHeldFrames([body.ref]);
47017
+ const [frame] = await eachFrame([body.ref], (target, journal) => setFrameSpeakerNotes(root, target, body.speakerNotes, {
47018
+ cwd,
47019
+ journal,
47020
+ expected: body.expected
47021
+ }), (records) => records.map((record) => record.ref));
47022
+ return c.json({
47023
+ ok: true,
47024
+ data: frame
47025
+ });
47026
+ });
45890
47027
  app.post("/api/frame/height", async (c) => {
45891
47028
  const body = await parseBody$1(c.req.raw, frameHeightSchema);
45892
47029
  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 +47285,23 @@ function cardFrames(project) {
46148
47285
  }
46149
47286
  // src/server/routes/thumbnails.ts
46150
47287
  /**
46151
- * The thumbnail routes, queueing stale renders so home hears each landing on
47288
+ * The thumbnail routes, answering each project's card frames or one named
47289
+ * page's visible frames, queueing stale renders so home hears each landing on
46152
47290
  * the socket, and caching a capture for good, since a change takes a new stamp.
46153
47291
  */
46154
47292
  function thumbnailRoutes(root, store) {
46155
47293
  const app = new Hono();
46156
47294
  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 }) => ({
47295
+ const theme = themeOf(c.req.query("theme"), "Ask for /api/thumbnails?theme=<light|dark>&page=<page-ref>.");
47296
+ const board = await scanBoard(root);
47297
+ const page = c.req.query("page");
47298
+ const frames = (page === void 0 ? board.projects.flatMap((project) => cardFrames(project)) : visibleFramesOf(board, page)).map(({ ref, box }) => ({
46159
47299
  ref,
46160
47300
  box: {
46161
47301
  width: box.width,
46162
47302
  height: box.height
46163
47303
  }
46164
- })));
47304
+ }));
46165
47305
  return c.json({
46166
47306
  ok: true,
46167
47307
  data: { stamps: store.ask(theme, frames) }
@@ -46186,6 +47326,11 @@ function thumbnailRoutes(root, store) {
46186
47326
  app.onError(answerRefusal);
46187
47327
  return app;
46188
47328
  }
47329
+ function visibleFramesOf(board, ref) {
47330
+ const page = board.projects.flatMap((project) => project.pages).find((candidate) => candidate.ref === ref);
47331
+ if (!page) throw new FrameboardError("page-not-found", `No page ${ref} on the board.`, { page: ref });
47332
+ return page.frames.filter((frame) => !frame.hidden);
47333
+ }
46189
47334
  function themeOf(value, usage) {
46190
47335
  if (!isTheme$1(value)) throw new FrameboardError("usage", usage, { theme: value ?? "" });
46191
47336
  return value;
@@ -46352,6 +47497,7 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
46352
47497
  app.route("/", historyRoutes(actions.access, history));
46353
47498
  app.route("/", notesRoutes(root, actions.access, delivery, dispatch));
46354
47499
  app.route("/", assetsRoutes(root, actions.access, { usage: assetUsage }));
47500
+ app.route("/", sourcingRoutes(root, actions.access));
46355
47501
  app.route("/", elementsRoutes(root, actions.access, selection, given));
46356
47502
  app.route("/", findRoutes(root));
46357
47503
  app.route("/", claimsRoutes(root, actions.access));
@@ -47174,10 +48320,17 @@ const frameRecordSchema = object$1({
47174
48320
  })),
47175
48321
  /** Whether the board draws the frame inside a device, absent when it does not. */
47176
48322
  showDevice: boolean$1().optional(),
47177
- /** The device the frame's width names while it shows one, absent when off or under 320 wide. */
48323
+ /**
48324
+ * The device the frame draws inside while it shows one: `foldable` when the
48325
+ * frame names it, else the one its width picks, absent when off or under 320 wide.
48326
+ */
47178
48327
  device: _enum$1(DEVICES).optional(),
48328
+ /** The pose a frame naming the foldable is folded to, shown or not, absent on every other frame. */
48329
+ pose: _enum$1(POSES).optional(),
47179
48330
  /** The transition the frame arrives with in present mode, over its page's, absent when it holds none. */
47180
48331
  transition: transitionRecordSchema.optional(),
48332
+ /** What the presenter means to say over the slide, plain text with its line breaks, absent when it holds none. */
48333
+ speakerNotes: string$1().optional(),
47181
48334
  placed: boolean$1(),
47182
48335
  modifiedAt: string$1()
47183
48336
  });
@@ -47703,7 +48856,12 @@ const RECORDS = {
47703
48856
  referencesSync: referencesSyncSchema,
47704
48857
  referencesCheck: referencesCheckSchema,
47705
48858
  previewStart: previewStartSchema,
47706
- previewStop: previewStopSchema
48859
+ previewStop: previewStopSchema,
48860
+ imageFind: imageFindSchema,
48861
+ savedImage: savedImageSchema,
48862
+ licenseFile: licenseFileSchema,
48863
+ imageGenerate: imageGenerateSchema,
48864
+ imageDoctor: imageDoctorSchema
47707
48865
  };
47708
48866
  // src/cli/docs/content-format.ts
47709
48867
  /** The content format `docs` prints, built from the constants the verbs run on. */
@@ -47732,6 +48890,7 @@ function contentFormat() {
47732
48890
  `scroll marks a frame that holds a fixed screen height and scrolls past it, such as a page with a sticky section. It fixes both axes, so either hug flag beside it reads as false, frame fit refuses it, and serve never measures it. frame add --scroll sets it, taking the height given or else the preset height of the width (${FRAME_SIZES.desktop.height} px at ${FRAME_SIZES.desktop.width}). frame resize --scroll sets it on a placed frame, dropping a hugging height to that preset height unless a height is given and keeping a fixed height as it stands, so resize a frame fixed past a screen with --height too. frame resize --no-scroll clears it, keeping the box.`,
47733
48891
  `widths lists the extra widths one frame file also shows at, as { width, height } objects, each drawn 80 px past the last in a row beside the frame at its y, so a responsive page is one file rather than a copy per width. Each width follows the frame's own height mode: it hugs its content at that width while hugHeight is on, and otherwise holds its height, the preset height of its width when first set and on frame resize --scroll. A value of any other shape reads as none. frame add --widths 834,390 and frame resize --widths set it, refusing a repeated width, the frame's own width, or a frame hugging its width, and frame resize --no-widths clears it. capture writes <frame>@<width>.<theme>.png beside <frame>.<theme>.png, check reports a browser finding at a linked width with that width and prints it as <path>@<width>, and a frames.json value of <project>/<page>/<frame>@<width> syncs that width's images.`,
47734
48892
  `showDevice true has the board draw the frame inside the device its width names: a phone from 320 to 479 px wide, a tablet from 480 to 1023, and a laptop from 1024 up, with none under 320. The phone's body stands ${BEZELS.phone.border} px past the box on every side and the tablet's ${BEZELS.tablet.border}, and the laptop's lid ${BEZELS.laptop.border} px past its top and sides, with a chin and a wider base below. A resize redraws the body with no write, and list reports the device the width names as device, absent when off or under 320. It never changes the frame file, its size, or its box. frame add, frame duplicate, and a paste place a frame beside another with its own body, a laptop's base included, 80 px past the other's body. A frame given --x keeps that x, a frame landing in a reserved box keeps that box with no room for a device, and a placed frame stays where it stands when its device turns on. Linked widths draw no device. Any other value of showDevice reads as off and is kept on write. A device string from before showDevice reads as on, and the entry's next write replaces it with showDevice. frame add --device on and frame device <frame-ref> <on|off> set it, taking phone and tablet as on and none as off.`,
48893
+ `foldable true has the frame name the foldable device over the one its width picks, and pose folds it: closed is the cover screen at ${POSE_SIZES.closed.width} by ${POSE_SIZES.closed.height}, and half and open are the inner screen at ${POSE_SIZES.open.width} by ${POSE_SIZES.open.height}, half shading the fold. Naming a foldable or setting a pose sets the box's width and height to that screen and turns both hug flags off, and writes the layout entry alone, never the frame file, so one file shows every pose and its content reflows as on the device. The body stands ${BEZELS.foldable.border} px past the box on every side. A newly named foldable starts in the pose nearest its width, closed up to 678 px wide and open past it. list reports device as foldable while it shows, and pose on every frame naming one, shown or not. With showDevice off the box keeps its pose's size and no body draws. A foldable draws no linked width and refuses a new one, and widths its entry held from before stay in the file undrawn, draw again once --no-foldable un-names it, and clear on frame resize --no-widths. Any other value of foldable reads as width-picked, a pose no reader knows reads as closed, and both are kept on write. An older Frameboard rewriting the entry may drop both keys, leaving a width-picked frame at the pose's size. frame device <frame-ref> --foldable names it and shows it, --pose <closed|half|open> folds it, and --no-foldable hands the pick back to the width at the size it stands.`,
47735
48894
  `An axis that hugs takes its size from the frame's content: a running serve measures it after each write to the frame file and when frame add places a file already written, its width at most ${FRAME_SIZES.desktop.width} px, and writes width and height alone, never a flag. Content sized off the viewport keeps the box it has.`,
47736
48895
  "frame add with no size hugs both axes, --size or --width fixes the width and hugs the height, and --height fixes the height alone, its box standing in until serve measures. frame resize and a hand resize fix each axis they set, and frame fit sets the height and turns hugHeight on.",
47737
48896
  "Frames sort by order, then name, and a write that changes order renumbers the page from 0.",
@@ -47744,6 +48903,7 @@ function contentFormat() {
47744
48903
  present: [
47745
48904
  `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
48905
  `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.`,
48906
+ `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
48907
  "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
48908
  `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
48909
  ],
@@ -47758,6 +48918,13 @@ function contentFormat() {
47758
48918
  `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
48919
  `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
48920
  ],
48921
+ images: [
48922
+ `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.`,
48923
+ `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.`,
48924
+ `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.`,
48925
+ "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.",
48926
+ `A frame links a saved image as ../${ASSETS_FOLDER}/<path>, never by its web address, since a frame loads nothing over the network.`
48927
+ ],
47761
48928
  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
48929
  look: [
47763
48930
  `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 +48982,10 @@ function formatLines(format) {
47815
48982
  ...format.present.map((line) => `${INDENT}${line}`),
47816
48983
  "Controls",
47817
48984
  ...format.controls.map((line) => `${INDENT}${line}`),
48985
+ "Kits",
48986
+ ...format.kits.map((line) => `${INDENT}${line}`),
48987
+ "Images",
48988
+ ...format.images.map((line) => `${INDENT}${line}`),
47818
48989
  "Assets",
47819
48990
  `${INDENT}${format.assets}`,
47820
48991
  "Look",
@@ -48136,11 +49307,12 @@ const DEVICE_ON = [
48136
49307
  "phone",
48137
49308
  "tablet"
48138
49309
  ];
48139
- /** What `frame device` did, naming the device the frame's width gave it. */
48140
- function deviceHeadline({ ref, box, showDevice, device }) {
48141
- if (!showDevice) return `Hid the device on ${ref}`;
49310
+ /** What `frame device` did, naming the device the frame draws inside and a foldable's pose. */
49311
+ function deviceHeadline({ ref, box, showDevice, device, pose }) {
49312
+ const folded = pose ? `, folded ${pose} at ${box.width} by ${box.height}` : "";
49313
+ if (!showDevice) return `Hid the device on ${ref}${folded}`;
48142
49314
  if (!device) return `Showed the device on ${ref}, though no device fits its ${box.width} px width`;
48143
- return `Showed the ${device} on ${ref}`;
49315
+ return `Showed the ${device} on ${ref}${folded}`;
48144
49316
  }
48145
49317
  const WIDTHS_HELP = "the extra widths the frame also shows at, a comma list such as 834,390, each drawn beside it and hugging or holding its height as the frame does";
48146
49318
  const POSITIVE = parseInteger(1);
@@ -48222,11 +49394,14 @@ function registerFrame(program, context) {
48222
49394
  human: `Deleted frame ${result.deleted}`
48223
49395
  };
48224
49396
  });
48225
- act(verb("device", "Show or hide the device the board draws around a frame, the phone, tablet, or laptop its width names, leaving the frame file and its size as they are").addArgument(new Argument("<on|off>", "on to show the device, off to hide it, with phone and tablet taken as on and none as off").choices(Object.keys(DEVICE_SWITCH))), context, async ([ref = "", value = ""], options) => {
48226
- const show = Object.hasOwn(DEVICE_SWITCH, value) ? DEVICE_SWITCH[value] : false;
49397
+ act(verb("device", "Show or hide the device the board draws around a frame, the phone, tablet, or laptop its width names or the foldable the frame names, and fold a foldable, leaving the frame file as it is").addArgument(new Argument("[on|off]", "on to show the device, off to hide it, with phone and tablet taken as on and none as off, and absent to leave it, which --foldable takes as on").choices(Object.keys(DEVICE_SWITCH))).addOption(new Option("--foldable", "name the foldable over the device the width picks, setting the box to the pose nearest its width")).addOption(new Option("--no-foldable", "hand the pick back to the width, leaving the box at its size")).addOption(new Option("--pose <pose>", "fold a foldable, setting its box to 466 by 678 closed and 890 by 626 half or open").choices(POSES)), context, async ([ref = "", value], { foldable, pose, ...options }) => {
49398
+ if (value === void 0 && foldable === void 0 && pose === void 0) throw new FrameboardError("usage", "frame device takes on or off, --foldable, --no-foldable, or --pose.");
49399
+ const show = value !== void 0 && Object.hasOwn(DEVICE_SWITCH, value) ? DEVICE_SWITCH[value] : void 0;
48227
49400
  const record = await setFrameDevice(await boardOf(options, io), ref, show, {
48228
49401
  ...options,
48229
- cwd: io.cwd
49402
+ cwd: io.cwd,
49403
+ foldable,
49404
+ pose
48230
49405
  });
48231
49406
  return {
48232
49407
  data: record,
@@ -48240,12 +49415,190 @@ function registerFrame(program, context) {
48240
49415
  });
48241
49416
  return done(record, record.transition ? `Set ${transitionLabel(record.transition.name)} on` : "Cleared the transition on");
48242
49417
  });
49418
+ 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 }) => {
49419
+ if (clear && text !== void 0) throw new FrameboardError("usage", "Pass the text or --clear, not both.");
49420
+ const root = await boardOf(options, io);
49421
+ const refOptions = {
49422
+ ...options,
49423
+ cwd: io.cwd
49424
+ };
49425
+ if (!clear && text === void 0) {
49426
+ const record = await readFrame(root, ref, refOptions);
49427
+ return {
49428
+ data: record,
49429
+ human: record.speakerNotes ?? `No speaker notes on ${record.ref}`
49430
+ };
49431
+ }
49432
+ const record = await setFrameSpeakerNotes(root, ref, clear ? null : text ?? null, refOptions);
49433
+ return done(record, record.speakerNotes ? "Set the speaker notes on" : "Cleared the speaker notes on");
49434
+ });
48243
49435
  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
49436
  ...options,
48245
49437
  on: !options.off,
48246
49438
  cwd: io.cwd
48247
49439
  }), options.off ? `Cleared ${flag} on` : `Set ${flag} on`));
48248
49440
  }
49441
+ /** How long a probe waits, so a machine with nothing listening answers at once. */
49442
+ const PROBE_TIMEOUT_MS = 1e3;
49443
+ function runNvidiaSmi(args) {
49444
+ return new Promise((resolve) => {
49445
+ execFile("nvidia-smi", args, { timeout: 5e3 }, (error, stdout) => resolve(error ? null : stdout));
49446
+ });
49447
+ }
49448
+ /**
49449
+ * The GPU, the local server, and which keys are set, reading each key's
49450
+ * presence and never its value. Installs and spends nothing.
49451
+ */
49452
+ async function diagnose({ env, send, queryGpu }) {
49453
+ const url = env.FRAMEBOARD_COMFYUI_URL?.trim() || "http://127.0.0.1:8188";
49454
+ const [gpu, running] = await Promise.all([readGpu(queryGpu), probe(url, send)]);
49455
+ const providers = PROVIDERS.map((provider) => ({
49456
+ provider: provider.name,
49457
+ model: provider.model,
49458
+ key: provider.keyEnv,
49459
+ ready: keyOf(provider, env) !== null
49460
+ }));
49461
+ return {
49462
+ version: 1,
49463
+ gpu,
49464
+ local: {
49465
+ url,
49466
+ running
49467
+ },
49468
+ keys: Object.fromEntries(providers.map((each) => [each.key, each.ready])),
49469
+ providers,
49470
+ provider: providers.find((each) => each.ready)?.provider ?? null
49471
+ };
49472
+ }
49473
+ async function readGpu(queryGpu) {
49474
+ const [name, memory] = ((await queryGpu(["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"]))?.split("\n")[0] ?? "").split(",").map((part) => part.trim());
49475
+ const memoryMiB = Number(memory);
49476
+ if (!name || !Number.isSafeInteger(memoryMiB)) return null;
49477
+ return {
49478
+ name,
49479
+ memoryMiB
49480
+ };
49481
+ }
49482
+ /** True when ComfyUI's `/system_stats` answers within the probe timeout. */
49483
+ async function probe(url, send) {
49484
+ try {
49485
+ return (await send(new URL("/system_stats", url), { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })).ok;
49486
+ } catch {
49487
+ return false;
49488
+ }
49489
+ }
49490
+ // src/cli/commands/image.ts
49491
+ function registerImage(program, context) {
49492
+ const { io } = context;
49493
+ const send = io.fetch ?? fetch;
49494
+ const image = program.command("image").description("Find an openly licensed image or generate one, saving it into a project's assets with its license");
49495
+ 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) => {
49496
+ const search = { credited: options.credited ?? false };
49497
+ if (options.save === void 0) {
49498
+ if (options.name !== void 0) throw new FrameboardError("usage", "--name needs --save.");
49499
+ const results = await searchImages(query, search, send);
49500
+ const record = {
49501
+ version: 1,
49502
+ query,
49503
+ licenses: licensesFor(search),
49504
+ results
49505
+ };
49506
+ return {
49507
+ data: record,
49508
+ 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")
49509
+ };
49510
+ }
49511
+ const stem = savedStem(options.name, query);
49512
+ const project = await resolveProject(await boardOf(options, io), options.project);
49513
+ const chosen = await pick(query, options.save, search);
49514
+ const saved = await saveImage(project, stem, await downloadImage(chosen.image.url, send), foundLicense(chosen.image, chosen.query, /* @__PURE__ */ new Date()));
49515
+ return {
49516
+ data: saved,
49517
+ human: savedLine(saved)
49518
+ };
49519
+ });
49520
+ 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) => {
49521
+ const plan = planGeneration({
49522
+ prompt,
49523
+ size: {
49524
+ width: options.width,
49525
+ height: options.height
49526
+ },
49527
+ provider: options.provider
49528
+ }, process.env);
49529
+ const record = {
49530
+ version: 1,
49531
+ provider: plan.provider.name,
49532
+ model: plan.provider.model,
49533
+ prompt,
49534
+ ...plan.size,
49535
+ priceUsd: plan.priceUsd,
49536
+ dryRun: options.dryRun ?? false,
49537
+ saved: null
49538
+ };
49539
+ const priced = `${record.provider} ${record.model} at ${record.width}x${record.height} for about $${record.priceUsd}`;
49540
+ if (record.dryRun) return {
49541
+ data: record,
49542
+ human: `Would generate on ${priced}`
49543
+ };
49544
+ const stem = savedStem(options.name, prompt);
49545
+ const saved = await saveImage(await resolveProject(await boardOf(options, io), options.project), stem, await generateImage(plan, send), {
49546
+ version: 1,
49547
+ origin: "generated",
49548
+ provider: record.provider,
49549
+ model: record.model,
49550
+ prompt,
49551
+ width: record.width,
49552
+ height: record.height,
49553
+ priceUsd: record.priceUsd,
49554
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
49555
+ });
49556
+ return {
49557
+ data: {
49558
+ ...record,
49559
+ saved
49560
+ },
49561
+ human: `Generated on ${priced}. ${savedLine(saved)}`
49562
+ };
49563
+ });
49564
+ act(addVerb(image, "doctor", "Report the GPU, a local ComfyUI server, and which provider keys are set, installing nothing"), context, async () => {
49565
+ const report = await diagnose({
49566
+ env: process.env,
49567
+ send,
49568
+ queryGpu: runNvidiaSmi
49569
+ });
49570
+ return {
49571
+ data: report,
49572
+ human: [
49573
+ `GPU\t${report.gpu === null ? "none found" : `${report.gpu.name}, ${report.gpu.memoryMiB} MiB`}`,
49574
+ `Local\t${report.local.url} ${report.local.running ? "answers" : "does not answer"}`,
49575
+ ...report.providers.map((each) => `${each.provider}\t${each.key} ${each.ready ? "set" : "unset"}`),
49576
+ `Generate runs on\t${report.provider ?? "nothing, since no key is set"}`
49577
+ ].join("\n")
49578
+ };
49579
+ });
49580
+ /** The result `--save` names: a number reruns the search, anything else is an id. */
49581
+ async function pick(query, save, search) {
49582
+ if (!/^\d+$/.test(save)) return {
49583
+ image: await imageById(save, search, send),
49584
+ query: null
49585
+ };
49586
+ const number = Number(save);
49587
+ const results = await searchImages(query, search, send);
49588
+ const found = results.find((each) => each.number === number);
49589
+ if (found === void 0) throw new FrameboardError("result-not-found", `The search for ${query} found ${results.length} results, so there is no result ${number}.`, {
49590
+ number,
49591
+ results: results.length
49592
+ });
49593
+ return {
49594
+ image: found,
49595
+ query
49596
+ };
49597
+ }
49598
+ }
49599
+ function savedLine(saved) {
49600
+ return `Saved assets/${saved.path} into ${saved.project}, its license in assets/${saved.licensePath}`;
49601
+ }
48249
49602
  // node_modules/ws/lib/constants.js
48250
49603
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
48251
49604
  const BINARY_TYPES = [
@@ -57531,7 +58884,7 @@ function innerPath(pathname, token, project) {
57531
58884
  const [given = "", ...rest] = pathname.slice(3).split("/");
57532
58885
  if (!sameToken(given, token)) return null;
57533
58886
  const inner = `/${rest.join("/")}`;
57534
- if (inner === "/frameboard/tokens.css" || inner.startsWith(`/frameboard/faces/`)) return inner;
58887
+ if (inner === "/frameboard/tokens.css" || inner === BRIDGE_URL || inner.startsWith(`/frameboard/faces/`)) return inner;
57535
58888
  const [area, named, ...within] = rest;
57536
58889
  if (area !== "frames" || within.length === 0) return null;
57537
58890
  let decoded;
@@ -58548,6 +59901,7 @@ function createProgram(context) {
58548
59901
  registerList(program, context);
58549
59902
  registerProject(program, context);
58550
59903
  registerKit(program, context);
59904
+ registerImage(program, context);
58551
59905
  registerPage(program, context);
58552
59906
  registerFrame(program, faced);
58553
59907
  registerEdit(program, context);