frameboard 0.44.0 → 0.45.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
@@ -9586,17 +9586,61 @@ const BATTERY = {
9586
9586
  radius: 3.5,
9587
9587
  cap: 2
9588
9588
  };
9589
- /** The height the device's status bar takes off the top of a frame's box, 0 for any device but the phone. */
9590
- function topInset(device) {
9591
- return device === "phone" ? STATUS_BAR.height : 0;
9589
+ /**
9590
+ * The ways a phone, a tablet, or a foldable is held, upright or turned a
9591
+ * quarter with its island on the left or on the right side.
9592
+ */
9593
+ const TURNS = [
9594
+ "upright",
9595
+ "left",
9596
+ "right"
9597
+ ];
9598
+ /** A layout entry's `turn` as a turn, upright for none or a value no reader knows. */
9599
+ function turnOf(value) {
9600
+ return value === "left" || value === "right" ? value : "upright";
9601
+ }
9602
+ /** Whether a device turns, which a phone, a tablet, and a foldable do and a laptop does not. */
9603
+ function turnsWith(device) {
9604
+ return device === "phone" || device === "tablet" || device === "foldable";
9605
+ }
9606
+ /** A layout entry's `upright` as a size, null for none or a value of another shape. */
9607
+ function uprightOf(value) {
9608
+ if (typeof value !== "object" || value === null) return null;
9609
+ if (!("width" in value) || !("height" in value)) return null;
9610
+ const { width, height } = value;
9611
+ if (typeof width !== "number" || typeof height !== "number") return null;
9612
+ return Number.isInteger(width) && Number.isInteger(height) && width > 0 && height > 0 ? {
9613
+ width,
9614
+ height
9615
+ } : null;
9616
+ }
9617
+ /**
9618
+ * The width that picks the device for a frame, its kept upright width while
9619
+ * turned, so a turned phone reads as a phone and never as the tablet its
9620
+ * landscape box is wide enough for.
9621
+ */
9622
+ function uprightWidth(entry) {
9623
+ const upright = uprightOf(entry.upright);
9624
+ return turnOf(entry.turn) !== "upright" && upright ? upright.width : entry.width;
9625
+ }
9626
+ /** Whether a device draws turned, which any device but a laptop does. */
9627
+ function isTurned(device, turn) {
9628
+ return turnsWith(device) && turnOf(turn) !== "upright";
9629
+ }
9630
+ /**
9631
+ * The height the device's status bar takes off the top of a frame's box, 0
9632
+ * for any device but an upright phone, since a turned one hides its bar.
9633
+ */
9634
+ function topInset(device, turn) {
9635
+ return device === "phone" && !isTurned(device, turn) ? STATUS_BAR.height : 0;
9592
9636
  }
9593
9637
  /**
9594
- * The page's box inside a frame's box, the box less the status bar while a
9595
- * phone shows and the box itself on every other device or none. A frame's
9596
- * box keeps the screen's size, and every surface reads the page through this.
9638
+ * The page's box inside a frame's box, less the status bar while an upright
9639
+ * phone shows. A frame's box keeps the screen's size, and every surface reads
9640
+ * the page through this.
9597
9641
  */
9598
- function pageBox(box, device) {
9599
- const inset = topInset(device);
9642
+ function pageBox(box, device, turn) {
9643
+ const inset = topInset(device, turn);
9600
9644
  return {
9601
9645
  x: box.x,
9602
9646
  y: box.y + inset,
@@ -9604,9 +9648,9 @@ function pageBox(box, device) {
9604
9648
  height: Math.max(0, box.height - inset)
9605
9649
  };
9606
9650
  }
9607
- /** The page's corners as a CSS `border-radius`, square on top under a phone's status bar. */
9608
- function pageCorners(device) {
9609
- if (device !== "phone") return screenCorners(device);
9651
+ /** The page's corners as a CSS `border-radius`, square on top under an upright phone's status bar. */
9652
+ function pageCorners(device, turn) {
9653
+ if (device !== "phone" || isTurned(device, turn)) return screenCorners(device);
9610
9654
  const { screenRadius } = BEZELS.phone;
9611
9655
  return `0 0 ${screenRadius}px ${screenRadius}px`;
9612
9656
  }
@@ -9668,23 +9712,44 @@ const FOLDABLE_ISLAND = {
9668
9712
  height: 30,
9669
9713
  top: 14
9670
9714
  };
9671
- /** Where the island's center sits across a pose's screen, as a share of its width. */
9672
- function islandCenter(pose) {
9673
- return pose === "closed" ? .5 : .75;
9715
+ /**
9716
+ * Where the island sits on a pose's screen, where a quarter turn puts it: a
9717
+ * turn left lays the top edge down the left side, so a share across the top
9718
+ * reads from the bottom, and a turn right lays it down the right side.
9719
+ */
9720
+ function islandCenter(pose, turn) {
9721
+ const across = pose === "closed" ? .5 : .75;
9722
+ if (turn === "left") return {
9723
+ edge: "left",
9724
+ along: 1 - across
9725
+ };
9726
+ if (turn === "right") return {
9727
+ edge: "right",
9728
+ along: across
9729
+ };
9730
+ return {
9731
+ edge: "top",
9732
+ along: across
9733
+ };
9674
9734
  }
9675
9735
  /**
9676
- * The band drawn down the middle of the inner screen, a faint crease open
9677
- * and a shaded fold half open, null on the cover screen, which has no fold.
9736
+ * The band drawn through the middle of the inner screen, a faint crease open
9737
+ * and a shaded fold half open, running down the screen upright and across it
9738
+ * turned, null on the cover screen, which has no fold.
9678
9739
  */
9679
- function foldBand(pose) {
9740
+ function foldBand(pose, turn) {
9680
9741
  if (pose === "closed") return null;
9742
+ const runs = turn === "upright" ? "down" : "across";
9743
+ const angle = runs === "down" ? "90deg" : "180deg";
9681
9744
  if (pose === "open") return {
9682
9745
  width: 26,
9683
- background: "linear-gradient(90deg, transparent, rgba(0,0,0,.05) 35%, rgba(0,0,0,.11) 50%, rgba(255,255,255,.5) 56%, transparent)"
9746
+ runs,
9747
+ background: `linear-gradient(${angle}, transparent, rgba(0,0,0,.05) 35%, rgba(0,0,0,.11) 50%, rgba(255,255,255,.5) 56%, transparent)`
9684
9748
  };
9685
9749
  return {
9686
9750
  width: 150,
9687
- 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)"
9751
+ runs,
9752
+ background: `linear-gradient(${angle}, 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)`
9688
9753
  };
9689
9754
  }
9690
9755
  /**
@@ -9734,18 +9799,21 @@ function bezelShadow(device, { board = true } = {}) {
9734
9799
  }
9735
9800
  /**
9736
9801
  * The box a device's body covers around a frame's box, the box itself with
9737
- * none. A laptop's base reaches past its lid and a phone's buttons past its
9738
- * sides, so their sides grow by more than their top.
9802
+ * none. A laptop's base and a phone's buttons reach past its sides, and a
9803
+ * turned phone's buttons past its top and bottom instead.
9739
9804
  */
9740
- function bezelBox(box, device) {
9805
+ function bezelBox(box, device, turn) {
9741
9806
  if (!device) return { ...box };
9742
9807
  const { border, bottom } = BEZELS[device];
9743
- const side = border + sideReach(device, box.width);
9808
+ const reach = sideReach(device, box.width);
9809
+ const turned = isTurned(device, turn);
9810
+ const side = border + (turned ? 0 : reach);
9811
+ const end = turned ? reach : 0;
9744
9812
  return {
9745
9813
  x: box.x - side,
9746
- y: box.y - border,
9814
+ y: box.y - border - end,
9747
9815
  width: box.width + 2 * side,
9748
- height: box.height + border + bottom
9816
+ height: box.height + border + bottom + 2 * end
9749
9817
  };
9750
9818
  }
9751
9819
  // src/shared/frame-widths.ts
@@ -9784,7 +9852,7 @@ function isSize(value) {
9784
9852
  */
9785
9853
  function linkedBoxes(box, widths, device) {
9786
9854
  const boxes = [];
9787
- const body = bezelBox(box, device);
9855
+ const body = bezelBox(box, device, "upright");
9788
9856
  const lid = device ? BEZELS[device].border : 0;
9789
9857
  let x = body.x + body.width - lid;
9790
9858
  for (const { width, height } of widths) {
@@ -9804,7 +9872,7 @@ function linkedBoxes(box, widths, device) {
9804
9872
  * width it draws, the frame's own with neither. Linked widths draw no device.
9805
9873
  */
9806
9874
  function drawnExtent(box, widths, device) {
9807
- const boxes = [bezelBox(box, device), ...linkedBoxes(box, widths, device)];
9875
+ const boxes = [bezelBox(box, device, "upright"), ...linkedBoxes(box, widths, device)];
9808
9876
  const left = Math.min(...boxes.map(({ x }) => x));
9809
9877
  const top = Math.min(...boxes.map(({ y }) => y));
9810
9878
  const right = Math.max(...boxes.map(({ x, width }) => x + width));
@@ -9826,7 +9894,7 @@ function xPast(edge, width, device) {
9826
9894
  y: 0,
9827
9895
  width,
9828
9896
  height: 0
9829
- }, device);
9897
+ }, device, "upright");
9830
9898
  return edge + 80 - body.x;
9831
9899
  }
9832
9900
  // src/shared/names.ts
@@ -10080,6 +10148,8 @@ const layoutEntrySchema = looseObject({
10080
10148
  foldable: unknown().optional(),
10081
10149
  pose: unknown().optional(),
10082
10150
  island: unknown().optional(),
10151
+ turn: unknown().optional(),
10152
+ upright: unknown().optional(),
10083
10153
  transition: unknown().optional(),
10084
10154
  speakerNotes: unknown().optional(),
10085
10155
  kit: unknown().optional()
@@ -24734,7 +24804,7 @@ const STEP = /^(?:from|to|\d+(?:\.\d+)?%)(?:\s*,\s*(?:from|to|\d+(?:\.\d+)?%))*$
24734
24804
  * it in its own document, a value that could load a file included.
24735
24805
  */
24736
24806
  function readTransitionSheet(name, css) {
24737
- if (!isOwnTransitionName(name)) return refused$1([{
24807
+ if (!isOwnTransitionName(name)) return refused$2([{
24738
24808
  message: `${name} is no transition name. Name the file in lowercase kebab case, and not after a built-in transition, none, or page`,
24739
24809
  location: null
24740
24810
  }]);
@@ -24744,7 +24814,7 @@ function readTransitionSheet(name, css) {
24744
24814
  } catch (error) {
24745
24815
  if (!(error instanceof CssSyntaxError)) throw error;
24746
24816
  const at = offsetOf(css, error.line ?? 1, error.column ?? 1);
24747
- return refused$1([{
24817
+ return refused$2([{
24748
24818
  message: `The stylesheet does not parse: ${error.reason}`,
24749
24819
  location: {
24750
24820
  line: error.line ?? 1,
@@ -24771,7 +24841,7 @@ function readTransitionSheet(name, css) {
24771
24841
  message: "@keyframes enter is missing",
24772
24842
  location: null
24773
24843
  });
24774
- if (!enter || problems.length > 0) return refused$1(problems);
24844
+ if (!enter || problems.length > 0) return refused$2(problems);
24775
24845
  const leave = held.get("leave");
24776
24846
  return {
24777
24847
  ok: true,
@@ -24779,7 +24849,7 @@ function readTransitionSheet(name, css) {
24779
24849
  leave: leave ? bodyOf(leave) : null
24780
24850
  };
24781
24851
  }
24782
- function refused$1(problems) {
24852
+ function refused$2(problems) {
24783
24853
  return {
24784
24854
  ok: false,
24785
24855
  problems
@@ -25062,7 +25132,9 @@ function placeFrames(frames, names, readTransition = storedTransitionOf) {
25062
25132
  const shown = showsDevice(entry);
25063
25133
  const foldable = entry.foldable === true;
25064
25134
  const kept = widthsOf(entry.widths);
25065
- const named = foldable ? "foldable" : deviceForWidth(box.width);
25135
+ const upright = uprightOf(entry.upright);
25136
+ const turn = foldable || upright ? turnOf(entry.turn) : "upright";
25137
+ const named = foldable ? "foldable" : deviceForWidth(uprightWidth(entry));
25066
25138
  const device = shown ? named : null;
25067
25139
  const transition = readTransition(entry.transition);
25068
25140
  const speakerNotes = speakerNotesOf(entry.speakerNotes);
@@ -25084,6 +25156,11 @@ function placeFrames(frames, names, readTransition = storedTransitionOf) {
25084
25156
  } : {},
25085
25157
  ...foldable && kept.length > 0 ? { keptWidths: kept } : {},
25086
25158
  ...islandOf(entry.island) === "wide" ? { island: "wide" } : {},
25159
+ ...turn !== "upright" && foldable ? { turn } : {},
25160
+ ...turn !== "upright" && !foldable && upright ? {
25161
+ turn,
25162
+ upright
25163
+ } : {},
25087
25164
  ...transition ? { transition } : {},
25088
25165
  ...speakerNotes ? { speakerNotes } : {},
25089
25166
  ...kit ? { kit } : {},
@@ -25196,7 +25273,7 @@ async function scanPage(root, project, name, index, transitions) {
25196
25273
  const placements = placeFrames(frames, names, (value) => transitionOf(value, own));
25197
25274
  const stacked = (await Promise.all(names.map(async (frame) => {
25198
25275
  const framePath = join(path, `${frame}${FRAME_EXTENSION}`);
25199
- const { foldable: _named, keptWidths: _kept, ...placement } = placements.get(frame) ?? placeNext([]);
25276
+ const { foldable: _named, keptWidths: _kept, upright: _upright, ...placement } = placements.get(frame) ?? placeNext([]);
25200
25277
  return {
25201
25278
  ref: `${project}/${name}/${frame}`,
25202
25279
  project,
@@ -25315,7 +25392,7 @@ async function isDirectory(path) {
25315
25392
  }
25316
25393
  }
25317
25394
  // package.json
25318
- var version$1 = "0.44.0";
25395
+ var version$1 = "0.45.0";
25319
25396
  var dependencies = { "playwright-core": "1.65.0" };
25320
25397
  var peerDependencies = { "oxfmt": "0.78.0" };
25321
25398
  // src/shared/version.ts
@@ -25819,6 +25896,11 @@ function resizedPlacement(placement, frameRef, size, options) {
25819
25896
  ref: frameRef,
25820
25897
  widths: options.widths
25821
25898
  });
25899
+ if (placement.turn && options.widths && options.widths.length > 0) throw new FrameboardError("usage", `${frameRef} is turned ${placement.turn}, and each extra width is an upright preview, so it shows at no other width. Turn it upright first.`, {
25900
+ ref: frameRef,
25901
+ turn: placement.turn,
25902
+ widths: options.widths
25903
+ });
25822
25904
  const scroll = options.scroll ?? placement.scroll;
25823
25905
  const width = size.width ?? placement.box.width;
25824
25906
  const drops = scroll && placement.hugHeight && size.height === void 0;
@@ -26102,24 +26184,30 @@ async function setFrameFlag(root, ref, flag, { on, ...options }) {
26102
26184
  }));
26103
26185
  }
26104
26186
  /**
26105
- * Shows or hides a frame's device, names or un-names the foldable, and folds
26106
- * it, never writing the frame's file. Naming a foldable shows it and, as a
26107
- * pose does, sets the box to that pose's screen, fixed on both axes.
26187
+ * Shows or hides a frame's device, names, folds, or turns it, never writing
26188
+ * the frame's file. A named foldable's box is its pose's screen, both axes
26189
+ * fixed, sides swapped while turned, and a turned frame stands upright first.
26108
26190
  */
26109
- async function setFrameDevice(root, ref, show, { foldable: name, pose: fold, island: pick, ...options }) {
26110
- return updatePlacement(root, ref, options, (placement, frameRef) => {
26111
- const { showDevice: held, device: _device, foldable: named, pose: stored, keptWidths, island: picked, ...rest } = placement;
26112
- const foldable = name ?? named === true;
26191
+ async function setFrameDevice(root, ref, show, { foldable: name, pose: fold, island: pick, turn, ...options }) {
26192
+ return updatePlacement(root, ref, options, (stood, frameRef) => {
26193
+ const foldable = name ?? stood.foldable === true;
26194
+ const shown = show ?? (name === true || stood.showDevice === true);
26195
+ const unfolded = stood.foldable === true ? unfoldedPlacement(stood, foldable) : stood;
26196
+ if (turn && turn !== "upright") refuseTurn(unfolded, frameRef, turn, {
26197
+ foldable,
26198
+ shown
26199
+ });
26200
+ const placement = stood.foldable === true && foldable ? unfolded : turnedPlacement(unfolded, foldable ? "upright" : turn);
26201
+ const { showDevice: _held, device: _device, foldable: named, pose: stored, keptWidths, island: picked, turn: held, ...rest } = placement;
26113
26202
  if (fold && !foldable) throw new FrameboardError("usage", `${frameRef} is not a foldable, so it has no pose. Name it with --foldable first.`, {
26114
26203
  ref: frameRef,
26115
26204
  pose: fold
26116
26205
  });
26117
- if (pick && (foldable || deviceForWidth(placement.box.width) !== "phone")) throw new FrameboardError("usage", `${frameRef} draws no phone, so it has no island. A frame 320 to 479 px wide that names no foldable draws one.`, {
26206
+ if (pick && (foldable || drawnDevice(placement) !== "phone")) throw new FrameboardError("usage", `${frameRef} draws no phone, so it has no island. A frame 320 to 479 px wide that names no foldable draws one.`, {
26118
26207
  ref: frameRef,
26119
26208
  island: pick
26120
26209
  });
26121
26210
  const island = pick ?? islandOf(picked);
26122
- const shown = show ?? (name === true || held === true);
26123
26211
  const base = {
26124
26212
  ...rest,
26125
26213
  ...shown ? { showDevice: true } : {},
@@ -26129,6 +26217,7 @@ async function setFrameDevice(root, ref, show, { foldable: name, pose: fold, isl
26129
26217
  const widths = (keptWidths ?? rest.widths).filter((linked) => linked.width !== placement.box.width);
26130
26218
  return {
26131
26219
  ...base,
26220
+ ...held ? { turn: held } : {},
26132
26221
  widths
26133
26222
  };
26134
26223
  }
@@ -26138,20 +26227,28 @@ async function setFrameDevice(root, ref, show, { foldable: name, pose: fold, isl
26138
26227
  ...undrawn.length > 0 ? { keptWidths: undrawn } : {}
26139
26228
  };
26140
26229
  const pose = fold ?? stored ?? nearestPose(placement.box.width);
26141
- if (!fold && named) return {
26230
+ const facing = turn ?? turnOf(held);
26231
+ const sideways = facing === "upright" ? {} : { turn: facing };
26232
+ if (!fold && !turn && named) return {
26142
26233
  ...base,
26143
26234
  ...kept,
26144
26235
  foldable,
26145
- pose
26236
+ pose,
26237
+ ...sideways
26146
26238
  };
26239
+ const screen = POSE_SIZES[pose];
26147
26240
  return {
26148
26241
  ...base,
26149
26242
  ...kept,
26150
26243
  foldable,
26151
26244
  pose,
26245
+ ...sideways,
26152
26246
  box: {
26153
26247
  ...placement.box,
26154
- ...POSE_SIZES[pose]
26248
+ ...facing === "upright" ? screen : {
26249
+ width: screen.height,
26250
+ height: screen.width
26251
+ }
26155
26252
  },
26156
26253
  hugWidth: false,
26157
26254
  hugHeight: false
@@ -26159,6 +26256,82 @@ async function setFrameDevice(root, ref, show, { foldable: name, pose: fold, isl
26159
26256
  });
26160
26257
  }
26161
26258
  /**
26259
+ * A named foldable left as it is while it stays named, and stood upright at
26260
+ * its pose's screen when named off, since no other device reads its turn.
26261
+ */
26262
+ function unfoldedPlacement(placement, foldable) {
26263
+ if (foldable) return placement;
26264
+ const { turn: held, upright: _upright, ...rest } = placement;
26265
+ if (!held) return rest;
26266
+ const screen = POSE_SIZES[poseOf(placement.pose)];
26267
+ return {
26268
+ ...rest,
26269
+ box: {
26270
+ ...placement.box,
26271
+ ...screen
26272
+ }
26273
+ };
26274
+ }
26275
+ /** The device a frame's width picks, its upright width while turned, shown or not. */
26276
+ function drawnDevice(placement) {
26277
+ return deviceForWidth(placement.upright?.width ?? placement.box.width);
26278
+ }
26279
+ /**
26280
+ * Refuses a quarter turn the board has no drawn answer for: a laptop, a frame
26281
+ * showing no device, and a frame whose extra widths are each an upright
26282
+ * preview of their own. A shown foldable turns in each pose.
26283
+ */
26284
+ function refuseTurn(placement, frameRef, turn, { foldable, shown }) {
26285
+ const device = drawnDevice(placement);
26286
+ if (!shown || !(foldable || device === "phone" || device === "tablet")) throw new FrameboardError("usage", `${frameRef} draws no phone, tablet, or foldable, so it does not turn. Show the device on a frame 320 to 1023 px wide or a foldable first.`, {
26287
+ ref: frameRef,
26288
+ turn
26289
+ });
26290
+ if (placement.widths.length > 0) {
26291
+ const widths = placement.widths.map((linked) => linked.width);
26292
+ throw new FrameboardError("usage", `${frameRef} also shows at ${widths.join(", ")} px, each an upright preview, so it does not turn. Clear them with frame resize --no-widths first.`, {
26293
+ ref: frameRef,
26294
+ turn,
26295
+ widths
26296
+ });
26297
+ }
26298
+ }
26299
+ /**
26300
+ * A frame turned to `turn`, keeping its upright size on the first turn. A
26301
+ * fixed or scroll box swaps its sides, and a hugging one, whose height is its
26302
+ * page's, takes the reference height of its upright width wide.
26303
+ */
26304
+ function turnedPlacement(placement, turn) {
26305
+ if (turn === void 0) return placement;
26306
+ const { turn: held, upright, ...rest } = placement;
26307
+ if (turn === "upright") return upright ? {
26308
+ ...rest,
26309
+ box: {
26310
+ ...placement.box,
26311
+ ...upright
26312
+ }
26313
+ } : rest;
26314
+ if (held) return {
26315
+ ...placement,
26316
+ turn
26317
+ };
26318
+ const size = {
26319
+ width: placement.box.width,
26320
+ height: placement.box.height
26321
+ };
26322
+ const hugs = placement.hugHeight && !placement.scroll;
26323
+ return {
26324
+ ...rest,
26325
+ turn,
26326
+ upright: size,
26327
+ box: {
26328
+ ...placement.box,
26329
+ width: hugs ? referenceHeight(size.width) : size.height,
26330
+ height: size.width
26331
+ }
26332
+ };
26333
+ }
26334
+ /**
26162
26335
  * Sets or clears a frame's present transition, refusing a name neither built
26163
26336
  * in nor the project's own.
26164
26337
  */
@@ -26306,7 +26479,7 @@ var PageLayout = class {
26306
26479
  * Writes the fixed keys after the entry's own, so unknown keys survive, and a
26307
26480
  * flag only once on or already held, so an older entry gains no key.
26308
26481
  */
26309
- set(name, { box, order, hidden, locked, scroll, widths, showDevice, foldable, pose, keptWidths, island, transition, speakerNotes, kit, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
26482
+ set(name, { box, order, hidden, locked, scroll, widths, showDevice, foldable, pose, keptWidths, island, turn, upright, transition, speakerNotes, kit, hugWidth: hugsWidth, hugHeight: hugsHeight }) {
26310
26483
  const hugWidth = hugsWidth && !scroll;
26311
26484
  const hugHeight = hugsHeight && !scroll;
26312
26485
  const held = this.file.frames[name];
@@ -26331,6 +26504,14 @@ var PageLayout = class {
26331
26504
  ...foldable ? { foldable } : {},
26332
26505
  ...foldable && pose && (held?.foldable !== true || poseOf(held.pose) !== pose) ? { pose } : {},
26333
26506
  ...island ? { island } : {},
26507
+ ...turn && upright && !foldable ? {
26508
+ turn,
26509
+ upright: {
26510
+ width: upright.width,
26511
+ height: upright.height
26512
+ }
26513
+ } : {},
26514
+ ...turn && foldable ? { turn } : {},
26334
26515
  ...transition ? { transition: { ...transition } } : {},
26335
26516
  ...speakerNotes ? { speakerNotes } : {},
26336
26517
  ...kit ? { kit } : {}
@@ -26342,6 +26523,11 @@ var PageLayout = class {
26342
26523
  }
26343
26524
  if (!showDevice && held?.showDevice === true) delete entry.showDevice;
26344
26525
  if (!island && islandOf(held?.island) === "wide") delete entry.island;
26526
+ if (!turn && turnOf(held?.turn) !== "upright") {
26527
+ delete entry.turn;
26528
+ delete entry.upright;
26529
+ }
26530
+ if (turn && foldable) delete entry.upright;
26345
26531
  if (typeof held?.device === "string") delete entry.device;
26346
26532
  if (!transition && storedTransitionOf(held?.transition)) delete entry.transition;
26347
26533
  if (!speakerNotes && speakerNotesOf(held?.speakerNotes)) delete entry.speakerNotes;
@@ -31479,7 +31665,11 @@ function isAcceptedUpload(name) {
31479
31665
  // src/shared/records/sourcing.ts
31480
31666
  /** So `house.jpg` carries its license in `house.jpg.license.json` beside it. */
31481
31667
  const LICENSE_FILE_SUFFIX = ".license.json";
31482
- const IMAGE_PROVIDERS = ["fal", "google"];
31668
+ const IMAGE_PROVIDERS = [
31669
+ "comfyui",
31670
+ "fal",
31671
+ "google"
31672
+ ];
31483
31673
  /** One image a search found, numbered from 1 in the order the source ranked it. */
31484
31674
  const imageResultSchema = object$1({
31485
31675
  number: int$1().min(1),
@@ -31548,8 +31738,7 @@ const modelFindSchema = object$1({
31548
31738
  }),
31549
31739
  results: array$1(modelResultSchema)
31550
31740
  });
31551
- /** The `<file>.license.json` beside every saved image or model, saying where it came from. */
31552
- const licenseFileSchema = discriminatedUnion("origin", [discriminatedUnion("source", [object$1({
31741
+ const foundLicenseSchema = discriminatedUnion("source", [object$1({
31553
31742
  version: literal(1),
31554
31743
  origin: literal("found"),
31555
31744
  source: literal("openverse"),
@@ -31584,9 +31773,12 @@ const licenseFileSchema = discriminatedUnion("origin", [discriminatedUnion("sour
31584
31773
  url: string$1(),
31585
31774
  size: _enum$1(MODEL_SIZES),
31586
31775
  savedAt: string$1()
31587
- })]), object$1({
31776
+ })]);
31777
+ const generatedImageLicenseSchema = object$1({
31588
31778
  version: literal(1),
31589
31779
  origin: literal("generated"),
31780
+ /** Absent on every image license written so far, which reads as an image. */
31781
+ kind: literal("image").optional(),
31590
31782
  provider: _enum$1(IMAGE_PROVIDERS),
31591
31783
  model: string$1(),
31592
31784
  prompt: string$1(),
@@ -31594,8 +31786,48 @@ const licenseFileSchema = discriminatedUnion("origin", [discriminatedUnion("sour
31594
31786
  height: int$1(),
31595
31787
  /** The price estimated before the call, in US dollars. */
31596
31788
  priceUsd: number(),
31789
+ /** The noise seed a local run drew, so the same image can be made again. */
31790
+ seed: int$1().optional(),
31791
+ /** The workflow file `--workflow` named, absent for the bundled one. */
31792
+ workflow: string$1().optional(),
31597
31793
  savedAt: string$1()
31598
- })]);
31794
+ });
31795
+ /** The picture a model was made from, so the model keeps the credit the picture carried. */
31796
+ const sourcePictureSchema = object$1({
31797
+ /**
31798
+ * Relative to the project's `assets/` for a project asset, else the file's
31799
+ * name alone, never a path on the machine.
31800
+ */
31801
+ path: string$1(),
31802
+ inAssets: boolean$1(),
31803
+ /** The picture's own license file's origin and license name, null when it has none. */
31804
+ license: object$1({
31805
+ origin: _enum$1(["found", "generated"]),
31806
+ /** The license a found picture carries, such as `cc0`, null for a generated one. */
31807
+ license: string$1().nullable()
31808
+ }).nullable()
31809
+ });
31810
+ /**
31811
+ * The `<file>.license.json` beside every saved image or model, saying where
31812
+ * it came from. A generated one carries `kind: 'model'` for a model, and no
31813
+ * kind or `kind: 'image'` for an image.
31814
+ */
31815
+ const licenseFileSchema = discriminatedUnion("origin", [foundLicenseSchema, discriminatedUnion("kind", [generatedImageLicenseSchema, object$1({
31816
+ version: literal(1),
31817
+ origin: literal("generated"),
31818
+ kind: literal("model"),
31819
+ provider: literal("comfyui"),
31820
+ /** The ComfyUI server the model was made on. */
31821
+ server: string$1(),
31822
+ /** The bundled model, or the workflow file's name when `--workflow` named one. */
31823
+ model: string$1(),
31824
+ /** The workflow file `--workflow` named, absent for the bundled one. */
31825
+ workflow: string$1().optional(),
31826
+ picture: sourcePictureSchema,
31827
+ /** The noise seed the run drew, so the same model can be made again. */
31828
+ seed: int$1(),
31829
+ savedAt: string$1()
31830
+ })])]);
31599
31831
  /** An image saved into a project's `assets/`, with the license file written beside it. */
31600
31832
  const savedImageSchema = object$1({
31601
31833
  version: literal(1),
@@ -31607,6 +31839,18 @@ const savedImageSchema = object$1({
31607
31839
  });
31608
31840
  /** A model saved into a project's `assets/` as one `.glb`, with the license file written beside it. */
31609
31841
  const savedModelSchema = savedImageSchema;
31842
+ /** What `model generate` answers, with `saved` null on a dry run. */
31843
+ const modelGenerateSchema = object$1({
31844
+ version: literal(1),
31845
+ provider: literal("comfyui"),
31846
+ /** The ComfyUI server at `FRAMEBOARD_COMFYUI_URL`. */
31847
+ server: string$1(),
31848
+ /** The bundled model, or the workflow file's name when `--workflow` named one. */
31849
+ model: string$1(),
31850
+ picture: sourcePictureSchema,
31851
+ dryRun: boolean$1(),
31852
+ saved: savedModelSchema.nullable()
31853
+ });
31610
31854
  /** What `image generate` answers, with `saved` null on a dry run. */
31611
31855
  const imageGenerateSchema = object$1({
31612
31856
  version: literal(1),
@@ -31637,6 +31881,22 @@ object$1({
31637
31881
  /** Every provider's key variable, in the order generation tries them. */
31638
31882
  keys: array$1(string$1())
31639
31883
  });
31884
+ object$1({
31885
+ version: literal(1),
31886
+ /** The ComfyUI server at `FRAMEBOARD_COMFYUI_URL`, or the default address. */
31887
+ url: string$1(),
31888
+ freed: literal(true)
31889
+ });
31890
+ /** A model file a bundled workflow loads, as ComfyUI's `models/<folder>/` should hold it. */
31891
+ const missingModelSchema = object$1({
31892
+ /** The verb whose bundled workflow loads it, `image` for image generate and `model` for model generate. */
31893
+ for: _enum$1(["image", "model"]),
31894
+ folder: string$1(),
31895
+ file: string$1(),
31896
+ bytes: int$1(),
31897
+ /** Where the file downloads from. */
31898
+ url: string$1()
31899
+ });
31640
31900
  /** What `image doctor` answers, naming each key as set or unset and never its value. */
31641
31901
  const imageDoctorSchema = object$1({
31642
31902
  version: literal(1),
@@ -31648,8 +31908,14 @@ const imageDoctorSchema = object$1({
31648
31908
  /** The ComfyUI server at `FRAMEBOARD_COMFYUI_URL`, or the default address. */
31649
31909
  local: object$1({
31650
31910
  url: string$1(),
31651
- running: boolean$1()
31911
+ running: boolean$1(),
31912
+ /** The ComfyUI version the server reports, null when none answers. */
31913
+ version: string$1().nullable(),
31914
+ /** Each bundled workflow's files the server lacks, image ones first, null when it does not answer. */
31915
+ missing: array$1(missingModelSchema).nullable()
31652
31916
  }),
31917
+ /** Commands that would get this machine generating locally, empty when it already can. */
31918
+ setup: array$1(string$1()),
31653
31919
  /** Each provider key by its environment variable, true when set and not empty. */
31654
31920
  keys: record(string$1(), boolean$1()),
31655
31921
  providers: array$1(object$1({
@@ -43451,8 +43717,9 @@ async function savedNames(kits) {
43451
43717
  // src/server/routes/kits.ts
43452
43718
  const name$1 = string$1().min(1).max(256);
43453
43719
  /**
43454
- * A preview card's policy, running the theme script alone by hash, since a
43455
- * saved kit's sample runs on the board's origin, and a sandbox would draw it light.
43720
+ * The policy on every kit page and SVG, running the theme script alone by
43721
+ * hash, since a kit file runs on the board's origin, where a frame could embed
43722
+ * one to write as the board, and a sandbox would draw a sample light.
43456
43723
  */
43457
43724
  const PREVIEW_POLICY = `script-src 'sha256-${createHash("sha256").update(THEME_SCRIPT).digest("base64")}'`;
43458
43725
  const installSchema = object$1({
@@ -43543,16 +43810,16 @@ function kitRoutes(root, access, history, { tokens, shipped = shippedKitsDir() }
43543
43810
  const type = file && CONTENT_TYPES$1[extname(file).toLowerCase()];
43544
43811
  if (!file || !type) return c.notFound();
43545
43812
  const bytes = new Uint8Array(await readFile(file));
43546
- const isSample = rest.length === 2 && rest[0] === "kit" && extname(file).toLowerCase() === ".html";
43547
- const body = isSample ? injectHead(bytes, frameHead([
43813
+ const body = rest.length === 2 && rest[0] === "kit" && extname(file).toLowerCase() === ".html" ? injectHead(bytes, frameHead([
43548
43814
  ...FACES.map(faceSheetUrl),
43549
43815
  `${KITS_URL}/${encodeURIComponent(kitName)}/${TOKEN_FILE}`,
43550
43816
  `${KITS_URL}/${encodeURIComponent(kitName)}/${KIT_SHEET}`
43551
43817
  ], contentHash(bytes))) : bytes;
43818
+ const document = type.startsWith("text/html") || type === "image/svg+xml";
43552
43819
  return c.body(body, 200, {
43553
43820
  "Content-Type": type,
43554
43821
  "Cache-Control": "no-store",
43555
- ...isSample ? { "Content-Security-Policy": PREVIEW_POLICY } : {}
43822
+ ...document ? { "Content-Security-Policy": PREVIEW_POLICY } : {}
43556
43823
  });
43557
43824
  });
43558
43825
  app.onError(answerRefusal);
@@ -43585,14 +43852,16 @@ const CONTENT_TYPES = {
43585
43852
  */
43586
43853
  function servedFrames(root, { facesDir, tokens, version, base }) {
43587
43854
  const look = { sheets: (project) => tokenSheetPaths(root, project, tokens) };
43588
- const routes = new Hono();
43589
- routes.route("/", lookRoutes({
43855
+ const looks = lookRoutes({
43590
43856
  facesDir,
43591
43857
  boardSheet: () => boardSheetPath(root, tokens)
43592
- }));
43858
+ });
43859
+ const routes = new Hono();
43860
+ routes.route("/", looks);
43593
43861
  routes.route("/", frameRoutes(root, look, version, base));
43594
43862
  return {
43595
43863
  look,
43864
+ lookRoutes: looks,
43596
43865
  routes
43597
43866
  };
43598
43867
  }
@@ -44260,7 +44529,7 @@ function imageExtension(mediaType, url) {
44260
44529
  * failed request, a body past `limit`, or a file that is no image.
44261
44530
  */
44262
44531
  async function downloadImage(url, send, limit = DOWNLOAD_LIMIT) {
44263
- const { bytes, mediaType, status } = await download(url, send, limit);
44532
+ const { bytes, mediaType, status } = await download$1(url, send, limit);
44264
44533
  const extension = imageExtension(mediaType, url);
44265
44534
  if (extension === null) throw new FrameboardError("source-failed", "The download is not an image a frame shows.", {
44266
44535
  url,
@@ -44276,7 +44545,7 @@ async function downloadImage(url, send, limit = DOWNLOAD_LIMIT) {
44276
44545
  * Refuses `source-failed` on a failed request or a body past `limit`, with
44277
44546
  * the URL and the status in the details.
44278
44547
  */
44279
- async function download(url, send, limit = DOWNLOAD_LIMIT) {
44548
+ async function download$1(url, send, limit = DOWNLOAD_LIMIT) {
44280
44549
  const failed = (message, status) => new FrameboardError("source-failed", message, {
44281
44550
  url,
44282
44551
  status
@@ -44376,6 +44645,819 @@ async function saveWithLicense(project, name, bytes, license) {
44376
44645
  license
44377
44646
  };
44378
44647
  }
44648
+ const realClock = {
44649
+ now: () => Date.now(),
44650
+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
44651
+ };
44652
+ /**
44653
+ * A route under the server's address, keeping any path the address carries,
44654
+ * so `http://host/comfy/` reaches `http://host/comfy/prompt`.
44655
+ */
44656
+ function routeOf(base, route) {
44657
+ return `${base.replace(/\/+$/, "")}/${route}`;
44658
+ }
44659
+ /**
44660
+ * Queues the workflow, waits for it to finish, and reads its first saved
44661
+ * image. Refuses `provider-failed` naming the node ComfyUI refused or failed
44662
+ * in, and on a prompt still unfinished at the clock's timeout.
44663
+ */
44664
+ async function runWorkflow(base, workflow, send, clock = realClock) {
44665
+ return readImage(base, firstSavedImage(await runPrompt(base, workflow, send, clock)), send);
44666
+ }
44667
+ /**
44668
+ * Queues the workflow, waits for it to finish, and reads the first GLB a save
44669
+ * node wrote, ignoring any later one. Refuses `provider-failed` as
44670
+ * `runWorkflow` does, and when the run saved no GLB.
44671
+ */
44672
+ async function runModelWorkflow(base, workflow, send, clock = realClock) {
44673
+ const file = firstSavedModel(await runPrompt(base, workflow, send, clock));
44674
+ const answer = await call(send, viewUrl(base, file));
44675
+ if (!answer.ok) throw failed(answer.status, `could not serve ${file.filename}`);
44676
+ return new Uint8Array(await answer.arrayBuffer());
44677
+ }
44678
+ /**
44679
+ * Hands a picture to the server through its own upload, answering the name a
44680
+ * `LoadImage` node reads it by. The server may store it under another name,
44681
+ * so a run takes the answered name rather than the one sent.
44682
+ */
44683
+ async function uploadImage(base, upload, send) {
44684
+ const form = new FormData();
44685
+ form.append("image", new Blob([upload.bytes.slice()]), upload.name);
44686
+ const answer = await call(send, routeOf(base, "upload/image"), {
44687
+ method: "POST",
44688
+ body: form
44689
+ });
44690
+ if (!answer.ok) throw failed(answer.status, `refused the upload of ${upload.name}`);
44691
+ const body = await answer.json().catch(() => null);
44692
+ const name = field(body, "name");
44693
+ if (typeof name !== "string" || name === "") throw failed(answer.status, "took the upload but answered no name");
44694
+ const subfolder = field(body, "subfolder");
44695
+ return typeof subfolder === "string" && subfolder !== "" ? `${subfolder}/${name}` : name;
44696
+ }
44697
+ /** Queues the workflow and waits for it to finish, answering the outputs its history records. */
44698
+ async function runPrompt(base, workflow, send, clock) {
44699
+ const queued = await call(send, routeOf(base, "prompt"), {
44700
+ method: "POST",
44701
+ headers: { "Content-Type": "application/json" },
44702
+ body: JSON.stringify({ prompt: workflow })
44703
+ });
44704
+ const body = await queued.json().catch(() => null);
44705
+ if (!queued.ok) throw refused$1(queued.status, body);
44706
+ const id = field(body, "prompt_id");
44707
+ if (typeof id !== "string") throw failed(queued.status, "queued the prompt but answered no prompt_id");
44708
+ const timeoutMs = clock.timeoutMs ?? 6e5;
44709
+ const deadline = clock.now() + timeoutMs;
44710
+ for (;;) {
44711
+ const entry = field(await (await call(send, routeOf(base, `history/${id}`))).json().catch(() => null), id);
44712
+ const status = field(entry, "status");
44713
+ if (field(status, "status_str") === "error") throw runFailed(status);
44714
+ if (field(status, "completed") === true) return field(entry, "outputs");
44715
+ if (clock.now() >= deadline) throw failed(null, `prompt ${id} did not finish in ${timeoutMs / 1e3} s, so the queue looks stalled`);
44716
+ await clock.wait(500);
44717
+ }
44718
+ }
44719
+ /** Asks the server to unload every model and free its memory, which the next run loads again. */
44720
+ async function freeMemory(base, send) {
44721
+ const answer = await call(send, routeOf(base, "free"), {
44722
+ method: "POST",
44723
+ headers: { "Content-Type": "application/json" },
44724
+ body: JSON.stringify({
44725
+ unload_models: true,
44726
+ free_memory: true
44727
+ })
44728
+ });
44729
+ if (!answer.ok) throw failed(answer.status, "refused to free its memory");
44730
+ }
44731
+ async function call(send, url, init) {
44732
+ try {
44733
+ return await send(url, init);
44734
+ } catch (error) {
44735
+ throw failed(null, `nothing answered at ${url}: ${String(error)}`);
44736
+ }
44737
+ }
44738
+ /** The first image a save node wrote, skipping the temporary ones a preview node shows. */
44739
+ function firstSavedImage(outputs) {
44740
+ const nodes = typeof outputs === "object" && outputs !== null ? Object.values(outputs) : [];
44741
+ for (const node of nodes) {
44742
+ const images = field(node, "images");
44743
+ for (const image of Array.isArray(images) ? images : []) {
44744
+ const filename = field(image, "filename");
44745
+ if (typeof filename === "string" && field(image, "type") === "output") {
44746
+ const subfolder = field(image, "subfolder");
44747
+ return {
44748
+ filename,
44749
+ subfolder: typeof subfolder === "string" ? subfolder : "",
44750
+ type: "output"
44751
+ };
44752
+ }
44753
+ }
44754
+ }
44755
+ throw failed(200, "the run finished and saved no image");
44756
+ }
44757
+ /** The first GLB a save node wrote, which ComfyUI lists under a node's `3d` output. */
44758
+ function firstSavedModel(outputs) {
44759
+ const nodes = typeof outputs === "object" && outputs !== null ? Object.values(outputs) : [];
44760
+ for (const node of nodes) {
44761
+ const files = field(node, "3d");
44762
+ for (const file of Array.isArray(files) ? files : []) {
44763
+ const filename = field(file, "filename");
44764
+ if (typeof filename === "string" && filename.toLowerCase().endsWith(".glb") && field(file, "type") === "output") {
44765
+ const subfolder = field(file, "subfolder");
44766
+ return {
44767
+ filename,
44768
+ subfolder: typeof subfolder === "string" ? subfolder : "",
44769
+ type: "output"
44770
+ };
44771
+ }
44772
+ }
44773
+ }
44774
+ throw failed(200, "the run finished and saved no GLB");
44775
+ }
44776
+ /** Where `/view` serves a saved file, which it answers as it is unless a `channel` asks for one. */
44777
+ function viewUrl(base, file) {
44778
+ const query = new URLSearchParams({
44779
+ filename: file.filename,
44780
+ subfolder: file.subfolder,
44781
+ type: file.type
44782
+ });
44783
+ return `${routeOf(base, "view")}?${query}`;
44784
+ }
44785
+ async function readImage(base, file, send) {
44786
+ const answer = await call(send, viewUrl(base, file));
44787
+ if (!answer.ok) throw failed(answer.status, `could not serve ${file.filename}`);
44788
+ const extension = imageExtension(answer.headers.get("content-type"), null) ?? imageExtension(null, new URL(file.filename, "file:///").href);
44789
+ if (extension === null) throw failed(answer.status, `${file.filename} is not an image`);
44790
+ return {
44791
+ bytes: new Uint8Array(await answer.arrayBuffer()),
44792
+ extension
44793
+ };
44794
+ }
44795
+ /** The refusal `/prompt` answers, naming the first node it found at fault and why. */
44796
+ function refused$1(status, body) {
44797
+ const nodeErrors = field(body, "node_errors");
44798
+ const [node, fault] = typeof nodeErrors === "object" && nodeErrors !== null ? Object.entries(nodeErrors)[0] ?? [] : [];
44799
+ const message = String(field(field(body, "error"), "message") ?? "refused");
44800
+ if (node === void 0) return failed(status, message);
44801
+ const errors = field(fault, "errors");
44802
+ const first = Array.isArray(errors) ? errors[0] : void 0;
44803
+ const reason = [field(first, "message"), field(first, "details")].filter((each) => typeof each === "string" && each !== "").join(", ");
44804
+ return failed(status, `node ${node} ${String(field(fault, "class_type") ?? "")}: ${reason || message}`, node);
44805
+ }
44806
+ /** The failure a finished run's history records, naming the node it failed in. */
44807
+ function runFailed(status) {
44808
+ const messages = field(status, "messages");
44809
+ const detail = (Array.isArray(messages) ? messages : []).find((each) => Array.isArray(each) && each[0] === "execution_error")?.[1];
44810
+ const node = field(detail, "node_id");
44811
+ return failed(200, `node ${String(node ?? "?")} ${String(field(detail, "node_type") ?? "")}: ${String(field(detail, "exception_message") ?? "the run failed")}`, typeof node === "string" ? node : void 0);
44812
+ }
44813
+ function failed(status, reason, node) {
44814
+ return new FrameboardError("provider-failed", `comfyui ${status === null ? "did not answer" : `answered ${status}`}: ${reason.slice(0, 300)}`, node === void 0 ? {
44815
+ provider: "comfyui",
44816
+ status
44817
+ } : {
44818
+ provider: "comfyui",
44819
+ status,
44820
+ node
44821
+ });
44822
+ }
44823
+ function field(value, key) {
44824
+ return typeof value === "object" && value !== null && key in value ? value[key] : void 0;
44825
+ }
44826
+ // src/server/sourcing/comfyui/flux2-klein.json
44827
+ var flux2_klein_default = {
44828
+ "70": {
44829
+ "class_type": "UNETLoader",
44830
+ "inputs": {
44831
+ "unet_name": "flux-2-klein-4b-fp8.safetensors",
44832
+ "weight_dtype": "default"
44833
+ }
44834
+ },
44835
+ "71": {
44836
+ "class_type": "CLIPLoader",
44837
+ "inputs": {
44838
+ "clip_name": "qwen_3_4b.safetensors",
44839
+ "type": "flux2",
44840
+ "device": "default"
44841
+ }
44842
+ },
44843
+ "72": {
44844
+ "class_type": "VAELoader",
44845
+ "inputs": { "vae_name": "flux2-vae.safetensors" }
44846
+ },
44847
+ "74": {
44848
+ "class_type": "CLIPTextEncode",
44849
+ "inputs": {
44850
+ "text": "{{prompt}}",
44851
+ "clip": ["71", 0]
44852
+ }
44853
+ },
44854
+ "76": {
44855
+ "class_type": "ConditioningZeroOut",
44856
+ "inputs": { "conditioning": ["74", 0] }
44857
+ },
44858
+ "63": {
44859
+ "class_type": "CFGGuider",
44860
+ "inputs": {
44861
+ "model": ["70", 0],
44862
+ "positive": ["74", 0],
44863
+ "negative": ["76", 0],
44864
+ "cfg": 1
44865
+ }
44866
+ },
44867
+ "61": {
44868
+ "class_type": "KSamplerSelect",
44869
+ "inputs": { "sampler_name": "euler" }
44870
+ },
44871
+ "62": {
44872
+ "class_type": "Flux2Scheduler",
44873
+ "inputs": {
44874
+ "steps": 4,
44875
+ "width": "{{width}}",
44876
+ "height": "{{height}}"
44877
+ }
44878
+ },
44879
+ "73": {
44880
+ "class_type": "RandomNoise",
44881
+ "inputs": { "noise_seed": "{{seed}}" }
44882
+ },
44883
+ "66": {
44884
+ "class_type": "EmptyFlux2LatentImage",
44885
+ "inputs": {
44886
+ "width": "{{width}}",
44887
+ "height": "{{height}}",
44888
+ "batch_size": 1
44889
+ }
44890
+ },
44891
+ "64": {
44892
+ "class_type": "SamplerCustomAdvanced",
44893
+ "inputs": {
44894
+ "noise": ["73", 0],
44895
+ "guider": ["63", 0],
44896
+ "sampler": ["61", 0],
44897
+ "sigmas": ["62", 0],
44898
+ "latent_image": ["66", 0]
44899
+ }
44900
+ },
44901
+ "65": {
44902
+ "class_type": "VAEDecode",
44903
+ "inputs": {
44904
+ "samples": ["64", 0],
44905
+ "vae": ["72", 0]
44906
+ }
44907
+ },
44908
+ "9": {
44909
+ "class_type": "SaveImage",
44910
+ "inputs": {
44911
+ "images": ["65", 0],
44912
+ "filename_prefix": "frameboard"
44913
+ }
44914
+ }
44915
+ };
44916
+ // src/server/sourcing/comfyui/pixal3d.json
44917
+ var pixal3d_default = {
44918
+ "3": {
44919
+ "class_type": "KSampler",
44920
+ "inputs": {
44921
+ "seed": "{{seed}}",
44922
+ "steps": 12,
44923
+ "cfg": 7.5,
44924
+ "sampler_name": "euler",
44925
+ "scheduler": "normal",
44926
+ "denoise": 1,
44927
+ "model": ["108", 0],
44928
+ "positive": ["314", 0],
44929
+ "negative": ["315", 0],
44930
+ "latent_image": ["87", 0]
44931
+ }
44932
+ },
44933
+ "4": {
44934
+ "class_type": "VoxelToMesh",
44935
+ "inputs": {
44936
+ "algorithm": "basic",
44937
+ "threshold": .6,
44938
+ "voxel": ["119", 0]
44939
+ }
44940
+ },
44941
+ "12": {
44942
+ "class_type": "KSampler",
44943
+ "inputs": {
44944
+ "seed": "{{seed}}",
44945
+ "steps": 12,
44946
+ "cfg": 1,
44947
+ "sampler_name": "euler",
44948
+ "scheduler": "normal",
44949
+ "denoise": 1,
44950
+ "model": ["318", 0],
44951
+ "positive": ["98", 0],
44952
+ "negative": ["98", 1],
44953
+ "latent_image": ["98", 2]
44954
+ }
44955
+ },
44956
+ "15": {
44957
+ "class_type": "CLIPVisionLoader",
44958
+ "inputs": { "clip_name": "dino_v3_L_naf_fp32.safetensors" }
44959
+ },
44960
+ "18": {
44961
+ "class_type": "KSampler",
44962
+ "inputs": {
44963
+ "seed": "{{seed}}",
44964
+ "steps": 20,
44965
+ "cfg": 7.5,
44966
+ "sampler_name": "euler",
44967
+ "scheduler": "normal",
44968
+ "denoise": 1,
44969
+ "model": ["126", 0],
44970
+ "positive": ["91", 0],
44971
+ "negative": ["91", 1],
44972
+ "latent_image": ["91", 2]
44973
+ }
44974
+ },
44975
+ "23": {
44976
+ "class_type": "KSampler",
44977
+ "inputs": {
44978
+ "seed": "{{seed}}",
44979
+ "steps": 12,
44980
+ "cfg": 7.5,
44981
+ "sampler_name": "euler",
44982
+ "scheduler": "simple",
44983
+ "denoise": 1,
44984
+ "model": ["126", 0],
44985
+ "positive": ["94", 0],
44986
+ "negative": ["94", 1],
44987
+ "latent_image": ["94", 2]
44988
+ }
44989
+ },
44990
+ "40": {
44991
+ "class_type": "UNETLoader",
44992
+ "inputs": {
44993
+ "unet_name": "trellis_2_int8_convrot.safetensors",
44994
+ "weight_dtype": "default"
44995
+ }
44996
+ },
44997
+ "55": {
44998
+ "class_type": "LoadMoGeModel",
44999
+ "inputs": { "model_name": "moge_2_vitl_normal_fp16.safetensors" }
45000
+ },
45001
+ "56": {
45002
+ "class_type": "MoGeInference",
45003
+ "inputs": {
45004
+ "resolution_level": 9,
45005
+ "fov_x_degrees": 0,
45006
+ "batch_size": 4,
45007
+ "force_projection": true,
45008
+ "apply_mask": true,
45009
+ "refine_steps": 3,
45010
+ "moge_model": ["55", 0],
45011
+ "image": ["302", 0]
45012
+ }
45013
+ },
45014
+ "87": {
45015
+ "class_type": "EmptyTrellis2LatentStructure",
45016
+ "inputs": { "batch_size": 1 }
45017
+ },
45018
+ "91": {
45019
+ "class_type": "Trellis2ShapeStage",
45020
+ "inputs": {
45021
+ "positive": ["314", 0],
45022
+ "negative": ["315", 0],
45023
+ "voxel": ["119", 0]
45024
+ }
45025
+ },
45026
+ "92": {
45027
+ "class_type": "VaeDecodeShapeTrellis",
45028
+ "inputs": {
45029
+ "samples": ["23", 0],
45030
+ "vae": ["117", 0]
45031
+ }
45032
+ },
45033
+ "93": {
45034
+ "class_type": "VaeDecodeTextureTrellis",
45035
+ "inputs": {
45036
+ "samples": ["12", 0],
45037
+ "vae": ["118", 0],
45038
+ "shape_subdivides": ["92", 1]
45039
+ }
45040
+ },
45041
+ "94": {
45042
+ "class_type": "Trellis2UpsampleStage",
45043
+ "inputs": {
45044
+ "target_resolution": 1024,
45045
+ "positive": ["91", 0],
45046
+ "negative": ["91", 1],
45047
+ "shape_latent": ["18", 0],
45048
+ "vae": ["117", 0]
45049
+ }
45050
+ },
45051
+ "98": {
45052
+ "class_type": "Trellis2TextureStage",
45053
+ "inputs": {
45054
+ "positive": ["94", 0],
45055
+ "negative": ["94", 1],
45056
+ "shape_latent": ["23", 0]
45057
+ }
45058
+ },
45059
+ "108": {
45060
+ "class_type": "ModelSamplingSD3",
45061
+ "inputs": {
45062
+ "shift": 5,
45063
+ "model": ["125", 0]
45064
+ }
45065
+ },
45066
+ "117": {
45067
+ "class_type": "VAELoader",
45068
+ "inputs": { "vae_name": "trellis_2_shape_vae_bf16.safetensors" }
45069
+ },
45070
+ "118": {
45071
+ "class_type": "VAELoader",
45072
+ "inputs": { "vae_name": "trellis_2_texture_vae_bf16.safetensors" }
45073
+ },
45074
+ "119": {
45075
+ "class_type": "VaeDecodeStructureTrellis2",
45076
+ "inputs": {
45077
+ "resolution": "32",
45078
+ "samples": ["3", 0],
45079
+ "vae": ["117", 0]
45080
+ }
45081
+ },
45082
+ "122": {
45083
+ "class_type": "LoadImage",
45084
+ "inputs": { "image": "{{image}}" }
45085
+ },
45086
+ "125": {
45087
+ "class_type": "RescaleCFG",
45088
+ "inputs": {
45089
+ "multiplier": .7,
45090
+ "model": ["199", 0]
45091
+ }
45092
+ },
45093
+ "126": {
45094
+ "class_type": "RescaleCFG",
45095
+ "inputs": {
45096
+ "multiplier": .5,
45097
+ "model": ["279", 0]
45098
+ }
45099
+ },
45100
+ "147": {
45101
+ "class_type": "BakeTextureFromVoxel",
45102
+ "inputs": {
45103
+ "texture_size": ["288", 0],
45104
+ "mesh": ["196", 0],
45105
+ "voxel_colors": ["93", 0],
45106
+ "reference_mesh": ["92", 0]
45107
+ }
45108
+ },
45109
+ "164": {
45110
+ "class_type": "PreviewImage",
45111
+ "inputs": { "images": ["147", 0] }
45112
+ },
45113
+ "186": {
45114
+ "class_type": "DecimateMesh",
45115
+ "inputs": {
45116
+ "target_face_count": 1e5,
45117
+ "placement_mode": "midpoint",
45118
+ "mesh": ["241", 0]
45119
+ }
45120
+ },
45121
+ "192": {
45122
+ "class_type": "RemoveBackground",
45123
+ "inputs": {
45124
+ "bg_removal_model": ["193", 0],
45125
+ "image": ["122", 0]
45126
+ }
45127
+ },
45128
+ "193": {
45129
+ "class_type": "LoadBackgroundRemovalModel",
45130
+ "inputs": { "bg_removal_name": "birefnet.safetensors" }
45131
+ },
45132
+ "196": {
45133
+ "class_type": "UnwrapMesh",
45134
+ "inputs": {
45135
+ "segmenter": "pec",
45136
+ "resolution": ["288", 0],
45137
+ "padding": 1,
45138
+ "weld_distance": 2e-4,
45139
+ "mesh": ["238", 0]
45140
+ }
45141
+ },
45142
+ "199": {
45143
+ "class_type": "CFGOverride",
45144
+ "inputs": {
45145
+ "cfg": 1,
45146
+ "start_percent": .667,
45147
+ "end_percent": 1,
45148
+ "model": ["318", 0]
45149
+ }
45150
+ },
45151
+ "202": {
45152
+ "class_type": "GetMeshInfo",
45153
+ "inputs": { "mesh": ["92", 0] }
45154
+ },
45155
+ "207": {
45156
+ "class_type": "PreviewImage",
45157
+ "inputs": { "images": ["147", 1] }
45158
+ },
45159
+ "208": {
45160
+ "class_type": "PreviewImage",
45161
+ "inputs": { "images": ["147", 2] }
45162
+ },
45163
+ "210": {
45164
+ "class_type": "ApplyTextureToMesh",
45165
+ "inputs": {
45166
+ "mesh": ["196", 0],
45167
+ "base_color": ["164", 0],
45168
+ "metallic": ["207", 0],
45169
+ "roughness": ["208", 0],
45170
+ "occlusion": ["235", 0],
45171
+ "normal_map": ["226", 0]
45172
+ }
45173
+ },
45174
+ "224": {
45175
+ "class_type": "BakeNormalMapFromMesh",
45176
+ "inputs": {
45177
+ "resolution": 2048,
45178
+ "cage_distance": .05,
45179
+ "ignore_backfaces": true,
45180
+ "low_poly": ["196", 0],
45181
+ "high_poly": ["241", 0]
45182
+ }
45183
+ },
45184
+ "226": {
45185
+ "class_type": "PreviewImage",
45186
+ "inputs": { "images": ["224", 0] }
45187
+ },
45188
+ "233": {
45189
+ "class_type": "BakeAmbientOcclusion",
45190
+ "inputs": {
45191
+ "resolution": 1024,
45192
+ "samples": 64,
45193
+ "max_distance": .71,
45194
+ "strength": 1,
45195
+ "bias": .01,
45196
+ "low_poly": ["196", 0],
45197
+ "high_poly": ["241", 0]
45198
+ }
45199
+ },
45200
+ "235": {
45201
+ "class_type": "PreviewImage",
45202
+ "inputs": { "images": ["233", 0] }
45203
+ },
45204
+ "238": {
45205
+ "class_type": "MeshSmoothNormals",
45206
+ "inputs": {
45207
+ "crease_angle": 180,
45208
+ "mesh": ["186", 0]
45209
+ }
45210
+ },
45211
+ "241": {
45212
+ "class_type": "RemeshMesh",
45213
+ "inputs": {
45214
+ "resolution": 768,
45215
+ "sign_mode": "solid",
45216
+ "sign_mode.fill": 20,
45217
+ "sign_mode.qef": false,
45218
+ "band": 1,
45219
+ "project_back": 0,
45220
+ "fix_poles": false,
45221
+ "smooth_iters": 20,
45222
+ "drop_small_components": .01,
45223
+ "precluster_max_verts": 2e7,
45224
+ "mesh": ["202", 0]
45225
+ }
45226
+ },
45227
+ "242": {
45228
+ "class_type": "MoGeGeometryToFOV",
45229
+ "inputs": {
45230
+ "axis": "horizontal",
45231
+ "unit": "degrees",
45232
+ "moge_geometry": ["56", 0]
45233
+ }
45234
+ },
45235
+ "247": {
45236
+ "class_type": "MeshToFile3D",
45237
+ "inputs": { "mesh": ["4", 0] }
45238
+ },
45239
+ "248": {
45240
+ "class_type": "ComfySwitchNode",
45241
+ "inputs": {
45242
+ "switch": true,
45243
+ "on_false": ["122", 1],
45244
+ "on_true": ["192", 0]
45245
+ }
45246
+ },
45247
+ "252": {
45248
+ "class_type": "PaintMesh",
45249
+ "inputs": {
45250
+ "mesh": ["238", 0],
45251
+ "voxel_colors": ["93", 0]
45252
+ }
45253
+ },
45254
+ "260": {
45255
+ "class_type": "MeshSmoothNormals",
45256
+ "inputs": {
45257
+ "crease_angle": 180,
45258
+ "mesh": ["210", 0]
45259
+ }
45260
+ },
45261
+ "261": {
45262
+ "class_type": "RenderUVAtlas",
45263
+ "inputs": {
45264
+ "resolution": 1024,
45265
+ "mesh": ["196", 0]
45266
+ }
45267
+ },
45268
+ "262": {
45269
+ "class_type": "PreviewImage",
45270
+ "inputs": { "images": ["261", 0] }
45271
+ },
45272
+ "279": {
45273
+ "class_type": "CFGOverride",
45274
+ "inputs": {
45275
+ "cfg": 1,
45276
+ "start_percent": .769,
45277
+ "end_percent": 1,
45278
+ "model": ["318", 0]
45279
+ }
45280
+ },
45281
+ "282": {
45282
+ "class_type": "MeshToFile3D",
45283
+ "inputs": { "mesh": ["252", 0] }
45284
+ },
45285
+ "285": {
45286
+ "class_type": "MeshToFile3D",
45287
+ "inputs": { "mesh": ["260", 0] }
45288
+ },
45289
+ "288": {
45290
+ "class_type": "PrimitiveInt",
45291
+ "inputs": { "value": 2048 }
45292
+ },
45293
+ "298": {
45294
+ "class_type": "Pixal3DConditioning",
45295
+ "inputs": {
45296
+ "camera_angle_x": ["242", 0],
45297
+ "clip_vision_model": ["15", 0],
45298
+ "image": ["302", 0]
45299
+ }
45300
+ },
45301
+ "299": {
45302
+ "class_type": "Trellis2Conditioning",
45303
+ "inputs": {
45304
+ "clip_vision_model": ["15", 0],
45305
+ "image": ["302", 0]
45306
+ }
45307
+ },
45308
+ "302": {
45309
+ "class_type": "PreviewImage",
45310
+ "inputs": { "images": ["312", 0] }
45311
+ },
45312
+ "303": {
45313
+ "class_type": "MaskPreview",
45314
+ "inputs": { "mask": ["248", 0] }
45315
+ },
45316
+ "312": {
45317
+ "class_type": "ImageCropToMask",
45318
+ "inputs": {
45319
+ "width": 1024,
45320
+ "height": 1024,
45321
+ "pad_factor": 1.1,
45322
+ "grow_mask": 0,
45323
+ "background": "#000000",
45324
+ "images": ["122", 0],
45325
+ "masks": ["303", 0]
45326
+ }
45327
+ },
45328
+ "314": {
45329
+ "class_type": "ComfySwitchNode",
45330
+ "inputs": {
45331
+ "switch": ["316", 0],
45332
+ "on_false": ["298", 0],
45333
+ "on_true": ["299", 0]
45334
+ }
45335
+ },
45336
+ "315": {
45337
+ "class_type": "ComfySwitchNode",
45338
+ "inputs": {
45339
+ "switch": ["316", 0],
45340
+ "on_false": ["298", 1],
45341
+ "on_true": ["299", 1]
45342
+ }
45343
+ },
45344
+ "316": {
45345
+ "class_type": "PrimitiveBoolean",
45346
+ "inputs": { "value": false }
45347
+ },
45348
+ "318": {
45349
+ "class_type": "ComfySwitchNode",
45350
+ "inputs": {
45351
+ "switch": ["316", 0],
45352
+ "on_false": ["319", 0],
45353
+ "on_true": ["40", 0]
45354
+ }
45355
+ },
45356
+ "319": {
45357
+ "class_type": "UNETLoader",
45358
+ "inputs": {
45359
+ "unet_name": "pixal3d_int8_convrot.safetensors",
45360
+ "weight_dtype": "default"
45361
+ }
45362
+ },
45363
+ "322": {
45364
+ "class_type": "SaveGLB",
45365
+ "inputs": {
45366
+ "mesh": ["285", 0],
45367
+ "filename_prefix": "3d/frameboard"
45368
+ }
45369
+ }
45370
+ };
45371
+ // src/server/sourcing/comfyui/workflow.ts
45372
+ /** FLUX.2 klein 4B's distilled text-to-image graph, the one a run takes without `--workflow`. */
45373
+ const BUNDLED_WORKFLOW = flux2_klein_default;
45374
+ /**
45375
+ * Pixal3D's image-to-model graph at web size, 100,000 triangles and 2048 px
45376
+ * textures, the one a model run takes without `--workflow`.
45377
+ */
45378
+ const BUNDLED_MODEL_WORKFLOW = pixal3d_default;
45379
+ const REQUIRED = {
45380
+ image: {
45381
+ name: "{{prompt}}",
45382
+ holds: "the prompt asked",
45383
+ input: "text input"
45384
+ },
45385
+ model: {
45386
+ name: "{{image}}",
45387
+ holds: "the picture given",
45388
+ input: "LoadImage node’s image input"
45389
+ }
45390
+ };
45391
+ const PLACEHOLDER = /\{\{(prompt|image|width|height|seed)\}\}/g;
45392
+ /**
45393
+ * The workflow with each placeholder the values name filled, leaving any other.
45394
+ * A lone number placeholder becomes a number, since ComfyUI refuses a width sent as text.
45395
+ */
45396
+ function fillWorkflow(workflow, values) {
45397
+ const known = { ...values };
45398
+ const fill = (value) => {
45399
+ if (typeof value === "string") {
45400
+ const whole = /^\{\{(width|height|seed)\}\}$/.exec(value)?.[1];
45401
+ if (whole !== void 0 && whole in known) return known[whole];
45402
+ return value.replace(PLACEHOLDER, (placeholder, name) => name in known ? String(known[name]) : placeholder);
45403
+ }
45404
+ if (Array.isArray(value)) return value.map(fill);
45405
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, each]) => [key, fill(each)]));
45406
+ return value;
45407
+ };
45408
+ return Object.fromEntries(Object.entries(workflow).map(([id, node]) => [id, {
45409
+ ...node,
45410
+ inputs: fill(node.inputs)
45411
+ }]));
45412
+ }
45413
+ /**
45414
+ * The value as an API-format workflow carrying the placeholder its kind
45415
+ * requires, `{{prompt}}` for an image and `{{image}}` for a model, refusing
45416
+ * `usage` otherwise, so a run never sends a graph that ignores its input.
45417
+ */
45418
+ function checkWorkflow(value, name, kind = "image") {
45419
+ const nodes = typeof value === "object" && value !== null && !Array.isArray(value) ? Object.values(value) : [];
45420
+ if (!(nodes.length > 0 && nodes.every((node) => typeof node === "object" && node !== null && "class_type" in node && typeof node.class_type === "string" && "inputs" in node && typeof node.inputs === "object" && node.inputs !== null))) throw new FrameboardError("usage", `${name} is not a ComfyUI workflow in the API format. Export it from ComfyUI with File, Export (API).`, { workflow: name });
45421
+ const required = REQUIRED[kind];
45422
+ if (!JSON.stringify(value).includes(required.name)) throw new FrameboardError("usage", `${name} holds no ${required.name}, so ${required.holds} would never reach it. Put ${required.name} in the ${required.input} that takes it.`, { workflow: name });
45423
+ return value;
45424
+ }
45425
+ /** Reads and checks a workflow file before any request, refusing `usage` for one that is absent, not JSON, or no workflow of its kind. */
45426
+ async function readWorkflow(path, kind = "image") {
45427
+ let text;
45428
+ try {
45429
+ text = await readFile(path, "utf8");
45430
+ } catch {
45431
+ throw new FrameboardError("usage", `No workflow file at ${path}.`, { workflow: path });
45432
+ }
45433
+ let parsed;
45434
+ try {
45435
+ parsed = JSON.parse(text);
45436
+ } catch {
45437
+ throw new FrameboardError("usage", `${path} is not JSON.`, { workflow: path });
45438
+ }
45439
+ return checkWorkflow(parsed, path, kind);
45440
+ }
45441
+ // src/server/sourcing/providers/comfyui.ts
45442
+ /**
45443
+ * A ComfyUI server the developer runs, its "key" the address it listens at.
45444
+ * It charges nothing and runs the bundled FLUX.2 klein 4B workflow unless the
45445
+ * request carries the developer's own.
45446
+ */
45447
+ const comfyui = {
45448
+ name: "comfyui",
45449
+ model: "flux-2-klein-4b-fp8",
45450
+ keyEnv: "FRAMEBOARD_COMFYUI_URL",
45451
+ sizeFor: (asked) => asked,
45452
+ priceFor: () => 0,
45453
+ generate({ prompt, size, key, seed, workflow }, send) {
45454
+ return runWorkflow(key, fillWorkflow(workflow?.graph ?? BUNDLED_WORKFLOW, {
45455
+ prompt,
45456
+ ...size,
45457
+ seed
45458
+ }), send);
45459
+ }
45460
+ };
44379
45461
  // src/server/sourcing/providers/provider.ts
44380
45462
  /**
44381
45463
  * The refusal a provider's failure answers, with its status and its own
@@ -44609,20 +45691,29 @@ function isRecord$4(value) {
44609
45691
  return typeof value === "object" && value !== null;
44610
45692
  }
44611
45693
  // src/server/sourcing/generate.ts
44612
- /** Every provider in the order `image generate` tries them. */
44613
- const PROVIDERS = [fal, google];
45694
+ /**
45695
+ * Every provider in the order `image generate` tries them, the developer's
45696
+ * own server first since it charges nothing and setting its URL opts in.
45697
+ */
45698
+ const PROVIDERS = [
45699
+ comfyui,
45700
+ fal,
45701
+ google
45702
+ ];
44614
45703
  /** A provider's key, null when unset or empty, so an empty string never reaches a request. */
44615
45704
  function keyOf(provider, env) {
44616
45705
  const key = env[provider.keyEnv]?.trim();
44617
45706
  return key === void 0 || key === "" ? null : key;
44618
45707
  }
44619
45708
  /**
44620
- * The provider a generation runs on, the one named or else the first whose
44621
- * key is set, with the size it produces and its price. Makes no request.
44622
- * Refuses `no-provider` when none is ready, and `usage` for an unknown name.
45709
+ * The provider named, else the first whose key is set, with its size and
45710
+ * price, making no request. A workflow runs on comfyui alone. Refuses
45711
+ * `no-provider` when none is ready, and `usage` for an unknown name or a workflow beside a hosted one.
44623
45712
  */
44624
- function planGeneration(request, env) {
44625
- const candidates = request.provider === void 0 ? PROVIDERS : PROVIDERS.filter((each) => each.name === request.provider);
45713
+ function planGeneration(request, env, random = Math.random) {
45714
+ const named = request.provider ?? (request.workflow ? comfyui.name : void 0);
45715
+ if (request.workflow && named !== comfyui.name) throw new FrameboardError("usage", `--workflow runs on ${comfyui.name} alone, not --provider ${named}.`, { provider: named });
45716
+ const candidates = named === void 0 ? PROVIDERS : PROVIDERS.filter((each) => each.name === named);
44626
45717
  if (candidates.length === 0) throw new FrameboardError("usage", `--provider ${request.provider} is not one of ${IMAGE_PROVIDERS.join(", ")}.`, { providers: [...IMAGE_PROVIDERS] });
44627
45718
  for (const provider of candidates) {
44628
45719
  const key = keyOf(provider, env);
@@ -44630,10 +45721,13 @@ function planGeneration(request, env) {
44630
45721
  const size = provider.sizeFor(request.size);
44631
45722
  return {
44632
45723
  provider,
45724
+ model: request.workflow ? basename(request.workflow.name) : provider.model,
44633
45725
  prompt: request.prompt,
44634
45726
  size,
44635
45727
  priceUsd: provider.priceFor(size),
44636
- key
45728
+ key,
45729
+ seed: Math.floor(random() * Number.MAX_SAFE_INTEGER),
45730
+ ...request.workflow && { workflow: request.workflow }
44637
45731
  };
44638
45732
  }
44639
45733
  const keys = candidates.map((each) => each.keyEnv);
@@ -44644,7 +45738,9 @@ function generateImage(plan, send) {
44644
45738
  return plan.provider.generate({
44645
45739
  prompt: plan.prompt,
44646
45740
  size: plan.size,
44647
- key: plan.key
45741
+ key: plan.key,
45742
+ seed: plan.seed,
45743
+ workflow: plan.workflow
44648
45744
  }, send);
44649
45745
  }
44650
45746
  // src/server/sourcing/openverse.ts
@@ -44764,11 +45860,318 @@ function text$1(value) {
44764
45860
  function integer$1(value) {
44765
45861
  return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
44766
45862
  }
45863
+ // src/server/sourcing/pack-glb.ts
45864
+ const GLB_MAGIC = 1179937895;
45865
+ const GLB_VERSION = 2;
45866
+ const JSON_CHUNK = 1313821514;
45867
+ const BIN_CHUNK = 5130562;
45868
+ const CHUNK_HEADER_BYTES = 8;
45869
+ /** The texture formats a glTF viewer reads with no extension named. */
45870
+ const IMAGE_TYPES = {
45871
+ jpg: "image/jpeg",
45872
+ jpeg: "image/jpeg",
45873
+ png: "image/png"
45874
+ };
45875
+ /**
45876
+ * Packs a glTF and the files `files` holds by the URI it names into one GLB
45877
+ * naming no outside file. Refuses `source-failed` for anything it cannot pack
45878
+ * whole rather than writing a file a viewer cannot load.
45879
+ */
45880
+ function packGlb(gltf, files) {
45881
+ const buffers = listOf(gltf.buffers);
45882
+ if (buffers.length > 1) throw refused(`The glTF names ${buffers.length} buffers, and one packs.`);
45883
+ const parts = [];
45884
+ let length = 0;
45885
+ const append = (bytes) => {
45886
+ const offset = length;
45887
+ parts.push({
45888
+ bytes,
45889
+ offset
45890
+ });
45891
+ length = align(offset + bytes.byteLength);
45892
+ return offset;
45893
+ };
45894
+ const buffer = buffers[0];
45895
+ if (buffer !== void 0) {
45896
+ const declared = buffer.byteLength;
45897
+ if (typeof declared !== "number") throw refused("The glTF buffer states no byteLength.");
45898
+ const bytes = fileFor(buffer.uri, files);
45899
+ if (bytes.byteLength < declared) throw refused(`The buffer holds ${bytes.byteLength} bytes, short of the ${declared} the glTF states.`);
45900
+ append(bytes.subarray(0, declared));
45901
+ }
45902
+ const packedViews = [...listOf(gltf.bufferViews)];
45903
+ const images = listOf(gltf.images).map((image) => {
45904
+ if (image.uri === void 0) return image;
45905
+ const bytes = fileFor(image.uri, files);
45906
+ const mimeType = mimeTypeOf(image);
45907
+ const byteOffset = append(bytes);
45908
+ packedViews.push({
45909
+ buffer: 0,
45910
+ byteOffset,
45911
+ byteLength: bytes.byteLength
45912
+ });
45913
+ const { uri: _uri, ...rest } = image;
45914
+ return {
45915
+ ...rest,
45916
+ bufferView: packedViews.length - 1,
45917
+ mimeType
45918
+ };
45919
+ });
45920
+ const json = { ...gltf };
45921
+ delete json.buffers;
45922
+ delete json.bufferViews;
45923
+ if (length > 0) json.buffers = [{ byteLength: length }];
45924
+ if (packedViews.length > 0) json.bufferViews = packedViews;
45925
+ if (gltf.images !== void 0) json.images = images;
45926
+ return container(json, parts, length);
45927
+ }
45928
+ function container(json, parts, binLength) {
45929
+ const text = new TextEncoder().encode(JSON.stringify(json));
45930
+ const jsonLength = align(text.byteLength);
45931
+ const binChunk = binLength === 0 ? 0 : CHUNK_HEADER_BYTES + binLength;
45932
+ const total = 20 + jsonLength + binChunk;
45933
+ const glb = new Uint8Array(total);
45934
+ const view = new DataView(glb.buffer);
45935
+ view.setUint32(0, GLB_MAGIC, true);
45936
+ view.setUint32(4, GLB_VERSION, true);
45937
+ view.setUint32(8, total, true);
45938
+ view.setUint32(12, jsonLength, true);
45939
+ view.setUint32(16, JSON_CHUNK, true);
45940
+ glb.set(text, 20);
45941
+ glb.fill(32, 20 + text.byteLength, 20 + jsonLength);
45942
+ if (binChunk === 0) return glb;
45943
+ const binStart = 20 + jsonLength;
45944
+ view.setUint32(binStart, binLength, true);
45945
+ view.setUint32(binStart + 4, BIN_CHUNK, true);
45946
+ const dataStart = binStart + CHUNK_HEADER_BYTES;
45947
+ for (const part of parts) glb.set(part.bytes, dataStart + part.offset);
45948
+ return glb;
45949
+ }
45950
+ function fileFor(uri, files) {
45951
+ if (typeof uri !== "string" || uri === "") throw refused("The glTF names a buffer or image with no uri.");
45952
+ if (uri.startsWith("data:")) throw refused("The glTF carries a data URI, which this packer does not read.");
45953
+ const bytes = files.get(uri) ?? files.get(safeDecode(uri));
45954
+ if (bytes === void 0) throw refused(`The glTF names ${uri}, which was not downloaded.`);
45955
+ return bytes;
45956
+ }
45957
+ function mimeTypeOf(image) {
45958
+ if (typeof image.mimeType === "string") {
45959
+ if (Object.values(IMAGE_TYPES).includes(image.mimeType)) return image.mimeType;
45960
+ throw refused(`The glTF names a texture of type ${image.mimeType}.`);
45961
+ }
45962
+ const uri = String(image.uri);
45963
+ const extension = uri.slice(uri.lastIndexOf(".") + 1).toLowerCase();
45964
+ const type = IMAGE_TYPES[extension];
45965
+ if (type === void 0) throw refused(`The texture ${uri} is neither JPEG nor PNG.`);
45966
+ return type;
45967
+ }
45968
+ function listOf(value) {
45969
+ return Array.isArray(value) ? value.filter((each) => typeof each === "object" && each !== null) : [];
45970
+ }
45971
+ function safeDecode(uri) {
45972
+ try {
45973
+ return decodeURIComponent(uri);
45974
+ } catch {
45975
+ return uri;
45976
+ }
45977
+ }
45978
+ function align(length) {
45979
+ return Math.ceil(length / 4) * 4;
45980
+ }
45981
+ function refused(message) {
45982
+ return new FrameboardError("source-failed", message, { source: "polyhaven" });
45983
+ }
45984
+ // src/server/sourcing/polyhaven.ts
45985
+ const POLYHAVEN_API = "https://api.polyhaven.com/";
45986
+ /** Named on every listing, which Poly Haven's API terms ask of any surface showing its content. */
45987
+ const POLYHAVEN_SOURCE = {
45988
+ name: "Poly Haven",
45989
+ url: "https://polyhaven.com"
45990
+ };
45991
+ const CC0_URL = "https://creativecommons.org/publicdomain/zero/1.0/";
45992
+ /** Poly Haven's `type` for a model, beside 0 for an HDRI and 1 for a texture. */
45993
+ const MODEL_TYPE = 2;
45994
+ /**
45995
+ * Poly Haven has no search, so this ranks its whole list here: by distinct
45996
+ * query words matching the name, tags, or categories, then download count,
45997
+ * then id, numbered from 1 and empty when no word matches.
45998
+ */
45999
+ async function searchModels(query, send) {
46000
+ const url = new URL("assets", POLYHAVEN_API);
46001
+ url.searchParams.set("t", "models");
46002
+ const body = await request(url, send);
46003
+ const words = new Set(wordsOf(query));
46004
+ const scored = Object.entries(isRecord$2(body) ? body : {}).map(([id, raw]) => toModel(id, raw)).filter((model) => model !== null).map((model) => {
46005
+ const own = new Set([
46006
+ model.name,
46007
+ ...model.tags,
46008
+ ...model.categories
46009
+ ].flatMap(wordsOf));
46010
+ return {
46011
+ model,
46012
+ score: [...words].filter((word) => own.has(word)).length
46013
+ };
46014
+ }).filter(({ score }) => score > 0);
46015
+ scored.sort((a, b) => b.score - a.score || (b.model.downloadCount ?? 0) - (a.model.downloadCount ?? 0) || a.model.id.localeCompare(b.model.id));
46016
+ return scored.slice(0, 20).map(({ model }, index) => ({
46017
+ number: index + 1,
46018
+ ...model
46019
+ }));
46020
+ }
46021
+ /**
46022
+ * One model by its Poly Haven id, refusing `result-not-found` for an id
46023
+ * Poly Haven does not hold or one naming a texture or an HDRI.
46024
+ */
46025
+ async function modelById(id, send) {
46026
+ const missing = new FrameboardError("result-not-found", `Poly Haven holds no model ${id}.`, { id });
46027
+ const model = toModel(id, await request(new URL(`info/${encodeURIComponent(id)}`, POLYHAVEN_API), send, missing));
46028
+ if (model === null) throw missing;
46029
+ return model;
46030
+ }
46031
+ /**
46032
+ * Downloads every file of one model at `size` into memory and packs them as
46033
+ * one GLB, so a failed download leaves nothing to write. Refuses `usage` with
46034
+ * the sizes offered, and `source-failed` on a failed download or pack.
46035
+ */
46036
+ async function fetchModel(id, size, send) {
46037
+ const body = await request(new URL(`files/${encodeURIComponent(id)}`, POLYHAVEN_API), send);
46038
+ const gltf = isRecord$2(body) && isRecord$2(body.gltf) ? body.gltf : {};
46039
+ const entryAt = (each) => {
46040
+ const sized = gltf[each];
46041
+ return isRecord$2(sized) && isRecord$2(sized.gltf) ? sized.gltf : null;
46042
+ };
46043
+ const sizes = MODEL_SIZES.filter((each) => entryAt(each) !== null);
46044
+ const entry = entryAt(size);
46045
+ if (sizes.length === 0) throw new FrameboardError("source-failed", `Poly Haven serves ${id} as no glTF, so it cannot be saved as a GLB.`, {
46046
+ source: "polyhaven",
46047
+ id,
46048
+ status: null
46049
+ });
46050
+ if (entry === null) throw new FrameboardError("usage", `Poly Haven serves ${id} at ${sizes.join(", ")}, not ${size}.`, {
46051
+ id,
46052
+ size,
46053
+ sizes
46054
+ });
46055
+ const gltfUrl = text(entry.url);
46056
+ if (gltfUrl === null) throw malformed(id);
46057
+ const includes = Object.entries(isRecord$2(entry.include) ? entry.include : {});
46058
+ const [main, ...files] = await Promise.all([download$1(gltfUrl, send), ...includes.map(([, file]) => {
46059
+ const fileUrl = isRecord$2(file) ? text(file.url) : null;
46060
+ if (fileUrl === null) throw malformed(id);
46061
+ return download$1(fileUrl, send);
46062
+ })]);
46063
+ let json;
46064
+ try {
46065
+ json = JSON.parse(new TextDecoder().decode(main?.bytes));
46066
+ } catch {
46067
+ throw malformed(id);
46068
+ }
46069
+ if (!isRecord$2(json)) throw malformed(id);
46070
+ const byUri = new Map(includes.map(([uri], index) => [uri, files[index]?.bytes ?? /* @__PURE__ */ new Uint8Array()]));
46071
+ return {
46072
+ bytes: packGlb(json, byUri),
46073
+ url: gltfUrl
46074
+ };
46075
+ }
46076
+ /** The license file for a Poly Haven model, `query` null when it was saved by id. */
46077
+ function polyhavenLicense(model, query, packed, savedAt) {
46078
+ return {
46079
+ version: 1,
46080
+ origin: "found",
46081
+ source: "polyhaven",
46082
+ id: model.id,
46083
+ query,
46084
+ title: model.name,
46085
+ authors: model.authors,
46086
+ license: "cc0",
46087
+ licenseUrl: CC0_URL,
46088
+ landingUrl: model.landingUrl,
46089
+ url: packed.url,
46090
+ size: packed.size,
46091
+ savedAt: savedAt.toISOString()
46092
+ };
46093
+ }
46094
+ async function request(url, send, missing) {
46095
+ let response;
46096
+ try {
46097
+ response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
46098
+ } catch (error) {
46099
+ throw new FrameboardError("source-failed", `Poly Haven did not answer: ${error instanceof Error ? error.message : String(error)}`, {
46100
+ source: "polyhaven",
46101
+ status: null
46102
+ });
46103
+ }
46104
+ if (response.status === 404 && missing) throw missing;
46105
+ if (!response.ok) throw new FrameboardError("source-failed", `Poly Haven answered ${response.status}.`, {
46106
+ source: "polyhaven",
46107
+ status: response.status
46108
+ });
46109
+ try {
46110
+ return await response.json();
46111
+ } catch {
46112
+ throw new FrameboardError("source-failed", "Poly Haven answered something other than JSON.", {
46113
+ source: "polyhaven",
46114
+ status: response.status
46115
+ });
46116
+ }
46117
+ }
46118
+ /** Poly Haven's snake_case asset as the record's fields, null for anything but a model with a name. */
46119
+ function toModel(id, raw) {
46120
+ if (!isRecord$2(raw) || raw.type !== MODEL_TYPE) return null;
46121
+ const name = text(raw.name);
46122
+ if (name === null) return null;
46123
+ const largest = Array.isArray(raw.max_resolution) ? Math.max(0, ...raw.max_resolution.filter((each) => typeof each === "number")) : 0;
46124
+ const dimensions = Array.isArray(raw.dimensions) ? raw.dimensions.filter((each) => typeof each === "number") : [];
46125
+ return {
46126
+ id,
46127
+ name,
46128
+ authors: isRecord$2(raw.authors) ? Object.keys(raw.authors) : [],
46129
+ categories: texts(raw.categories),
46130
+ tags: texts(raw.tags),
46131
+ license: "cc0",
46132
+ landingUrl: `${POLYHAVEN_SOURCE.url}/a/${encodeURIComponent(id)}`,
46133
+ thumbnail: text(raw.thumbnail_url),
46134
+ polycount: integer(raw.polycount),
46135
+ dimensionsMm: dimensions.length === 3 ? [
46136
+ dimensions[0] ?? 0,
46137
+ dimensions[1] ?? 0,
46138
+ dimensions[2] ?? 0
46139
+ ] : null,
46140
+ sizes: MODEL_SIZES.filter((each) => Number.parseInt(each) * 1024 <= largest),
46141
+ downloadCount: integer(raw.download_count)
46142
+ };
46143
+ }
46144
+ function malformed(id) {
46145
+ return new FrameboardError("source-failed", `Poly Haven's file list for ${id} names no glTF to download.`, {
46146
+ source: "polyhaven",
46147
+ status: null
46148
+ });
46149
+ }
46150
+ function wordsOf(value) {
46151
+ return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
46152
+ }
46153
+ function isRecord$2(value) {
46154
+ return typeof value === "object" && value !== null && !Array.isArray(value);
46155
+ }
46156
+ function text(value) {
46157
+ return typeof value === "string" && value !== "" ? value : null;
46158
+ }
46159
+ function texts(value) {
46160
+ return Array.isArray(value) ? value.filter((each) => typeof each === "string") : [];
46161
+ }
46162
+ function integer(value) {
46163
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
46164
+ }
44767
46165
  // src/server/routes/sourcing.ts
44768
46166
  /** How long a search waits on Openverse before the panel says it did not answer. */
44769
46167
  const FIND_TIMEOUT_MS = 15e3;
44770
46168
  /** How long each request of a save, its lookup and its download, may take. */
44771
46169
  const SAVE_TIMEOUT_MS = 6e4;
46170
+ /**
46171
+ * How long each request of a model save may take, longer than an image's,
46172
+ * since a model's buffer and textures download before packing.
46173
+ */
46174
+ const MODEL_SAVE_TIMEOUT_MS = 18e4;
44772
46175
  /** How long a provider may take, so a provider that never answers frees the button. */
44773
46176
  const GENERATE_TIMEOUT_MS = 12e4;
44774
46177
  /** The size the panel asks a provider for, the verb's own default. */
@@ -44782,6 +46185,10 @@ const saveBodySchema = object$1({
44782
46185
  query: queryLimit,
44783
46186
  credited: boolean$1().default(false)
44784
46187
  });
46188
+ const modelSaveBodySchema = object$1({
46189
+ id: string$1().min(1).max(200),
46190
+ query: queryLimit
46191
+ });
44785
46192
  const generateBodySchema = object$1({ prompt: string$1().trim().min(1).max(2e3) });
44786
46193
  const STATUS = {
44787
46194
  usage: 400,
@@ -44803,6 +46210,7 @@ function sourcingRoutes(root, access, { send = (input, init) => fetch(input, ini
44803
46210
  const authorized = requireWriter(access);
44804
46211
  const base = "/api/projects/:project/sourcing";
44805
46212
  const saving = /* @__PURE__ */ new Map();
46213
+ const savingModel = /* @__PURE__ */ new Map();
44806
46214
  let generating = false;
44807
46215
  app.onError((error, c) => answer(error, c));
44808
46216
  app.get(`${base}/find`, async (c) => {
@@ -44839,6 +46247,35 @@ function sourcingRoutes(root, access, { send = (input, init) => fetch(input, ini
44839
46247
  data: await pending
44840
46248
  });
44841
46249
  });
46250
+ app.get(`${base}/models`, async (c) => {
46251
+ projectOf$1(root, c.req.param("project"));
46252
+ const query = queryLimit.safeParse(c.req.query("q") ?? "");
46253
+ if (!query.success) throw new FrameboardError("usage", "Send ?q=<what the model shows>, up to 200 characters.");
46254
+ const record = {
46255
+ version: 1,
46256
+ query: query.data,
46257
+ source: { ...POLYHAVEN_SOURCE },
46258
+ results: await searchModels(query.data, timed(send, FIND_TIMEOUT_MS))
46259
+ };
46260
+ return c.json({
46261
+ ok: true,
46262
+ data: record
46263
+ });
46264
+ });
46265
+ app.post(`${base}/models/save`, authorized, async (c) => {
46266
+ const project = projectOf$1(root, c.req.param("project"));
46267
+ const body = await parseBody$1(c.req.raw, modelSaveBodySchema);
46268
+ const key = JSON.stringify([project.name, body.id]);
46269
+ let pending = savingModel.get(key);
46270
+ if (pending === void 0) {
46271
+ pending = saveFoundModel(project, body, timed(send, MODEL_SAVE_TIMEOUT_MS)).finally(() => savingModel.delete(key));
46272
+ savingModel.set(key, pending);
46273
+ }
46274
+ return c.json({
46275
+ ok: true,
46276
+ data: await pending
46277
+ });
46278
+ });
44842
46279
  app.get(`${base}/provider`, (c) => {
44843
46280
  projectOf$1(root, c.req.param("project"));
44844
46281
  return c.json({
@@ -44904,6 +46341,14 @@ async function saveFound(project, body, send) {
44904
46341
  const image = await imageById(body.id, { credited: body.credited }, send);
44905
46342
  return saveImage(project, savedStem(void 0, body.query), await downloadImage(image.url, send), foundLicense(image, body.query, /* @__PURE__ */ new Date()));
44906
46343
  }
46344
+ async function saveFoundModel(project, body, send) {
46345
+ const model = await modelById(body.id, send);
46346
+ const packed = await fetchModel(model.id, "1k", send);
46347
+ return saveModel(project, savedStem(void 0, body.query, "model"), packed.bytes, polyhavenLicense(model, body.query, {
46348
+ url: packed.url,
46349
+ size: "1k"
46350
+ }, /* @__PURE__ */ new Date()));
46351
+ }
44907
46352
  /** The provider a generation would run on and its price, naming each key by its variable alone. */
44908
46353
  function offer(env, enabled) {
44909
46354
  const keys = PROVIDERS.map((provider) => provider.keyEnv);
@@ -45168,7 +46613,7 @@ const BOARD_ROUTE_RULES = [{
45168
46613
  id: "board-route",
45169
46614
  tier: "exact",
45170
46615
  severity: "error",
45171
- description: "A frame's scripts and event handlers name no path under /api/, which on the board's origin reaches the board's own server"
46616
+ description: "A frame's scripts and event handlers name no path under /api/, which fails from a frame on its own port, apart from the board's server"
45172
46617
  }];
45173
46618
  const finding$10 = findingFor(BOARD_ROUTE_RULES);
45174
46619
  /**
@@ -45186,7 +46631,7 @@ function checkBoardRoutes(source) {
45186
46631
  return finding$10("board-route", {
45187
46632
  frame: source.ref,
45188
46633
  path: boardPath(source.root, code.path),
45189
- message: `${code.via} names ${match[2]}, a route of the board's own server, which a frame on the board's origin reaches. Mock an app's calls with data kept in the script, or list board-route in the project's checks.off if its frames mean to call /api/.`,
46634
+ message: `${code.via} names ${match[2]}, a route of the board's own server, which fails from a frame on its own port. Mock an app's calls with data kept in the script, or list board-route in the project's checks.off if its frames mean to call /api/.`,
45190
46635
  location: start === null ? code.at : locate$1(code.file, start, start + match[0].length)
45191
46636
  });
45192
46637
  }));
@@ -46289,12 +47734,12 @@ function createWarmRenderer({ baseUrl, browser, scale: defaultScale }) {
46289
47734
  x: 0,
46290
47735
  y: 0,
46291
47736
  ...frame.box
46292
- }, device), scale);
47737
+ }, device, frame.turn), scale);
46293
47738
  const open = await browser.get();
46294
47739
  const opened = await openFrame(open, {
46295
47740
  baseUrl: baseUrl(),
46296
47741
  ref: frame.ref,
46297
- box: pageSize(frame.box, device),
47742
+ box: pageSize(frame.box, device, frame.turn),
46298
47743
  theme,
46299
47744
  scale
46300
47745
  });
@@ -46302,7 +47747,7 @@ function createWarmRenderer({ baseUrl, browser, scale: defaultScale }) {
46302
47747
  let colors = null;
46303
47748
  try {
46304
47749
  await hideControls(opened.page);
46305
- if (topInset(device) > 0) colors = await readPageColors(opened.page);
47750
+ if (topInset(device, frame.turn) > 0) colors = await readPageColors(opened.page);
46306
47751
  shot = element === void 0 ? await opened.page.screenshot({
46307
47752
  animations: "disabled",
46308
47753
  caret: "hide"
@@ -46314,6 +47759,7 @@ function createWarmRenderer({ baseUrl, browser, scale: defaultScale }) {
46314
47759
  device,
46315
47760
  pose: frame.pose,
46316
47761
  island: frame.island,
47762
+ turn: frame.turn,
46317
47763
  bar: {
46318
47764
  colors,
46319
47765
  theme
@@ -46356,17 +47802,17 @@ async function shootElement(page, ref, index, scale) {
46356
47802
  * A frame's shot drawn inside a device's body, as the board draws it, on a
46357
47803
  * page the size of the body, so the PNG holds the body and nothing past it.
46358
47804
  */
46359
- async function drawBezel(browser, shot, box, { device, pose = "closed", island = "compact", bar }, scale) {
47805
+ async function drawBezel(browser, shot, box, { device, pose = "closed", island = "compact", turn, bar }, scale) {
46360
47806
  const outer = bezelBox({
46361
47807
  x: 0,
46362
47808
  y: 0,
46363
47809
  ...box
46364
- }, device);
47810
+ }, device, turn);
46365
47811
  const page = pageBox({
46366
47812
  x: 0,
46367
47813
  y: 0,
46368
47814
  ...box
46369
- }, device);
47815
+ }, device, turn);
46370
47816
  const laptop = device === "laptop";
46371
47817
  const context = await browser.newContext({
46372
47818
  viewport: {
@@ -46377,9 +47823,10 @@ async function drawBezel(browser, shot, box, { device, pose = "closed", island =
46377
47823
  });
46378
47824
  try {
46379
47825
  const tab = await context.newPage();
46380
- const marks = device === "phone" ? statusBarHtml(bar.colors, bar.theme) + phoneMarks(island) : laptop ? laptopMarks(box) : device === "foldable" ? foldableMarks(pose) : "";
47826
+ const sideways = turnOf(turn);
47827
+ const marks = device === "phone" ? sideways === "upright" ? statusBarHtml(bar.colors, bar.theme) + phoneMarks(island) : turnedPhoneMarks(island, sideways) : laptop ? laptopMarks(box) : device === "foldable" ? foldableMarks(pose, sideways) : "";
46381
47828
  const radius = screenCorners(device);
46382
- await tab.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="position:absolute;left:0;top:${page.y}px;width:${page.width}px;height:${page.height}px;border-radius:${pageCorners(device)}"><div style="position:absolute;inset:0;border-radius:${radius};box-shadow:${bezelShadow(device, { board: false })}">${marks}</div></div></body></html>`, { waitUntil: "load" });
47829
+ await tab.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="position:absolute;left:0;top:${page.y}px;width:${page.width}px;height:${page.height}px;border-radius:${pageCorners(device, turn)}"><div style="position:absolute;inset:0;border-radius:${radius};box-shadow:${bezelShadow(device, { board: false })}">${marks}</div></div></body></html>`, { waitUntil: "load" });
46383
47830
  return await tab.screenshot({
46384
47831
  omitBackground: true,
46385
47832
  caret: "hide"
@@ -46397,7 +47844,7 @@ async function underStatusBar(browser, shot, box, { colors, theme }, scale) {
46397
47844
  x: 0,
46398
47845
  y: 0,
46399
47846
  ...box
46400
- }, "phone");
47847
+ }, "phone", "upright");
46401
47848
  const context = await browser.newContext({
46402
47849
  viewport: box,
46403
47850
  deviceScaleFactor: scale
@@ -46415,12 +47862,12 @@ function readPageColors(page) {
46415
47862
  return page.evaluate(pageColors);
46416
47863
  }
46417
47864
  /** The viewport a frame's page opens at, its box less a phone's status bar, at least one pixel tall. */
46418
- function pageSize(box, device) {
47865
+ function pageSize(box, device, turn) {
46419
47866
  const page = pageBox({
46420
47867
  x: 0,
46421
47868
  y: 0,
46422
47869
  ...box
46423
- }, device);
47870
+ }, device, turn);
46424
47871
  return {
46425
47872
  width: page.width,
46426
47873
  height: Math.max(1, page.height)
@@ -46452,15 +47899,32 @@ function phoneMarks(island) {
46452
47899
  const { border } = BEZELS.phone;
46453
47900
  const buttons = PHONE_BUTTONS.map(({ side, top, height }) => `<span style="position:absolute;${side}:${-border - 4}px;top:${top - border}px;width:4px;height:${height}px;border-radius:2px;background:${BEZEL_COLORS.button}"></span>`).join("");
46454
47901
  const shape = phoneIsland(island);
46455
- const timer = island === "wide" ? `<span style="display:flex;align-items:center;gap:5px"><span style="width:6px;height:6px;border-radius:3px;background:${BEZEL_COLORS.islandLive}"></span>${WIDE_ISLAND_TIMER}</span><span style="display:flex;align-items:flex-end;gap:2px">${WIDE_ISLAND_LEVEL.map((tall) => `<span style="width:2px;height:${tall}px;border-radius:1px;background:${BEZEL_COLORS.islandLive}"></span>`).join("")}</span>` : "";
46456
- return buttons + `<span style="${pill(shape.width, shape.height, BEZEL_COLORS.island)}top:${shape.top}px;box-sizing:border-box;display:flex;align-items:center;justify-content:space-between;padding:0 11px;color:${BEZEL_COLORS.islandText};font:600 11px/1 ${STATUS_FONT};font-variant-numeric:tabular-nums">${timer}</span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>`;
47902
+ return buttons + `<span style="${pill(shape.width, shape.height, BEZEL_COLORS.island)}top:${shape.top}px;${ISLAND_TEXT}">${islandTimer(island)}</span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>`;
47903
+ }
47904
+ const ISLAND_TEXT = `box-sizing:border-box;display:flex;align-items:center;justify-content:space-between;padding:0 11px;color:${BEZEL_COLORS.islandText};font:600 11px/1 ${STATUS_FONT};font-variant-numeric:tabular-nums`;
47905
+ function islandTimer(island) {
47906
+ if (island !== "wide") return "";
47907
+ return `<span style="display:flex;align-items:center;gap:5px"><span style="width:6px;height:6px;border-radius:3px;background:${BEZEL_COLORS.islandLive}"></span>${WIDE_ISLAND_TIMER}</span><span style="display:flex;align-items:flex-end;gap:2px">${WIDE_ISLAND_LEVEL.map((tall) => `<span style="width:2px;height:${tall}px;border-radius:1px;background:${BEZEL_COLORS.islandLive}"></span>`).join("")}</span>`;
47908
+ }
47909
+ /** A turned phone's island on end and its buttons on the long edges, as the board's bezel draws them. */
47910
+ function turnedPhoneMarks(island, turn) {
47911
+ const { border } = BEZELS.phone;
47912
+ const from = turn === "left" ? "left" : "right";
47913
+ const buttons = PHONE_BUTTONS.map(({ side, top, height }) => {
47914
+ return `<span style="position:absolute;${side === "left" === (turn === "left") ? "bottom" : "top"}:${-border - 4}px;${from}:${top - border}px;width:${height}px;height:4px;border-radius:2px;background:${BEZEL_COLORS.button}"></span>`;
47915
+ }).join("");
47916
+ const shape = phoneIsland(island);
47917
+ const center = shape.top + shape.height / 2;
47918
+ return buttons + `<span style="position:absolute;left:${turn === "left" ? `${center}px` : `calc(100% - ${center}px)`};top:50%;transform:translate(-50%,-50%) rotate(${turn === "left" ? -90 : 90}deg);width:${shape.width}px;height:${shape.height}px;border-radius:${shape.height / 2}px;background:${BEZEL_COLORS.island};${ISLAND_TEXT}">${islandTimer(island)}</span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>`;
46457
47919
  }
46458
- /** The foldable's fold band, island, and home bar as the board draws them for a pose. */
46459
- function foldableMarks(pose) {
46460
- const band = foldBand(pose);
47920
+ /** The foldable's fold band, island, and home bar as the board draws them for a pose and a turn. */
47921
+ function foldableMarks(pose, turn) {
47922
+ const band = foldBand(pose, turn);
46461
47923
  const reach = pose === "half" ? -BEZELS.foldable.border : 0;
46462
- const island = pill(FOLDABLE_ISLAND.width, FOLDABLE_ISLAND.height, BEZEL_COLORS.island, islandCenter(pose));
46463
- 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>`;
47924
+ const place = islandCenter(pose, turn);
47925
+ const { width, height, top } = FOLDABLE_ISLAND;
47926
+ const island = place.edge === "top" ? `${pill(width, height, BEZEL_COLORS.island, place.along)}top:${top}px` : `position:absolute;${place.edge}:${top}px;top:${place.along * 100}%;transform:translateY(-50%);width:${height}px;height:${width}px;border-radius:${height / 2}px;background:${BEZEL_COLORS.island}`;
47927
+ return (!band ? "" : band.runs === "down" ? `<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="position:absolute;top:50%;transform:translateY(-50%);left:${reach}px;right:${reach}px;height:${band.width}px;background:${band.background}"></span>`) + `<span style="${island}"></span><span style="${pill(HOME_BAR.width, HOME_BAR.height, BEZEL_COLORS.homeBar)}bottom:${HOME_BAR.bottom}px"></span>`;
46464
47928
  }
46465
47929
  function pill(width, height, color, center = .5) {
46466
47930
  return `position:absolute;left:${center * 100}%;transform:translateX(-50%);width:${width}px;height:${height}px;border-radius:${height / 2}px;background:${color};`;
@@ -46560,7 +48024,7 @@ async function fitFrame(browser, { baseUrl, frame, ...options }) {
46560
48024
  const measured = await measureContent(browser, {
46561
48025
  baseUrl,
46562
48026
  ref: frame.ref,
46563
- box: pageBox(frame.box, frame.device),
48027
+ box: pageBox(frame.box, frame.device, frame.turn),
46564
48028
  hugWidth: false
46565
48029
  });
46566
48030
  const widths = [];
@@ -46580,7 +48044,7 @@ async function fitFrame(browser, { baseUrl, frame, ...options }) {
46580
48044
  });
46581
48045
  }
46582
48046
  return {
46583
- frame: await fitHeight(options.root, frame.ref, measured.height + topInset(frame.device), {
48047
+ frame: await fitHeight(options.root, frame.ref, measured.height + topInset(frame.device, frame.turn), {
46584
48048
  ...options,
46585
48049
  widths
46586
48050
  }),
@@ -47498,8 +48962,8 @@ function readConfig(root, project) {
47498
48962
  } catch {
47499
48963
  return {};
47500
48964
  }
47501
- const checks = isRecord$2(parsed) ? parsed.checks : void 0;
47502
- if (!isRecord$2(checks)) return {};
48965
+ const checks = isRecord$1(parsed) ? parsed.checks : void 0;
48966
+ if (!isRecord$1(checks)) return {};
47503
48967
  const config = {};
47504
48968
  if (Array.isArray(checks.allowedFonts) && checks.allowedFonts.every((font) => typeof font === "string")) config.allowedFonts = checks.allowedFonts;
47505
48969
  if (typeof checks.noUppercase === "boolean") config.noUppercase = checks.noUppercase;
@@ -47508,7 +48972,7 @@ function readConfig(root, project) {
47508
48972
  if (Array.isArray(checks.off) && checks.off.every((rule) => typeof rule === "string")) config.off = checks.off;
47509
48973
  return config;
47510
48974
  }
47511
- function isRecord$2(value) {
48975
+ function isRecord$1(value) {
47512
48976
  return typeof value === "object" && value !== null && !Array.isArray(value);
47513
48977
  }
47514
48978
  // src/server/checks/outranked.ts
@@ -47885,7 +49349,8 @@ const frameDeviceSchema = object$1({
47885
49349
  show: boolean$1().optional(),
47886
49350
  foldable: boolean$1().optional(),
47887
49351
  pose: _enum$1(POSES).optional(),
47888
- island: _enum$1(ISLANDS).optional()
49352
+ island: _enum$1(ISLANDS).optional(),
49353
+ turn: _enum$1(TURNS).optional()
47889
49354
  });
47890
49355
  /** More widths than any device list offers, so a body cannot grow without bound. */
47891
49356
  const widthList = array$1(int$1().min(1)).max(64);
@@ -48270,7 +49735,8 @@ function structureRoutes(root, access, history, measure, tokens = null) {
48270
49735
  journal,
48271
49736
  foldable: body.foldable,
48272
49737
  pose: body.pose,
48273
- island: body.island
49738
+ island: body.island,
49739
+ turn: body.turn
48274
49740
  }), (records) => records.map((record) => record.ref));
48275
49741
  return c.json({
48276
49742
  ok: true,
@@ -48783,7 +50249,7 @@ function boardHostGuard(port) {
48783
50249
  await next();
48784
50250
  };
48785
50251
  }
48786
- function createApp({ clientDir, root, port, actions, tickets, openRoute, renderFrame, renderFilmstrip, clipboard = null, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion, assetUsage, preview }) {
50252
+ function createApp({ clientDir, root, port, framePort, actions, tickets, openRoute, renderFrame, renderFilmstrip, clipboard = null, facesDir, tokens, delivery, dispatch, history, selection, checks, thumbnails, measure, frameVersion, settledVersion, assetUsage, preview }) {
48787
50253
  const app = new Hono();
48788
50254
  const given = tokens ?? null;
48789
50255
  app.use("*", async (c, next) => {
@@ -48820,7 +50286,13 @@ function createApp({ clientDir, root, port, actions, tickets, openRoute, renderF
48820
50286
  if (checks) app.route("/", checkRoutes(actions.access, checks));
48821
50287
  if (thumbnails) app.route("/", thumbnailRoutes(root, thumbnails));
48822
50288
  if (preview) app.route("/", previewRoutes(root, actions.access, preview));
48823
- app.route("/", frames.routes);
50289
+ app.route("/", frames.lookRoutes);
50290
+ app.on(["GET", "HEAD"], "/frames/*", (c) => {
50291
+ const url = new URL(c.req.url);
50292
+ url.port = String(framePort());
50293
+ return c.redirect(url.href, 307);
50294
+ });
50295
+ app.all("/frames/*", (c) => c.notFound());
48824
50296
  app.use("*", serveStatic({ root: clientDir }));
48825
50297
  app.get("/p/*", serveStatic({
48826
50298
  root: clientDir,
@@ -48868,7 +50340,7 @@ function firstLine(error) {
48868
50340
  return message.split("\n").find((line) => line.trim() !== "") ?? message;
48869
50341
  }
48870
50342
  // src/server/capture/host.ts
48871
- const HOSTNAME$1 = "127.0.0.1";
50343
+ const HOSTNAME$2 = "127.0.0.1";
48872
50344
  /**
48873
50345
  * Serves frames on a loopback port for a verb with no server running, through
48874
50346
  * the server's own routes, so a capture sees what the board shows.
@@ -48881,7 +50353,7 @@ async function startFrameHost({ root, facesDir }) {
48881
50353
  const server = await new Promise((resolve, reject) => {
48882
50354
  const created = serve({
48883
50355
  fetch: app.fetch,
48884
- hostname: HOSTNAME$1,
50356
+ hostname: HOSTNAME$2,
48885
50357
  port: 0
48886
50358
  }, (info) => {
48887
50359
  bound = info.port;
@@ -48890,7 +50362,7 @@ async function startFrameHost({ root, facesDir }) {
48890
50362
  created.once("error", reject);
48891
50363
  });
48892
50364
  return {
48893
- url: `http://${HOSTNAME$1}:${bound}`,
50365
+ url: `http://${HOSTNAME$2}:${bound}`,
48894
50366
  close: () => new Promise((done, fail) => {
48895
50367
  server.close((error) => error ? fail(error) : done());
48896
50368
  server.closeAllConnections();
@@ -49084,7 +50556,8 @@ async function captureMotionImages(browser, { baseUrl, frame, themes, out, scale
49084
50556
  frame: {
49085
50557
  ref: frame.ref,
49086
50558
  box: view,
49087
- device: viewDevice(frame, view)
50559
+ device: viewDevice(frame, view),
50560
+ turn: frame.turn
49088
50561
  },
49089
50562
  theme,
49090
50563
  scale,
@@ -49110,6 +50583,7 @@ async function captureMotionImages(browser, { baseUrl, frame, themes, out, scale
49110
50583
  ref: frame.ref,
49111
50584
  view,
49112
50585
  device: viewDevice(frame, view),
50586
+ turn: frame.turn,
49113
50587
  theme,
49114
50588
  scale,
49115
50589
  motionTimeoutMs,
@@ -49151,6 +50625,7 @@ async function renderFilmstrip(browser, { baseUrl, frame, theme, scale = 1, coun
49151
50625
  ref: frame.ref,
49152
50626
  view,
49153
50627
  device: frame.device,
50628
+ turn: frame.turn,
49154
50629
  theme,
49155
50630
  scale,
49156
50631
  motionTimeoutMs,
@@ -49170,19 +50645,19 @@ async function renderFilmstrip(browser, { baseUrl, frame, theme, scale = 1, coun
49170
50645
  * Opens one frame with its animation clock held, finds its timeline, and
49171
50646
  * shoots it at each moment `moments` picks from what it found.
49172
50647
  */
49173
- async function holdShots(browser, { baseUrl, ref, view, device, theme, scale, motionTimeoutMs, moments }) {
50648
+ async function holdShots(browser, { baseUrl, ref, view, device, turn, theme, scale, motionTimeoutMs, moments }) {
49174
50649
  assertScreenshotFits(ref, view, scale);
49175
50650
  const opened = await openFrame(browser, {
49176
50651
  baseUrl,
49177
50652
  ref,
49178
- box: pageSize(view, device),
50653
+ box: pageSize(view, device, turn),
49179
50654
  theme,
49180
50655
  scale,
49181
50656
  motion: "hold"
49182
50657
  });
49183
50658
  try {
49184
50659
  const motion = await findMotion(opened.page, ref, motionTimeoutMs);
49185
- const colors = topInset(device) > 0 ? await readPageColors(opened.page) : null;
50660
+ const colors = topInset(device, turn) > 0 ? await readPageColors(opened.page) : null;
49186
50661
  const held = [];
49187
50662
  for (const moment of moments(motion)) {
49188
50663
  const at = await seekMotion(opened.page, motion, moment);
@@ -49222,7 +50697,7 @@ async function renderFrame(browser, baseUrl, frame, view, theme, scale, scroll)
49222
50697
  const opened = await openFrame(browser, {
49223
50698
  baseUrl,
49224
50699
  ref: frame.ref,
49225
- box: pageSize(box, device),
50700
+ box: pageSize(box, device, frame.turn),
49226
50701
  theme,
49227
50702
  scale
49228
50703
  });
@@ -49230,7 +50705,7 @@ async function renderFrame(browser, baseUrl, frame, view, theme, scale, scroll)
49230
50705
  const scrollY = scroll === void 0 ? void 0 : await opened.page.evaluate(scrollAndSettle, scroll);
49231
50706
  const shot = await opened.page.screenshot(SCREENSHOT);
49232
50707
  return {
49233
- bytes: topInset(device) > 0 ? await underStatusBar(browser, shot, box, {
50708
+ bytes: topInset(device, frame.turn) > 0 ? await underStatusBar(browser, shot, box, {
49234
50709
  colors: await readPageColors(opened.page),
49235
50710
  theme
49236
50711
  }, scale) : shot,
@@ -49460,7 +50935,7 @@ async function requestBoard(address, path, init, timeoutMs = REQUEST_TIMEOUT_MS)
49460
50935
  }
49461
50936
  const envelope = await response.json().catch(() => null);
49462
50937
  const refusal = envelope?.error;
49463
- if (!response.ok && isErrorCode(refusal?.code) && typeof refusal?.message === "string") throw new FrameboardError(refusal.code, refusal.message, isRecord$1(refusal.details) ? refusal.details : {});
50938
+ if (!response.ok && isErrorCode(refusal?.code) && typeof refusal?.message === "string") throw new FrameboardError(refusal.code, refusal.message, isRecord(refusal.details) ? refusal.details : {});
49464
50939
  if (!response.ok || !envelope) throw new FrameboardError("internal", `The frameboard server at ${address.url} refused ${path} with ${response.status}.`, {
49465
50940
  url: address.url,
49466
50941
  status: response.status
@@ -49470,7 +50945,7 @@ async function requestBoard(address, path, init, timeoutMs = REQUEST_TIMEOUT_MS)
49470
50945
  function isErrorCode(code) {
49471
50946
  return typeof code === "string" && Object.hasOwn(EXIT_CODES, code);
49472
50947
  }
49473
- function isRecord$1(value) {
50948
+ function isRecord(value) {
49474
50949
  return typeof value === "object" && value !== null && !Array.isArray(value);
49475
50950
  }
49476
50951
  // src/cli/commands/check.ts
@@ -49648,6 +51123,11 @@ const frameRecordSchema = object$1({
49648
51123
  pose: _enum$1(POSES).optional(),
49649
51124
  /** `wide` while the frame picks the phone's wide island, shown or not, absent for the compact one. */
49650
51125
  island: literal("wide").optional(),
51126
+ /**
51127
+ * The way a phone, tablet, or foldable frame is turned, shown or not, absent upright.
51128
+ * A turned frame's box is landscape, and a turned phone draws no status bar.
51129
+ */
51130
+ turn: _enum$1(["left", "right"]).optional(),
49651
51131
  /** The transition the frame arrives with in present mode, over its page's, absent when it holds none. */
49652
51132
  transition: transitionRecordSchema.optional(),
49653
51133
  /** What the presenter means to say over the slide, plain text with its line breaks, absent when it holds none. */
@@ -50211,310 +51691,105 @@ const RECORDS = {
50211
51691
  imageGenerate: imageGenerateSchema,
50212
51692
  imageDoctor: imageDoctorSchema,
50213
51693
  modelFind: modelFindSchema,
51694
+ modelGenerate: modelGenerateSchema,
50214
51695
  savedModel: savedModelSchema
50215
51696
  };
50216
- // src/server/sourcing/pack-glb.ts
50217
- const GLB_MAGIC = 1179937895;
50218
- const GLB_VERSION = 2;
50219
- const JSON_CHUNK = 1313821514;
50220
- const BIN_CHUNK = 5130562;
50221
- const CHUNK_HEADER_BYTES = 8;
50222
- /** The texture formats a glTF viewer reads with no extension named. */
50223
- const IMAGE_TYPES = {
50224
- jpg: "image/jpeg",
50225
- jpeg: "image/jpeg",
50226
- png: "image/png"
50227
- };
50228
- /**
50229
- * Packs a glTF and the files `files` holds by the URI it names into one GLB
50230
- * naming no outside file. Refuses `source-failed` for anything it cannot pack
50231
- * whole rather than writing a file a viewer cannot load.
50232
- */
50233
- function packGlb(gltf, files) {
50234
- const buffers = listOf(gltf.buffers);
50235
- if (buffers.length > 1) throw refused(`The glTF names ${buffers.length} buffers, and one packs.`);
50236
- const parts = [];
50237
- let length = 0;
50238
- const append = (bytes) => {
50239
- const offset = length;
50240
- parts.push({
50241
- bytes,
50242
- offset
50243
- });
50244
- length = align(offset + bytes.byteLength);
50245
- return offset;
51697
+ // src/server/sourcing/generate-model.ts
51698
+ /** The environment variable naming the ComfyUI server a model is made on. */
51699
+ const COMFYUI_URL_ENV = "FRAMEBOARD_COMFYUI_URL";
51700
+ /** The model the bundled workflow runs, named by its file as the image provider names FLUX.2 klein. */
51701
+ const BUNDLED_MODEL = "pixal3d-int8-convrot";
51702
+ /**
51703
+ * The picture at `path`, read from `cwd`, the project, or its `assets/`, carrying a project asset's license forward.
51704
+ * Refuses `usage` for no file, or a file whose bytes are no PNG, JPEG, WebP, or GIF.
51705
+ */
51706
+ async function readPicture(path, cwd, project) {
51707
+ const assets = join(project.path, ASSETS_FOLDER);
51708
+ const found = await firstFile(isAbsolute(path) ? [path] : [
51709
+ resolve$1(cwd, path),
51710
+ resolve$1(project.path, path),
51711
+ resolve$1(assets, path)
51712
+ ]);
51713
+ if (found === null) throw new FrameboardError("usage", `No picture at ${path}, read from here, the project, or its ${ASSETS_FOLDER}/.`, { picture: path });
51714
+ const bytes = new Uint8Array(await readFile(found));
51715
+ const name = basename(found);
51716
+ if (!isPicture(bytes)) throw new FrameboardError("usage", `${name} is not a PNG, JPEG, WebP, or GIF picture, so there is nothing to make a model from.`, { picture: name });
51717
+ const inAssets = relative(assets, found);
51718
+ return {
51719
+ bytes,
51720
+ name,
51721
+ source: inAssets !== "" && !inAssets.startsWith("..") && !isAbsolute(inAssets) ? {
51722
+ path: inAssets.split(sep).join("/"),
51723
+ inAssets: true,
51724
+ license: await pictureLicense(found)
51725
+ } : {
51726
+ path: name,
51727
+ inAssets: false,
51728
+ license: null
51729
+ }
50246
51730
  };
50247
- const buffer = buffers[0];
50248
- if (buffer !== void 0) {
50249
- const declared = buffer.byteLength;
50250
- if (typeof declared !== "number") throw refused("The glTF buffer states no byteLength.");
50251
- const bytes = fileFor(buffer.uri, files);
50252
- if (bytes.byteLength < declared) throw refused(`The buffer holds ${bytes.byteLength} bytes, short of the ${declared} the glTF states.`);
50253
- append(bytes.subarray(0, declared));
50254
- }
50255
- const packedViews = [...listOf(gltf.bufferViews)];
50256
- const images = listOf(gltf.images).map((image) => {
50257
- if (image.uri === void 0) return image;
50258
- const bytes = fileFor(image.uri, files);
50259
- const mimeType = mimeTypeOf(image);
50260
- const byteOffset = append(bytes);
50261
- packedViews.push({
50262
- buffer: 0,
50263
- byteOffset,
50264
- byteLength: bytes.byteLength
50265
- });
50266
- const { uri: _uri, ...rest } = image;
50267
- return {
50268
- ...rest,
50269
- bufferView: packedViews.length - 1,
50270
- mimeType
50271
- };
50272
- });
50273
- const json = { ...gltf };
50274
- delete json.buffers;
50275
- delete json.bufferViews;
50276
- if (length > 0) json.buffers = [{ byteLength: length }];
50277
- if (packedViews.length > 0) json.bufferViews = packedViews;
50278
- if (gltf.images !== void 0) json.images = images;
50279
- return container(json, parts, length);
50280
51731
  }
50281
- function container(json, parts, binLength) {
50282
- const text = new TextEncoder().encode(JSON.stringify(json));
50283
- const jsonLength = align(text.byteLength);
50284
- const binChunk = binLength === 0 ? 0 : CHUNK_HEADER_BYTES + binLength;
50285
- const total = 20 + jsonLength + binChunk;
50286
- const glb = new Uint8Array(total);
50287
- const view = new DataView(glb.buffer);
50288
- view.setUint32(0, GLB_MAGIC, true);
50289
- view.setUint32(4, GLB_VERSION, true);
50290
- view.setUint32(8, total, true);
50291
- view.setUint32(12, jsonLength, true);
50292
- view.setUint32(16, JSON_CHUNK, true);
50293
- glb.set(text, 20);
50294
- glb.fill(32, 20 + text.byteLength, 20 + jsonLength);
50295
- if (binChunk === 0) return glb;
50296
- const binStart = 20 + jsonLength;
50297
- view.setUint32(binStart, binLength, true);
50298
- view.setUint32(binStart + 4, BIN_CHUNK, true);
50299
- const dataStart = binStart + CHUNK_HEADER_BYTES;
50300
- for (const part of parts) glb.set(part.bytes, dataStart + part.offset);
50301
- return glb;
50302
- }
50303
- function fileFor(uri, files) {
50304
- if (typeof uri !== "string" || uri === "") throw refused("The glTF names a buffer or image with no uri.");
50305
- if (uri.startsWith("data:")) throw refused("The glTF carries a data URI, which this packer does not read.");
50306
- const bytes = files.get(uri) ?? files.get(safeDecode(uri));
50307
- if (bytes === void 0) throw refused(`The glTF names ${uri}, which was not downloaded.`);
50308
- return bytes;
50309
- }
50310
- function mimeTypeOf(image) {
50311
- if (typeof image.mimeType === "string") {
50312
- if (Object.values(IMAGE_TYPES).includes(image.mimeType)) return image.mimeType;
50313
- throw refused(`The glTF names a texture of type ${image.mimeType}.`);
50314
- }
50315
- const uri = String(image.uri);
50316
- const extension = uri.slice(uri.lastIndexOf(".") + 1).toLowerCase();
50317
- const type = IMAGE_TYPES[extension];
50318
- if (type === void 0) throw refused(`The texture ${uri} is neither JPEG nor PNG.`);
50319
- return type;
50320
- }
50321
- function listOf(value) {
50322
- return Array.isArray(value) ? value.filter((each) => typeof each === "object" && each !== null) : [];
50323
- }
50324
- function safeDecode(uri) {
50325
- try {
50326
- return decodeURIComponent(uri);
50327
- } catch {
50328
- return uri;
50329
- }
50330
- }
50331
- function align(length) {
50332
- return Math.ceil(length / 4) * 4;
50333
- }
50334
- function refused(message) {
50335
- return new FrameboardError("source-failed", message, { source: "polyhaven" });
50336
- }
50337
- // src/server/sourcing/polyhaven.ts
50338
- const POLYHAVEN_API = "https://api.polyhaven.com/";
50339
- /** Named on every listing, which Poly Haven's API terms ask of any surface showing its content. */
50340
- const POLYHAVEN_SOURCE = {
50341
- name: "Poly Haven",
50342
- url: "https://polyhaven.com"
50343
- };
50344
- const CC0_URL = "https://creativecommons.org/publicdomain/zero/1.0/";
50345
- /** Poly Haven's `type` for a model, beside 0 for an HDRI and 1 for a texture. */
50346
- const MODEL_TYPE = 2;
50347
51732
  /**
50348
- * Poly Haven has no search, so this ranks its whole list here: by distinct
50349
- * query words matching the name, tags, or categories, then download count,
50350
- * then id, numbered from 1 and empty when no word matches.
51733
+ * The server, model, and seed a generation runs with, making no request.
51734
+ * Refuses `no-provider` naming `FRAMEBOARD_COMFYUI_URL` while it is unset or
51735
+ * empty, since a model runs on the developer's own server alone.
50351
51736
  */
50352
- async function searchModels(query, send) {
50353
- const url = new URL("assets", POLYHAVEN_API);
50354
- url.searchParams.set("t", "models");
50355
- const body = await request(url, send);
50356
- const words = new Set(wordsOf(query));
50357
- const scored = Object.entries(isRecord(body) ? body : {}).map(([id, raw]) => toModel(id, raw)).filter((model) => model !== null).map((model) => {
50358
- const own = new Set([
50359
- model.name,
50360
- ...model.tags,
50361
- ...model.categories
50362
- ].flatMap(wordsOf));
50363
- return {
50364
- model,
50365
- score: [...words].filter((word) => own.has(word)).length
50366
- };
50367
- }).filter(({ score }) => score > 0);
50368
- scored.sort((a, b) => b.score - a.score || (b.model.downloadCount ?? 0) - (a.model.downloadCount ?? 0) || a.model.id.localeCompare(b.model.id));
50369
- return scored.slice(0, 20).map(({ model }, index) => ({
50370
- number: index + 1,
50371
- ...model
50372
- }));
50373
- }
50374
- /**
50375
- * One model by its Poly Haven id, refusing `result-not-found` for an id
50376
- * Poly Haven does not hold or one naming a texture or an HDRI.
50377
- */
50378
- async function modelById(id, send) {
50379
- const missing = new FrameboardError("result-not-found", `Poly Haven holds no model ${id}.`, { id });
50380
- const model = toModel(id, await request(new URL(`info/${encodeURIComponent(id)}`, POLYHAVEN_API), send, missing));
50381
- if (model === null) throw missing;
50382
- return model;
51737
+ function planModelGeneration(request, env, random = Math.random) {
51738
+ const server = env[COMFYUI_URL_ENV]?.trim();
51739
+ if (server === void 0 || server === "") throw new FrameboardError("no-provider", `No ComfyUI server is set. Set ${COMFYUI_URL_ENV} in the environment, and run frameboard image doctor for the files Pixal3D needs.`, { keys: [COMFYUI_URL_ENV] });
51740
+ return {
51741
+ server,
51742
+ model: request.workflow ? basename(request.workflow.name) : BUNDLED_MODEL,
51743
+ picture: request.picture,
51744
+ seed: Math.floor(random() * Number.MAX_SAFE_INTEGER),
51745
+ ...request.workflow && { workflow: request.workflow }
51746
+ };
50383
51747
  }
50384
51748
  /**
50385
- * Downloads every file of one model at `size` into memory and packs them as
50386
- * one GLB, so a failed download leaves nothing to write. Refuses `usage` with
50387
- * the sizes offered, and `source-failed` on a failed download or pack.
51749
+ * Uploads the picture, runs the workflow on it, and answers the GLB's bytes,
51750
+ * the one point a generation reaches the server. Refuses `provider-failed`
51751
+ * on any failure the client reports.
50388
51752
  */
50389
- async function fetchModel(id, size, send) {
50390
- const body = await request(new URL(`files/${encodeURIComponent(id)}`, POLYHAVEN_API), send);
50391
- const gltf = isRecord(body) && isRecord(body.gltf) ? body.gltf : {};
50392
- const entryAt = (each) => {
50393
- const sized = gltf[each];
50394
- return isRecord(sized) && isRecord(sized.gltf) ? sized.gltf : null;
50395
- };
50396
- const sizes = MODEL_SIZES.filter((each) => entryAt(each) !== null);
50397
- const entry = entryAt(size);
50398
- if (sizes.length === 0) throw new FrameboardError("source-failed", `Poly Haven serves ${id} as no glTF, so it cannot be saved as a GLB.`, {
50399
- source: "polyhaven",
50400
- id,
50401
- status: null
50402
- });
50403
- if (entry === null) throw new FrameboardError("usage", `Poly Haven serves ${id} at ${sizes.join(", ")}, not ${size}.`, {
50404
- id,
50405
- size,
50406
- sizes
51753
+ async function generateModel(plan, send) {
51754
+ const image = await uploadImage(plan.server, {
51755
+ name: plan.picture.name,
51756
+ bytes: plan.picture.bytes
51757
+ }, send);
51758
+ const graph = fillWorkflow(plan.workflow?.graph ?? BUNDLED_MODEL_WORKFLOW, {
51759
+ image,
51760
+ seed: plan.seed
50407
51761
  });
50408
- const gltfUrl = text(entry.url);
50409
- if (gltfUrl === null) throw malformed(id);
50410
- const includes = Object.entries(isRecord(entry.include) ? entry.include : {});
50411
- const [main, ...files] = await Promise.all([download(gltfUrl, send), ...includes.map(([, file]) => {
50412
- const fileUrl = isRecord(file) ? text(file.url) : null;
50413
- if (fileUrl === null) throw malformed(id);
50414
- return download(fileUrl, send);
50415
- })]);
50416
- let json;
50417
- try {
50418
- json = JSON.parse(new TextDecoder().decode(main?.bytes));
50419
- } catch {
50420
- throw malformed(id);
50421
- }
50422
- if (!isRecord(json)) throw malformed(id);
50423
- const byUri = new Map(includes.map(([uri], index) => [uri, files[index]?.bytes ?? /* @__PURE__ */ new Uint8Array()]));
50424
- return {
50425
- bytes: packGlb(json, byUri),
50426
- url: gltfUrl
50427
- };
51762
+ return runModelWorkflow(plan.server, graph, send);
50428
51763
  }
50429
- /** The license file for a Poly Haven model, `query` null when it was saved by id. */
50430
- function polyhavenLicense(model, query, packed, savedAt) {
50431
- return {
50432
- version: 1,
50433
- origin: "found",
50434
- source: "polyhaven",
50435
- id: model.id,
50436
- query,
50437
- title: model.name,
50438
- authors: model.authors,
50439
- license: "cc0",
50440
- licenseUrl: CC0_URL,
50441
- landingUrl: model.landingUrl,
50442
- url: packed.url,
50443
- size: packed.size,
50444
- savedAt: savedAt.toISOString()
50445
- };
51764
+ async function firstFile(paths) {
51765
+ for (const path of paths) if ((await stat(path).catch(() => null))?.isFile()) return path;
51766
+ return null;
50446
51767
  }
50447
- async function request(url, send, missing) {
50448
- let response;
50449
- try {
50450
- response = await send(url, { headers: { "User-Agent": `frameboard/${version}` } });
50451
- } catch (error) {
50452
- throw new FrameboardError("source-failed", `Poly Haven did not answer: ${error instanceof Error ? error.message : String(error)}`, {
50453
- source: "polyhaven",
50454
- status: null
50455
- });
50456
- }
50457
- if (response.status === 404 && missing) throw missing;
50458
- if (!response.ok) throw new FrameboardError("source-failed", `Poly Haven answered ${response.status}.`, {
50459
- source: "polyhaven",
50460
- status: response.status
50461
- });
51768
+ /** True for the leading bytes of a PNG, JPEG, WebP, or GIF, the pictures ComfyUI's LoadImage reads. */
51769
+ function isPicture(bytes) {
51770
+ const starts = (offset, text) => [...text].every((char, at) => bytes[offset + at] === char.charCodeAt(0));
51771
+ return starts(0, "‰PNG") || bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 || starts(0, "RIFF") && starts(8, "WEBP") || starts(0, "GIF8");
51772
+ }
51773
+ /** The picture's own license file's origin and license name, null when it has none or one that does not parse. */
51774
+ async function pictureLicense(path) {
51775
+ const text = await readFile(`${path}${LICENSE_FILE_SUFFIX}`, "utf8").catch(() => null);
51776
+ if (text === null) return null;
51777
+ let parsed;
50462
51778
  try {
50463
- return await response.json();
51779
+ parsed = JSON.parse(text);
50464
51780
  } catch {
50465
- throw new FrameboardError("source-failed", "Poly Haven answered something other than JSON.", {
50466
- source: "polyhaven",
50467
- status: response.status
50468
- });
51781
+ return null;
50469
51782
  }
50470
- }
50471
- /** Poly Haven's snake_case asset as the record's fields, null for anything but a model with a name. */
50472
- function toModel(id, raw) {
50473
- if (!isRecord(raw) || raw.type !== MODEL_TYPE) return null;
50474
- const name = text(raw.name);
50475
- if (name === null) return null;
50476
- const largest = Array.isArray(raw.max_resolution) ? Math.max(0, ...raw.max_resolution.filter((each) => typeof each === "number")) : 0;
50477
- const dimensions = Array.isArray(raw.dimensions) ? raw.dimensions.filter((each) => typeof each === "number") : [];
50478
- return {
50479
- id,
50480
- name,
50481
- authors: isRecord(raw.authors) ? Object.keys(raw.authors) : [],
50482
- categories: texts(raw.categories),
50483
- tags: texts(raw.tags),
50484
- license: "cc0",
50485
- landingUrl: `${POLYHAVEN_SOURCE.url}/a/${encodeURIComponent(id)}`,
50486
- thumbnail: text(raw.thumbnail_url),
50487
- polycount: integer(raw.polycount),
50488
- dimensionsMm: dimensions.length === 3 ? [
50489
- dimensions[0] ?? 0,
50490
- dimensions[1] ?? 0,
50491
- dimensions[2] ?? 0
50492
- ] : null,
50493
- sizes: MODEL_SIZES.filter((each) => Number.parseInt(each) * 1024 <= largest),
50494
- downloadCount: integer(raw.download_count)
51783
+ const license = licenseFileSchema.safeParse(parsed);
51784
+ if (!license.success) return null;
51785
+ return license.data.origin === "found" ? {
51786
+ origin: "found",
51787
+ license: license.data.license
51788
+ } : {
51789
+ origin: "generated",
51790
+ license: null
50495
51791
  };
50496
51792
  }
50497
- function malformed(id) {
50498
- return new FrameboardError("source-failed", `Poly Haven's file list for ${id} names no glTF to download.`, {
50499
- source: "polyhaven",
50500
- status: null
50501
- });
50502
- }
50503
- function wordsOf(value) {
50504
- return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
50505
- }
50506
- function isRecord(value) {
50507
- return typeof value === "object" && value !== null && !Array.isArray(value);
50508
- }
50509
- function text(value) {
50510
- return typeof value === "string" && value !== "" ? value : null;
50511
- }
50512
- function texts(value) {
50513
- return Array.isArray(value) ? value.filter((each) => typeof each === "string") : [];
50514
- }
50515
- function integer(value) {
50516
- return typeof value === "number" && Number.isSafeInteger(value) ? value : null;
50517
- }
50518
51793
  // src/cli/docs/content-format.ts
50519
51794
  /** The content format `docs` prints, built from the constants the verbs run on. */
50520
51795
  function contentFormat() {
@@ -50544,6 +51819,7 @@ function contentFormat() {
50544
51819
  `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, with side buttons 4 px past that, 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.`,
50545
51820
  `While a phone shows, the board draws a status bar over the top ${STATUS_BAR.height} px of the frame's box, in the page's own fill and text color, and the page starts under it: a frame ${FRAME_SIZES.phone.width} by ${FRAME_SIZES.phone.height} shows a page ${FRAME_SIZES.phone.width} by ${FRAME_SIZES.phone.height - STATUS_BAR.height}. The box in layout.json keeps the screen's size, and the frame file gains no padding. A hugging height measures the page and stores it plus the bar, frame fit does the same, and capture, check, inspect, and present each read the page under the bar. An export draws the bar only with its device included, and lays the page out at the whole box without it. A linked width draws no device and no bar. With the device off, or on any other device, the page is the whole box.`,
50546
51821
  `island wide has a phone draw its wide island, the one a call or a timer shows, and absent draws the compact one. It is kept while the device is off and reads as compact on any other device. Any other value reads as compact and is kept on write. frame device <frame-ref> --island wide sets it, --island compact clears it, and both refuse a frame whose width names no phone or that names the foldable.`,
51822
+ `turn left or right turns a phone, a tablet, or a foldable a quarter, with the island on the left side for left and the right for right, and absent stands it upright. A phone's or a tablet's first turn keeps the box's upright width and height in upright, and the upright width still picks the device, so a turned phone reads as a phone however wide its box. A fixed or scroll box swaps its sides, and a hugging one takes the reference height of its upright width, ${FRAME_SIZES.phone.height} px for a phone, and hugs its height at that width. A turned phone draws no status bar, so its page is the whole box, and its buttons stand on its long edges. list reports turn while the frame is turned, shown or not, and never upright. Turning upright restores the kept size, even after a hand resize of the turned box. A turned foldable keeps no upright, since its pose gives its screen: its box is that screen with the sides swapped, ${POSE_SIZES.closed.height} by ${POSE_SIZES.closed.width} closed and ${POSE_SIZES.open.height} by ${POSE_SIZES.open.width} half or open, its island sits where the quarter turn puts it, and its fold runs across the screen. A fold keeps the turn and takes the new pose's swapped screen, upright restores the pose's screen, and --no-foldable stands it upright at that screen. frame device <frame-ref> --turn <upright|left|right> sets it, writing the layout entry alone, and a quarter turn refuses a laptop, a frame showing no device, and a frame holding extra widths, each with usage. A turned frame refuses new extra widths, and naming a turned phone or tablet the foldable stands it upright first. A phone's or a tablet's turn with no readable upright, or a value no reader knows, reads as upright.`,
50547
51823
  `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.`,
50548
51824
  `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.`,
50549
51825
  "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.",
@@ -50576,9 +51852,10 @@ function contentFormat() {
50576
51852
  ],
50577
51853
  images: [
50578
51854
  `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.`,
50579
- `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.`,
51855
+ `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. comfyui's key is the address of a ComfyUI server the developer runs, charging nothing, and it runs the bundled FLUX.2 klein 4B workflow, or with --workflow <file> a workflow exported from ComfyUI in the API format, its {{prompt}} filled with the prompt and any {{width}}, {{height}}, and {{seed}} with typed numbers. --workflow runs on comfyui alone and refuses usage beside another --provider, or for a file holding no {{prompt}}, before any request. Each local run draws a new seed, which the license file records with the workflow named. 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.`,
50580
51856
  `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.`,
50581
- "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.",
51857
+ "image doctor reports the GPU nvidia-smi names, whether a ComfyUI server answers at FRAMEBOARD_COMFYUI_URL or the default address with its version, the model files each bundled workflow loads that server lacks, each tagged for image or model to name the verb it serves, and each key as set or unset, never its value. setup lists the commands that would get the machine running both image generate and model generate locally, empty when it already can, so a missing model file leaves image generate working when every image file is present. torch comes from the CUDA index only where nvidia-smi names a GPU, and the start command reserves a tenth of that GPU's memory with --reserve-vram. It installs and spends nothing, so the developer runs each step.",
51858
+ "image free asks that ComfyUI server to unload its models and free their memory, which the model holds between runs so the next one starts warm. Run it once a batch of generations ends, and the next generate loads the model again.",
50582
51859
  `A frame links a saved image as ../${ASSETS_FOLDER}/<path>, never by its web address, since a frame loads nothing over the network.`
50583
51860
  ],
50584
51861
  models: [
@@ -50586,7 +51863,8 @@ function contentFormat() {
50586
51863
  `The element draws only in a frame whose head loads the viewer, as ${VIEWER_SCRIPT}. Placing a model on the board copies ${VIEWER_FILE} into the project's ${ASSETS_FOLDER}/ once and adds that tag to a head loading no viewer, and removing the last model leaves both. The file ships with the tool at ${shippedViewerPath()}, so copy it to the project's ${ASSETS_FOLDER}/${VIEWER_FILE} before writing the element in a project that holds none. A frame loads nothing over the network, so never link the viewer from a CDN.`,
50587
51864
  `Every staging control is an attribute on the element, set with edit --attr. camera-orbit="<theta>deg <phi>deg <radius>" places the camera, across and then down from the top, and defaults to 0deg 75deg auto. The viewer holds the camera inside max-camera-orbit, so state both once the radius passes the model's own framing, as camera-orbit="30deg 70deg 6m" max-camera-orbit="auto auto 6m". orientation="<roll>deg <pitch>deg <yaw>deg" turns the model itself, scale="<x> <y> <z>" sizes it, animation-name picks one of its clips, and autoplay starts it. The board's Model section writes these same attributes, the angle as both orbit attributes in one undo step, and a double-click on a selected model turns it by drag.`,
50588
51865
  `check reports missing-file at error for a ${VIEWER_TAG} whose ${MODEL_LOADS.join(", ")} names no file, as it does for the viewer script. capture waits for each model to draw inside the frame's load budget and holds its clip at the start, and --at seeks every clip to that moment, so two captures match. A model that fails to load, or is still loading when the budget ends, never refuses: the image lists it under models with state error or pending.`,
50589
- `model find searches ${POLYHAVEN_SOURCE.name}'s CC0 models, which ask no credit, and writes nothing. ${POLYHAVEN_SOURCE.name} has no search, so it reads the whole list in one request and ranks it here: by how many distinct query words match a word of the name, the tags, or the categories, then by download count, then by id, listing up to 20 numbered from 1 and none for a query matching nothing. Its results and human output name ${POLYHAVEN_SOURCE.name}, as its terms ask of any surface showing its content. --save <number> runs the search again, and --save <id> saves that ${POLYHAVEN_SOURCE.name} model with no search. A saved model is one .glb packed from the glTF, its buffer, and its textures, at 1k textures unless --size names one of ${MODEL_SIZES.join(", ")}, refusing usage with the sizes it offers for one the model lacks. A larger size weighs more, about 1 MB at 1k and 40 MB at 8k for a stool. Every file is held whole before anything is written, and its license file records the authors and the model's page.`
51866
+ `model find searches ${POLYHAVEN_SOURCE.name}'s CC0 models, which ask no credit, and writes nothing. ${POLYHAVEN_SOURCE.name} has no search, so it reads the whole list in one request and ranks it here: by how many distinct query words match a word of the name, the tags, or the categories, then by download count, then by id, listing up to 20 numbered from 1 and none for a query matching nothing. Its results and human output name ${POLYHAVEN_SOURCE.name}, as its terms ask of any surface showing its content. --save <number> runs the search again, and --save <id> saves that ${POLYHAVEN_SOURCE.name} model with no search. A saved model is one .glb packed from the glTF, its buffer, and its textures, at 1k textures unless --size names one of ${MODEL_SIZES.join(", ")}, refusing usage with the sizes it offers for one the model lacks. A larger size weighs more, about 1 MB at 1k and 40 MB at 8k for a stool. Every file is held whole before anything is written, and its license file records the authors and the model's page.`,
51867
+ `model generate <picture> makes a model from one PNG, JPEG, WebP, or GIF on the ComfyUI server ${COMFYUI_URL_ENV} names, running the bundled Pixal3D workflow at web size, 100,000 triangles and 2048 px textures, about 17 MB, or with --workflow <file> a workflow exported in the API format, its {{image}} filled with the uploaded picture's name and any {{seed}} with a typed number. The picture is read from here, the project's folder, or its ${ASSETS_FOLDER}/, and refuses usage when it names no file or no picture. A call takes about a minute and prints nothing until it returns. The license file records the server, the model, the workflow, the seed, and the picture: its ${ASSETS_FOLDER}/ path and its own license's origin and license name for a project asset, its file name alone otherwise. --dry-run answers with saved null and makes no request. An unset ${COMFYUI_URL_ENV} refuses no-provider, and a failed run refuses provider-failed naming the node. The model stays loaded between calls until image free unloads it, so run image free after a batch.`
50590
51868
  ],
50591
51869
  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}/.`,
50592
51870
  look: [
@@ -50973,11 +52251,12 @@ const DEVICE_ON = [
50973
52251
  "tablet"
50974
52252
  ];
50975
52253
  /** What `frame device` did, naming the device the frame draws inside and a foldable's pose. */
50976
- function deviceHeadline({ ref, box, showDevice, device, pose, island }) {
52254
+ function deviceHeadline({ ref, box, showDevice, device, pose, island, turn }) {
50977
52255
  const folded = pose ? `, folded ${pose} at ${box.width} by ${box.height}` : "";
50978
- if (!showDevice) return `Hid the device on ${ref}${folded}`;
52256
+ const turned = turn ? `, turned ${turn} at ${box.width} by ${box.height}` : "";
52257
+ if (!showDevice) return `Hid the device on ${ref}${folded}${turned}`;
50979
52258
  if (!device) return `Showed the device on ${ref}, though no device fits its ${box.width} px width`;
50980
- return `Showed the ${device} on ${ref}${folded}${device === "phone" ? ` with the ${islandOf(island)} island` : ""}`;
52259
+ return `Showed the ${device} on ${ref}${folded}${turned}${device === "phone" ? ` with the ${islandOf(island)} island` : ""}`;
50981
52260
  }
50982
52261
  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";
50983
52262
  const POSITIVE = parseInteger(1);
@@ -51059,15 +52338,16 @@ function registerFrame(program, context) {
51059
52338
  human: `Deleted frame ${result.deleted}`
51060
52339
  };
51061
52340
  });
51062
- 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, fold a foldable, and pick a phone’s island, 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)).addOption(new Option("--island <width>", "pick the phone island drawn over a frame 320 to 479 px wide, compact or the wide one a call or a timer shows").choices(ISLANDS)), context, async ([ref = "", value], { foldable, pose, island, ...options }) => {
51063
- if (value === void 0 && foldable === void 0 && pose === void 0 && island === void 0) throw new FrameboardError("usage", "frame device takes on or off, --foldable, --no-foldable, --pose, or --island.");
52341
+ 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, fold a foldable, pick a phone’s island, and turn a phone, tablet, or 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, or at its pose’s upright screen while turned")).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)).addOption(new Option("--island <width>", "pick the phone island drawn over a frame 320 to 479 px wide, compact or the wide one a call or a timer shows").choices(ISLANDS)).addOption(new Option("--turn <turn>", "turn a phone, tablet, or foldable a quarter, laying its page out landscape at its upright height wide with no status bar, a foldable at its pose’s screen with the sides swapped through every fold, left with the island on the left and right with it on the right, or upright to restore the size it held").choices(TURNS)), context, async ([ref = "", value], { foldable, pose, island, turn, ...options }) => {
52342
+ if (value === void 0 && foldable === void 0 && pose === void 0 && island === void 0 && turn === void 0) throw new FrameboardError("usage", "frame device takes on or off, --foldable, --no-foldable, --pose, --island, or --turn.");
51064
52343
  const show = value !== void 0 && Object.hasOwn(DEVICE_SWITCH, value) ? DEVICE_SWITCH[value] : void 0;
51065
52344
  const record = await setFrameDevice(await boardOf(options, io), ref, show, {
51066
52345
  ...options,
51067
52346
  cwd: io.cwd,
51068
52347
  foldable,
51069
52348
  pose,
51070
- island
52349
+ island,
52350
+ turn
51071
52351
  });
51072
52352
  return {
51073
52353
  data: record,
@@ -51111,8 +52391,98 @@ function registerFrame(program, context) {
51111
52391
  cwd: io.cwd
51112
52392
  }), options.off ? `Cleared ${flag} on` : `Set ${flag} on`));
51113
52393
  }
52394
+ // src/server/sourcing/doctor.ts
52395
+ /** Where a local ComfyUI server listens unless `FRAMEBOARD_COMFYUI_URL` names another. */
52396
+ const DEFAULT_COMFYUI_URL = "http://127.0.0.1:8188";
51114
52397
  /** How long a probe waits, so a machine with nothing listening answers at once. */
51115
52398
  const PROBE_TIMEOUT_MS = 1e3;
52399
+ /** The oldest ComfyUI whose native nodes run FLUX.2 klein, the release groundwork 54 ran. */
52400
+ const MIN_COMFYUI_VERSION = "0.46.0";
52401
+ /** The files the bundled image workflow loads, with the size and source each was measured at. */
52402
+ const BUNDLED_MODELS = [
52403
+ {
52404
+ for: "image",
52405
+ folder: "diffusion_models",
52406
+ file: "flux-2-klein-4b-fp8.safetensors",
52407
+ bytes: 4070624520,
52408
+ url: "https://huggingface.co/black-forest-labs/FLUX.2-klein-4b-fp8/resolve/main/flux-2-klein-4b-fp8.safetensors"
52409
+ },
52410
+ {
52411
+ for: "image",
52412
+ folder: "text_encoders",
52413
+ file: "qwen_3_4b.safetensors",
52414
+ bytes: 8044982048,
52415
+ url: "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors"
52416
+ },
52417
+ {
52418
+ for: "image",
52419
+ folder: "vae",
52420
+ file: "flux2-vae.safetensors",
52421
+ bytes: 336213556,
52422
+ url: "https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors"
52423
+ }
52424
+ ];
52425
+ /**
52426
+ * The files the bundled Pixal3D workflow loads, sized as groundwork 54
52427
+ * measured them. TRELLIS.2's model sits behind a switch the workflow leaves
52428
+ * off, and ComfyUI still checks that every loader's file exists.
52429
+ */
52430
+ const BUNDLED_MODEL_FILES = [
52431
+ {
52432
+ for: "model",
52433
+ folder: "diffusion_models",
52434
+ file: "pixal3d_int8_convrot.safetensors",
52435
+ bytes: 5584555824,
52436
+ url: "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/diffusion_models/pixal3d_int8_convrot.safetensors"
52437
+ },
52438
+ {
52439
+ for: "model",
52440
+ folder: "diffusion_models",
52441
+ file: "trellis_2_int8_convrot.safetensors",
52442
+ bytes: 5253048192,
52443
+ url: "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/diffusion_models/trellis_2_int8_convrot.safetensors"
52444
+ },
52445
+ {
52446
+ for: "model",
52447
+ folder: "vae",
52448
+ file: "trellis_2_shape_vae_bf16.safetensors",
52449
+ bytes: 1095844024,
52450
+ url: "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors"
52451
+ },
52452
+ {
52453
+ for: "model",
52454
+ folder: "vae",
52455
+ file: "trellis_2_texture_vae_bf16.safetensors",
52456
+ bytes: 948461364,
52457
+ url: "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors"
52458
+ },
52459
+ {
52460
+ for: "model",
52461
+ folder: "clip_vision",
52462
+ file: "dino_v3_L_naf_fp32.safetensors",
52463
+ bytes: 1215214176,
52464
+ url: "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/clip_vision/dino_v3_L_naf_fp32.safetensors"
52465
+ },
52466
+ {
52467
+ for: "model",
52468
+ folder: "background_removal",
52469
+ file: "birefnet.safetensors",
52470
+ bytes: 444473596,
52471
+ url: "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors"
52472
+ },
52473
+ {
52474
+ for: "model",
52475
+ folder: "geometry_estimation",
52476
+ file: "moge_2_vitl_normal_fp16.safetensors",
52477
+ bytes: 661859924,
52478
+ url: "https://huggingface.co/Comfy-Org/MoGe/resolve/main/geometry_estimation/moge_2_vitl_normal_fp16.safetensors"
52479
+ }
52480
+ ];
52481
+ const EVERY_MODEL = [...BUNDLED_MODELS, ...BUNDLED_MODEL_FILES];
52482
+ /** The ComfyUI server `FRAMEBOARD_COMFYUI_URL` names, else the default address. */
52483
+ function comfyuiUrl(env) {
52484
+ return env.FRAMEBOARD_COMFYUI_URL?.trim() || "http://127.0.0.1:8188";
52485
+ }
51116
52486
  function runNvidiaSmi(args) {
51117
52487
  return new Promise((resolve) => {
51118
52488
  execFile("nvidia-smi", args, { timeout: 5e3 }, (error, stdout) => resolve(error ? null : stdout));
@@ -51123,8 +52493,10 @@ function runNvidiaSmi(args) {
51123
52493
  * presence and never its value. Installs and spends nothing.
51124
52494
  */
51125
52495
  async function diagnose({ env, send, queryGpu }) {
51126
- const url = env.FRAMEBOARD_COMFYUI_URL?.trim() || "http://127.0.0.1:8188";
51127
- const [gpu, running] = await Promise.all([readGpu(queryGpu), probe(url, send)]);
52496
+ const url = comfyuiUrl(env);
52497
+ const [gpu, version] = await Promise.all([readGpu(queryGpu), probe(url, send)]);
52498
+ const running = version !== void 0;
52499
+ const missing = running ? await missingModels(url, send) : null;
51128
52500
  const providers = PROVIDERS.map((provider) => ({
51129
52501
  provider: provider.name,
51130
52502
  model: provider.model,
@@ -51136,8 +52508,16 @@ async function diagnose({ env, send, queryGpu }) {
51136
52508
  gpu,
51137
52509
  local: {
51138
52510
  url,
51139
- running
52511
+ running,
52512
+ version: version ?? null,
52513
+ missing
51140
52514
  },
52515
+ setup: setupSteps({
52516
+ gpu,
52517
+ version,
52518
+ missing,
52519
+ urlSet: Boolean(env.FRAMEBOARD_COMFYUI_URL?.trim())
52520
+ }),
51141
52521
  keys: Object.fromEntries(providers.map((each) => [each.key, each.ready])),
51142
52522
  providers,
51143
52523
  provider: providers.find((each) => each.ready)?.provider ?? null
@@ -51152,14 +52532,73 @@ async function readGpu(queryGpu) {
51152
52532
  memoryMiB
51153
52533
  };
51154
52534
  }
51155
- /** True when ComfyUI's `/system_stats` answers within the probe timeout. */
52535
+ /**
52536
+ * The version ComfyUI's `/system_stats` reports, null when it answers with
52537
+ * none, and undefined when nothing answers within the probe timeout.
52538
+ */
51156
52539
  async function probe(url, send) {
51157
52540
  try {
51158
- return (await send(new URL("/system_stats", url), { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })).ok;
52541
+ const response = await send(routeOf(url, "system_stats"), { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
52542
+ if (!response.ok) return void 0;
52543
+ const body = await response.json().catch(() => null);
52544
+ const system = typeof body === "object" && body !== null && "system" in body ? body.system : null;
52545
+ return typeof system === "object" && system !== null && "comfyui_version" in system && typeof system.comfyui_version === "string" ? system.comfyui_version : null;
51159
52546
  } catch {
51160
- return false;
52547
+ return;
51161
52548
  }
51162
52549
  }
52550
+ /** The bundled workflow's files that the folder listing ComfyUI answers lacks. */
52551
+ async function missingModels(url, send) {
52552
+ const folders = [...new Set(EVERY_MODEL.map((each) => each.folder))];
52553
+ const listed = await Promise.all(folders.map(async (folder) => {
52554
+ try {
52555
+ const response = await send(routeOf(url, `models/${folder}`), { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
52556
+ const body = response.ok ? await response.json() : [];
52557
+ return [folder, Array.isArray(body) ? body : []];
52558
+ } catch {
52559
+ return [folder, []];
52560
+ }
52561
+ }));
52562
+ const held = new Map(listed);
52563
+ return EVERY_MODEL.filter((model) => !held.get(model.folder)?.includes(model.file));
52564
+ }
52565
+ /**
52566
+ * The commands that would get this machine generating locally, empty when
52567
+ * it already can. The doctor prints them and never runs one.
52568
+ */
52569
+ function setupSteps({ gpu, version, missing, urlSet }) {
52570
+ const nvidia = gpu !== null;
52571
+ const reserve = gpu === null ? "" : ` --reserve-vram ${Math.ceil(.09999999999999998 * gpu.memoryMiB / 1024)}`;
52572
+ const exportUrl = urlSet ? [] : [`export FRAMEBOARD_COMFYUI_URL=${DEFAULT_COMFYUI_URL}`];
52573
+ if (missing === null) return [
52574
+ `git clone https://github.com/Comfy-Org/ComfyUI && cd ComfyUI # v${MIN_COMFYUI_VERSION} or later`,
52575
+ "uv venv --python 3.13 && source .venv/bin/activate",
52576
+ nvidia ? "uv pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu130" : "uv pip install torch torchvision torchaudio",
52577
+ "uv pip install -r requirements.txt",
52578
+ ...EVERY_MODEL.map(download),
52579
+ `python main.py --listen 127.0.0.1 --port 8188${reserve}`,
52580
+ ...exportUrl
52581
+ ];
52582
+ return [
52583
+ ...version !== null && version !== void 0 && olderThanMinimum(version) ? [`git pull && uv pip install -r requirements.txt # in the ComfyUI folder, since FLUX.2 klein needs v${MIN_COMFYUI_VERSION} or later`] : [],
52584
+ ...missing.map(download),
52585
+ ...exportUrl
52586
+ ];
52587
+ }
52588
+ function download(model) {
52589
+ const gigabytes = (model.bytes / 1e9).toFixed(2);
52590
+ return `curl -L -o models/${model.folder}/${model.file} ${model.url} # ${gigabytes} GB`;
52591
+ }
52592
+ function olderThanMinimum(version) {
52593
+ const parts = (text) => text.replace(/^v/, "").split(".").map((each) => Number.parseInt(each, 10) || 0);
52594
+ const have = parts(version);
52595
+ const need = parts(MIN_COMFYUI_VERSION);
52596
+ for (let index = 0; index < need.length; index += 1) {
52597
+ const gap = (have[index] ?? 0) - (need[index] ?? 0);
52598
+ if (gap !== 0) return gap < 0;
52599
+ }
52600
+ return false;
52601
+ }
51163
52602
  // src/cli/commands/image.ts
51164
52603
  function registerImage(program, context) {
51165
52604
  const { io } = context;
@@ -51190,19 +52629,24 @@ function registerImage(program, context) {
51190
52629
  human: savedLine$1(saved)
51191
52630
  };
51192
52631
  });
51193
- 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) => {
52632
+ 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("--workflow <file>", "run this ComfyUI workflow in the API format on comfyui, with {{prompt}} and optionally {{width}}, {{height}}, and {{seed}} in it").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) => {
52633
+ const workflow = options.workflow === void 0 ? void 0 : {
52634
+ name: options.workflow,
52635
+ graph: await readWorkflow(options.workflow)
52636
+ };
51194
52637
  const plan = planGeneration({
51195
52638
  prompt,
51196
52639
  size: {
51197
52640
  width: options.width,
51198
52641
  height: options.height
51199
52642
  },
51200
- provider: options.provider
52643
+ provider: options.provider,
52644
+ workflow
51201
52645
  }, process.env);
51202
52646
  const record = {
51203
52647
  version: 1,
51204
52648
  provider: plan.provider.name,
51205
- model: plan.provider.model,
52649
+ model: plan.model,
51206
52650
  prompt,
51207
52651
  ...plan.size,
51208
52652
  priceUsd: plan.priceUsd,
@@ -51224,6 +52668,8 @@ function registerImage(program, context) {
51224
52668
  width: record.width,
51225
52669
  height: record.height,
51226
52670
  priceUsd: record.priceUsd,
52671
+ ...plan.provider.name === "comfyui" && { seed: plan.seed },
52672
+ ...plan.workflow && { workflow: plan.workflow.name },
51227
52673
  savedAt: (/* @__PURE__ */ new Date()).toISOString()
51228
52674
  });
51229
52675
  return {
@@ -51234,7 +52680,7 @@ function registerImage(program, context) {
51234
52680
  human: `Generated on ${priced}. ${savedLine$1(saved)}`
51235
52681
  };
51236
52682
  });
51237
- act(addVerb(image, "doctor", "Report the GPU, a local ComfyUI server, and which provider keys are set, installing nothing"), context, async () => {
52683
+ act(addVerb(image, "doctor", "Report the GPU, a local ComfyUI server's version and missing model files, and which provider keys are set, printing setup steps and installing nothing"), context, async () => {
51238
52684
  const report = await diagnose({
51239
52685
  env: process.env,
51240
52686
  send,
@@ -51244,12 +52690,30 @@ function registerImage(program, context) {
51244
52690
  data: report,
51245
52691
  human: [
51246
52692
  `GPU\t${report.gpu === null ? "none found" : `${report.gpu.name}, ${report.gpu.memoryMiB} MiB`}`,
51247
- `Local\t${report.local.url} ${report.local.running ? "answers" : "does not answer"}`,
52693
+ `Local\t${report.local.url} ${report.local.running ? `answers, ComfyUI ${report.local.version ?? "of unknown version"}` : "does not answer"}`,
52694
+ ...(report.local.missing ?? []).map((each) => `Missing\tmodels/${each.folder}/${each.file}, ${(each.bytes / 1e9).toFixed(2)} GB, for ${each.for} generate`),
51248
52695
  ...report.providers.map((each) => `${each.provider}\t${each.key} ${each.ready ? "set" : "unset"}`),
51249
- `Generate runs on\t${report.provider ?? "nothing, since no key is set"}`
52696
+ `Generate runs on\t${report.provider ?? "nothing, since no key is set"}`,
52697
+ ...report.setup.length === 0 ? [] : [
52698
+ "",
52699
+ "To generate locally, run these yourself:",
52700
+ ...report.setup
52701
+ ]
51250
52702
  ].join("\n")
51251
52703
  };
51252
52704
  });
52705
+ act(addVerb(image, "free", "Ask the ComfyUI server to unload its models and free their memory, which the next generate loads again"), context, async () => {
52706
+ const url = comfyuiUrl(process.env);
52707
+ await freeMemory(url, send);
52708
+ return {
52709
+ data: {
52710
+ version: 1,
52711
+ url,
52712
+ freed: true
52713
+ },
52714
+ human: `Freed the models ${url} held`
52715
+ };
52716
+ });
51253
52717
  /** The result `--save` names: a number reruns the search, anything else is an id. */
51254
52718
  async function pick(query, save, search) {
51255
52719
  if (!/^\d+$/.test(save)) return {
@@ -54996,7 +56460,7 @@ async function inspectFrame(browser, { baseUrl, frame, theme, index }) {
54996
56460
  const opened = await openFrame(browser, {
54997
56461
  baseUrl,
54998
56462
  ref: frame.ref,
54999
- box: pageSize(frame.box, frame.device),
56463
+ box: pageSize(frame.box, frame.device, frame.turn),
55000
56464
  theme
55001
56465
  });
55002
56466
  let live;
@@ -55164,7 +56628,8 @@ const CREDIT = `Models from ${POLYHAVEN_SOURCE.name}, ${POLYHAVEN_SOURCE.url}, C
55164
56628
  function registerModel(program, context) {
55165
56629
  const { io } = context;
55166
56630
  const send = io.fetch ?? fetch;
55167
- act(addVerb(program.command("model").description("Find a public domain 3D model and save it into a project's assets as one GLB with its license"), "find", "Search Poly Haven's CC0 models, writing nothing unless --save names a result", { project: true }).argument("<query>", "what the model shows").option("--save <number-or-id>", "save the result with this number, or the Poly Haven model with this id, into the project's assets").option("--size <size>", `the texture size saved, one of ${MODEL_SIZES.join(", ")}, 1k by default`, parseSize).option("--name <stem>", "the saved file name without its extension, the query by default"), context, async ([query = ""], options) => {
56631
+ const model = program.command("model").description("Find a public domain 3D model or make one from a picture, saving it into a project's assets as one GLB with its license");
56632
+ act(addVerb(model, "find", "Search Poly Haven's CC0 models, writing nothing unless --save names a result", { project: true }).argument("<query>", "what the model shows").option("--save <number-or-id>", "save the result with this number, or the Poly Haven model with this id, into the project's assets").option("--size <size>", `the texture size saved, one of ${MODEL_SIZES.join(", ")}, 1k by default`, parseSize).option("--name <stem>", "the saved file name without its extension, the query by default"), context, async ([query = ""], options) => {
55168
56633
  if (options.save === void 0) {
55169
56634
  for (const flag of ["name", "size"]) if (options[flag] !== void 0) throw new FrameboardError("usage", `--${flag} needs --save.`);
55170
56635
  const results = await searchModels(query, send);
@@ -55192,6 +56657,52 @@ function registerModel(program, context) {
55192
56657
  human: savedLine(saved)
55193
56658
  };
55194
56659
  });
56660
+ act(addVerb(model, "generate", "Make a 3D model from a picture on the ComfyUI server at FRAMEBOARD_COMFYUI_URL and save it into the project's assets as one GLB with its license, in about a minute and with no progress line. Refuses no-provider while that address is unset", { project: true }).argument("<picture>", "a PNG, JPEG, WebP, or GIF, read from here, the project's folder, or its assets/").option("--workflow <file>", "run this ComfyUI workflow in the API format, with {{image}} and optionally {{seed}} in it, rather than the bundled Pixal3D one").option("--dry-run", "answer the server, model, and picture, and make no request").option("--name <stem>", "the saved file name without its extension, the picture's by default"), context, async ([path = ""], options) => {
56661
+ const workflow = options.workflow === void 0 ? void 0 : {
56662
+ name: options.workflow,
56663
+ graph: await readWorkflow(options.workflow, "model")
56664
+ };
56665
+ const project = await resolveProject(await boardOf(options, io), options.project);
56666
+ const picture = await readPicture(path, io.cwd, project);
56667
+ const stem = savedStem(options.name, picture.name.replace(/\.[^.]*$/, ""), "model");
56668
+ const plan = planModelGeneration({
56669
+ picture,
56670
+ workflow
56671
+ }, process.env);
56672
+ const record = {
56673
+ version: 1,
56674
+ provider: "comfyui",
56675
+ server: plan.server,
56676
+ model: plan.model,
56677
+ picture: picture.source,
56678
+ dryRun: options.dryRun ?? false,
56679
+ saved: null
56680
+ };
56681
+ const made = `${record.model} on ${record.server} from ${picture.source.path}`;
56682
+ if (record.dryRun) return {
56683
+ data: record,
56684
+ human: `Would generate ${made}`
56685
+ };
56686
+ const saved = await saveModel(project, stem, await generateModel(plan, send), {
56687
+ version: 1,
56688
+ origin: "generated",
56689
+ kind: "model",
56690
+ provider: "comfyui",
56691
+ server: plan.server,
56692
+ model: plan.model,
56693
+ ...plan.workflow && { workflow: plan.workflow.name },
56694
+ picture: picture.source,
56695
+ seed: plan.seed,
56696
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
56697
+ });
56698
+ return {
56699
+ data: {
56700
+ ...record,
56701
+ saved
56702
+ },
56703
+ human: `Generated ${made}. Saved assets/${saved.path} into ${saved.project}, its license in assets/${saved.licensePath}`
56704
+ };
56705
+ });
55195
56706
  /** The model `--save` names: a number reruns the search, anything else is an id. */
55196
56707
  async function pick(query, save) {
55197
56708
  if (!/^\d+$/.test(save)) return {
@@ -56420,10 +57931,10 @@ const THEMED_RULES = [
56420
57931
  * face in the board's fallback rather than refusing, after animations finish.
56421
57932
  */
56422
57933
  async function checkRendered(browser, { baseUrl, root, frame: shown, config }) {
56423
- const { device, ...target } = shown;
57934
+ const { device, turn, ...target } = shown;
56424
57935
  const frame = {
56425
57936
  ...target,
56426
- box: pageSize(target.box, device)
57937
+ box: pageSize(target.box, device, turn)
56427
57938
  };
56428
57939
  const [project = "", page = "", name = ""] = frame.ref.split("/");
56429
57940
  const source = readFrame$1({
@@ -56583,6 +58094,60 @@ function createClaimsPush(root, { broadcast, inTurn, now = () => /* @__PURE__ */
56583
58094
  }
56584
58095
  };
56585
58096
  }
58097
+ // src/server/frame-origin/listener.ts
58098
+ const HOSTNAME$1 = "127.0.0.1";
58099
+ /**
58100
+ * Lets a frame page sit in the board on either loopback name and any port,
58101
+ * which covers the board's own port and Vite's in dev, and no foreign page.
58102
+ */
58103
+ const FRAME_ANCESTORS = "frame-ancestors 'self' http://127.0.0.1:* http://localhost:*";
58104
+ const LOOPBACK_ORIGIN = /^http:\/\/(127\.0\.0\.1|localhost):\d{1,5}$/;
58105
+ /**
58106
+ * The frames, their assets, and the look on an origin apart from the board's,
58107
+ * so a frame's script carries an `Origin` the board's write guard refuses.
58108
+ * It answers GET and HEAD under the frame and look routes alone.
58109
+ */
58110
+ function frameOriginApp(port, { root, facesDir, tokens, version }) {
58111
+ const app = new Hono();
58112
+ app.use("*", boardHostGuard(port));
58113
+ app.use("*", async (c, next) => {
58114
+ await next();
58115
+ const type = c.res.headers.get("Content-Type") ?? "";
58116
+ if (type.startsWith("text/html") || type.startsWith("image/svg+xml")) c.res.headers.set("Content-Security-Policy", FRAME_ANCESTORS);
58117
+ const origin = c.req.header("Origin");
58118
+ if (origin !== void 0 && LOOPBACK_ORIGIN.test(origin)) c.res.headers.set("Access-Control-Allow-Origin", origin);
58119
+ c.res.headers.append("Vary", "Origin");
58120
+ });
58121
+ app.route("/", servedFrames(root, {
58122
+ facesDir,
58123
+ tokens: tokens ?? null,
58124
+ version
58125
+ }).routes);
58126
+ return app;
58127
+ }
58128
+ /** Starts the frame listener on a free loopback port. */
58129
+ async function startFrameOrigin(options) {
58130
+ let bound = 0;
58131
+ const app = frameOriginApp(() => bound, options);
58132
+ const server = await new Promise((resolve, reject) => {
58133
+ const created = serve({
58134
+ fetch: app.fetch,
58135
+ hostname: HOSTNAME$1,
58136
+ port: 0
58137
+ }, (info) => {
58138
+ bound = info.port;
58139
+ resolve(created);
58140
+ });
58141
+ created.once("error", reject);
58142
+ });
58143
+ return {
58144
+ port: bound,
58145
+ close: () => new Promise((done, fail) => {
58146
+ server.close((error) => error ? fail(error) : done());
58147
+ server.closeAllConnections();
58148
+ })
58149
+ };
58150
+ }
56586
58151
  // node_modules/readdirp/index.js
56587
58152
  const EntryTypes = {
56588
58153
  FILE_TYPE: "files",
@@ -60072,7 +61637,7 @@ function checkOne(root, frame, context) {
60072
61637
  * The live socket every board tab holds. An `inbox` client never counts as a
60073
61638
  * tab and needs the bearer token, since a browser page must never register one.
60074
61639
  */
60075
- function createHub({ tabs, port, access, snapshot, findings, notes, delivery, history, claims, changes, closeTab, dispatch = false }) {
61640
+ function createHub({ tabs, port, access, snapshot, findings, notes, delivery, history, claims, changes, closeTab, dispatch = false, framePort }) {
60076
61641
  const server = new import_websocket_server.default({ noServer: true });
60077
61642
  const boards = /* @__PURE__ */ new Map();
60078
61643
  const inboxes = /* @__PURE__ */ new Map();
@@ -60107,6 +61672,10 @@ function createHub({ tabs, port, access, snapshot, findings, notes, delivery, hi
60107
61672
  boards.set(socket, writer);
60108
61673
  if (typeof message.tab === "string") tabIds.set(socket, message.tab);
60109
61674
  tabs.open(writer);
61675
+ if (framePort) send(socket, {
61676
+ type: "frames",
61677
+ port: framePort()
61678
+ });
60110
61679
  snapshot().then(async (board) => {
60111
61680
  send(socket, {
60112
61681
  type: "board",
@@ -60283,14 +61852,14 @@ function failureOf(error) {
60283
61852
  async function measureParts(measure, frame, parts) {
60284
61853
  const size = {};
60285
61854
  if (parts !== "linked") {
60286
- const page = pageBox(frame.box, frame.device);
61855
+ const page = pageBox(frame.box, frame.device, frame.turn);
60287
61856
  const own = await measure({
60288
61857
  ...frame,
60289
61858
  box: page
60290
61859
  });
60291
61860
  if (!own.empty) Object.assign(size, {
60292
61861
  width: own.width,
60293
- height: own.height + topInset(frame.device)
61862
+ height: own.height + topInset(frame.device, frame.turn)
60294
61863
  });
60295
61864
  }
60296
61865
  if (parts !== "own" && frame.hugHeight && frame.widths.length > 0) {
@@ -60895,9 +62464,16 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
60895
62464
  inTurn(() => tracker.own(step));
60896
62465
  });
60897
62466
  const selection = createSelectionHolder(() => tabs.writers);
62467
+ const frameOrigin = await startFrameOrigin({
62468
+ root,
62469
+ facesDir,
62470
+ tokens,
62471
+ version: tracker.version
62472
+ });
60898
62473
  const hub = createHub({
60899
62474
  tabs,
60900
62475
  port: boundPort,
62476
+ framePort: () => frameOrigin.port,
60901
62477
  access,
60902
62478
  snapshot: () => inTurn(async () => {
60903
62479
  shown.board = await scanBoard(root);
@@ -60923,7 +62499,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
60923
62499
  purpose: "Board PNGs, thumbnails, and browser checks",
60924
62500
  launch
60925
62501
  }));
60926
- const baseUrl = () => `http://${HOSTNAME}:${bound}`;
62502
+ const baseUrl = () => `http://${HOSTNAME}:${frameOrigin.port}`;
60927
62503
  const renderFrame = createWarmRenderer({
60928
62504
  baseUrl,
60929
62505
  browser,
@@ -60959,7 +62535,8 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
60959
62535
  box,
60960
62536
  scroll: frame.scroll,
60961
62537
  hugHeight: frame.hugHeight,
60962
- device: box.width === frame.box.width ? frame.device : void 0
62538
+ device: box.width === frame.box.width ? frame.device : void 0,
62539
+ turn: frame.turn
60963
62540
  },
60964
62541
  config: readConfig(root, frame.project)
60965
62542
  }));
@@ -60999,6 +62576,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
60999
62576
  tokens,
61000
62577
  root,
61001
62578
  port: boundPort,
62579
+ framePort: () => frameOrigin.port,
61002
62580
  tickets,
61003
62581
  openRoute,
61004
62582
  delivery,
@@ -61066,6 +62644,9 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
61066
62644
  resolve(created);
61067
62645
  });
61068
62646
  created.once("error", reject);
62647
+ }).catch(async (error) => {
62648
+ await frameOrigin.close();
62649
+ throw error;
61069
62650
  });
61070
62651
  server.on("upgrade", hub.handleUpgrade);
61071
62652
  const measuredAtStart = inTurn(async () => {
@@ -61130,6 +62711,7 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
61130
62711
  return {
61131
62712
  hostname: HOSTNAME,
61132
62713
  port: bound,
62714
+ framePort: frameOrigin.port,
61133
62715
  tabs,
61134
62716
  watcher,
61135
62717
  authorize: (next) => {
@@ -61150,7 +62732,8 @@ async function listen({ clientDir, facesDir, root, tokens, port, openUrl, launch
61150
62732
  hub.close(),
61151
62733
  browser.close(),
61152
62734
  emptyTrash(root),
61153
- preview.stop()
62735
+ preview.stop(),
62736
+ frameOrigin.close()
61154
62737
  ]);
61155
62738
  await new Promise((done, fail) => {
61156
62739
  server.close((error) => error ? fail(error) : done());