pixelkiln 0.110.0 → 0.111.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
@@ -67,8 +67,8 @@ function exitCodeFor(err) {
67
67
  }
68
68
 
69
69
  // src/cli/main.ts
70
- import { existsSync as existsSync56 } from "fs";
71
- import { readFile as readFile50 } from "fs/promises";
70
+ import { existsSync as existsSync58 } from "fs";
71
+ import { readFile as readFile51 } from "fs/promises";
72
72
 
73
73
  // src/cli/args.ts
74
74
  import path from "path";
@@ -126,6 +126,10 @@ var VALUE_FLAGS = [
126
126
  "--fps",
127
127
  "--lib",
128
128
  "--margin",
129
+ "--camera",
130
+ "--hue",
131
+ "--param",
132
+ "--tune",
129
133
  "--sprite-frames",
130
134
  "--sprite-fps",
131
135
  "--artist",
@@ -257,7 +261,7 @@ var REFINE_SUBCOMMANDS = ["run", "approve", "check"];
257
261
  var RECIPE_SUBCOMMANDS = ["list", "inspect", "install", "verify"];
258
262
  var QUALITY_SUBCOMMANDS = ["snapshot", "check"];
259
263
  var EDIT_SUBCOMMANDS = ["start", "detach"];
260
- var MODEL_SUBCOMMANDS = ["list", "export", "import", "blender", "adopt", "normal-map"];
264
+ var MODEL_SUBCOMMANDS = ["list", "resolve", "export", "import", "blender", "adopt", "normal-map"];
261
265
  var TOOLS_SUBCOMMANDS = ["status", "install"];
262
266
  var TOOLS = ["editor"];
263
267
  var VFX_SUBCOMMANDS = ["make", "presets", "parts", "effects"];
@@ -336,8 +340,8 @@ function parseArgs(argv) {
336
340
  if (rest[0] === subcommand) rest = rest.slice(1);
337
341
  if (subcommand !== "list") {
338
342
  target = rest[0]?.startsWith("-") ? void 0 : rest[0];
339
- if (target === void 0) throw new UsageError(`model ${subcommand} needs a model: its path, its file name, or its gallery id`);
340
- rest = rest.slice(1);
343
+ if (target === void 0 && subcommand !== "resolve") throw new UsageError(`model ${subcommand} needs a model: its path, its file name, or its gallery id`);
344
+ if (target !== void 0) rest = rest.slice(1);
341
345
  }
342
346
  } else if (command === "tools") {
343
347
  subcommand = rest[0]?.startsWith("-") || rest[0] === void 0 ? "status" : rest[0];
@@ -601,6 +605,10 @@ function parseArgs(argv) {
601
605
  sprite: get("--sprite"),
602
606
  fps: numberOption("--fps", { min: 1, max: 60, integer: true }),
603
607
  lib: get("--lib"),
608
+ camera: get("--camera"),
609
+ hue: numberOption("--hue", { min: -360, max: 360 }),
610
+ param: list("--param"),
611
+ tune: list("--tune"),
604
612
  margin: numberOption("--margin", { min: 0, max: 256, integer: true }),
605
613
  spriteFrames: numberOption("--sprite-frames", { min: 1, max: 32, integer: true }),
606
614
  spriteFps: numberOption("--sprite-fps", { min: 1, max: 60, integer: true }),
@@ -731,6 +739,8 @@ Commands
731
739
  with its region guide to paint anywhere, import it into an edited
732
740
  copy under edits/, open the model in Blender, adopt its export,
733
741
  or add PixelLab normal map detail (normal-map; priced, 0.1 a call).
742
+ model resolve [model] prints the file a game should load: the
743
+ edited copy when it is current, else the model as built.
734
744
  tools status/install editor: the in-browser editor (Pixelorama) is a
735
745
  46 MB web build fetched once per release into a user cache and
736
746
  verified against pinned hashes. Offline once installed.
@@ -758,6 +768,9 @@ Commands
758
768
  the pixelfx library on this machine instead (free, nothing
759
769
  sent; install it with: npm i github:patch-gg/pixelfx); vfx
760
770
  effects lists them.
771
+ With --lib codex, renders an --effect <id> from pixel-vfx-codex
772
+ the same way (npm i github:888wing/pixel-vfx-codex), through a
773
+ --camera 2d, 25d or 3d; vfx effects --lib codex lists them.
761
774
  font PixelLab: generate a pixel font (--description, --out); writes a
762
775
  .ttf and a glyph atlas PNG. 15 generations; asks first.
763
776
  music PixelLab: a song from a style (--description, --out); writes two
@@ -865,12 +878,16 @@ Options
865
878
  --preset <name> vfx: start from a whole-effect preset (vfx presets lists them)
866
879
  --recipe <file> vfx: render a recipe or an earlier run's .vfx.json record
867
880
  --effect <id> vfx: start from a saved My effects id and export over it;
868
- with --lib pixelfx, the effect to render (fire/torch)
881
+ with --lib pixelfx or codex, the effect to render (fire/torch, fireball)
869
882
  --part <name> vfx: add a part (repeatable; vfx parts lists them)
870
883
  --sprite <ref> vfx: build around a sprite: a file, a URL, or character:<id>:<dir>
871
884
  --fps <n> vfx: frames per second, 1-60
872
- --lib <name> vfx: pixellab (default) or pixelfx, the local effects library
873
- --margin <px> vfx --lib pixelfx: transparent pixels around the effect's canvas
885
+ --lib <name> vfx: pixellab (default), or pixelfx or codex, local effects libraries
886
+ --margin <px> vfx --lib pixelfx or codex: transparent pixels around the effect
887
+ --camera <view> vfx --lib codex: 2d (default), 25d or 3d
888
+ --hue <degrees> vfx --lib codex: turn the effect's colors, -360 to 360
889
+ --param <name=n> vfx --lib codex: an effect's own parameter (repeatable)
890
+ --tune <name=n> vfx --lib codex: a shared knob such as size or density
874
891
  --sprite-frames <n> vfx --description: --sprite is a strip of n equal frames (2-32)
875
892
  --sprite-fps <n> vfx --description: how fast the sprite animation plays (default 12)
876
893
  --game-pack vfx: also download the game-pack ZIP
@@ -1426,10 +1443,10 @@ function normalizeHex(value) {
1426
1443
  function sha256(data) {
1427
1444
  return createHash("sha256").update(data).digest("hex");
1428
1445
  }
1429
- async function sha256File(path74) {
1446
+ async function sha256File(path76) {
1430
1447
  return new Promise((resolve, reject) => {
1431
1448
  const hash = createHash("sha256");
1432
- const stream = createReadStream(path74);
1449
+ const stream = createReadStream(path76);
1433
1450
  stream.on("data", (chunk2) => hash.update(chunk2));
1434
1451
  stream.on("error", reject);
1435
1452
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -3142,7 +3159,7 @@ var AssetDeriveSchema = z.object({
3142
3159
  /** key-skin: how far a pixel may sit from a `skin` colour. despeckle: how near a reference colour must be to vouch for a pixel. */
3143
3160
  tolerance: z.number().min(0).max(442).optional()
3144
3161
  }).strict().superRefine((derive, context) => {
3145
- const issue = (message6, path74) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path74] });
3162
+ const issue = (message6, path76) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path76] });
3146
3163
  if (Boolean(derive.from) === Boolean(derive.file)) {
3147
3164
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
3148
3165
  }
@@ -9055,9 +9072,9 @@ var PixelLabClient = class {
9055
9072
  apiKey;
9056
9073
  http;
9057
9074
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
9058
- async request(path74, init) {
9075
+ async request(path76, init) {
9059
9076
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
9060
- const res = await this.http(`${BASE}${path74}`, {
9077
+ const res = await this.http(`${BASE}${path76}`, {
9061
9078
  ...init,
9062
9079
  headers: {
9063
9080
  Authorization: auth,
@@ -9068,13 +9085,13 @@ var PixelLabClient = class {
9068
9085
  const text = await res.text();
9069
9086
  if (!res.ok) {
9070
9087
  const hint = res.status === 500 && text.includes("Failed to start any animation jobs") ? '; a skeleton-v3 loop needs a character with a stored 3D skeleton (a v3 base), use mode: "template" on a standard one' : "";
9071
- throw new PixelLabError(`${init?.method ?? "GET"} ${path74} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
9088
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path76} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
9072
9089
  }
9073
9090
  if (!text) return {};
9074
9091
  try {
9075
9092
  return JSON.parse(text);
9076
9093
  } catch {
9077
- throw new Error(`${init?.method ?? "GET"} ${path74} returned invalid JSON`);
9094
+ throw new Error(`${init?.method ?? "GET"} ${path76} returned invalid JSON`);
9078
9095
  }
9079
9096
  }
9080
9097
  async balance() {
@@ -9621,10 +9638,10 @@ var PixelLabClient = class {
9621
9638
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
9622
9639
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
9623
9640
  const south = args.reference?.south;
9624
- let path74;
9641
+ let path76;
9625
9642
  let body;
9626
9643
  if (args.mode === "v3") {
9627
- path74 = "/create-character-v3";
9644
+ path76 = "/create-character-v3";
9628
9645
  body = {
9629
9646
  description: args.description,
9630
9647
  image_size: imageSize,
@@ -9638,7 +9655,7 @@ var PixelLabClient = class {
9638
9655
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
9639
9656
  };
9640
9657
  } else if (args.mode === "pro-flash") {
9641
- path74 = "/create-character-pro-flash";
9658
+ path76 = "/create-character-pro-flash";
9642
9659
  const traits = args.styleTraits;
9643
9660
  body = {
9644
9661
  description: args.description,
@@ -9662,7 +9679,7 @@ var PixelLabClient = class {
9662
9679
  } : {}
9663
9680
  };
9664
9681
  } else if (args.mode === "pro") {
9665
- path74 = "/create-character-pro";
9682
+ path76 = "/create-character-pro";
9666
9683
  body = {
9667
9684
  description: args.description,
9668
9685
  image_size: imageSize,
@@ -9676,7 +9693,7 @@ var PixelLabClient = class {
9676
9693
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
9677
9694
  };
9678
9695
  } else {
9679
- path74 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
9696
+ path76 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
9680
9697
  body = {
9681
9698
  description: args.description,
9682
9699
  image_size: imageSize,
@@ -9694,8 +9711,8 @@ var PixelLabClient = class {
9694
9711
  };
9695
9712
  }
9696
9713
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
9697
- const raw = await this.request(path74, { method: "POST", body: JSON.stringify(body) });
9698
- return validateResponse(CharacterSubmitSchema, raw, path74.slice(1));
9714
+ const raw = await this.request(path76, { method: "POST", body: JSON.stringify(body) });
9715
+ return validateResponse(CharacterSubmitSchema, raw, path76.slice(1));
9699
9716
  }
9700
9717
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
9701
9718
  async createCharacterState(args) {
@@ -15021,9 +15038,9 @@ var RetroDiffusionClient = class {
15021
15038
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
15022
15039
  return Buffer.from(await response.arrayBuffer());
15023
15040
  }
15024
- async call(path74, init = {}) {
15041
+ async call(path76, init = {}) {
15025
15042
  if (!this.token) throw new Error("RD_API_KEY is not set");
15026
- const response = await this.request(`${this.baseUrl}${path74}`, {
15043
+ const response = await this.request(`${this.baseUrl}${path76}`, {
15027
15044
  ...init,
15028
15045
  headers: {
15029
15046
  "Content-Type": "application/json",
@@ -18319,10 +18336,10 @@ function isSha256Hash(value) {
18319
18336
  function parseCache(value) {
18320
18337
  return HashCacheSchema.parse(value);
18321
18338
  }
18322
- async function loadCache(path74) {
18323
- if (!existsSync18(path74)) return { version: 1, hashes: {} };
18339
+ async function loadCache(path76) {
18340
+ if (!existsSync18(path76)) return { version: 1, hashes: {} };
18324
18341
  try {
18325
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile13(path74, "utf8")));
18342
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile13(path76, "utf8")));
18326
18343
  if (!parsed.success) return { version: 1, hashes: {} };
18327
18344
  return {
18328
18345
  version: 1,
@@ -18334,18 +18351,18 @@ async function loadCache(path74) {
18334
18351
  return { version: 1, hashes: {} };
18335
18352
  }
18336
18353
  }
18337
- async function saveCache(path74, cache) {
18354
+ async function saveCache(path76, cache) {
18338
18355
  const sorted = {};
18339
18356
  for (const key2 of Object.keys(cache.hashes).sort()) {
18340
18357
  const hash = cache.hashes[key2];
18341
18358
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
18342
18359
  sorted[key2] = hash;
18343
18360
  }
18344
- await mkdir9(pathModule.dirname(pathModule.resolve(path74)), { recursive: true });
18345
- const tmp = `${path74}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18361
+ await mkdir9(pathModule.dirname(pathModule.resolve(path76)), { recursive: true });
18362
+ const tmp = `${path76}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18346
18363
  try {
18347
18364
  await writeFile9(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
18348
- await rename7(tmp, path74);
18365
+ await rename7(tmp, path76);
18349
18366
  } finally {
18350
18367
  await rm5(tmp, { force: true });
18351
18368
  }
@@ -22160,6 +22177,18 @@ async function readModelCompanion(editFile) {
22160
22177
  return null;
22161
22178
  }
22162
22179
  }
22180
+ function modelEditStatus(companion, builtSha256) {
22181
+ if (!companion) return "unrecorded";
22182
+ return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
22183
+ }
22184
+ async function modelLoadPath(model) {
22185
+ const base = { styleId: model.styleId, file: model.file };
22186
+ if (!existsSync26(model.editFile)) return { ...base, load: model.file, from: "built", edit: null, status: null };
22187
+ const companion = await readModelCompanion(model.editFile);
22188
+ const status = companion ? modelEditStatus(companion, sha256(await readFile22(model.file))) : "unrecorded";
22189
+ const useEdit = status !== "rebuilt-since";
22190
+ return { ...base, load: useEdit ? model.editFile : model.file, from: useEdit ? "edit" : "built", edit: model.editFile, status };
22191
+ }
22163
22192
  async function replaceFile2(file, bytes) {
22164
22193
  await mkdir14(path34.dirname(file), { recursive: true });
22165
22194
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
@@ -22566,13 +22595,13 @@ function poseNodes(document, pose) {
22566
22595
  const posed = /* @__PURE__ */ new Map();
22567
22596
  for (const channel of animation.channels) {
22568
22597
  const node = channel.target.node;
22569
- const path74 = channel.target.path;
22570
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path74)) continue;
22598
+ const path76 = channel.target.path;
22599
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path76)) continue;
22571
22600
  const sampler = animation.samplers[channel.sampler];
22572
22601
  if (!sampler) continue;
22573
22602
  const times = readAccessor(document, sampler.input).data;
22574
22603
  const values = readAccessor(document, sampler.output);
22575
- const width = path74 === "rotation" ? 4 : 3;
22604
+ const width = path76 === "rotation" ? 4 : 3;
22576
22605
  const cubic = sampler.interpolation === "CUBICSPLINE";
22577
22606
  const valueAt = (key3) => Array.from(values.data.subarray((cubic ? key3 * 3 + 1 : key3) * width, (cubic ? key3 * 3 + 1 : key3) * width + width));
22578
22607
  const last = times.length - 1;
@@ -22584,16 +22613,16 @@ function poseNodes(document, pose) {
22584
22613
  const span = times[key2 + 1] - times[key2];
22585
22614
  const f = span > 0 ? (time - times[key2]) / span : 0;
22586
22615
  const next = valueAt(key2 + 1);
22587
- const sign = path74 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
22616
+ const sign = path76 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
22588
22617
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
22589
22618
  }
22590
- if (path74 === "rotation") {
22619
+ if (path76 === "rotation") {
22591
22620
  const length = Math.hypot(...value) || 1;
22592
22621
  value = value.map((v) => v / length);
22593
22622
  }
22594
22623
  const base = posed.get(node) ?? { ...document.json.nodes?.[node] ?? {} };
22595
22624
  if (base.matrix) delete base.matrix;
22596
- base[path74] = value;
22625
+ base[path76] = value;
22597
22626
  posed.set(node, base);
22598
22627
  }
22599
22628
  return posed;
@@ -23443,7 +23472,7 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
23443
23472
  });
23444
23473
  edit = {
23445
23474
  ...described,
23446
- status: !companion ? "unrecorded" : companion.outputs[0].basedOn === file.sha256 ? "edited" : "rebuilt-since",
23475
+ status: modelEditStatus(companion, file.sha256),
23447
23476
  editor: companion?.editor ?? null,
23448
23477
  savedAt: companion?.savedAt ?? null,
23449
23478
  changedSince: companion ? companion.outputs[0].sha256 !== described.sha256 : false,
@@ -24885,6 +24914,42 @@ async function runModel(args) {
24885
24914
  }
24886
24915
  return;
24887
24916
  }
24917
+ if (sub === "resolve") {
24918
+ const models = args.target ? [await resolveModel(loaded, args.target, styles)] : await discoverModels(loaded, styles);
24919
+ const resolved = await Promise.all(models.map(modelLoadPath));
24920
+ const portable = (file) => portableOutputPath(file, loaded.root);
24921
+ if (args.json) {
24922
+ const rows = resolved.map((entry) => ({
24923
+ styleId: entry.styleId,
24924
+ file: portable(entry.file),
24925
+ load: portable(entry.load),
24926
+ from: entry.from,
24927
+ edit: entry.edit ? portable(entry.edit) : null,
24928
+ status: entry.status,
24929
+ absolute: entry.load
24930
+ }));
24931
+ log(JSON.stringify(args.target ? rows[0] : rows, null, 2));
24932
+ return;
24933
+ }
24934
+ for (const entry of resolved) {
24935
+ if (entry.status === "rebuilt-since") {
24936
+ console.error(` ${portable(entry.file)}: the edit at ${portable(entry.edit)} was made before the model was rebuilt, so the model as built is named; fix the new build or look at both in the gallery`);
24937
+ }
24938
+ }
24939
+ if (args.target) {
24940
+ log(portable(resolved[0].load));
24941
+ return;
24942
+ }
24943
+ if (!resolved.length) {
24944
+ log(" no models: put a .glb under a style's outDir");
24945
+ return;
24946
+ }
24947
+ for (const entry of resolved) {
24948
+ const why = entry.from === "edit" ? `edited copy, ${entry.status}` : entry.status ? `as built; edit is ${entry.status}` : "as built, no edit";
24949
+ log(` ${portable(entry.file)} -> ${portable(entry.load)} (${why})`);
24950
+ }
24951
+ return;
24952
+ }
24888
24953
  const ref = args.target;
24889
24954
  if (!ref) throw new Error(`model ${sub} needs a model: its path, its file name, or its gallery id. pixelkiln model list shows them.`);
24890
24955
  const model = await resolveModel(loaded, ref, styles);
@@ -29629,15 +29694,383 @@ function sheetFormat(args) {
29629
29694
  }
29630
29695
 
29631
29696
  // src/cli/commands/pixellab-utils.ts
29632
- import { readFile as readFile39 } from "fs/promises";
29633
- import path55 from "path";
29697
+ import { readFile as readFile40 } from "fs/promises";
29698
+ import path57 from "path";
29634
29699
 
29635
- // src/pixelfx-vfx.ts
29636
- import { existsSync as existsSync45, readFileSync as readFileSync9 } from "fs";
29637
- import { mkdir as mkdir19, readFile as readFile38, writeFile as writeFile24 } from "fs/promises";
29700
+ // src/codex-vfx.ts
29701
+ import { createHash as createHash7 } from "crypto";
29702
+ import { existsSync as existsSync46, readFileSync as readFileSync9, readdirSync as readdirSync2 } from "fs";
29703
+ import { readFile as readFile38 } from "fs/promises";
29638
29704
  import { createRequire as createRequire2 } from "module";
29639
- import path54 from "path";
29705
+ import path55 from "path";
29640
29706
  import { pathToFileURL } from "url";
29707
+ import vm from "vm";
29708
+
29709
+ // src/local-vfx.ts
29710
+ import { existsSync as existsSync45 } from "fs";
29711
+ import { mkdir as mkdir19, writeFile as writeFile24 } from "fs/promises";
29712
+ import path54 from "path";
29713
+ function localSheet(render) {
29714
+ const { width, height, frames } = render;
29715
+ const columns = Math.min(frames.length, Math.max(1, Math.ceil(Math.sqrt(frames.length * height / width))));
29716
+ const rows = Math.ceil(frames.length / columns);
29717
+ const sheet = Buffer.alloc(columns * width * rows * height * 4);
29718
+ const rects = frames.map((rgba, index) => {
29719
+ const x = index % columns * width;
29720
+ const y = Math.floor(index / columns) * height;
29721
+ for (let row = 0; row < height; row++) {
29722
+ rgba.copy(sheet, ((y + row) * columns * width + x) * 4, row * width * 4, (row + 1) * width * 4);
29723
+ }
29724
+ return { x, y, w: width, h: height };
29725
+ });
29726
+ return { png: encodeRgbaPng(columns * width, rows * height, sheet), columns, rows, rects };
29727
+ }
29728
+ function assertFreshOutputs(out, force) {
29729
+ const paths = vfxOutputPaths(out);
29730
+ if (!force) {
29731
+ for (const file of [paths.sheet, paths.atlas, paths.provenance]) {
29732
+ if (existsSync45(file)) throw new Error(`${file} already exists; pass --force to replace it`);
29733
+ }
29734
+ }
29735
+ return paths;
29736
+ }
29737
+ async function writeLocalVfx(opts) {
29738
+ const { paths, render } = opts;
29739
+ const sheet = localSheet(render);
29740
+ const clip = path54.basename(paths.sheet, ".png");
29741
+ const anchor = { kind: "origin", ...render.anchor };
29742
+ const size = { w: render.width, h: render.height };
29743
+ const atlas = {
29744
+ frames: sheet.rects.map((frame, index) => ({
29745
+ filename: `${clip} ${index}`,
29746
+ frame,
29747
+ rotated: false,
29748
+ trimmed: false,
29749
+ spriteSourceSize: { x: 0, y: 0, ...size },
29750
+ sourceSize: size,
29751
+ duration: Math.round(1e3 / render.fps)
29752
+ })),
29753
+ meta: {
29754
+ app: "pixelkiln",
29755
+ version: "1",
29756
+ image: path54.basename(paths.sheet),
29757
+ format: "RGBA8888",
29758
+ size: { w: sheet.columns * render.width, h: sheet.rows * render.height },
29759
+ scale: "1",
29760
+ frameTags: [{ name: clip, from: 0, to: render.frames.length - 1, direction: "forward" }],
29761
+ anchor,
29762
+ [opts.atlasKey]: {
29763
+ id: opts.effect,
29764
+ name: opts.name,
29765
+ ...opts.atlasFacts,
29766
+ fps: render.fps,
29767
+ loop: render.loop,
29768
+ frames: render.frames.length,
29769
+ frameSize: [render.width, render.height],
29770
+ pivot: [anchor.x, anchor.y],
29771
+ columns: sheet.columns
29772
+ }
29773
+ }
29774
+ };
29775
+ const sheetSha256 = sha256(sheet.png);
29776
+ const facts = {
29777
+ name: opts.name,
29778
+ effect: opts.effect,
29779
+ width: render.width,
29780
+ height: render.height,
29781
+ frames: render.frames.length,
29782
+ fps: render.fps,
29783
+ loop: render.loop,
29784
+ anchor
29785
+ };
29786
+ const record = {
29787
+ version: 1,
29788
+ ...opts.record,
29789
+ ...facts,
29790
+ files: { sheet: path54.basename(paths.sheet), atlas: path54.basename(paths.atlas) },
29791
+ sheetSha256,
29792
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
29793
+ recipe: opts.recipe
29794
+ };
29795
+ await mkdir19(path54.dirname(paths.sheet), { recursive: true });
29796
+ await writeFile24(paths.sheet, sheet.png);
29797
+ await writeFile24(paths.atlas, `${JSON.stringify(atlas, null, 2)}
29798
+ `);
29799
+ await writeFile24(paths.provenance, `${JSON.stringify(record, null, 2)}
29800
+ `);
29801
+ return { facts, columns: sheet.columns, sheetSha256, paths: { sheet: paths.sheet, atlas: paths.atlas, provenance: paths.provenance } };
29802
+ }
29803
+
29804
+ // src/codex-vfx.ts
29805
+ var CODEX_ID = "codex";
29806
+ var CODEX_PACKAGE = "pixel-vfx-codex";
29807
+ var CODEX_REPOSITORY = "https://github.com/888wing/pixel-vfx-codex";
29808
+ var CODEX_INSTALL = "npm i github:888wing/pixel-vfx-codex";
29809
+ var CODEX_CAMERAS = ["2d", "25d", "3d"];
29810
+ var CANVAS = { "2d": [160, 100], "25d": [240, 150], "3d": [240, 150] };
29811
+ var CODEX_TUNE_KEYS = ["size", "gain", "density", "dither", "outline", "hitstop", "shake", "flash", "snap"];
29812
+ function missingCodex(cause) {
29813
+ return new PixelKilnError(
29814
+ "pixel-vfx-codex is not installed, so there is nothing to render these effects with",
29815
+ "capability",
29816
+ { hint: `Install it beside your project: ${CODEX_INSTALL} (${CODEX_REPOSITORY}, MIT; it is not on the npm registry)`, cause }
29817
+ );
29818
+ }
29819
+ function findCodexRoot(from) {
29820
+ const bases = from?.map((base) => pathToFileURL(path55.resolve(base, "package.json")).href) ?? [
29821
+ pathToFileURL(path55.join(process.cwd(), "package.json")).href,
29822
+ import.meta.url
29823
+ ];
29824
+ let failure;
29825
+ for (const base of bases) {
29826
+ try {
29827
+ return path55.dirname(createRequire2(base).resolve(`${CODEX_PACKAGE}/package.json`));
29828
+ } catch (error) {
29829
+ failure = error;
29830
+ }
29831
+ }
29832
+ throw missingCodex(failure);
29833
+ }
29834
+ function loadCodex(from) {
29835
+ const root = findCodexRoot(from);
29836
+ const read = (...parts) => readFileSync9(path55.join(root, ...parts), "utf8");
29837
+ const pkg = JSON.parse(read("package.json"));
29838
+ const version = typeof pkg.version === "string" ? pkg.version : "unknown";
29839
+ for (const required of ["engine/pxfx.js", "engine/kit.js", "fx", "data/meta.json"]) {
29840
+ if (!existsSync46(path55.join(root, required))) {
29841
+ throw new PixelKilnError(`The installed ${CODEX_PACKAGE} (${version}) has no ${required}; PixelKiln was written against its 1.0.0 layout`, "capability");
29842
+ }
29843
+ }
29844
+ const sources = [read("engine", "pxfx.js"), read("engine", "kit.js")];
29845
+ const context = vm.createContext({ console });
29846
+ sources.forEach((source, index) => vm.runInContext(source, context, { filename: index ? "engine/kit.js" : "engine/pxfx.js" }));
29847
+ const engine = context.PXFX;
29848
+ if (!engine || typeof engine.View !== "function" || typeof engine.get !== "function") {
29849
+ throw new PixelKilnError(`The installed ${CODEX_PACKAGE} (${version}) does not define PXFX.View and PXFX.get`, "capability");
29850
+ }
29851
+ const loadErrors = [];
29852
+ for (const file of readdirSync2(path55.join(root, "fx")).filter((name) => name.endsWith(".js")).sort()) {
29853
+ try {
29854
+ vm.runInContext(read("fx", file), context, { filename: `fx/${file}` });
29855
+ } catch (error) {
29856
+ loadErrors.push(`${file}: ${error instanceof Error ? error.message : String(error)}`);
29857
+ }
29858
+ }
29859
+ const meta = JSON.parse(read("data", "meta.json"));
29860
+ const catalogue = meta.flatMap(
29861
+ (entry) => typeof entry.id === "string" && engine.get(entry.id) ? [{
29862
+ id: entry.id,
29863
+ en: typeof entry.en === "string" ? entry.en : entry.id,
29864
+ descEn: typeof entry.descEn === "string" ? entry.descEn : "",
29865
+ category: typeof entry.category === "string" ? entry.category : "other",
29866
+ schools: Array.isArray(entry.schools) ? entry.schools.filter((school) => typeof school === "string") : []
29867
+ }] : []
29868
+ );
29869
+ if (!catalogue.length) throw new PixelKilnError(`The installed ${CODEX_PACKAGE} (${version}) loaded no effects`, "capability");
29870
+ const engineSha256 = createHash7("sha256").update(sources.join("\n")).digest("hex").slice(0, 12);
29871
+ return { version, engineSha256, engine, catalogue, loadErrors };
29872
+ }
29873
+ function listCodexEffects(lib) {
29874
+ return lib.catalogue.map((entry) => {
29875
+ const def = lib.engine.get(entry.id);
29876
+ return {
29877
+ ...entry,
29878
+ loopSeconds: def.loop,
29879
+ params: Object.fromEntries(
29880
+ Object.entries(def.params ?? {}).map(([key2, param]) => [key2, { label: param.en ?? key2, min: param.min, max: param.max, value: param.value }])
29881
+ )
29882
+ };
29883
+ });
29884
+ }
29885
+ function formatCodexEffects(lib) {
29886
+ const effects = listCodexEffects(lib);
29887
+ const categories = [...new Set(effects.map((effect) => effect.category))];
29888
+ const lines = [`pixel-vfx-codex ${lib.version}: ${effects.length} effects (${CODEX_REPOSITORY}, MIT)`];
29889
+ for (const category of categories) {
29890
+ const inCategory = effects.filter((effect) => effect.category === category);
29891
+ lines.push("", `${category} (${inCategory.length})`);
29892
+ for (const effect of inCategory) lines.push(` ${effect.id.padEnd(28)} ${effect.en}`);
29893
+ }
29894
+ lines.push("", "--json lists every effect's parameters, with their ranges.");
29895
+ return lines.join("\n");
29896
+ }
29897
+ function findDef(lib, id) {
29898
+ const info = listCodexEffects(lib).find((entry) => entry.id === id);
29899
+ if (!info) {
29900
+ const near = lib.catalogue.map((entry) => entry.id).filter((other) => other.includes(id) || id.includes(other));
29901
+ throw new UsageError(
29902
+ `pixel-vfx-codex ${lib.version} has no effect "${id}"` + (near.length ? `; close: ${near.slice(0, 10).join(", ")}` : ""),
29903
+ { hint: "List them with: pixelkiln vfx effects --lib codex" }
29904
+ );
29905
+ }
29906
+ return { def: lib.engine.get(id), info };
29907
+ }
29908
+ function checkCodexRecipe(lib, recipe) {
29909
+ const { info } = findDef(lib, recipe.effect);
29910
+ const { camera, fps, margin, hue, params = {}, tune = {} } = recipe;
29911
+ if (camera !== void 0 && !CODEX_CAMERAS.includes(camera)) {
29912
+ throw new UsageError(`--camera must be ${CODEX_CAMERAS.join(", ")}, got "${camera}"`);
29913
+ }
29914
+ if (fps !== void 0 && (!Number.isInteger(fps) || fps < 1 || fps > 60)) throw new UsageError(`codex fps must be a whole number 1 to 60, got ${fps}`);
29915
+ if (margin !== void 0 && (!Number.isInteger(margin) || margin < 0 || margin > 64)) {
29916
+ throw new UsageError(`codex margin must be a whole number 0 to 64, got ${margin}`);
29917
+ }
29918
+ if (hue !== void 0 && (typeof hue !== "number" || !Number.isFinite(hue) || hue < -360 || hue > 360)) {
29919
+ throw new UsageError(`codex hue is degrees from -360 to 360, got ${JSON.stringify(hue)}`);
29920
+ }
29921
+ for (const [key2, value] of Object.entries(params)) {
29922
+ const param = info.params[key2];
29923
+ if (!param) {
29924
+ const known = Object.keys(info.params);
29925
+ throw new UsageError(`${recipe.effect} has no parameter "${key2}"${known.length ? `; it has ${known.join(", ")}` : " (it takes none)"}`);
29926
+ }
29927
+ if (typeof value !== "number" || !Number.isFinite(value) || value < param.min || value > param.max) {
29928
+ throw new UsageError(`${recipe.effect} ${key2} is a number from ${param.min} to ${param.max}, got ${JSON.stringify(value)}`);
29929
+ }
29930
+ }
29931
+ for (const [key2, value] of Object.entries(tune)) {
29932
+ if (!CODEX_TUNE_KEYS.includes(key2)) throw new UsageError(`unknown tune knob "${key2}"; they are ${CODEX_TUNE_KEYS.join(", ")}`);
29933
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new UsageError(`tune ${key2} is a number, got ${JSON.stringify(value)}`);
29934
+ }
29935
+ return info;
29936
+ }
29937
+ function cropFrames(frames, width, height, pivot, margin) {
29938
+ let x0 = Math.floor(pivot.x), x1 = Math.floor(pivot.x), y0 = Math.floor(pivot.y), y1 = Math.floor(pivot.y);
29939
+ x0 = Math.max(0, Math.min(x0, width - 1));
29940
+ x1 = Math.max(0, Math.min(x1, width - 1));
29941
+ y0 = Math.max(0, Math.min(y0, height - 1));
29942
+ y1 = Math.max(0, Math.min(y1, height - 1));
29943
+ for (const frame of frames) {
29944
+ for (let y = 0; y < height; y++) {
29945
+ for (let x = 0; x < width; x++) {
29946
+ if (frame[(y * width + x) * 4 + 3]) {
29947
+ if (x < x0) x0 = x;
29948
+ if (x > x1) x1 = x;
29949
+ if (y < y0) y0 = y;
29950
+ if (y > y1) y1 = y;
29951
+ }
29952
+ }
29953
+ }
29954
+ }
29955
+ const cropWidth = x1 - x0 + 1 + margin * 2;
29956
+ const cropHeight = y1 - y0 + 1 + margin * 2;
29957
+ const cropped = frames.map((frame) => {
29958
+ const out = Buffer.alloc(cropWidth * cropHeight * 4);
29959
+ for (let y = 0; y < cropHeight; y++) {
29960
+ const sy = y0 - margin + y;
29961
+ if (sy < 0 || sy >= height) continue;
29962
+ for (let x = 0; x < cropWidth; x++) {
29963
+ const sx = x0 - margin + x;
29964
+ if (sx < 0 || sx >= width) continue;
29965
+ frame.copy(out, (y * cropWidth + x) * 4, (sy * width + sx) * 4, (sy * width + sx) * 4 + 4);
29966
+ }
29967
+ }
29968
+ return out;
29969
+ });
29970
+ return { width: cropWidth, height: cropHeight, frames: cropped, anchor: { x: pivot.x - x0 + margin, y: pivot.y - y0 + margin } };
29971
+ }
29972
+ function planCodex(lib, recipe) {
29973
+ checkCodexRecipe(lib, recipe);
29974
+ const camera = recipe.camera ?? "2d";
29975
+ const fps = recipe.fps ?? lib.engine.MODES[camera]?.fps ?? 12;
29976
+ const seconds = lib.engine.timing(lib.engine.get(recipe.effect), { ...recipe.tune ?? {} }).length;
29977
+ return { camera, fps, frames: Math.max(1, Math.round(seconds * fps)), seconds };
29978
+ }
29979
+ function renderCodex(lib, recipe) {
29980
+ const info = checkCodexRecipe(lib, recipe);
29981
+ const def = lib.engine.get(recipe.effect);
29982
+ const camera = recipe.camera ?? "2d";
29983
+ const [canvasWidth, canvasHeight] = CANVAS[camera];
29984
+ const fps = recipe.fps ?? lib.engine.MODES[camera]?.fps ?? 12;
29985
+ const view = new lib.engine.View(null, canvasWidth, canvasHeight);
29986
+ view.mode = camera;
29987
+ view.night = false;
29988
+ view.hue = recipe.hue ?? 0;
29989
+ view.params = { ...recipe.params ?? {} };
29990
+ view.tune = { ...recipe.tune ?? {} };
29991
+ view.transparent = true;
29992
+ view.noProps = true;
29993
+ view.shakeX = 0;
29994
+ view.shakeY = 0;
29995
+ view.camera(def);
29996
+ view.P(0, 0, 0);
29997
+ const pivot = { x: Math.round(view.px), y: Math.round(view.py) };
29998
+ const timing = lib.engine.timing(def, view.tune);
29999
+ const count = Math.max(1, Math.round(timing.length * fps));
30000
+ const frames = [];
30001
+ for (let index = 0; index < count; index++) {
30002
+ view.renderAt(def, lib.engine.frameTime(index / count * timing.length, camera), timing);
30003
+ frames.push(Buffer.from(view.pix.buffer.slice(0)));
30004
+ }
30005
+ const cropped = cropFrames(frames, canvasWidth, canvasHeight, pivot, recipe.margin ?? 0);
30006
+ return { effect: info, fps, loop: true, ...cropped };
30007
+ }
30008
+ async function readCodexRecipe(file, opts = {}) {
30009
+ const parsed = JSON.parse(await readFile38(file, "utf8"));
30010
+ const record = parsed.tool === CODEX_ID;
30011
+ if (!record && !(opts.bare && parsed.tool === void 0)) return null;
30012
+ const raw = record ? parsed.recipe : parsed;
30013
+ if (!raw || typeof raw !== "object" || typeof raw.effect !== "string" || Array.isArray(raw.layers)) {
30014
+ if (record) throw new Error(`${file} is a codex record with no recipe naming an effect`);
30015
+ return null;
30016
+ }
30017
+ const recipe = { effect: raw.effect };
30018
+ if (raw.camera !== void 0) recipe.camera = raw.camera;
30019
+ for (const key2 of ["fps", "margin", "hue"]) if (raw[key2] !== void 0) recipe[key2] = raw[key2];
30020
+ for (const key2 of ["params", "tune"]) {
30021
+ const value = raw[key2];
30022
+ if (value === void 0) continue;
30023
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${file}: a codex recipe's ${key2} is an object`);
30024
+ recipe[key2] = value;
30025
+ }
30026
+ const library = record ? parsed.library : void 0;
30027
+ return {
30028
+ recipe,
30029
+ ...typeof library?.version === "string" ? { libraryVersion: library.version } : {},
30030
+ ...typeof library?.engineSha256 === "string" ? { engineSha256: library.engineSha256 } : {}
30031
+ };
30032
+ }
30033
+ async function makeCodexVfx(lib, opts) {
30034
+ const recipe = {
30035
+ effect: opts.effect,
30036
+ ...opts.camera && opts.camera !== "2d" ? { camera: opts.camera } : {},
30037
+ ...opts.fps !== void 0 ? { fps: opts.fps } : {},
30038
+ ...opts.margin ? { margin: opts.margin } : {},
30039
+ ...opts.hue ? { hue: opts.hue } : {},
30040
+ ...opts.params && Object.keys(opts.params).length ? { params: opts.params } : {},
30041
+ ...opts.tune && Object.keys(opts.tune).length ? { tune: opts.tune } : {}
30042
+ };
30043
+ checkCodexRecipe(lib, recipe);
30044
+ const paths = assertFreshOutputs(opts.out, opts.force);
30045
+ const render = renderCodex(lib, recipe);
30046
+ const library = { name: CODEX_PACKAGE, version: lib.version, engineSha256: lib.engineSha256 };
30047
+ const written = await writeLocalVfx({
30048
+ paths,
30049
+ name: opts.name ?? render.effect.en,
30050
+ effect: opts.effect,
30051
+ render,
30052
+ atlasKey: CODEX_ID,
30053
+ atlasFacts: { version: lib.version, engineSha256: lib.engineSha256, camera: recipe.camera ?? "2d" },
30054
+ record: { provider: CODEX_ID, tool: CODEX_ID, library: { ...library, repository: CODEX_REPOSITORY, license: "MIT" } },
30055
+ recipe
30056
+ });
30057
+ return {
30058
+ provider: CODEX_ID,
30059
+ library,
30060
+ ...written.facts,
30061
+ columns: written.columns,
30062
+ sheetSha256: written.sheetSha256,
30063
+ paths: written.paths,
30064
+ recipe
30065
+ };
30066
+ }
30067
+
30068
+ // src/pixelfx-vfx.ts
30069
+ import { existsSync as existsSync47, readFileSync as readFileSync10 } from "fs";
30070
+ import { readFile as readFile39 } from "fs/promises";
30071
+ import { createRequire as createRequire3 } from "module";
30072
+ import path56 from "path";
30073
+ import { pathToFileURL as pathToFileURL2 } from "url";
29641
30074
  var PIXELFX_TOOL = "pixelfx";
29642
30075
  var PIXELFX_REPOSITORY = "https://github.com/patch-gg/pixelfx";
29643
30076
  var PIXELFX_INSTALL = "npm i github:patch-gg/pixelfx";
@@ -29649,24 +30082,24 @@ function missingPixelfx(cause) {
29649
30082
  );
29650
30083
  }
29651
30084
  function pixelfxVersion(entry) {
29652
- for (let dir = path54.dirname(entry); dir !== path54.dirname(dir); dir = path54.dirname(dir)) {
29653
- const file = path54.join(dir, "package.json");
29654
- if (!existsSync45(file)) continue;
29655
- const pkg = JSON.parse(readFileSync9(file, "utf8"));
30085
+ for (let dir = path56.dirname(entry); dir !== path56.dirname(dir); dir = path56.dirname(dir)) {
30086
+ const file = path56.join(dir, "package.json");
30087
+ if (!existsSync47(file)) continue;
30088
+ const pkg = JSON.parse(readFileSync10(file, "utf8"));
29656
30089
  if (pkg.name === "pixelfx") return typeof pkg.version === "string" ? pkg.version : "unknown";
29657
30090
  }
29658
30091
  return "unknown";
29659
30092
  }
29660
30093
  async function loadPixelfx(from) {
29661
- const bases = from?.map((base) => pathToFileURL(path54.resolve(base)).href) ?? [
29662
- pathToFileURL(path54.join(process.cwd(), "package.json")).href,
30094
+ const bases = from?.map((base) => pathToFileURL2(path56.resolve(base)).href) ?? [
30095
+ pathToFileURL2(path56.join(process.cwd(), "package.json")).href,
29663
30096
  import.meta.url
29664
30097
  ];
29665
30098
  let resolved;
29666
30099
  let failure;
29667
30100
  for (const base of bases) {
29668
30101
  try {
29669
- const require2 = createRequire2(base);
30102
+ const require2 = createRequire3(base);
29670
30103
  resolved = { core: require2.resolve("pixelfx"), index: require2.resolve("pixelfx/fx/index") };
29671
30104
  break;
29672
30105
  } catch (error) {
@@ -29674,8 +30107,8 @@ async function loadPixelfx(from) {
29674
30107
  }
29675
30108
  }
29676
30109
  if (!resolved) throw missingPixelfx(failure);
29677
- const core = await import(pathToFileURL(resolved.core).href);
29678
- const index = await import(pathToFileURL(resolved.index).href);
30110
+ const core = await import(pathToFileURL2(resolved.core).href);
30111
+ const index = await import(pathToFileURL2(resolved.index).href);
29679
30112
  const version = pixelfxVersion(resolved.core);
29680
30113
  for (const name of ["createFrame", "clearFrame", "createFx", "composite"]) {
29681
30114
  if (typeof core[name] !== "function") {
@@ -29825,23 +30258,8 @@ function renderPixelfx(lib, recipe) {
29825
30258
  frames
29826
30259
  };
29827
30260
  }
29828
- function pixelfxSheet(render) {
29829
- const { width, height, frames } = render;
29830
- const columns = Math.min(frames.length, Math.max(1, Math.ceil(Math.sqrt(frames.length * height / width))));
29831
- const rows = Math.ceil(frames.length / columns);
29832
- const sheet = Buffer.alloc(columns * width * rows * height * 4);
29833
- const rects = frames.map((rgba, index) => {
29834
- const x = index % columns * width;
29835
- const y = Math.floor(index / columns) * height;
29836
- for (let row = 0; row < height; row++) {
29837
- rgba.copy(sheet, ((y + row) * columns * width + x) * 4, row * width * 4, (row + 1) * width * 4);
29838
- }
29839
- return { x, y, w: width, h: height };
29840
- });
29841
- return { png: encodeRgbaPng(columns * width, rows * height, sheet), columns, rows, rects };
29842
- }
29843
30261
  async function readPixelfxRecipe(file) {
29844
- const parsed = JSON.parse(await readFile38(file, "utf8"));
30262
+ const parsed = JSON.parse(await readFile39(file, "utf8"));
29845
30263
  const record = parsed.tool === PIXELFX_TOOL;
29846
30264
  const raw = record ? parsed.recipe : parsed;
29847
30265
  if (!raw || typeof raw !== "object" || typeof raw.effect !== "string" || Array.isArray(raw.layers)) {
@@ -29863,7 +30281,6 @@ async function readPixelfxRecipe(file) {
29863
30281
  return { recipe, ...typeof version === "string" ? { libraryVersion: version } : {} };
29864
30282
  }
29865
30283
  async function makePixelfxVfx(lib, opts) {
29866
- const paths = vfxOutputPaths(opts.out);
29867
30284
  const recipe = {
29868
30285
  effect: opts.effect,
29869
30286
  ...opts.fps !== void 0 ? { fps: opts.fps } : {},
@@ -29871,91 +30288,36 @@ async function makePixelfxVfx(lib, opts) {
29871
30288
  ...opts.options && Object.keys(opts.options).length ? { options: opts.options } : {}
29872
30289
  };
29873
30290
  checkPixelfxRecipe(lib, recipe);
29874
- if (!opts.force) {
29875
- for (const file of [paths.sheet, paths.atlas, paths.provenance]) {
29876
- if (existsSync45(file)) throw new Error(`${file} already exists; pass --force to replace it`);
29877
- }
29878
- }
30291
+ const paths = assertFreshOutputs(opts.out, opts.force);
29879
30292
  const render = renderPixelfx(lib, recipe);
29880
- const sheet = pixelfxSheet(render);
29881
- const name = opts.name ?? render.effect.name;
29882
- const clip = path54.basename(paths.sheet, ".png");
29883
- const anchor = { kind: "origin", ...render.anchor };
29884
- const size = { w: render.width, h: render.height };
29885
- const atlas = {
29886
- frames: sheet.rects.map((frame, index) => ({
29887
- filename: `${clip} ${index}`,
29888
- frame,
29889
- rotated: false,
29890
- trimmed: false,
29891
- spriteSourceSize: { x: 0, y: 0, ...size },
29892
- sourceSize: size,
29893
- duration: Math.round(1e3 / render.fps)
29894
- })),
29895
- meta: {
29896
- app: "pixelkiln",
29897
- version: "1",
29898
- image: path54.basename(paths.sheet),
29899
- format: "RGBA8888",
29900
- size: { w: sheet.columns * render.width, h: sheet.rows * render.height },
29901
- scale: "1",
29902
- frameTags: [{ name: clip, from: 0, to: render.frames.length - 1, direction: "forward" }],
29903
- anchor,
29904
- pixelfx: {
29905
- id: opts.effect,
29906
- name,
29907
- version: lib.version,
29908
- fps: render.fps,
29909
- loop: render.loop,
29910
- frames: render.frames.length,
29911
- frameSize: [render.width, render.height],
29912
- pivot: [anchor.x, anchor.y],
29913
- columns: sheet.columns
29914
- }
29915
- }
29916
- };
29917
- const sheetSha256 = sha256(sheet.png);
29918
- const facts = {
29919
- name,
30293
+ const written = await writeLocalVfx({
30294
+ paths,
30295
+ name: opts.name ?? render.effect.name,
29920
30296
  effect: opts.effect,
29921
- width: render.width,
29922
- height: render.height,
29923
- frames: render.frames.length,
29924
- fps: render.fps,
29925
- loop: render.loop,
29926
- anchor
29927
- };
29928
- const provenance = {
29929
- version: 1,
29930
- provider: "pixelfx",
29931
- tool: PIXELFX_TOOL,
29932
- library: { name: "pixelfx", version: lib.version, repository: PIXELFX_REPOSITORY, license: "MIT" },
29933
- ...facts,
29934
- files: { sheet: path54.basename(paths.sheet), atlas: path54.basename(paths.atlas) },
29935
- sheetSha256,
29936
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
30297
+ render,
30298
+ atlasKey: "pixelfx",
30299
+ atlasFacts: { version: lib.version },
30300
+ record: {
30301
+ provider: "pixelfx",
30302
+ tool: PIXELFX_TOOL,
30303
+ library: { name: "pixelfx", version: lib.version, repository: PIXELFX_REPOSITORY, license: "MIT" }
30304
+ },
29937
30305
  recipe
29938
- };
29939
- await mkdir19(path54.dirname(paths.sheet), { recursive: true });
29940
- await writeFile24(paths.sheet, sheet.png);
29941
- await writeFile24(paths.atlas, `${JSON.stringify(atlas, null, 2)}
29942
- `);
29943
- await writeFile24(paths.provenance, `${JSON.stringify(provenance, null, 2)}
29944
- `);
30306
+ });
29945
30307
  return {
29946
30308
  provider: "pixelfx",
29947
30309
  library: { name: "pixelfx", version: lib.version },
29948
- ...facts,
29949
- columns: sheet.columns,
29950
- sheetSha256,
29951
- paths: { sheet: paths.sheet, atlas: paths.atlas, provenance: paths.provenance },
30310
+ ...written.facts,
30311
+ columns: written.columns,
30312
+ sheetSha256: written.sheetSha256,
30313
+ paths: written.paths,
29952
30314
  recipe
29953
30315
  };
29954
30316
  }
29955
30317
 
29956
30318
  // src/cli/commands/pixellab-utils.ts
29957
30319
  function loadKeys(args) {
29958
- loadEnvFiles(path55.dirname(path55.resolve(args.manifest)));
30320
+ loadEnvFiles(path57.dirname(path57.resolve(args.manifest)));
29959
30321
  loadEnvFiles(process.cwd());
29960
30322
  }
29961
30323
  async function runUnzoom(args) {
@@ -30117,14 +30479,56 @@ async function runNormalMap(args) {
30117
30479
  }
30118
30480
  log(` ${res.width}x${res.height}${res.frames > 1 ? `, ${res.frames} frames` : ""}; wrote ${res.out}`);
30119
30481
  }
30120
- var VFX_LIBS = ["pixellab", "pixelfx"];
30482
+ var VFX_LIBS = ["pixellab", "pixelfx", "codex"];
30483
+ async function readLocalRecipe(file, lib) {
30484
+ const codex = await readCodexRecipe(file, { bare: lib === "codex" });
30485
+ if (codex) {
30486
+ if (lib === "pixelfx") throw new UsageError(`${file} is a record from pixel-vfx-codex; drop --lib pixelfx, or use --lib codex`);
30487
+ return { lib: "codex", read: codex };
30488
+ }
30489
+ if (lib === "codex") return null;
30490
+ const pixelfx = await readPixelfxRecipe(file);
30491
+ if (pixelfx) return { lib: "pixelfx", read: pixelfx };
30492
+ return null;
30493
+ }
30494
+ function pixelfxOnly(args) {
30495
+ return [["--seed", args.seed], ["--palette", args.palette.length ? args.palette : void 0]];
30496
+ }
30497
+ function numberPairs(flag, pairs) {
30498
+ const out = {};
30499
+ for (const pair of pairs) {
30500
+ const [key2, raw, ...rest] = pair.split("=");
30501
+ const value = Number(raw);
30502
+ if (!key2 || raw === void 0 || rest.length || raw.trim() === "" || !Number.isFinite(value)) {
30503
+ throw new UsageError(`${flag} takes name=number, got "${pair}"`);
30504
+ }
30505
+ out[key2] = value;
30506
+ }
30507
+ return out;
30508
+ }
30121
30509
  async function runVfx(args) {
30122
30510
  if (args.lib !== void 0 && !VFX_LIBS.includes(args.lib)) {
30123
- throw new UsageError(`--lib must be ${VFX_LIBS.join(" or ")}, got "${args.lib}"`);
30124
- }
30125
- const pixelfxOnly = [["--margin", args.margin], ["--seed", args.seed], ["--palette", args.palette.length ? args.palette : void 0]];
30126
- if (args.subcommand === "effects" || args.lib === "pixelfx" && args.subcommand === "presets") {
30127
- if (args.lib === "pixellab") throw new UsageError("vfx effects lists the pixelfx library's effects; PixelLab's lists are vfx presets and vfx parts");
30511
+ throw new UsageError(`--lib must be ${VFX_LIBS.join(", ")}, got "${args.lib}"`);
30512
+ }
30513
+ const pixelfxOnly_ = pixelfxOnly(args);
30514
+ const codexOnly = [
30515
+ ["--camera", args.camera],
30516
+ ["--hue", args.hue],
30517
+ ["--param", args.param.length ? args.param : void 0],
30518
+ ["--tune", args.tune.length ? args.tune : void 0]
30519
+ ];
30520
+ const listsLocal = args.subcommand === "effects" || (args.lib === "pixelfx" || args.lib === "codex") && args.subcommand === "presets";
30521
+ if (listsLocal) {
30522
+ if (args.lib === "pixellab") throw new UsageError("vfx effects lists a local library's effects; PixelLab's lists are vfx presets and vfx parts");
30523
+ if (args.lib === "codex") {
30524
+ const lib2 = loadCodex();
30525
+ if (args.json) {
30526
+ log(JSON.stringify({ version: 1, library: { name: "pixel-vfx-codex", version: lib2.version, engineSha256: lib2.engineSha256 }, effects: listCodexEffects(lib2) }, null, 2));
30527
+ return;
30528
+ }
30529
+ log(formatCodexEffects(lib2));
30530
+ return;
30531
+ }
30128
30532
  const lib = await loadPixelfx();
30129
30533
  if (args.json) {
30130
30534
  log(JSON.stringify({ version: 1, library: { name: "pixelfx", version: lib.version }, categories: lib.categories, effects: listPixelfxEffects(lib) }, null, 2));
@@ -30133,15 +30537,17 @@ async function runVfx(args) {
30133
30537
  log(formatPixelfxEffects(lib));
30134
30538
  return;
30135
30539
  }
30136
- if (args.subcommand === "parts" && args.lib === "pixelfx") {
30137
- throw new UsageError("pixelfx has no parts: its effects are whole; list them with vfx effects");
30540
+ if (args.subcommand === "parts" && (args.lib === "pixelfx" || args.lib === "codex")) {
30541
+ throw new UsageError(`${args.lib} has no parts: its effects are whole; list them with vfx effects --lib ${args.lib}`);
30138
30542
  }
30139
30543
  if (args.subcommand === "make") {
30140
- const pixelfxRecipe = args.recipe && args.lib !== "pixellab" ? await readPixelfxRecipe(args.recipe) : null;
30141
- if (args.lib === "pixelfx" || pixelfxRecipe) return runPixelfxVfx(args, pixelfxRecipe);
30544
+ const local = args.recipe && args.lib !== "pixellab" ? await readLocalRecipe(args.recipe, args.lib) : null;
30545
+ const source = local?.lib ?? (args.lib === "pixelfx" || args.lib === "codex" ? args.lib : null);
30546
+ if (source === "pixelfx") return runPixelfxVfx(args, local?.lib === "pixelfx" ? local.read : null);
30547
+ if (source === "codex") return runCodexVfx(args, local?.lib === "codex" ? local.read : null);
30142
30548
  }
30143
- for (const [flag, value] of pixelfxOnly) {
30144
- if (value !== void 0) throw new UsageError(`vfx takes ${flag} only with --lib pixelfx`);
30549
+ for (const [flag, value] of [...pixelfxOnly_, ...codexOnly, ["--margin", args.margin]]) {
30550
+ if (value !== void 0) throw new UsageError(`vfx takes ${flag} only with --lib pixelfx or --lib codex`);
30145
30551
  }
30146
30552
  if (args.subcommand === "presets" || args.subcommand === "parts") {
30147
30553
  if (args.dryRun) {
@@ -30167,7 +30573,7 @@ async function runVfx(args) {
30167
30573
  const fromRecipe = args.recipe ? await readVfxRecipe(args.recipe) : void 0;
30168
30574
  const sprite = args.sprite ?? fromRecipe?.sprite;
30169
30575
  const recipeName = typeof fromRecipe?.recipe.name === "string" ? fromRecipe.recipe.name : void 0;
30170
- const name = args.name ?? (args.effect ? void 0 : recipeName ?? args.preset ?? path55.basename(paths.sheet, ".png"));
30576
+ const name = args.name ?? (args.effect ? void 0 : recipeName ?? args.preset ?? path57.basename(paths.sheet, ".png"));
30171
30577
  const from = args.preset ? `preset ${args.preset}` : args.recipe ? `recipe ${args.recipe}` : args.effect ? `saved effect ${args.effect}` : "nothing";
30172
30578
  log(
30173
30579
  ` vfx ${name ? `"${name}"` : "(keeping its saved name)"} from ${from}${args.parts.length ? ` + ${args.parts.join(", ")}` : ""}${sprite ? ` around ${sprite}` : ""} \u2192 ${paths.sheet} (+ .gif, .json, .vfx.json${args.gamePack ? ", -game.zip" : ""})`
@@ -30217,6 +30623,9 @@ async function runPixelfxVfx(args, fromFile) {
30217
30623
  for (const [flag, value] of pixellabOnly) {
30218
30624
  if (value !== void 0) throw new UsageError(`${flag} is for PixelLab's VFX tools; a pixelfx effect takes --effect, --palette, --seed, --fps and --margin`);
30219
30625
  }
30626
+ for (const [flag, value] of [["--camera", args.camera], ["--hue", args.hue], ["--param", args.param.length ? args.param : void 0], ["--tune", args.tune.length ? args.tune : void 0]]) {
30627
+ if (value !== void 0) throw new UsageError(`${flag} is for --lib codex; a pixelfx effect takes --effect, --palette, --seed, --fps and --margin`);
30628
+ }
30220
30629
  if (args.recipe && !fromFile) throw new UsageError(`${args.recipe} is not a pixelfx recipe: it names no pixelfx effect`);
30221
30630
  if (args.recipe && args.effect) throw new UsageError("vfx takes one of --effect or --recipe, not both");
30222
30631
  const effect = fromFile?.recipe.effect ?? args.effect;
@@ -30258,6 +30667,68 @@ async function runPixelfxVfx(args, fromFile) {
30258
30667
  for (const file of [res.paths.sheet, res.paths.atlas, res.paths.provenance]) log(` wrote ${file}`);
30259
30668
  log(` render it again: pixelkiln vfx --recipe ${res.paths.provenance} --out <base>`);
30260
30669
  }
30670
+ async function runCodexVfx(args, fromFile) {
30671
+ if (!args.out) throw new UsageError("vfx needs --out <base>: <base>.png, .json, and .vfx.json are written");
30672
+ const refused = [
30673
+ ["--preset", args.preset],
30674
+ ["--part", args.parts.length ? args.parts : void 0],
30675
+ ["--sprite", args.sprite],
30676
+ ["--description", args.description],
30677
+ ["--artist", args.artist],
30678
+ ["--sprite-frames", args.spriteFrames],
30679
+ ["--sprite-fps", args.spriteFps],
30680
+ ["--game-pack", args.gamePack || void 0]
30681
+ ];
30682
+ for (const [flag, value] of refused) {
30683
+ if (value !== void 0) throw new UsageError(`${flag} is for PixelLab's VFX tools; a codex effect takes --effect, --camera, --fps, --margin, --hue, --param and --tune`);
30684
+ }
30685
+ for (const [flag, value] of pixelfxOnly(args)) {
30686
+ if (value !== void 0) throw new UsageError(`${flag} is for --lib pixelfx: codex effects take no seed or palette (they are pure functions of time; recolour with --hue)`);
30687
+ }
30688
+ if (args.recipe && !fromFile) throw new UsageError(`${args.recipe} is not a codex recipe: it names no pixel-vfx-codex effect`);
30689
+ if (args.recipe && args.effect) throw new UsageError("vfx takes one of --effect or --recipe, not both");
30690
+ const effect = fromFile?.recipe.effect ?? args.effect;
30691
+ if (!effect) throw new UsageError("vfx --lib codex needs --effect <id> (vfx effects --lib codex lists them) or --recipe <file>");
30692
+ const params = { ...fromFile?.recipe.params ?? {}, ...numberPairs("--param", args.param) };
30693
+ const tune = { ...fromFile?.recipe.tune ?? {}, ...numberPairs("--tune", args.tune) };
30694
+ const camera = args.camera ?? fromFile?.recipe.camera;
30695
+ if (args.camera !== void 0 && !CODEX_CAMERAS.includes(args.camera)) {
30696
+ throw new UsageError(`--camera must be ${CODEX_CAMERAS.join(", ")}, got "${args.camera}"`);
30697
+ }
30698
+ const recipe = {
30699
+ effect,
30700
+ ...camera ? { camera } : {},
30701
+ ...(args.fps ?? fromFile?.recipe.fps) !== void 0 ? { fps: args.fps ?? fromFile?.recipe.fps } : {},
30702
+ ...(args.margin ?? fromFile?.recipe.margin) !== void 0 ? { margin: args.margin ?? fromFile?.recipe.margin } : {},
30703
+ ...(args.hue ?? fromFile?.recipe.hue) !== void 0 ? { hue: args.hue ?? fromFile?.recipe.hue } : {},
30704
+ ...Object.keys(params).length ? { params } : {},
30705
+ ...Object.keys(tune).length ? { tune } : {}
30706
+ };
30707
+ const lib = loadCodex();
30708
+ const info = checkCodexRecipe(lib, recipe);
30709
+ const plan = planCodex(lib, recipe);
30710
+ const paths = vfxOutputPaths(args.out);
30711
+ log(
30712
+ ` vfx "${args.name ?? info.en}" from pixel-vfx-codex ${lib.version} ${effect}${args.recipe ? ` (recipe ${args.recipe})` : ""} \u2192 ${paths.sheet} (+ .json, .vfx.json)`
30713
+ );
30714
+ log(` ${plan.camera} camera, about ${plan.frames} frames @ ${plan.fps} fps over ${plan.seconds.toFixed(1)} s, cropped to the effect; loops`);
30715
+ log(" cost: free; rendered on this machine, nothing sent");
30716
+ if (fromFile?.engineSha256 && fromFile.engineSha256 !== lib.engineSha256) {
30717
+ log(` note: the record was rendered with engine ${fromFile.engineSha256}; this install is ${lib.engineSha256}, so it may draw the effect differently`);
30718
+ }
30719
+ if (args.dryRun) {
30720
+ log(" dry run: nothing written");
30721
+ return;
30722
+ }
30723
+ const res = await makeCodexVfx(lib, { ...recipe, out: args.out, name: args.name, force: args.force });
30724
+ if (args.json) {
30725
+ log(JSON.stringify({ version: 1, ...res }, null, 2));
30726
+ return;
30727
+ }
30728
+ log(` ${res.width}x${res.height}, ${res.frames} frames @ ${res.fps} fps`);
30729
+ for (const file of [res.paths.sheet, res.paths.atlas, res.paths.provenance]) log(` wrote ${file}`);
30730
+ log(` render it again: pixelkiln vfx --recipe ${res.paths.provenance} --out <base>`);
30731
+ }
30261
30732
  async function runVfxArtist(args, out) {
30262
30733
  const description = args.description.trim();
30263
30734
  if (!description) throw new UsageError('vfx --description needs the effect in words, e.g. "a blue lightning strike that leaves sparks"');
@@ -30284,7 +30755,7 @@ async function runVfxArtist(args, out) {
30284
30755
  if ((args.spriteFrames !== void 0 || args.spriteFps !== void 0) && !args.sprite) {
30285
30756
  throw new UsageError("--sprite-frames and --sprite-fps describe a --sprite; add one");
30286
30757
  }
30287
- const taken = args.sprite ? vfxArtistSprite(await readFile39(args.sprite), args.sprite, args.spriteFrames ?? 1) : void 0;
30758
+ const taken = args.sprite ? vfxArtistSprite(await readFile40(args.sprite), args.sprite, args.spriteFrames ?? 1) : void 0;
30288
30759
  if (args.spriteFps !== void 0 && !taken?.animated) {
30289
30760
  throw new UsageError("--sprite-fps is the speed of an animated sprite: a GIF, or a PNG strip with --sprite-frames 2 or more");
30290
30761
  }
@@ -30297,7 +30768,7 @@ async function runVfxArtist(args, out) {
30297
30768
  );
30298
30769
  if (args.effect) {
30299
30770
  log(
30300
- ` changes saved effect ${args.effect} in place` + (conversation ? `, priced as a change (its conversation is in ${path55.basename(paths.provenance)})` : `; ${path55.basename(paths.provenance)} holds no conversation for it, so PixelLab prices it as a new effect`)
30771
+ ` changes saved effect ${args.effect} in place` + (conversation ? `, priced as a change (its conversation is in ${path57.basename(paths.provenance)})` : `; ${path57.basename(paths.provenance)} holds no conversation for it, so PixelLab prices it as a new effect`)
30301
30772
  );
30302
30773
  }
30303
30774
  log(` cost: about ${quote} generations by PixelLab's table, billed on delivery; at most ${ceiling} if the effect runs long`);
@@ -30347,13 +30818,13 @@ async function runVfxArtist(args, out) {
30347
30818
  }
30348
30819
 
30349
30820
  // src/cli/commands/audio.ts
30350
- import { readFile as readFile40 } from "fs/promises";
30351
- import path57 from "path";
30821
+ import { readFile as readFile41 } from "fs/promises";
30822
+ import path59 from "path";
30352
30823
 
30353
30824
  // src/pixellab-audio.ts
30354
- import { existsSync as existsSync46 } from "fs";
30825
+ import { existsSync as existsSync48 } from "fs";
30355
30826
  import { mkdir as mkdir20, writeFile as writeFile25 } from "fs/promises";
30356
- import path56 from "path";
30827
+ import path58 from "path";
30357
30828
  var MUSIC_COST_GENERATIONS = 10;
30358
30829
  var MUSIC_LOOP_COST_GENERATIONS = 4;
30359
30830
  var MUSIC_LOOP_MIN_BODY_SECONDS = 36;
@@ -30410,7 +30881,7 @@ async function billedUsage(client2, jobId) {
30410
30881
  }
30411
30882
  }
30412
30883
  function musicOutputPaths(out) {
30413
- const base = path56.resolve(out.replace(/\.(music\.json|mp3)$/i, ""));
30884
+ const base = path58.resolve(out.replace(/\.(music\.json|mp3)$/i, ""));
30414
30885
  return {
30415
30886
  takes: [`${base}.mp3`, `${base}.take2.mp3`],
30416
30887
  loops: [`${base}.loop.mp3`, `${base}.loop.take2.mp3`],
@@ -30432,7 +30903,7 @@ async function collectTakes(client2, songs, files, what, opts) {
30432
30903
  if (!song.audio_url) throw new Error(`PixelLab ${what} ${song.id} completed without an audio URL`);
30433
30904
  const bytes = await client2.download(song.audio_url);
30434
30905
  validateAudio(bytes, "mp3");
30435
- await mkdir20(path56.dirname(file), { recursive: true });
30906
+ await mkdir20(path58.dirname(file), { recursive: true });
30436
30907
  await writeFile25(file, bytes);
30437
30908
  finished.push(song);
30438
30909
  takes.push({
@@ -30460,7 +30931,7 @@ async function generateMusic(client2, opts) {
30460
30931
  }
30461
30932
  const writes = [paths.record, ...opts.loopOf ? [] : paths.takes, ...wantsLoop ? paths.loops : []];
30462
30933
  if (!opts.force) {
30463
- for (const file of writes) if (existsSync46(file)) throw new Error(`${file} already exists; pass --force to replace it`);
30934
+ for (const file of writes) if (existsSync48(file)) throw new Error(`${file} already exists; pass --force to replace it`);
30464
30935
  }
30465
30936
  const usage2 = [];
30466
30937
  let quoted = null;
@@ -30498,9 +30969,9 @@ async function generateMusic(client2, opts) {
30498
30969
  quotedGenerations: quoted,
30499
30970
  usage: usage2
30500
30971
  });
30501
- const relative = (take) => ({ ...take, file: path56.basename(take.file) });
30972
+ const relative = (take) => ({ ...take, file: path58.basename(take.file) });
30502
30973
  const writeRecord = async (result2) => {
30503
- await mkdir20(path56.dirname(paths.record), { recursive: true });
30974
+ await mkdir20(path58.dirname(paths.record), { recursive: true });
30504
30975
  await writeFile25(
30505
30976
  paths.record,
30506
30977
  JSON.stringify(
@@ -30541,7 +31012,7 @@ async function generateMusic(client2, opts) {
30541
31012
  submitted = await client2.loopMusic(loopSource);
30542
31013
  } catch (error) {
30543
31014
  const detail = refusalDetail(error);
30544
- const kept = takes.length ? ` The song's takes are saved (${path56.basename(paths.record)}); nothing was charged for the loop.` : "";
31015
+ const kept = takes.length ? ` The song's takes are saved (${path58.basename(paths.record)}); nothing was charged for the loop.` : "";
30545
31016
  throw new Error(`PixelLab refused to loop ${loopSource}: ${detail ?? (error instanceof Error ? error.message : String(error))}${kept}`, { cause: error });
30546
31017
  }
30547
31018
  quoted = (quoted ?? 0) + (submitted.quoted_generations ?? 0);
@@ -30555,13 +31026,13 @@ async function generateMusic(client2, opts) {
30555
31026
  return result;
30556
31027
  }
30557
31028
  function soundEffectOutputPaths(out) {
30558
- const base = path56.resolve(out.replace(/\.(sfx\.json|wav)$/i, ""));
31029
+ const base = path58.resolve(out.replace(/\.(sfx\.json|wav)$/i, ""));
30559
31030
  return { wav: `${base}.wav`, record: `${base}.sfx.json` };
30560
31031
  }
30561
31032
  async function generateSoundEffect(client2, opts) {
30562
31033
  const { wav, record } = soundEffectOutputPaths(opts.out);
30563
31034
  if (!opts.force) {
30564
- for (const file of [wav, record]) if (existsSync46(file)) throw new Error(`${file} already exists; pass --force to replace it`);
31035
+ for (const file of [wav, record]) if (existsSync48(file)) throw new Error(`${file} already exists; pass --force to replace it`);
30565
31036
  }
30566
31037
  const seconds = opts.seconds ?? 2;
30567
31038
  const submitted = await client2.createSoundEffect({ prompt: opts.prompt, seconds, name: opts.name });
@@ -30570,7 +31041,7 @@ async function generateSoundEffect(client2, opts) {
30570
31041
  if (!clip.audio_url) throw new Error(`PixelLab sound effect ${id} completed without an audio URL`);
30571
31042
  const bytes = await client2.download(clip.audio_url);
30572
31043
  validateAudio(bytes, "wav");
30573
- await mkdir20(path56.dirname(wav), { recursive: true });
31044
+ await mkdir20(path58.dirname(wav), { recursive: true });
30574
31045
  await writeFile25(wav, bytes);
30575
31046
  const result = {
30576
31047
  soundEffectId: id,
@@ -30593,7 +31064,7 @@ async function generateSoundEffect(client2, opts) {
30593
31064
  prompt: opts.prompt,
30594
31065
  seconds,
30595
31066
  soundEffectId: id,
30596
- file: path56.basename(wav),
31067
+ file: path58.basename(wav),
30597
31068
  sha256: result.sha256,
30598
31069
  durationMs: result.durationMs,
30599
31070
  quotedGenerations: result.quotedGenerations,
@@ -30608,7 +31079,7 @@ async function generateSoundEffect(client2, opts) {
30608
31079
 
30609
31080
  // src/cli/commands/audio.ts
30610
31081
  function loadKeys2(args) {
30611
- loadEnvFiles(path57.dirname(path57.resolve(args.manifest)));
31082
+ loadEnvFiles(path59.dirname(path59.resolve(args.manifest)));
30612
31083
  loadEnvFiles(process.cwd());
30613
31084
  }
30614
31085
  function progress() {
@@ -30665,7 +31136,7 @@ async function runMusic(args) {
30665
31136
  const cost = musicCost({ loop: args.loop, loopOf: args.loopOf });
30666
31137
  const paths = musicOutputPaths(args.out);
30667
31138
  const what = args.loopOf ? `loop of ${args.loopOf} (two loop takes)` : `"${args.description}"${vocals ? ", with vocals" : ", instrumental"}, two takes${args.loop ? " plus loops of take 1" : ""}`;
30668
- log(` music: ${what} \u2192 ${path57.relative(process.cwd(), args.loopOf ? paths.loops[0] : paths.takes[0])} \u2026`);
31139
+ log(` music: ${what} \u2192 ${path59.relative(process.cwd(), args.loopOf ? paths.loops[0] : paths.takes[0])} \u2026`);
30669
31140
  log(` cost: ${cost} generations (PixelLab's published price)${args.improve ? ", plus about 0.05 for --improve" : ""}`);
30670
31141
  if (args.budget !== void 0 && args.budget < cost) {
30671
31142
  throw new Error(`--budget ${args.budget} is below this run's ${cost}-generation cost`);
@@ -30682,7 +31153,7 @@ async function runMusic(args) {
30682
31153
  style = (await client2.improveMusicStyle({ style, instrumental: !vocals, bpm: args.bpm })).style;
30683
31154
  log(` style: ${style}`);
30684
31155
  }
30685
- const lyrics = args.lyrics ? await readFile40(path57.resolve(args.lyrics), "utf8") : void 0;
31156
+ const lyrics = args.lyrics ? await readFile41(path59.resolve(args.lyrics), "utf8") : void 0;
30686
31157
  const res = await generateMusic(client2, {
30687
31158
  style,
30688
31159
  lyrics,
@@ -30718,7 +31189,7 @@ async function runSfx(args) {
30718
31189
  const seconds = args.seconds ?? 2;
30719
31190
  const cost = soundEffectCost(seconds);
30720
31191
  const { wav } = soundEffectOutputPaths(args.out);
30721
- log(` sfx: "${args.description}", ${seconds} s \u2192 ${path57.relative(process.cwd(), wav)}`);
31192
+ log(` sfx: "${args.description}", ${seconds} s \u2192 ${path59.relative(process.cwd(), wav)}`);
30722
31193
  log(` cost: ${cost} generation${cost === 1 ? "" : "s"} (PixelLab's published price, by length)`);
30723
31194
  if (args.budget !== void 0 && args.budget < cost) {
30724
31195
  throw new Error(`--budget ${args.budget} is below this clip's ${cost}-generation cost`);
@@ -30746,12 +31217,12 @@ async function runSfx(args) {
30746
31217
  }
30747
31218
 
30748
31219
  // src/cli/commands/ui.ts
30749
- import path59 from "path";
31220
+ import path61 from "path";
30750
31221
 
30751
31222
  // src/pixellab-ui.ts
30752
- import { existsSync as existsSync47 } from "fs";
31223
+ import { existsSync as existsSync49 } from "fs";
30753
31224
  import { mkdir as mkdir21, writeFile as writeFile26 } from "fs/promises";
30754
- import path58 from "path";
31225
+ import path60 from "path";
30755
31226
  var UI_STATES_COSTS = [10, 15, 25];
30756
31227
  var UI_STATES_MAX_COST = 25;
30757
31228
  var UI_STATES_MAX_ELEMENTS = 64;
@@ -30844,8 +31315,8 @@ async function pullUiAsset(client2, uiAssetId, opts) {
30844
31315
  const asset = await client2.getUiAssetDetail(uiAssetId);
30845
31316
  if (asset.status && asset.status !== "completed") throw new Error(`UI asset ${uiAssetId} is ${asset.status}; pull it once it is completed`);
30846
31317
  if (!asset.image_url) throw new Error(`UI asset ${uiAssetId} has no image yet`);
30847
- const dir = path58.resolve(opts.out);
30848
- const record = path58.join(dir, "ui.json");
31318
+ const dir = path60.resolve(opts.out);
31319
+ const record = path60.join(dir, "ui.json");
30849
31320
  const plan = [];
30850
31321
  const insets = (part) => part.nine_slice ? { nineSlice: { left: part.nine_slice.left, right: part.nine_slice.right, top: part.nine_slice.top, bottom: part.nine_slice.bottom } } : {};
30851
31322
  const taken = /* @__PURE__ */ new Set();
@@ -30893,16 +31364,16 @@ async function pullUiAsset(client2, uiAssetId, opts) {
30893
31364
  }
30894
31365
  if (kind === "element") addStates(asset, rootName, asset.states);
30895
31366
  if (!opts.force) {
30896
- for (const file of [record, ...plan.map((item) => path58.join(dir, item.file))]) {
30897
- if (existsSync47(file)) throw new Error(`${file} already exists; pass --force to replace it`);
31367
+ for (const file of [record, ...plan.map((item) => path60.join(dir, item.file))]) {
31368
+ if (existsSync49(file)) throw new Error(`${file} already exists; pass --force to replace it`);
30898
31369
  }
30899
31370
  }
30900
31371
  const files = [];
30901
31372
  for (const { url, ...item } of plan) {
30902
31373
  const bytes = await client2.download(url);
30903
31374
  validateMedia(bytes, MediaType.PNG);
30904
- const target = path58.join(dir, item.file);
30905
- await mkdir21(path58.dirname(target), { recursive: true });
31375
+ const target = path60.join(dir, item.file);
31376
+ await mkdir21(path60.dirname(target), { recursive: true });
30906
31377
  await writeFile26(target, bytes);
30907
31378
  files.push({ ...item, sha256: sha256(bytes) });
30908
31379
  }
@@ -30928,7 +31399,7 @@ async function pullUiAsset(client2, uiAssetId, opts) {
30928
31399
 
30929
31400
  // src/cli/commands/ui.ts
30930
31401
  function loadKeys3(args) {
30931
- loadEnvFiles(path59.dirname(path59.resolve(args.manifest)));
31402
+ loadEnvFiles(path61.dirname(path61.resolve(args.manifest)));
30932
31403
  loadEnvFiles(process.cwd());
30933
31404
  }
30934
31405
  function requireId(args) {
@@ -31042,18 +31513,18 @@ async function runUi(args) {
31042
31513
  log(JSON.stringify({ version: 1, ...res }, null, 2));
31043
31514
  return;
31044
31515
  }
31045
- for (const file of res.files) log(` wrote ${path59.join(args.out, file.file)} (${file.kind}, ${file.size.width}x${file.size.height})`);
31046
- log(` wrote ${path59.join(args.out, "ui.json")}`);
31516
+ for (const file of res.files) log(` wrote ${path61.join(args.out, file.file)} (${file.kind}, ${file.size.width}x${file.size.height})`);
31517
+ log(` wrote ${path61.join(args.out, "ui.json")}`);
31047
31518
  }
31048
31519
 
31049
31520
  // src/cli/commands/asset.ts
31050
- import { readFile as readFile42 } from "fs/promises";
31051
- import path61 from "path";
31521
+ import { readFile as readFile43 } from "fs/promises";
31522
+ import path63 from "path";
31052
31523
 
31053
31524
  // src/pixellab-assets.ts
31054
- import { existsSync as existsSync48 } from "fs";
31055
- import { mkdir as mkdir22, readdir as readdir5, readFile as readFile41, stat as stat6, writeFile as writeFile27 } from "fs/promises";
31056
- import path60 from "path";
31525
+ import { existsSync as existsSync50 } from "fs";
31526
+ import { mkdir as mkdir22, readdir as readdir5, readFile as readFile42, stat as stat6, writeFile as writeFile27 } from "fs/promises";
31527
+ import path62 from "path";
31057
31528
  var ASSET_KINDS = ["object", "character"];
31058
31529
  var EXPORT_FORMATS = ["zip", "spritesheet", "aseprite", "gif"];
31059
31530
  var MIRROR_DIRECTIONS = ["east", "west", "south-east", "south-west", "north-east", "north-west"];
@@ -31073,7 +31544,7 @@ function parseCanvasSize(text, kind) {
31073
31544
  }
31074
31545
  function exportOutPath(out, format) {
31075
31546
  const extension = format === "aseprite" ? ".aseprite" : format === "gif" ? ".gif" : ".zip";
31076
- return path60.extname(out) ? path60.resolve(out) : path60.resolve(`${out}${extension}`);
31547
+ return path62.extname(out) ? path62.resolve(out) : path62.resolve(`${out}${extension}`);
31077
31548
  }
31078
31549
  function checkExportBytes(bytes, format) {
31079
31550
  const ok = format === "gif" ? bytes.subarray(0, 4).toString("ascii") === "GIF8" : format === "aseprite" ? bytes.length > 6 && bytes.readUInt16LE(4) === 42464 : bytes.subarray(0, 2).toString("ascii") === "PK";
@@ -31081,15 +31552,15 @@ function checkExportBytes(bytes, format) {
31081
31552
  }
31082
31553
  async function exportAssetFile(client2, kind, id, format, opts) {
31083
31554
  const out = exportOutPath(opts.out, format);
31084
- if (existsSync48(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
31555
+ if (existsSync50(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
31085
31556
  const bytes = await client2.exportAsset(kind, id, format, { animationGroupId: opts.animationGroupId, direction: opts.direction });
31086
31557
  checkExportBytes(bytes, format);
31087
- await mkdir22(path60.dirname(out), { recursive: true });
31558
+ await mkdir22(path62.dirname(out), { recursive: true });
31088
31559
  await writeFile27(out, bytes);
31089
31560
  return { out, bytes: bytes.length };
31090
31561
  }
31091
31562
  async function importObjectFile(client2, file, opts = {}) {
31092
- const bytes = await readFile41(file);
31563
+ const bytes = await readFile42(file);
31093
31564
  const metadata = imageMetadata(bytes);
31094
31565
  if (!metadata || metadata.format !== "png") throw new Error(`${file} is not a PNG; PixelLab imports PNG only (JPEG compression would be stored as pixels)`);
31095
31566
  if (metadata.width > IMPORT_MAX_SIDE || metadata.height > IMPORT_MAX_SIDE) {
@@ -31131,11 +31602,11 @@ async function pullExpansionReview(client2, id, opts) {
31131
31602
  if (object.status !== "review-expansion" || !review?.rotation_urls) {
31132
31603
  throw new Error(`object ${id} is ${object.status ?? "unknown"}; there is no expansion waiting for review`);
31133
31604
  }
31134
- const dir = path60.resolve(opts.out);
31605
+ const dir = path62.resolve(opts.out);
31135
31606
  const entries = Object.entries(review.rotation_urls).filter((entry) => typeof entry[1] === "string");
31136
- const files = entries.map(([direction]) => ({ direction, file: path60.join(dir, `${direction}.png`) }));
31607
+ const files = entries.map(([direction]) => ({ direction, file: path62.join(dir, `${direction}.png`) }));
31137
31608
  if (!opts.force) {
31138
- for (const { file } of files) if (existsSync48(file)) throw new Error(`${file} already exists; pass --force to replace it`);
31609
+ for (const { file } of files) if (existsSync50(file)) throw new Error(`${file} already exists; pass --force to replace it`);
31139
31610
  }
31140
31611
  await mkdir22(dir, { recursive: true });
31141
31612
  for (const [index, [, url]] of entries.entries()) {
@@ -31182,7 +31653,7 @@ function readPng(bytes, file) {
31182
31653
  return metadata;
31183
31654
  }
31184
31655
  async function importTilesetFile(client2, file, opts = {}) {
31185
- const bytes = await readFile41(file);
31656
+ const bytes = await readFile42(file);
31186
31657
  const { width, height } = readPng(bytes, file);
31187
31658
  const reading = chooseTilesetSheetReading(file, width, height, opts.tileSize);
31188
31659
  const mode2 = opts.mode ?? "topdown";
@@ -31200,11 +31671,11 @@ async function importTilesetFile(client2, file, opts = {}) {
31200
31671
  return { tilesetId: res.tileset_id, mode: mode2, tileSize: reading.tileSize, layout: reading.layout };
31201
31672
  }
31202
31673
  async function pngFilesAt(from) {
31203
- if (!existsSync48(from)) throw new Error(`${from} does not exist`);
31674
+ if (!existsSync50(from)) throw new Error(`${from} does not exist`);
31204
31675
  if (!(await stat6(from)).isDirectory()) return [from];
31205
31676
  const names = (await readdir5(from)).filter((name) => /\.png$/i.test(name)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
31206
31677
  if (names.length === 0) throw new Error(`${from} holds no PNG files`);
31207
- return names.map((name) => path60.join(from, name));
31678
+ return names.map((name) => path62.join(from, name));
31208
31679
  }
31209
31680
  function importTileHeights(tileType, tileSize) {
31210
31681
  if (tileType === "square_topdown" || tileType === "octagon") return { min: tileSize, max: tileSize };
@@ -31219,7 +31690,7 @@ async function importTilesFiles(client2, from, opts) {
31219
31690
  const heights = importTileHeights(opts.tileType, opts.tileSize);
31220
31691
  const frames = [];
31221
31692
  for (const file of files) {
31222
- const bytes = await readFile41(file);
31693
+ const bytes = await readFile42(file);
31223
31694
  const { width, height } = readPng(bytes, file);
31224
31695
  if (width !== opts.tileSize || height < heights.min || height > heights.max) {
31225
31696
  const tall = heights.min === heights.max ? `${heights.min}` : `${heights.min} to ${heights.max}`;
@@ -31239,13 +31710,13 @@ function checkSaveTarget(target) {
31239
31710
  }
31240
31711
  function saveUndoDir(target, now = /* @__PURE__ */ new Date()) {
31241
31712
  const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
31242
- return path60.resolve("pixelkiln-undo", `${target.replace(/[^a-zA-Z0-9-]+/g, "_")}-${stamp}`);
31713
+ return path62.resolve("pixelkiln-undo", `${target.replace(/[^a-zA-Z0-9-]+/g, "_")}-${stamp}`);
31243
31714
  }
31244
31715
  async function writeUndo(frames, dir) {
31245
31716
  await mkdir22(dir, { recursive: true });
31246
31717
  const files = [];
31247
31718
  for (const [index, frame] of frames.entries()) {
31248
- const file = path60.join(dir, frames.length === 1 ? "previous.png" : `previous-${String(index).padStart(2, "0")}.png`);
31719
+ const file = path62.join(dir, frames.length === 1 ? "previous.png" : `previous-${String(index).padStart(2, "0")}.png`);
31249
31720
  await writeFile27(file, Buffer.from(frame.base64, "base64"));
31250
31721
  files.push(file);
31251
31722
  }
@@ -31255,13 +31726,13 @@ async function saveToAssetFile(client2, target, from, opts = {}) {
31255
31726
  checkSaveTarget(target);
31256
31727
  if ((opts.name || opts.description) && target !== "gallery:new") throw new Error("a name and a description belong to a new gallery image: --target gallery:new");
31257
31728
  const files = await pngFilesAt(from).catch(async (error) => {
31258
- if (existsSync48(from) && /\.gif$/i.test(from)) return [from];
31729
+ if (existsSync50(from) && /\.gif$/i.test(from)) return [from];
31259
31730
  throw error;
31260
31731
  });
31261
31732
  let image;
31262
31733
  let frames;
31263
31734
  if (files.length === 1) {
31264
- const bytes = await readFile41(files[0]);
31735
+ const bytes = await readFile42(files[0]);
31265
31736
  const gif = bytes.subarray(0, 4).toString("ascii") === "GIF8";
31266
31737
  if (!gif) readPng(bytes, files[0]);
31267
31738
  image = { base64: bytes.toString("base64"), format: gif ? "gif" : "png" };
@@ -31270,14 +31741,14 @@ async function saveToAssetFile(client2, target, from, opts = {}) {
31270
31741
  let size;
31271
31742
  frames = [];
31272
31743
  for (const file of files) {
31273
- const bytes = await readFile41(file);
31744
+ const bytes = await readFile42(file);
31274
31745
  const { width, height } = readPng(bytes, file);
31275
31746
  if (size && size !== `${width}x${height}`) throw new Error(`${file} is ${width}x${height}, but the frames before it are ${size}; an animation's frames share one size`);
31276
31747
  size = `${width}x${height}`;
31277
31748
  frames.push({ base64: bytes.toString("base64"), format: "png" });
31278
31749
  }
31279
31750
  }
31280
- const undoDir = opts.undoDir ? path60.resolve(opts.undoDir) : saveUndoDir(target);
31751
+ const undoDir = opts.undoDir ? path62.resolve(opts.undoDir) : saveUndoDir(target);
31281
31752
  let res;
31282
31753
  try {
31283
31754
  res = await client2.saveToAsset({ target, image, frames, name: opts.name, description: opts.description });
@@ -31313,7 +31784,7 @@ async function saveToAssetFile(client2, target, from, opts = {}) {
31313
31784
 
31314
31785
  // src/cli/commands/asset.ts
31315
31786
  function loadKeys4(args) {
31316
- loadEnvFiles(path61.dirname(path61.resolve(args.manifest)));
31787
+ loadEnvFiles(path63.dirname(path63.resolve(args.manifest)));
31317
31788
  loadEnvFiles(process.cwd());
31318
31789
  }
31319
31790
  function kindOf(args) {
@@ -31434,7 +31905,7 @@ async function runAsset(args) {
31434
31905
  const res2 = await pullExpansionReview(clientFromEnv(), id, { out: args.out, force: args.force });
31435
31906
  if (args.json) emit(res2);
31436
31907
  else {
31437
- for (const file of res2.files) log(` wrote ${path61.join(args.out, `${file.direction}.png`)}${file.direction === res2.existingDirection ? " (your image, unchanged)" : ""}`);
31908
+ for (const file of res2.files) log(` wrote ${path63.join(args.out, `${file.direction}.png`)}${file.direction === res2.existingDirection ? " (your image, unchanged)" : ""}`);
31438
31909
  log(` keep them: pixelkiln asset expand --id ${id} --keep discard: pixelkiln asset expand --id ${id} --discard`);
31439
31910
  }
31440
31911
  return;
@@ -31479,7 +31950,7 @@ async function runTileImport(args, emit) {
31479
31950
  if (args.tileType) throw new UsageError("--tile-type belongs to --kind tiles; a tileset is a Wang sheet");
31480
31951
  const opts2 = { mode: mode2, tileSize, lowerDescription: args.lower, upperDescription: args.upper, transitionDescription: args.transition, name: args.name };
31481
31952
  if (args.dryRun) {
31482
- const metadata = imageMetadata(await readFile42(args.from));
31953
+ const metadata = imageMetadata(await readFile43(args.from));
31483
31954
  if (!metadata || metadata.format !== "png") throw new UsageError(`${args.from} is not a PNG`);
31484
31955
  const reading = await usage(() => chooseTilesetSheetReading(args.from, metadata.width, metadata.height, tileSize));
31485
31956
  log(` would import ${args.from} as a ${mode2} tileset of ${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"}); nothing sent`);
@@ -31518,7 +31989,7 @@ async function runSave(args, emit) {
31518
31989
  if (!args.from) throw new UsageError("asset save needs --from: a PNG, an animated GIF, or a directory of PNG frames");
31519
31990
  await usage(() => checkSaveTarget(target));
31520
31991
  const adding = target === "gallery:new";
31521
- const undoDir = args.out ? path61.resolve(args.out) : saveUndoDir(target);
31992
+ const undoDir = args.out ? path63.resolve(args.out) : saveUndoDir(target);
31522
31993
  if (adding) log(` add ${args.from} to your PixelLab gallery as a new image (free)`);
31523
31994
  else {
31524
31995
  log(` save ${args.from} over ${target} on PixelLab (free)`);
@@ -31541,21 +32012,21 @@ async function runSave(args, emit) {
31541
32012
  else {
31542
32013
  log(` ${res.target}: ${res.kind} saved, ${res.width}x${res.height}, ${res.frames} frame(s), ${res.changedPixels} pixel(s) changed`);
31543
32014
  for (const file of res.undo) log(` kept the old pixels: ${file}`);
31544
- if (res.undo.length) log(` undo: pixelkiln asset save --target ${res.target} --from ${res.undo.length === 1 ? res.undo[0] : path61.dirname(res.undo[0])} --yes`);
32015
+ if (res.undo.length) log(` undo: pixelkiln asset save --target ${res.target} --from ${res.undo.length === 1 ? res.undo[0] : path63.dirname(res.undo[0])} --yes`);
31545
32016
  }
31546
32017
  if (res.note) log(` ${res.note}`);
31547
32018
  if (res.maps) log(` ${res.maps}`);
31548
32019
  }
31549
32020
 
31550
32021
  // src/cli/commands/talk.ts
31551
- import { existsSync as existsSync50 } from "fs";
31552
- import { mkdir as mkdir24, readFile as readFile44, writeFile as writeFile29 } from "fs/promises";
31553
- import path63 from "path";
32022
+ import { existsSync as existsSync52 } from "fs";
32023
+ import { mkdir as mkdir24, readFile as readFile45, writeFile as writeFile29 } from "fs/promises";
32024
+ import path65 from "path";
31554
32025
 
31555
32026
  // src/pixellab-talk.ts
31556
- import { existsSync as existsSync49 } from "fs";
31557
- import { mkdir as mkdir23, readFile as readFile43, writeFile as writeFile28 } from "fs/promises";
31558
- import path62 from "path";
32027
+ import { existsSync as existsSync51 } from "fs";
32028
+ import { mkdir as mkdir23, readFile as readFile44, writeFile as writeFile28 } from "fs/promises";
32029
+ import path64 from "path";
31559
32030
  var TALK_MOODS = ["neutral", "happy", "angry", "sad", "surprised"];
31560
32031
  var VISEME_COUNTS = [3, 5, 7, 12];
31561
32032
  var VISEME_ENGINES = ["v3", "pixminimax"];
@@ -31566,7 +32037,7 @@ function visemeCost(engine, side, count) {
31566
32037
  return Math.ceil(forSeven * count / 7);
31567
32038
  }
31568
32039
  function talkOutputPaths(out) {
31569
- const base = path62.resolve(out.replace(/\.(png|json)$/i, "").replace(/\.(talk|visemes)$/i, ""));
32040
+ const base = path64.resolve(out.replace(/\.(png|json)$/i, "").replace(/\.(talk|visemes)$/i, ""));
31570
32041
  return { strip: `${base}.visemes.png`, record: `${base}.talk.json` };
31571
32042
  }
31572
32043
  function readPortrait(bytes, label) {
@@ -31608,14 +32079,14 @@ async function makeVisemes(client2, opts) {
31608
32079
  if (Boolean(opts.portrait) === Boolean(opts.characterId)) throw new Error("give a portrait file or a character id, not both");
31609
32080
  const paths = talkOutputPaths(opts.out);
31610
32081
  if (!opts.force) {
31611
- for (const file of [paths.strip, paths.record]) if (existsSync49(file)) throw new Error(`${file} already exists; pass --force to replace it`);
32082
+ for (const file of [paths.strip, paths.record]) if (existsSync51(file)) throw new Error(`${file} already exists; pass --force to replace it`);
31612
32083
  }
31613
32084
  const progress2 = opts.onProgress ?? (() => {
31614
32085
  });
31615
32086
  const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
31616
32087
  const interval = opts.intervalMs ?? 8e3;
31617
32088
  const timeout = opts.timeoutMs ?? 10 * 6e4;
31618
- const portrait = opts.portrait ? readPortrait(await readFile43(opts.portrait), opts.portrait) : void 0;
32089
+ const portrait = opts.portrait ? readPortrait(await readFile44(opts.portrait), opts.portrait) : void 0;
31619
32090
  const engine = opts.engine ?? "v3";
31620
32091
  const visemeCount = opts.visemeCount ?? 7;
31621
32092
  const submitted = await client2.createVocalAnimation({
@@ -31660,7 +32131,7 @@ async function makeVisemes(client2, opts) {
31660
32131
  throw new Error(`PixelLab vocal-animation job ${jobId} finished with no mouth positions and no spritesheet`);
31661
32132
  }
31662
32133
  const usage2 = (await client2.getBackgroundJob(jobId).catch(() => null))?.usage ?? job.usage ?? null;
31663
- await mkdir23(path62.dirname(paths.strip), { recursive: true });
32134
+ await mkdir23(path64.dirname(paths.strip), { recursive: true });
31664
32135
  await writeFile28(paths.strip, strip);
31665
32136
  const record = {
31666
32137
  version: 1,
@@ -31671,8 +32142,8 @@ async function makeVisemes(client2, opts) {
31671
32142
  visemeCount,
31672
32143
  visemeOrder,
31673
32144
  cell,
31674
- strip: path62.basename(paths.strip),
31675
- source: opts.portrait ? { portrait: path62.relative(path62.dirname(paths.record), path62.resolve(opts.portrait)).split(path62.sep).join("/") } : { characterId: opts.characterId },
32145
+ strip: path64.basename(paths.strip),
32146
+ source: opts.portrait ? { portrait: path64.relative(path64.dirname(paths.record), path64.resolve(opts.portrait)).split(path64.sep).join("/") } : { characterId: opts.characterId },
31676
32147
  ...job.moods_on_character ? { moodsOnCharacter: job.moods_on_character } : {},
31677
32148
  jobId,
31678
32149
  usage: usage2,
@@ -31685,17 +32156,17 @@ async function makeVisemes(client2, opts) {
31685
32156
  async function readTalkRecord(file) {
31686
32157
  let record;
31687
32158
  try {
31688
- record = JSON.parse(await readFile43(file, "utf8"));
32159
+ record = JSON.parse(await readFile44(file, "utf8"));
31689
32160
  } catch (error) {
31690
32161
  throw new Error(`${file} is not a readable .talk.json record: ${error instanceof Error ? error.message : String(error)}`);
31691
32162
  }
31692
32163
  if (record?.tool !== "vocal-animation" || !Array.isArray(record.visemeOrder) || !record.cell || !record.strip) {
31693
32164
  throw new Error(`${file} is not a .talk.json record from pixelkiln talk visemes`);
31694
32165
  }
31695
- const stripFile = path62.resolve(path62.dirname(path62.resolve(file)), record.strip);
31696
- if (!existsSync49(stripFile)) throw new Error(`${file} names ${record.strip}, which is missing beside it`);
32166
+ const stripFile = path64.resolve(path64.dirname(path64.resolve(file)), record.strip);
32167
+ if (!existsSync51(stripFile)) throw new Error(`${file} names ${record.strip}, which is missing beside it`);
31697
32168
  const row = Math.max(0, record.moodsOnCharacter?.indexOf(record.mood) ?? 0);
31698
- const cells = cutStrip(await readFile43(stripFile), record.visemeOrder.length, record.cell, row);
32169
+ const cells = cutStrip(await readFile44(stripFile), record.visemeOrder.length, record.cell, row);
31699
32170
  const visemes = Object.fromEntries(record.visemeOrder.map((id, index) => [id, { base64: cells[index].toString("base64"), format: "png" }]));
31700
32171
  return { record, visemes };
31701
32172
  }
@@ -31708,14 +32179,14 @@ function checkText(text) {
31708
32179
  async function makeTalkingGif(client2, text, source, opts) {
31709
32180
  if (Boolean(source.record) === Boolean(source.characterId)) throw new Error("give a .talk.json record or a character id, not both");
31710
32181
  if (source.record && source.mood) throw new Error("a record holds one expression; --mood picks among a character's stored ones");
31711
- const out = path62.extname(opts.out) ? path62.resolve(opts.out) : path62.resolve(`${opts.out}.gif`);
31712
- if (existsSync49(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
32182
+ const out = path64.extname(opts.out) ? path64.resolve(opts.out) : path64.resolve(`${opts.out}.gif`);
32183
+ if (existsSync51(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
31713
32184
  const line = checkText(text);
31714
32185
  const visemes = source.record ? (await readTalkRecord(source.record)).visemes : void 0;
31715
32186
  const res = await client2.createTalkingGif({ text: line, visemes, characterId: source.characterId, mood: source.mood, frameMs: opts.frameMs, holdMs: opts.holdMs });
31716
32187
  const bytes = Buffer.from(res.gif_base64, "base64");
31717
32188
  if (bytes.subarray(0, 4).toString("ascii") !== "GIF8") throw new Error(`PixelLab's talking GIF was not a GIF (${bytes.length} bytes)`);
31718
- await mkdir23(path62.dirname(out), { recursive: true });
32189
+ await mkdir23(path64.dirname(out), { recursive: true });
31719
32190
  await writeFile28(out, bytes);
31720
32191
  return { out, frames: res.frames, durationMs: res.duration_ms, frameMs: res.frame_ms, holdMs: res.hold_ms, width: res.width, height: res.height, bytes: bytes.length };
31721
32192
  }
@@ -31748,7 +32219,7 @@ async function planLipSync(client2, text, source, opts = {}) {
31748
32219
 
31749
32220
  // src/cli/commands/talk.ts
31750
32221
  function loadKeys5(args) {
31751
- loadEnvFiles(path63.dirname(path63.resolve(args.manifest)));
32222
+ loadEnvFiles(path65.dirname(path65.resolve(args.manifest)));
31752
32223
  loadEnvFiles(process.cwd());
31753
32224
  }
31754
32225
  function moodOf(args) {
@@ -31770,7 +32241,7 @@ function textOf(args) {
31770
32241
  }
31771
32242
  function sourceOf(args) {
31772
32243
  if (args.from && args.id) throw new UsageError("pass --from <record.talk.json> or --id <character id>, not both");
31773
- if (args.from && !existsSync50(args.from)) throw new UsageError(`${args.from} does not exist; --from is the .talk.json record talk visemes wrote`);
32244
+ if (args.from && !existsSync52(args.from)) throw new UsageError(`${args.from} does not exist; --from is the .talk.json record talk visemes wrote`);
31774
32245
  return { record: args.from, characterId: args.id };
31775
32246
  }
31776
32247
  async function runVisemes(args) {
@@ -31786,9 +32257,9 @@ async function runVisemes(args) {
31786
32257
  const paths = talkOutputPaths(args.out);
31787
32258
  let side = "unknown";
31788
32259
  if (args.from) {
31789
- if (!existsSync50(args.from)) throw new UsageError(`${args.from} does not exist`);
32260
+ if (!existsSync52(args.from)) throw new UsageError(`${args.from} does not exist`);
31790
32261
  try {
31791
- side = readPortrait(await readFile44(args.from), args.from).side;
32262
+ side = readPortrait(await readFile45(args.from), args.from).side;
31792
32263
  } catch (error) {
31793
32264
  throw new UsageError(error instanceof Error ? error.message : String(error));
31794
32265
  }
@@ -31871,9 +32342,9 @@ async function runPlan2(args) {
31871
32342
  log(json.trimEnd());
31872
32343
  return;
31873
32344
  }
31874
- const out = path63.extname(args.out) ? path63.resolve(args.out) : path63.resolve(`${args.out}.json`);
31875
- if (existsSync50(out) && !args.force) throw new Error(`${out} already exists; pass --force to replace it`);
31876
- await mkdir24(path63.dirname(out), { recursive: true });
32345
+ const out = path65.extname(args.out) ? path65.resolve(args.out) : path65.resolve(`${args.out}.json`);
32346
+ if (existsSync52(out) && !args.force) throw new Error(`${out} already exists; pass --force to replace it`);
32347
+ await mkdir24(path65.dirname(out), { recursive: true });
31877
32348
  await writeFile29(out, json);
31878
32349
  if (args.json) log(json.trimEnd());
31879
32350
  else log(` wrote ${out} (${plan.frames.length} frames, ${(plan.totalMs / 1e3).toFixed(2)} s, free)`);
@@ -31885,19 +32356,19 @@ async function runTalk(args) {
31885
32356
  }
31886
32357
 
31887
32358
  // src/cli/commands/quality.ts
31888
- import path65 from "path";
31889
- import { readFile as readFile46 } from "fs/promises";
32359
+ import path67 from "path";
32360
+ import { readFile as readFile47 } from "fs/promises";
31890
32361
 
31891
32362
  // src/pipeline/quality-regression.ts
31892
- import path64 from "path";
31893
- import { existsSync as existsSync51 } from "fs";
31894
- import { readFile as readFile45 } from "fs/promises";
32363
+ import path66 from "path";
32364
+ import { existsSync as existsSync53 } from "fs";
32365
+ import { readFile as readFile46 } from "fs/promises";
31895
32366
  import { z as z16 } from "zod";
31896
32367
  var SHA256_RE = /^[0-9a-f]{64}$/;
31897
32368
  var HEX_RE = /^#[0-9a-f]{6}$/;
31898
32369
  var MAX_REDMEAN_DISTANCE = 765;
31899
32370
  var QualityPathSchema = z16.string().min(1).refine(
31900
- (value) => !path64.posix.isAbsolute(value) && !value.includes("\\"),
32371
+ (value) => !path66.posix.isAbsolute(value) && !value.includes("\\"),
31901
32372
  "expected a portable relative path"
31902
32373
  );
31903
32374
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -32044,10 +32515,10 @@ function measureDecodedImageQuality(png, digest2) {
32044
32515
  };
32045
32516
  }
32046
32517
  async function measureImageQuality(file) {
32047
- const absolute = path64.resolve(file);
32518
+ const absolute = path66.resolve(file);
32048
32519
  let bytes;
32049
32520
  try {
32050
- bytes = await readFile45(absolute);
32521
+ bytes = await readFile46(absolute);
32051
32522
  } catch (error) {
32052
32523
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
32053
32524
  }
@@ -32066,11 +32537,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
32066
32537
  }
32067
32538
  const ids = parsed.data.map((entry) => entry.id);
32068
32539
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
32069
- const root = path64.dirname(path64.resolve(inputsFilePath));
32540
+ const root = path66.dirname(path66.resolve(inputsFilePath));
32070
32541
  return parsed.data.map((entry) => ({
32071
32542
  id: entry.id,
32072
- file: path64.resolve(root, entry.path),
32073
- ...entry.record ? { record: path64.resolve(root, entry.record) } : {},
32543
+ file: path66.resolve(root, entry.path),
32544
+ ...entry.record ? { record: path66.resolve(root, entry.record) } : {},
32074
32545
  tolerances: QualityToleranceSchema.parse({
32075
32546
  ...DEFAULT_QUALITY_TOLERANCES,
32076
32547
  ...entry.tolerances
@@ -32078,7 +32549,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
32078
32549
  }));
32079
32550
  }
32080
32551
  function portableRelative2(from, to) {
32081
- return path64.relative(from, path64.resolve(to)).split(path64.sep).join("/") || ".";
32552
+ return path66.relative(from, path66.resolve(to)).split(path66.sep).join("/") || ".";
32082
32553
  }
32083
32554
  async function verifyRecordForImage(recordPath, imagePath) {
32084
32555
  const verification = await verifyArtifactBundle(recordPath);
@@ -32093,20 +32564,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
32093
32564
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
32094
32565
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
32095
32566
  }
32096
- const outputs = record.outputs.map((output) => path64.resolve(path64.dirname(recordPath), output.path));
32097
- if (!outputs.includes(path64.resolve(imagePath))) {
32567
+ const outputs = record.outputs.map((output) => path66.resolve(path66.dirname(recordPath), output.path));
32568
+ if (!outputs.includes(path66.resolve(imagePath))) {
32098
32569
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
32099
32570
  }
32100
32571
  }
32101
32572
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
32102
32573
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
32103
- const absolute = path64.resolve(baselinePath);
32574
+ const absolute = path66.resolve(baselinePath);
32104
32575
  for (const input of inputs) {
32105
- if (path64.resolve(input.file) === absolute || input.record && path64.resolve(input.record) === absolute) {
32576
+ if (path66.resolve(input.file) === absolute || input.record && path66.resolve(input.record) === absolute) {
32106
32577
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
32107
32578
  }
32108
32579
  }
32109
- const root = path64.dirname(absolute);
32580
+ const root = path66.dirname(absolute);
32110
32581
  const cases = [];
32111
32582
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
32112
32583
  const expected = await measureImageQuality(input.file);
@@ -32133,8 +32604,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
32133
32604
  cases
32134
32605
  });
32135
32606
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
32136
- if (existsSync51(absolute) && !options.force) {
32137
- const current = await readFile45(absolute);
32607
+ if (existsSync53(absolute) && !options.force) {
32608
+ const current = await readFile46(absolute);
32138
32609
  if (!current.equals(data)) {
32139
32610
  throw new OverwriteRefusedError(
32140
32611
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -32146,13 +32617,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
32146
32617
  return { baseline, path: absolute, changed: result.changed.length > 0 };
32147
32618
  }
32148
32619
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
32149
- const absolute = path64.resolve(baselinePath);
32150
- if (!existsSync51(absolute)) {
32620
+ const absolute = path66.resolve(baselinePath);
32621
+ if (!existsSync53(absolute)) {
32151
32622
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
32152
32623
  }
32153
32624
  let raw;
32154
32625
  try {
32155
- raw = JSON.parse(await readFile45(absolute, "utf8"));
32626
+ raw = JSON.parse(await readFile46(absolute, "utf8"));
32156
32627
  } catch (error) {
32157
32628
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
32158
32629
  }
@@ -32162,12 +32633,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
32162
32633
  if (unknown.length) {
32163
32634
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
32164
32635
  }
32165
- const root = path64.dirname(absolute);
32636
+ const root = path66.dirname(absolute);
32166
32637
  const cases = [...raw.cases];
32167
32638
  const report = [];
32168
32639
  for (const id of only) {
32169
32640
  const input = byId.get(id);
32170
- if (path64.resolve(input.file) === absolute || input.record && path64.resolve(input.record) === absolute) {
32641
+ if (path66.resolve(input.file) === absolute || input.record && path66.resolve(input.record) === absolute) {
32171
32642
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
32172
32643
  }
32173
32644
  const expected = await measureImageQuality(input.file);
@@ -32197,16 +32668,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
32197
32668
  }
32198
32669
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
32199
32670
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
32200
- const current = await readFile45(absolute);
32671
+ const current = await readFile46(absolute);
32201
32672
  const changed = !current.equals(data);
32202
32673
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
32203
32674
  return { baseline, path: absolute, changed, cases: report };
32204
32675
  }
32205
32676
  async function readQualityBaseline(baselinePath) {
32206
- const absolute = path64.resolve(baselinePath);
32677
+ const absolute = path66.resolve(baselinePath);
32207
32678
  let raw;
32208
32679
  try {
32209
- raw = JSON.parse(await readFile45(absolute, "utf8"));
32680
+ raw = JSON.parse(await readFile46(absolute, "utf8"));
32210
32681
  } catch (error) {
32211
32682
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
32212
32683
  }
@@ -32228,7 +32699,7 @@ async function readQualityBaseline(baselinePath) {
32228
32699
  throw new Error(
32229
32700
  `Invalid quality baseline ${absolute}:
32230
32701
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
32231
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path64.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
32702
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path66.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
32232
32703
  );
32233
32704
  }
32234
32705
  return parsed.data;
@@ -32290,12 +32761,12 @@ function regressionViolations(expected, actual, tolerances) {
32290
32761
  return { violations, warnings };
32291
32762
  }
32292
32763
  async function checkQualityBaseline(baselinePath) {
32293
- const absolute = path64.resolve(baselinePath);
32764
+ const absolute = path66.resolve(baselinePath);
32294
32765
  const baseline = await readQualityBaseline(absolute);
32295
- const root = path64.dirname(absolute);
32766
+ const root = path66.dirname(absolute);
32296
32767
  const cases = [];
32297
32768
  for (const entry of baseline.cases) {
32298
- const file = path64.resolve(root, entry.file);
32769
+ const file = path66.resolve(root, entry.file);
32299
32770
  let actual = null;
32300
32771
  const violations = [];
32301
32772
  const warnings = [];
@@ -32308,7 +32779,7 @@ async function checkQualityBaseline(baselinePath) {
32308
32779
  violations.push(message4(error));
32309
32780
  }
32310
32781
  if (entry.record) {
32311
- const recordPath = path64.resolve(root, entry.record.path);
32782
+ const recordPath = path66.resolve(root, entry.record.path);
32312
32783
  try {
32313
32784
  const recordHash = await sha256File(recordPath);
32314
32785
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -32350,15 +32821,15 @@ async function runQuality(args) {
32350
32821
  if (!args.out) throw new Error("quality snapshot needs --out <pixelkiln.quality.json>.");
32351
32822
  let raw;
32352
32823
  try {
32353
- raw = JSON.parse(await readFile46(path65.resolve(args.inputs), "utf8"));
32824
+ raw = JSON.parse(await readFile47(path67.resolve(args.inputs), "utf8"));
32354
32825
  } catch (error) {
32355
32826
  throw new Error(
32356
- `Could not read quality inputs ${path65.resolve(args.inputs)}: ${error instanceof Error ? error.message : String(error)}`,
32827
+ `Could not read quality inputs ${path67.resolve(args.inputs)}: ${error instanceof Error ? error.message : String(error)}`,
32357
32828
  { cause: error }
32358
32829
  );
32359
32830
  }
32360
32831
  const inputs = resolveQualityInputs(raw, args.inputs);
32361
- if (path65.resolve(args.inputs) === path65.resolve(args.out)) {
32832
+ if (path67.resolve(args.inputs) === path67.resolve(args.out)) {
32362
32833
  throw new Error("quality snapshot --out must not overwrite its --inputs file.");
32363
32834
  }
32364
32835
  if (args.assets.length) {
@@ -32373,7 +32844,7 @@ async function runQuality(args) {
32373
32844
  }
32374
32845
  log(
32375
32846
  `
32376
- ${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${path65.relative(process.cwd(), result2.path)}; other cases left as they were.`
32847
+ ${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${path67.relative(process.cwd(), result2.path)}; other cases left as they were.`
32377
32848
  );
32378
32849
  return;
32379
32850
  }
@@ -32388,7 +32859,7 @@ async function runQuality(args) {
32388
32859
  }, null, 2));
32389
32860
  } else {
32390
32861
  log(
32391
- ` ${result.changed ? "wrote" : "unchanged"} ${path65.relative(process.cwd(), result.path)} (${result.baseline.cases.length} case(s))`
32862
+ ` ${result.changed ? "wrote" : "unchanged"} ${path67.relative(process.cwd(), result.path)} (${result.baseline.cases.length} case(s))`
32392
32863
  );
32393
32864
  log(` Review the tolerances, commit the baseline, then run quality check in CI.`);
32394
32865
  }
@@ -32414,12 +32885,12 @@ async function runQuality(args) {
32414
32885
  }
32415
32886
 
32416
32887
  // src/cli/commands/recipe.ts
32417
- import path67 from "path";
32888
+ import path69 from "path";
32418
32889
 
32419
32890
  // src/recipes.ts
32420
- import path66 from "path";
32421
- import { existsSync as existsSync52 } from "fs";
32422
- import { readdir as readdir6, readFile as readFile47 } from "fs/promises";
32891
+ import path68 from "path";
32892
+ import { existsSync as existsSync54 } from "fs";
32893
+ import { readdir as readdir6, readFile as readFile48 } from "fs/promises";
32423
32894
  import { fileURLToPath as fileURLToPath2 } from "url";
32424
32895
  import { z as z17 } from "zod";
32425
32896
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
@@ -32428,7 +32899,7 @@ var VERSION_RE = /^\d+\.\d+\.\d+$/;
32428
32899
  var RECIPE_FILE = "pixelkiln.recipe.json";
32429
32900
  var RECIPE_DIR_TOKEN = "{{recipeDir}}";
32430
32901
  var PortablePathSchema = z17.string().min(1).refine((value) => {
32431
- if (value.includes("\\") || path66.posix.isAbsolute(value)) return false;
32902
+ if (value.includes("\\") || path68.posix.isAbsolute(value)) return false;
32432
32903
  const parts = value.split("/");
32433
32904
  return !parts.includes("") && !parts.includes(".") && !parts.includes("..");
32434
32905
  }, "expected a portable relative path without '.', '..', or backslashes");
@@ -32604,10 +33075,10 @@ function message5(error) {
32604
33075
  return error instanceof Error ? error.message : String(error);
32605
33076
  }
32606
33077
  async function readRecipeFile(recipePath, bundled) {
32607
- const absolute = path66.resolve(recipePath);
33078
+ const absolute = path68.resolve(recipePath);
32608
33079
  let raw;
32609
33080
  try {
32610
- raw = JSON.parse(await readFile47(absolute, "utf8"));
33081
+ raw = JSON.parse(await readFile48(absolute, "utf8"));
32611
33082
  } catch (error) {
32612
33083
  throw new Error(`Could not read recipe ${absolute}: ${message5(error)}`, { cause: error });
32613
33084
  }
@@ -32618,13 +33089,13 @@ async function readRecipeFile(recipePath, bundled) {
32618
33089
  ` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
32619
33090
  );
32620
33091
  }
32621
- return { recipe: parsed.data, authored: raw, path: absolute, dir: path66.dirname(absolute), bundled };
33092
+ return { recipe: parsed.data, authored: raw, path: absolute, dir: path68.dirname(absolute), bundled };
32622
33093
  }
32623
33094
  async function walkRecipeFiles(root) {
32624
- if (!existsSync52(root)) return [];
33095
+ if (!existsSync54(root)) return [];
32625
33096
  const out = [];
32626
33097
  for (const entry of await readdir6(root, { withFileTypes: true })) {
32627
- const resolved = path66.join(root, entry.name);
33098
+ const resolved = path68.join(root, entry.name);
32628
33099
  if (entry.isDirectory()) out.push(...await walkRecipeFiles(resolved));
32629
33100
  else if (entry.isFile() && entry.name === RECIPE_FILE) out.push(resolved);
32630
33101
  }
@@ -32635,7 +33106,7 @@ function bundledRecipeRoot() {
32635
33106
  }
32636
33107
  async function listBundledRecipes(root = bundledRecipeRoot()) {
32637
33108
  const recipes = await Promise.all(
32638
- (await walkRecipeFiles(path66.resolve(root))).map((file) => readRecipeFile(file, true))
33109
+ (await walkRecipeFiles(path68.resolve(root))).map((file) => readRecipeFile(file, true))
32639
33110
  );
32640
33111
  return recipes.sort(
32641
33112
  (a, b) => a.recipe.id.localeCompare(b.recipe.id) || compareVersions(b.recipe.version, a.recipe.version)
@@ -32658,9 +33129,9 @@ function parseSelector(selector) {
32658
33129
  return { id: match[1], version: match[2] };
32659
33130
  }
32660
33131
  async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
32661
- const local = path66.resolve(target);
32662
- if (existsSync52(local)) {
32663
- const recipePath = path66.basename(local) === RECIPE_FILE ? local : path66.join(local, RECIPE_FILE);
33132
+ const local = path68.resolve(target);
33133
+ if (existsSync54(local)) {
33134
+ const recipePath = path68.basename(local) === RECIPE_FILE ? local : path68.join(local, RECIPE_FILE);
32664
33135
  return readRecipeFile(recipePath, false);
32665
33136
  }
32666
33137
  if (target.startsWith(".") || target.startsWith("/") || target.includes("\\")) {
@@ -32674,8 +33145,8 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
32674
33145
  return matches[0];
32675
33146
  }
32676
33147
  async function verifyFile(root, file) {
32677
- const absolute = path66.resolve(root, ...file.path.split("/"));
32678
- if (!existsSync52(absolute)) {
33148
+ const absolute = path68.resolve(root, ...file.path.split("/"));
33149
+ if (!existsSync54(absolute)) {
32679
33150
  return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
32680
33151
  }
32681
33152
  const actualSha256 = await sha256File(absolute);
@@ -32690,7 +33161,7 @@ async function verifyRecipe(target, options = {}) {
32690
33161
  const loaded = await resolveRecipe(target, options.bundledRoot);
32691
33162
  const actualIntegrity = recipeDigest(loaded.authored);
32692
33163
  const files = await Promise.all(loaded.recipe.files.map((file) => verifyFile(loaded.dir, file)));
32693
- const modelRoot = options.modelRoot ? path66.resolve(options.modelRoot) : null;
33164
+ const modelRoot = options.modelRoot ? path68.resolve(options.modelRoot) : null;
32694
33165
  const models = modelRoot ? await Promise.all(loaded.recipe.models.map(async (model) => ({
32695
33166
  ...await verifyFile(modelRoot, model),
32696
33167
  source: model.source,
@@ -32724,7 +33195,7 @@ async function verifyRecipe(target, options = {}) {
32724
33195
  };
32725
33196
  }
32726
33197
  function renderStyle(style, destination, cwd) {
32727
- const portableDir = path66.relative(cwd, destination).split(path66.sep).join("/") || ".";
33198
+ const portableDir = path68.relative(cwd, destination).split(path68.sep).join("/") || ".";
32728
33199
  const replace = (value) => {
32729
33200
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
32730
33201
  if (Array.isArray(value)) return value.map(replace);
@@ -32736,25 +33207,25 @@ function renderStyle(style, destination, cwd) {
32736
33207
  return replace(style);
32737
33208
  }
32738
33209
  async function installRecipe(target, options = {}) {
32739
- const cwd = path66.resolve(options.cwd ?? process.cwd());
33210
+ const cwd = path68.resolve(options.cwd ?? process.cwd());
32740
33211
  const loaded = await resolveRecipe(target, options.bundledRoot);
32741
33212
  const verification = await verifyRecipe(loaded.path);
32742
33213
  if (!verification.ok) {
32743
33214
  throw new Error(`Recipe ${loaded.recipe.id}@${loaded.recipe.version} failed integrity verification.`);
32744
33215
  }
32745
- const destination = options.out ? path66.resolve(cwd, options.out) : path66.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
33216
+ const destination = options.out ? path68.resolve(cwd, options.out) : path68.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
32746
33217
  const sources = [
32747
33218
  { path: RECIPE_FILE, source: loaded.path },
32748
- ...loaded.recipe.files.map((file) => ({ path: file.path, source: path66.join(loaded.dir, ...file.path.split("/")) }))
33219
+ ...loaded.recipe.files.map((file) => ({ path: file.path, source: path68.join(loaded.dir, ...file.path.split("/")) }))
32749
33220
  ];
32750
33221
  const files = await Promise.all(sources.map(async (file) => ({
32751
- path: path66.join(destination, ...file.path.split("/")),
32752
- data: await readFile47(file.source)
33222
+ path: path68.join(destination, ...file.path.split("/")),
33223
+ data: await readFile48(file.source)
32753
33224
  })));
32754
33225
  if (!options.force) {
32755
33226
  for (const file of files) {
32756
- if (!existsSync52(file.path)) continue;
32757
- const current = await readFile47(file.path);
33227
+ if (!existsSync54(file.path)) continue;
33228
+ const current = await readFile48(file.path);
32758
33229
  if (!current.equals(file.data)) {
32759
33230
  throw new OverwriteRefusedError(
32760
33231
  `Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
@@ -32848,14 +33319,14 @@ async function runRecipe(args) {
32848
33319
  }, null, 2));
32849
33320
  } else {
32850
33321
  log(` installed ${result.recipe.id}@${result.recipe.version}`);
32851
- log(` ${path67.relative(process.cwd(), result.destination) || "."}`);
33322
+ log(` ${path69.relative(process.cwd(), result.destination) || "."}`);
32852
33323
  log(`
32853
33324
  Add this entry under your manifest's styles object:`);
32854
33325
  log(JSON.stringify({ [result.styleId]: result.style }, null, 2));
32855
33326
  if (result.recipe.models.length) {
32856
33327
  log(`
32857
33328
  Models are not downloaded automatically. Verify them with:`);
32858
- log(` pixelkiln recipe verify ${path67.relative(process.cwd(), result.destination)} --model-root <ComfyUI/models>`);
33329
+ log(` pixelkiln recipe verify ${path69.relative(process.cwd(), result.destination)} --model-root <ComfyUI/models>`);
32859
33330
  }
32860
33331
  }
32861
33332
  return;
@@ -32863,7 +33334,7 @@ async function runRecipe(args) {
32863
33334
  }
32864
33335
 
32865
33336
  // src/cli/commands/refine.ts
32866
- import path68 from "path";
33337
+ import path70 from "path";
32867
33338
  async function runRefine(args) {
32868
33339
  if (args.from || args.subcommand === "approve") {
32869
33340
  if (!args.from) {
@@ -32893,12 +33364,12 @@ async function runRefine(args) {
32893
33364
  ` recovered ${result3.detection.columns}x${result3.detection.rows} native grid (${result3.detection.confidence}: ${result3.detection.consensus})`
32894
33365
  );
32895
33366
  log(` enforced ${result3.palette.length}-color palette without dithering`);
32896
- log(` wrote ${path68.relative(process.cwd(), result3.output)}`);
32897
- log(` quality record: ${path68.relative(process.cwd(), result3.record)}`);
33367
+ log(` wrote ${path70.relative(process.cwd(), result3.output)}`);
33368
+ log(` quality record: ${path70.relative(process.cwd(), result3.record)}`);
32898
33369
  log(`
32899
33370
  Automated checks passed. Human 1\xD7 review is still required:`);
32900
33371
  log(
32901
- ` pixelkiln refine approve --from ${path68.relative(process.cwd(), result3.record)} --reviewer "Your Name"`
33372
+ ` pixelkiln refine approve --from ${path70.relative(process.cwd(), result3.record)} --reviewer "Your Name"`
32902
33373
  );
32903
33374
  }
32904
33375
  return;
@@ -32926,7 +33397,7 @@ async function runRefine(args) {
32926
33397
  if (args.json) log(JSON.stringify(result3, null, 2));
32927
33398
  else {
32928
33399
  log(
32929
- result3.options.frameSet ? ` approved ${result3.outputs.length} frames in ${path68.relative(process.cwd(), result3.record)} by ${args.reviewer.trim()}` : ` approved ${path68.relative(process.cwd(), result3.output)} by ${args.reviewer.trim()}`
33400
+ result3.options.frameSet ? ` approved ${result3.outputs.length} frames in ${path70.relative(process.cwd(), result3.record)} by ${args.reviewer.trim()}` : ` approved ${path70.relative(process.cwd(), result3.output)} by ${args.reviewer.trim()}`
32930
33401
  );
32931
33402
  }
32932
33403
  return;
@@ -32935,7 +33406,7 @@ async function runRefine(args) {
32935
33406
  if (args.json) {
32936
33407
  log(JSON.stringify(result2, null, 2));
32937
33408
  } else {
32938
- log(` ${result2.safe ? "release-ready" : "not release-ready"}: ${path68.relative(process.cwd(), result2.output || result2.record)}`);
33409
+ log(` ${result2.safe ? "release-ready" : "not release-ready"}: ${path70.relative(process.cwd(), result2.output || result2.record)}`);
32939
33410
  for (const reason of result2.reasons) log(` ${reason}`);
32940
33411
  }
32941
33412
  if (!result2.safe) process.exitCode = 1;
@@ -32981,7 +33452,7 @@ async function runRefine(args) {
32981
33452
  log(` ${item.state.padEnd(16)} ${item.key} ${item.reason}`);
32982
33453
  if (item.state === "needs-approval") {
32983
33454
  log(
32984
- ` pixelkiln refine approve --from ${path68.relative(process.cwd(), item.record)} --reviewer "Your Name"`
33455
+ ` pixelkiln refine approve --from ${path70.relative(process.cwd(), item.record)} --reviewer "Your Name"`
32985
33456
  );
32986
33457
  }
32987
33458
  }
@@ -32992,7 +33463,7 @@ async function runRefine(args) {
32992
33463
  }
32993
33464
 
32994
33465
  // src/cli/commands/anchors.ts
32995
- import path69 from "path";
33466
+ import path71 from "path";
32996
33467
  async function runAnchors(args) {
32997
33468
  const target = args.target;
32998
33469
  const { specs, lock } = await openProject2(args);
@@ -33013,7 +33484,7 @@ async function runAnchors(args) {
33013
33484
  dryRun: args.dryRun,
33014
33485
  onProgress: log
33015
33486
  });
33016
- const file = path69.relative(spec.root, result.file) || result.file;
33487
+ const file = path71.relative(spec.root, result.file) || result.file;
33017
33488
  if (args.dryRun) {
33018
33489
  log(` ${result.estimated} frame${result.estimated === 1 ? "" : "s"} to estimate (about ${cost(result.estimated)}), ${result.current} already current`);
33019
33490
  } else if (result.estimated) {
@@ -33025,12 +33496,12 @@ async function runAnchors(args) {
33025
33496
  }
33026
33497
 
33027
33498
  // src/cli/commands/redraw.ts
33028
- import path71 from "path";
33499
+ import path73 from "path";
33029
33500
 
33030
33501
  // src/pipeline/redraw.ts
33031
- import { existsSync as existsSync53 } from "fs";
33032
- import { mkdir as mkdir25, readFile as readFile48, rename as rename14, writeFile as writeFile30 } from "fs/promises";
33033
- import path70 from "path";
33502
+ import { existsSync as existsSync55 } from "fs";
33503
+ import { mkdir as mkdir25, readFile as readFile49, rename as rename14, writeFile as writeFile30 } from "fs/promises";
33504
+ import path72 from "path";
33034
33505
  function redrawRoles(spec, lock) {
33035
33506
  return (lock.entries[lockKey(spec.styleId, spec.assetId)]?.outputs ?? []).map((output) => output.role ?? "");
33036
33507
  }
@@ -33072,7 +33543,7 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
33072
33543
  const still = source.spec.character?.kind !== "animation";
33073
33544
  for (const [index, output] of sourceEntry.outputs.entries()) {
33074
33545
  if (!still && !owners.includes(source.assetId)) continue;
33075
- const png = await readFile48(currentEntryOutputPath(sourceEntry, source.spec, index));
33546
+ const png = await readFile49(currentEntryOutputPath(sourceEntry, source.spec, index));
33076
33547
  if (still) stills.push(png);
33077
33548
  if (!owners.includes(source.assetId)) continue;
33078
33549
  const role = output.role ?? String(index).padStart(2, "0");
@@ -33106,23 +33577,23 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
33106
33577
  continue;
33107
33578
  }
33108
33579
  const file = at2 >= 0 ? currentEntryOutputPath(entry, spec, at2) : null;
33109
- if (!file || !existsSync53(file)) {
33580
+ if (!file || !existsSync55(file)) {
33110
33581
  layers.push(null);
33111
33582
  continue;
33112
33583
  }
33113
33584
  const pair = offset?.per && offset.per[source.assetId] || offset;
33114
- const png = await readFile48(file);
33585
+ const png = await readFile49(file);
33115
33586
  layers.push(pair ? shiftPixels(png, -pair.x, -pair.y).png : png);
33116
33587
  }
33117
33588
  const prepared = redrawSheet(built, layers, redraw);
33118
33589
  const size = decodePng(prepared.keyed);
33119
33590
  const cost = proTierCost(size.width, size.height);
33120
- const workDir = path70.join(layerWorkDir(spec), "redraw");
33591
+ const workDir = path72.join(layerWorkDir(spec), "redraw");
33121
33592
  const result = { roles, guides, sheet: { width: size.width, height: size.height }, cost, billed: null, written: [], workDir };
33122
33593
  if (opts.dryRun) return result;
33123
33594
  await mkdir25(workDir, { recursive: true });
33124
- await writeFile30(path70.join(workDir, "keyed.png"), prepared.keyed);
33125
- await writeFile30(path70.join(workDir, "mask.png"), prepared.mask);
33595
+ await writeFile30(path72.join(workDir, "keyed.png"), prepared.keyed);
33596
+ await writeFile30(path72.join(workDir, "mask.png"), prepared.mask);
33126
33597
  const count = roles.length;
33127
33598
  const description = `${spec.prompt}. Every figure but ${count === 1 ? "one" : count} already wears it. Dress the unfinished figure${count === 1 ? "" : "s"} in exactly the same thing, the same colours and details, seen from the side ${count === 1 ? "that figure faces" : "each of those figures faces"}.`;
33128
33599
  const jobId = await painter.paintSheet({ description, keyed: prepared.keyed, mask: prepared.mask, seed: opts.seed ?? spec.seed });
@@ -33140,13 +33611,13 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
33140
33611
  if (Date.now() > deadline) throw new Error(`${label}: redraw job ${jobId} did not finish in time; nothing was changed`);
33141
33612
  await new Promise((resolve) => setTimeout(resolve, opts.pollMs ?? 3e3));
33142
33613
  }
33143
- await writeFile30(path70.join(workDir, "result.png"), painted);
33614
+ await writeFile30(path72.join(workDir, "result.png"), painted);
33144
33615
  const returned = decodePng(painted);
33145
33616
  if (returned.width !== size.width || returned.height !== size.height) {
33146
33617
  throw new Error(`${label}: redraw job ${jobId} returned a ${returned.width}x${returned.height} image for a ${size.width}x${size.height} sheet`);
33147
33618
  }
33148
33619
  const cut = cutLayerFrames(painted, { keyed: prepared.keyed, mask: prepared.mask, frames: built.frames }, { key: layer.key, region: layer.region });
33149
- const cacheDir = path70.resolve(opts.cacheDir ?? path70.join(path70.dirname(opts.lockPath), ".pixelkiln", "cache"));
33620
+ const cacheDir = path72.resolve(opts.cacheDir ?? path72.join(path72.dirname(opts.lockPath), ".pixelkiln", "cache"));
33150
33621
  const outputs = [...entry.outputs];
33151
33622
  const renames = [];
33152
33623
  for (const [index, at2] of targets) {
@@ -33155,7 +33626,7 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
33155
33626
  const empty = !decodePng(raw).pixels.some((value, i) => i % 4 === 3 && value > 0);
33156
33627
  if (empty) throw new Error(`${label}: the redraw of ${role} came back with nothing drawn; nothing was changed. Run it again, or with another --seed`);
33157
33628
  const target = currentEntryOutputPath(entry, spec, at2);
33158
- if (existsSync53(target)) await cacheMedia(cacheDir, await readFile48(target), MediaType.PNG);
33629
+ if (existsSync55(target)) await cacheMedia(cacheDir, await readFile49(target), MediaType.PNG);
33159
33630
  await cacheMedia(cacheDir, raw, MediaType.PNG);
33160
33631
  const processed = applyPostprocess(raw, MediaType.PNG, entry.postprocess, [], role);
33161
33632
  await cacheMedia(cacheDir, processed.bytes, MediaType.PNG);
@@ -33204,7 +33675,7 @@ async function runRedraw(args) {
33204
33675
  const painter = args.dryRun ? { paintSheet: never, paintedSheet: never } : new PixelLabProvider(clientFromEnv());
33205
33676
  const result = await redrawLayerFrames(spec, project2.lock, painter, {
33206
33677
  frames: args.redrawFrames,
33207
- lockPath: path71.resolve(args.lock),
33678
+ lockPath: path73.resolve(args.lock),
33208
33679
  seed: args.seed,
33209
33680
  dryRun: args.dryRun,
33210
33681
  onProgress: log
@@ -33215,16 +33686,16 @@ async function runRedraw(args) {
33215
33686
  log(` would redraw ${frames} (${result.roles.join(", ")}) beside ${result.guides} dressed, on a ${sheet} sheet: about ${result.cost} generations`);
33216
33687
  return;
33217
33688
  }
33218
- for (const file of result.written) log(` wrote ${path71.relative(process.cwd(), file)}`);
33689
+ for (const file of result.written) log(` wrote ${path73.relative(process.cwd(), file)}`);
33219
33690
  const billed = result.billed ? `${result.billed.amount} ${result.billed.unit} billed` : `about ${result.cost} generations`;
33220
- log(` redrew ${frames} of ${target} (${billed}); the sheet and result are in ${path71.relative(process.cwd(), result.workDir)}`);
33691
+ log(` redrew ${frames} of ${target} (${billed}); the sheet and result are in ${path73.relative(process.cwd(), result.workDir)}`);
33221
33692
  log(` look at ${result.written.length === 1 ? "it" : "them"}, then run pixelkiln gen to rebuild anything made from this layer`);
33222
33693
  }
33223
33694
 
33224
33695
  // src/cli/commands/skeleton.ts
33225
- import path72 from "path";
33226
- import { existsSync as existsSync54 } from "fs";
33227
- import { readFile as readFile49, writeFile as writeFile31 } from "fs/promises";
33696
+ import path74 from "path";
33697
+ import { existsSync as existsSync56 } from "fs";
33698
+ import { readFile as readFile50, writeFile as writeFile31 } from "fs/promises";
33228
33699
 
33229
33700
  // src/skeleton-preview.ts
33230
33701
  var RIGHT = [255, 140, 40, 255];
@@ -33335,12 +33806,12 @@ var Canvas = class {
33335
33806
  async function runEstimateSkeleton(args) {
33336
33807
  const image = args.target;
33337
33808
  if (!image) throw new UsageError("estimate-skeleton needs an image path: pixelkiln estimate-skeleton <image> [--out keypoints.json]");
33338
- if (args.out && existsSync54(path72.resolve(args.out)) && !args.force) {
33809
+ if (args.out && existsSync56(path74.resolve(args.out)) && !args.force) {
33339
33810
  throw new UsageError(`${args.out} already exists; pass --force to replace it`);
33340
33811
  }
33341
- loadEnvFiles(path72.dirname(path72.resolve(args.manifest)));
33812
+ loadEnvFiles(path74.dirname(path74.resolve(args.manifest)));
33342
33813
  loadEnvFiles(process.cwd());
33343
- const bytes = await readFile49(path72.resolve(image));
33814
+ const bytes = await readFile50(path74.resolve(image));
33344
33815
  const metadata = imageMetadata(bytes);
33345
33816
  if (!metadata) throw new UsageError(`${image} is not a readable PNG or JPEG`);
33346
33817
  const sizeProblem = estimateSkeletonSizeProblem(metadata.width, metadata.height);
@@ -33352,7 +33823,7 @@ async function runEstimateSkeleton(args) {
33352
33823
  const frames = args.frames ?? DEFAULT_SCAFFOLD_FRAMES;
33353
33824
  const json = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames), null, 2);
33354
33825
  if (args.out) {
33355
- await writeFile31(path72.resolve(args.out), json + "\n");
33826
+ await writeFile31(path74.resolve(args.out), json + "\n");
33356
33827
  log(` wrote ${args.out}: the estimated pose and ${frames} frames to edit`);
33357
33828
  log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
33358
33829
  } else {
@@ -33365,8 +33836,8 @@ async function runSkeletonPreview(args) {
33365
33836
  let sourceFile;
33366
33837
  let label;
33367
33838
  if (target.endsWith(".json")) {
33368
- keypointsFile = path72.resolve(target);
33369
- sourceFile = args.from ? path72.resolve(args.from) : void 0;
33839
+ keypointsFile = path74.resolve(target);
33840
+ sourceFile = args.from ? path74.resolve(args.from) : void 0;
33370
33841
  label = target;
33371
33842
  } else {
33372
33843
  const loaded = await loadManifest(args.manifest);
@@ -33378,31 +33849,31 @@ async function runSkeletonPreview(args) {
33378
33849
  );
33379
33850
  }
33380
33851
  keypointsFile = spec.revision.keypointsFile;
33381
- sourceFile = args.from ? path72.resolve(args.from) : spec.revision.sourceFile;
33852
+ sourceFile = args.from ? path74.resolve(args.from) : spec.revision.sourceFile;
33382
33853
  label = `${spec.styleId}/${spec.assetId}`;
33383
33854
  }
33384
- if (!existsSync54(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
33855
+ if (!existsSync56(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
33385
33856
  let json;
33386
33857
  try {
33387
- json = JSON.parse(await readFile49(keypointsFile, "utf8"));
33858
+ json = JSON.parse(await readFile50(keypointsFile, "utf8"));
33388
33859
  } catch (error) {
33389
33860
  throw new UsageError(`${keypointsFile} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
33390
33861
  }
33391
33862
  const set = parseSkeletonSet(json, keypointsFile);
33392
33863
  let source;
33393
33864
  if (sourceFile) {
33394
- if (!existsSync54(sourceFile)) {
33865
+ if (!existsSync56(sourceFile)) {
33395
33866
  log(` source image does not exist yet, drawing on a plain ground: ${sourceFile}`);
33396
33867
  } else {
33397
- const bytes = await readFile49(sourceFile);
33868
+ const bytes = await readFile50(sourceFile);
33398
33869
  if (imageMetadata(bytes)?.format !== "png") throw new UsageError(`${sourceFile} must be a PNG to preview over`);
33399
33870
  source = decodePng(bytes);
33400
33871
  }
33401
33872
  }
33402
- const out = path72.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
33873
+ const out = path74.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
33403
33874
  await writeFile31(out, renderSkeletonSheet(set, { source }));
33404
33875
  log(` ${label}: ${set.frames.length} frames after the starting pose`);
33405
- const shown2 = path72.relative(process.cwd(), out);
33876
+ const shown2 = path74.relative(process.cwd(), out);
33406
33877
  log(` wrote ${shown2.startsWith("..") ? out : shown2}`);
33407
33878
  }
33408
33879
 
@@ -33448,15 +33919,15 @@ async function runTools(args) {
33448
33919
  }
33449
33920
 
33450
33921
  // src/cli/commands/workspace.ts
33451
- import path73 from "path";
33452
- import { existsSync as existsSync55 } from "fs";
33922
+ import path75 from "path";
33923
+ import { existsSync as existsSync57 } from "fs";
33453
33924
  async function runWorkspace(args) {
33454
- const workspacePath = path73.resolve(args.workspace ?? "pixelkiln.workspace.json");
33455
- const dir = path73.dirname(workspacePath);
33925
+ const workspacePath = path75.resolve(args.workspace ?? "pixelkiln.workspace.json");
33926
+ const dir = path75.dirname(workspacePath);
33456
33927
  if (args.subcommand === "add") {
33457
- const manifestPath = path73.resolve(args.target);
33928
+ const manifestPath = path75.resolve(args.target);
33458
33929
  const loadedTarget = await loadManifest(manifestPath);
33459
- const lockPath = args.explicitLock ? path73.resolve(args.explicitLock) : path73.join(path73.dirname(manifestPath), "pixelkiln.lock.json");
33930
+ const lockPath = args.explicitLock ? path75.resolve(args.explicitLock) : path75.join(path75.dirname(manifestPath), "pixelkiln.lock.json");
33460
33931
  const ws = await loadWorkspace(workspacePath);
33461
33932
  const id = args.name ?? loadedTarget.manifest.name;
33462
33933
  if (ws.projects.some((p) => p.id === id)) {
@@ -33476,10 +33947,10 @@ async function runWorkspace(args) {
33476
33947
  ...args.account ? { account: args.account } : {}
33477
33948
  };
33478
33949
  await saveWorkspace(workspacePath, { version: 1, projects: [...ws.projects, project2] });
33479
- log(` registered "${id}" in ${path73.relative(process.cwd(), workspacePath)}`);
33950
+ log(` registered "${id}" in ${path75.relative(process.cwd(), workspacePath)}`);
33480
33951
  log(` manifest: ${project2.manifest}`);
33481
33952
  log(` lock: ${project2.lock}`);
33482
- if (!existsSync55(lockPath)) {
33953
+ if (!existsSync57(lockPath)) {
33483
33954
  log(
33484
33955
  ` warning: no lockfile there yet; this project contributes no claims until one is generated`
33485
33956
  );
@@ -33488,7 +33959,7 @@ async function runWorkspace(args) {
33488
33959
  }
33489
33960
  if (args.subcommand === "remove") {
33490
33961
  const ws = await loadWorkspace(workspacePath);
33491
- const resolvedTarget = path73.resolve(args.target);
33962
+ const resolvedTarget = path75.resolve(args.target);
33492
33963
  const match = ws.projects.find(
33493
33964
  (p) => p.id === args.target || resolveProject(dir, p).manifestPath === resolvedTarget
33494
33965
  );
@@ -33499,11 +33970,11 @@ async function runWorkspace(args) {
33499
33970
  version: 1,
33500
33971
  projects: ws.projects.filter((p) => p !== match)
33501
33972
  });
33502
- log(` removed "${match.id}" from ${path73.relative(process.cwd(), workspacePath)}`);
33973
+ log(` removed "${match.id}" from ${path75.relative(process.cwd(), workspacePath)}`);
33503
33974
  return;
33504
33975
  }
33505
33976
  if (args.subcommand === "list") {
33506
- if (!existsSync55(workspacePath)) {
33977
+ if (!existsSync57(workspacePath)) {
33507
33978
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
33508
33979
  }
33509
33980
  const ws = await loadWorkspace(workspacePath);
@@ -33511,9 +33982,9 @@ async function runWorkspace(args) {
33511
33982
  if (args.json) {
33512
33983
  log(JSON.stringify({ version: 1, workspace: workspacePath, projects: ws.projects, diagnostics }, null, 2));
33513
33984
  } else if (!ws.projects.length) {
33514
- log(` no projects registered in ${path73.relative(process.cwd(), workspacePath)}`);
33985
+ log(` no projects registered in ${path75.relative(process.cwd(), workspacePath)}`);
33515
33986
  } else {
33516
- log(` ${ws.projects.length} project(s) in ${path73.relative(process.cwd(), workspacePath)}:`);
33987
+ log(` ${ws.projects.length} project(s) in ${path75.relative(process.cwd(), workspacePath)}:`);
33517
33988
  for (const p of ws.projects) {
33518
33989
  log(` ${p.id.padEnd(24)} ${p.manifest.padEnd(40)} (${p.provider}${p.account ? `, ${p.account}` : ""})`);
33519
33990
  }
@@ -33523,7 +33994,7 @@ async function runWorkspace(args) {
33523
33994
  return;
33524
33995
  }
33525
33996
  if (args.subcommand === "status") {
33526
- if (!existsSync55(workspacePath)) {
33997
+ if (!existsSync57(workspacePath)) {
33527
33998
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
33528
33999
  }
33529
34000
  const ws = await loadWorkspace(workspacePath);
@@ -33531,7 +34002,7 @@ async function runWorkspace(args) {
33531
34002
  if (args.json) {
33532
34003
  log(JSON.stringify({ ...report, workspace: workspacePath }, null, 2));
33533
34004
  } else {
33534
- log(` workspace: ${path73.relative(process.cwd(), workspacePath)}`);
34005
+ log(` workspace: ${path75.relative(process.cwd(), workspacePath)}`);
33535
34006
  for (const p of report.projects) {
33536
34007
  if (p.error) {
33537
34008
  log(`
@@ -33585,8 +34056,8 @@ async function runHelp() {
33585
34056
  async function runVersion() {
33586
34057
  for (const up of ["../package.json", "../../package.json"]) {
33587
34058
  const url = new URL(up, import.meta.url);
33588
- if (!existsSync56(url)) continue;
33589
- const pkg = JSON.parse(await readFile50(url, "utf8"));
34059
+ if (!existsSync58(url)) continue;
34060
+ const pkg = JSON.parse(await readFile51(url, "utf8"));
33590
34061
  if (pkg.name === "pixelkiln") {
33591
34062
  log(`${pkg.name} ${pkg.version}`);
33592
34063
  return;