pixelkiln 0.148.0 → 0.149.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/index.js CHANGED
@@ -422,6 +422,13 @@ var CharacterLayerSchema = z.object({
422
422
  skin: z.array(HexColorSchema).min(1).max(64).optional(),
423
423
  /** The stand-in colour skin is painted before the provider sees it. Default cyan. */
424
424
  key: HexColorSchema.optional(),
425
+ /**
426
+ * Key every opaque pixel inside the mask, whatever its colour, not only
427
+ * skin. For a base that wears underwear (or anything else it cannot be
428
+ * drawn without): what it wears is body to dress over, so the outfit
429
+ * covers it instead of being drawn around it. Default false.
430
+ */
431
+ cover: z.boolean().optional(),
425
432
  /**
426
433
  * Remove animation ghosts from the loops before dressing them, judged
427
434
  * against the stills among `of` (bases and states). Default true; it has
@@ -462,7 +469,7 @@ var CharacterLayerSchema = z.object({
462
469
  attach: CharacterAttachSchema.optional()
463
470
  }).strict().superRefine((layer, context) => {
464
471
  if (!layer.attach) return;
465
- for (const field of ["mask", "keyed", "skin", "key", "clean", "region"]) {
472
+ for (const field of ["mask", "keyed", "skin", "key", "cover", "clean", "region"]) {
466
473
  if (layer[field] !== void 0) {
467
474
  context.addIssue({
468
475
  code: z.ZodIssueCode.custom,
@@ -1466,7 +1473,7 @@ var AssetDeriveSchema = z.object({
1466
1473
  /** 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. */
1467
1474
  tolerance: z.number().min(0).max(442).optional()
1468
1475
  }).strict().superRefine((derive, context) => {
1469
- const issue = (message6, path54) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path54] });
1476
+ const issue = (message6, path55) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path55] });
1470
1477
  if (Boolean(derive.from) === Boolean(derive.file)) {
1471
1478
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1472
1479
  }
@@ -3045,9 +3052,9 @@ var PixelLabClient = class {
3045
3052
  apiKey;
3046
3053
  http;
3047
3054
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
3048
- async request(path54, init) {
3055
+ async request(path55, init) {
3049
3056
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
3050
- const res = await this.http(`${BASE}${path54}`, {
3057
+ const res = await this.http(`${BASE}${path55}`, {
3051
3058
  ...init,
3052
3059
  headers: {
3053
3060
  Authorization: auth,
@@ -3058,13 +3065,13 @@ var PixelLabClient = class {
3058
3065
  const text = await res.text();
3059
3066
  if (!res.ok) {
3060
3067
  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' : "";
3061
- throw new PixelLabError(`${init?.method ?? "GET"} ${path54} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3068
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path55} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
3062
3069
  }
3063
3070
  if (!text) return {};
3064
3071
  try {
3065
3072
  return JSON.parse(text);
3066
3073
  } catch {
3067
- throw new Error(`${init?.method ?? "GET"} ${path54} returned invalid JSON`);
3074
+ throw new Error(`${init?.method ?? "GET"} ${path55} returned invalid JSON`);
3068
3075
  }
3069
3076
  }
3070
3077
  async balance() {
@@ -3616,10 +3623,10 @@ var PixelLabClient = class {
3616
3623
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
3617
3624
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3618
3625
  const south = args.reference?.south;
3619
- let path54;
3626
+ let path55;
3620
3627
  let body;
3621
3628
  if (args.mode === "v3") {
3622
- path54 = "/create-character-v3";
3629
+ path55 = "/create-character-v3";
3623
3630
  body = {
3624
3631
  description: args.description,
3625
3632
  image_size: imageSize,
@@ -3633,7 +3640,7 @@ var PixelLabClient = class {
3633
3640
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
3634
3641
  };
3635
3642
  } else if (args.mode === "pro-flash") {
3636
- path54 = "/create-character-pro-flash";
3643
+ path55 = "/create-character-pro-flash";
3637
3644
  const traits = args.styleTraits;
3638
3645
  body = {
3639
3646
  description: args.description,
@@ -3657,7 +3664,7 @@ var PixelLabClient = class {
3657
3664
  } : {}
3658
3665
  };
3659
3666
  } else if (args.mode === "pro") {
3660
- path54 = "/create-character-pro";
3667
+ path55 = "/create-character-pro";
3661
3668
  body = {
3662
3669
  description: args.description,
3663
3670
  image_size: imageSize,
@@ -3671,7 +3678,7 @@ var PixelLabClient = class {
3671
3678
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
3672
3679
  };
3673
3680
  } else {
3674
- path54 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3681
+ path55 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3675
3682
  body = {
3676
3683
  description: args.description,
3677
3684
  image_size: imageSize,
@@ -3689,8 +3696,8 @@ var PixelLabClient = class {
3689
3696
  };
3690
3697
  }
3691
3698
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
3692
- const raw = await this.request(path54, { method: "POST", body: JSON.stringify(body) });
3693
- return validateResponse(CharacterSubmitSchema, raw, path54.slice(1));
3699
+ const raw = await this.request(path55, { method: "POST", body: JSON.stringify(body) });
3700
+ return validateResponse(CharacterSubmitSchema, raw, path55.slice(1));
3694
3701
  }
3695
3702
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
3696
3703
  async createCharacterState(args) {
@@ -4744,8 +4751,8 @@ var PixelLabClient = class {
4744
4751
  }
4745
4752
  /** Irreversible: the character, its states are separate records, and its animations. Checks `success` like `deleteObject`. */
4746
4753
  async deleteCharacter(characterId) {
4747
- const path54 = `/characters/${encodeURIComponent(characterId)}`;
4748
- return deleteSucceeded(await this.request(path54, { method: "DELETE" }), `DELETE ${path54}`);
4754
+ const path55 = `/characters/${encodeURIComponent(characterId)}`;
4755
+ return deleteSucceeded(await this.request(path55, { method: "DELETE" }), `DELETE ${path55}`);
4749
4756
  }
4750
4757
  setCharacterTags(characterId, tags) {
4751
4758
  return this.request(`/characters/${encodeURIComponent(characterId)}/tags`, {
@@ -5381,10 +5388,10 @@ function normalizeHex(value) {
5381
5388
  function sha256(data) {
5382
5389
  return createHash("sha256").update(data).digest("hex");
5383
5390
  }
5384
- async function sha256File(path54) {
5391
+ async function sha256File(path55) {
5385
5392
  return new Promise((resolve, reject) => {
5386
5393
  const hash = createHash("sha256");
5387
- const stream = createReadStream(path54);
5394
+ const stream = createReadStream(path55);
5388
5395
  stream.on("data", (chunk2) => hash.update(chunk2));
5389
5396
  stream.on("error", reject);
5390
5397
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -5527,6 +5534,8 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
5527
5534
  keyed: spec.character.layer.keyed?.sha256,
5528
5535
  skin: spec.character.layer.skin?.map(normalizeHex),
5529
5536
  key: spec.character.layer.key ? normalizeHex(spec.character.layer.key) : void 0,
5537
+ // Omitted unless set so a layer made before it existed keeps its identity.
5538
+ cover: spec.character.layer.cover,
5530
5539
  clean: spec.character.layer.clean,
5531
5540
  columns: spec.character.layer.columns,
5532
5541
  // Omitted at their defaults so a layer made before these existed keeps its identity.
@@ -6754,6 +6763,7 @@ function hsv(r, g, b) {
6754
6763
  }
6755
6764
  var DEFAULT_KEY = "#00ffff";
6756
6765
  var KEY_SATURATION = 0.85;
6766
+ var COVER_FLOOR = 96;
6757
6767
  function keySkin(png, options = {}) {
6758
6768
  const image = decodePng(png);
6759
6769
  const key3 = parseHex(options.key ?? DEFAULT_KEY);
@@ -6806,23 +6816,103 @@ function neckRow(image, cell = whole(image)) {
6806
6816
  }
6807
6817
  return best === null ? null : cell.y + best;
6808
6818
  }
6809
- function bodyMask(sheet, cells, region = "body") {
6819
+ function longestRun(image, cell, y) {
6820
+ let best = null;
6821
+ let start = -1;
6822
+ for (let x = 0; x <= cell.width; x++) {
6823
+ const on = x < cell.width && opaque(image, cell.x + x, cell.y + y);
6824
+ if (on && start < 0) start = x;
6825
+ if (!on && start >= 0) {
6826
+ if (!best || x - 1 - start > best[1] - best[0]) best = [start, x - 1];
6827
+ start = -1;
6828
+ }
6829
+ }
6830
+ return best;
6831
+ }
6832
+ var median = (values) => {
6833
+ const sorted = [...values].sort((a, b) => a - b);
6834
+ return sorted[Math.floor((sorted.length - 1) / 2)];
6835
+ };
6836
+ function layerMask(sheet, cells, region = "body") {
6810
6837
  const image = decodePng(sheet);
6811
6838
  const out = Buffer.alloc(image.width * image.height * 4);
6812
6839
  for (let i = 3; i < out.length; i += 4) out[i] = 255;
6813
- for (const cell of cells ?? [whole(image)]) {
6840
+ const all = cells ?? [whole(image)];
6841
+ const first = all.map((cell) => {
6842
+ let top = -1;
6843
+ let bottom = -1;
6844
+ for (let y = 0; y < cell.height && top < 0; y++) if (longestRun(image, cell, y)) top = y;
6845
+ for (let y = cell.height - 1; y >= 0 && bottom < 0; y--) if (longestRun(image, cell, y)) bottom = y;
6846
+ if (top < 0) return null;
6814
6847
  const neck = neckRow(image, cell);
6815
- if (neck === null) continue;
6816
- const from = region === "head" ? cell.y : neck + 1;
6817
- const to = region === "head" ? neck + 1 : cell.y + cell.height;
6848
+ return { top, bottom, detected: neck === null ? null : neck - cell.y };
6849
+ });
6850
+ const seen = first.filter((frame) => frame !== null);
6851
+ const offsets = seen.filter((frame) => frame.detected !== null).map((frame) => frame.detected - frame.top);
6852
+ if (!offsets.length) return { png: encodeRgbaPng(image.width, image.height, out), necks: all.map(() => null) };
6853
+ const drop = median(offsets);
6854
+ const heads = seen.map((frame) => {
6855
+ const cell = all[first.indexOf(frame)];
6856
+ const run = longestRun(image, cell, Math.min(frame.bottom, frame.top + Math.floor(drop / 2)));
6857
+ return run ? run[1] - run[0] + 1 : 1;
6858
+ });
6859
+ const wide = Math.max(1, Math.ceil(median(heads) / 2));
6860
+ const necks = all.map((cell, index) => {
6861
+ const frame = first[index];
6862
+ if (!frame) return null;
6863
+ let head = frame.top;
6864
+ for (let y = frame.top; y <= frame.bottom; y++) {
6865
+ const run = longestRun(image, cell, y);
6866
+ if (run && run[1] - run[0] + 1 >= wide) {
6867
+ head = y;
6868
+ break;
6869
+ }
6870
+ }
6871
+ const row = Math.min(head + drop, frame.bottom);
6872
+ const slack = Math.max(2, Math.round((frame.bottom - frame.top + 1) * 0.06));
6873
+ const corrected = frame.detected === null || Math.abs(frame.detected - row) > slack;
6874
+ const from = region === "head" ? 0 : row + 1;
6875
+ const to = region === "head" ? row + 1 : cell.height;
6818
6876
  for (let y = from; y < to; y++) {
6819
- for (let x = cell.x; x < cell.x + cell.width; x++) {
6820
- if (region === "body" && !opaque(image, x, y)) continue;
6821
- out.fill(255, at(image, x, y), at(image, x, y) + 3);
6877
+ for (let x = 0; x < cell.width; x++) {
6878
+ if (region === "body" && !opaque(image, cell.x + x, cell.y + y)) continue;
6879
+ out.fill(255, at(image, cell.x + x, cell.y + y), at(image, cell.x + x, cell.y + y) + 3);
6880
+ }
6881
+ }
6882
+ if (region === "body") {
6883
+ const seed = longestRun(image, cell, head);
6884
+ const inHead = new Uint8Array(cell.width * (row + 1));
6885
+ const queue = [];
6886
+ for (let x = seed[0]; x <= seed[1]; x++) {
6887
+ inHead[head * cell.width + x] = 1;
6888
+ queue.push([x, head]);
6889
+ }
6890
+ let left = seed[0];
6891
+ let right = seed[1];
6892
+ while (queue.length) {
6893
+ const [x, y] = queue.pop();
6894
+ left = Math.min(left, x);
6895
+ right = Math.max(right, x);
6896
+ for (const [dx, dy] of STEPS) {
6897
+ const nx = x + dx;
6898
+ const ny = y + dy;
6899
+ if (nx < 0 || nx >= cell.width || ny < 0 || ny > row) continue;
6900
+ if (inHead[ny * cell.width + nx] || !opaque(image, cell.x + nx, cell.y + ny)) continue;
6901
+ inHead[ny * cell.width + nx] = 1;
6902
+ queue.push([nx, ny]);
6903
+ }
6904
+ }
6905
+ for (let y = 0; y <= row; y++) {
6906
+ for (let x = 0; x < cell.width; x++) {
6907
+ if (x >= left - 1 && x <= right + 1) continue;
6908
+ if (!opaque(image, cell.x + x, cell.y + y)) continue;
6909
+ out.fill(255, at(image, cell.x + x, cell.y + y), at(image, cell.x + x, cell.y + y) + 3);
6910
+ }
6822
6911
  }
6823
6912
  }
6824
- }
6825
- return encodeRgbaPng(image.width, image.height, out);
6913
+ return { row, head, detected: frame.detected, corrected };
6914
+ });
6915
+ return { png: encodeRgbaPng(image.width, image.height, out), necks };
6826
6916
  }
6827
6917
  function extractLayer(result, keyed, mask, options = {}) {
6828
6918
  const out = decodePng(result);
@@ -6855,10 +6945,10 @@ function despeckle(png, options) {
6855
6945
  for (const still of options.reference) {
6856
6946
  const { pixels } = decodePng(still);
6857
6947
  for (let i = 0; i < pixels.length; i += 4) {
6858
- if (pixels[i + 3] === 0 || outline(pixels, i)) continue;
6948
+ if (pixels[i + 3] === 0) continue;
6859
6949
  const rgb = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
6860
6950
  palette.set(rgb, (palette.get(rgb) ?? 0) + 1);
6861
- total++;
6951
+ if (!outline(pixels, i)) total++;
6862
6952
  }
6863
6953
  }
6864
6954
  if (!total) throw new Error("the reference stills have no opaque pixels that are not outline");
@@ -6918,7 +7008,7 @@ function despeckle(png, options) {
6918
7008
  const strange = run.filter(([x, y]) => foreign(at(image, x, y))).length / run.length > 0.5;
6919
7009
  let debris;
6920
7010
  const exposed = run.some(([x, y]) => STEPS.some(([dx, dy]) => open(x + dx, y + dy)));
6921
- if (strange && !exposed && run.length > limb) {
7011
+ if (strange && run.length > limb) {
6922
7012
  debris = false;
6923
7013
  limbs.add(index);
6924
7014
  } else if (exposed) {
@@ -6953,6 +7043,7 @@ function despeckle(png, options) {
6953
7043
  if (src[at(image, x, y) + 3] > 0 && out[at(image, x, y) + 3] === 0) frontier.push([x, y]);
6954
7044
  }
6955
7045
  }
7046
+ const seeds = frontier.length;
6956
7047
  for (let n = 0; n < frontier.length; n++) {
6957
7048
  const [fx, fy] = frontier[n];
6958
7049
  for (let dy = -1; dy <= 1; dy++) {
@@ -6976,6 +7067,31 @@ function despeckle(png, options) {
6976
7067
  }
6977
7068
  }
6978
7069
  }
7070
+ const chained = new Set(frontier.slice(seeds).map(([x, y]) => local(x, y)));
7071
+ const visited = /* @__PURE__ */ new Set();
7072
+ for (const [sx, sy] of frontier.slice(seeds)) {
7073
+ if (visited.has(local(sx, sy))) continue;
7074
+ const group = [[sx, sy]];
7075
+ visited.add(local(sx, sy));
7076
+ for (let n = 0; n < group.length; n++) {
7077
+ const [gx, gy] = group[n];
7078
+ for (let dy = -1; dy <= 1; dy++) {
7079
+ for (let dx = -1; dx <= 1; dx++) {
7080
+ const x = gx + dx;
7081
+ const y = gy + dy;
7082
+ if (!inside(cell, x, y) || visited.has(local(x, y)) || !chained.has(local(x, y))) continue;
7083
+ visited.add(local(x, y));
7084
+ group.push([x, y]);
7085
+ }
7086
+ }
7087
+ }
7088
+ if (group.length <= limb) continue;
7089
+ for (const [x, y] of group) {
7090
+ const i = at(image, x, y);
7091
+ src.copy(out, i, i, i + 4);
7092
+ removed--;
7093
+ }
7094
+ }
6979
7095
  }
6980
7096
  return { png: encodeRgbaPng(image.width, image.height, out), removed };
6981
7097
  }
@@ -7091,23 +7207,55 @@ function buildLayerSheet(sources, options) {
7091
7207
  }
7092
7208
  return png;
7093
7209
  };
7094
- const mask = options.mask ? sized("mask", options.mask) : bodyMask(sheetPng, frames.map((frame) => frame.cell), options.region);
7210
+ const computed = options.mask ? void 0 : layerMask(sheetPng, frames.map((frame) => frame.cell), options.region);
7211
+ const mask = options.mask ? sized("mask", options.mask) : computed.png;
7212
+ const keyed = options.keyed ? void 0 : keyInsideMask(sheetPng, mask, { key: options.key, skin: options.skin, cover: options.cover });
7095
7213
  return {
7096
7214
  sheet: sheetPng,
7097
- keyed: options.keyed ? sized("keyed sheet", options.keyed) : keyInsideMask(sheetPng, mask, { key: options.key, skin: options.skin }),
7215
+ keyed: options.keyed ? sized("keyed sheet", options.keyed) : keyed.png,
7098
7216
  mask,
7099
7217
  frames,
7100
- cleaned
7218
+ cleaned,
7219
+ ...computed ? { necks: computed.necks } : {},
7220
+ ...keyed ? { closed: keyed.closed } : {}
7101
7221
  };
7102
7222
  }
7103
7223
  function keyInsideMask(sheet, mask, options) {
7104
7224
  const original = decodePng(sheet);
7105
- const keyed = decodePng(keySkin(sheet, options));
7106
7225
  const allowed = decodePng(mask);
7226
+ const key3 = parseHex(options.key ?? DEFAULT_KEY);
7227
+ const keyed = options.cover ? { ...original, pixels: Buffer.from(original.pixels) } : decodePng(keySkin(sheet, options));
7228
+ const paint = (i, lift) => {
7229
+ const brightest = Math.max(original.pixels[i], original.pixels[i + 1], original.pixels[i + 2]);
7230
+ const value = lift ? COVER_FLOOR + Math.floor(brightest * (255 - COVER_FLOOR) / 255) : brightest;
7231
+ const tint = (channel) => Math.floor(value * (1 - KEY_SATURATION + KEY_SATURATION * channel / 255));
7232
+ keyed.pixels[i] = tint(key3.r);
7233
+ keyed.pixels[i + 1] = tint(key3.g);
7234
+ keyed.pixels[i + 2] = tint(key3.b);
7235
+ };
7107
7236
  for (let i = 0; i < keyed.pixels.length; i += 4) {
7108
7237
  if (allowed.pixels[i] !== 255) original.pixels.copy(keyed.pixels, i, i, i + 4);
7238
+ else if (options.cover && original.pixels[i + 3]) paint(i, true);
7239
+ }
7240
+ let closed = 0;
7241
+ if (!options.cover && !options.skin) {
7242
+ const changed = (i) => original.pixels[i + 3] > 0 && original.pixels.compare(keyed.pixels, i, i + 3, i, i + 3) !== 0;
7243
+ const holes = [];
7244
+ for (let y = 0; y < keyed.height; y++) {
7245
+ for (let x = 0; x < keyed.width; x++) {
7246
+ const i = (y * keyed.width + x) * 4;
7247
+ if (allowed.pixels[i] !== 255 || !original.pixels[i + 3] || changed(i)) continue;
7248
+ const near = (dir) => [1, 2, 3].some((k) => {
7249
+ const nx = x + dir * k;
7250
+ return nx >= 0 && nx < keyed.width && allowed.pixels[i + dir * k * 4] === 255 && changed(i + dir * k * 4);
7251
+ });
7252
+ if (near(-1) && near(1)) holes.push(i);
7253
+ }
7254
+ }
7255
+ for (const i of holes) paint(i, false);
7256
+ closed = holes.length;
7109
7257
  }
7110
- return encodeRgbaPng(keyed.width, keyed.height, keyed.pixels);
7258
+ return { png: encodeRgbaPng(keyed.width, keyed.height, keyed.pixels), closed };
7111
7259
  }
7112
7260
  var SPECK = 8;
7113
7261
  var BLEED = 20;
@@ -7779,10 +7927,13 @@ function applyPostprocess(bytes, mediaType, record, reference = [], role) {
7779
7927
  if (mediaType !== MediaType.PNG || !record?.palette && !record?.despeckle && !record?.offset) return { bytes, changed: false };
7780
7928
  let out = bytes;
7781
7929
  let removed = 0;
7930
+ let opaque2 = 0;
7782
7931
  if (record.despeckle) {
7783
7932
  if (!reference.length) throw new Error(`cleaning needs the rotations of ${record.despeckle.of}, and none were given`);
7784
7933
  const cleaned = despeckle(out, { reference });
7785
7934
  if (cleaned.removed) {
7935
+ const { pixels } = decodePng(out);
7936
+ for (let i = 3; i < pixels.length; i += 4) if (pixels[i] > 0) opaque2++;
7786
7937
  out = cleaned.png;
7787
7938
  removed = cleaned.removed;
7788
7939
  }
@@ -7806,8 +7957,9 @@ function applyPostprocess(bytes, mediaType, record, reference = [], role) {
7806
7957
  }
7807
7958
  }
7808
7959
  if (!removed && !snapped && !moved) return { bytes, changed: false };
7809
- return { bytes: out, changed: true, ...removed ? { removed } : {}, ...snapped ? { snapped } : {}, ...moved ? { moved } : {} };
7960
+ return { bytes: out, changed: true, ...removed ? { removed, opaque: opaque2 } : {}, ...snapped ? { snapped } : {}, ...moved ? { moved } : {} };
7810
7961
  }
7962
+ var CLEAN_DAMAGE_SHARE = 0.03;
7811
7963
 
7812
7964
  // src/pipeline/mirror.ts
7813
7965
  function mirrorSourceHash(source) {
@@ -8228,6 +8380,37 @@ var GRASP_PROMPT = "Every cyan mannequin on this spritesheet carries the same it
8228
8380
  function layerWorkDir(spec) {
8229
8381
  return path7.join(spec.root, ".pixelkiln", "layers", spec.styleId, spec.assetId);
8230
8382
  }
8383
+ function layerSheetFor(spec, outputs) {
8384
+ const character = spec.character;
8385
+ const layer = character.layer;
8386
+ const label = `${spec.styleId}/${spec.assetId}`;
8387
+ if (!outputs.length) throw new Error(`${label}: its layer sources have no downloaded frames`);
8388
+ const sources = outputs.map((output) => ({
8389
+ assetId: output.assetId ?? character.parentAssetId,
8390
+ ...output.role ? { role: output.role } : {},
8391
+ png: readFileSync(output.path),
8392
+ still: output.still === true
8393
+ }));
8394
+ const supplied = (name, file) => {
8395
+ if (!file) return void 0;
8396
+ const bytes = readFileSync(file.path);
8397
+ if (sha256(bytes) !== file.sha256) throw new Error(`${label}: layer ${name} changed after the manifest was resolved: ${file.path}`);
8398
+ return bytes;
8399
+ };
8400
+ return buildLayerSheet(sources, {
8401
+ minSide: 32,
8402
+ maxSide: LAYER_SHEET_MAX_SIDE,
8403
+ columns: layer.columns,
8404
+ region: layer.region,
8405
+ padding: layer.padding,
8406
+ key: layer.key,
8407
+ skin: layer.skin,
8408
+ cover: layer.cover,
8409
+ reference: layer.clean ? sources.filter((source) => source.still).map((source) => source.png) : [],
8410
+ mask: supplied("mask", layer.mask),
8411
+ keyed: supplied("keyed sheet", layer.keyed)
8412
+ });
8413
+ }
8231
8414
  var PixelLabProvider = class _PixelLabProvider {
8232
8415
  /**
8233
8416
  * `mcp` reaches the tools PixelLab offers only over MCP (the VFX
@@ -9119,31 +9302,7 @@ var PixelLabProvider = class _PixelLabProvider {
9119
9302
  const layer = character.layer;
9120
9303
  const label = `${spec.styleId}/${spec.assetId}`;
9121
9304
  const outputs = context?.parentOutputs ?? [];
9122
- if (!outputs.length) throw new Error(`${label}: its layer sources have no downloaded frames`);
9123
- const sources = outputs.map((output) => ({
9124
- assetId: output.assetId ?? character.parentAssetId,
9125
- ...output.role ? { role: output.role } : {},
9126
- png: readFileSync(output.path),
9127
- still: output.still === true
9128
- }));
9129
- const supplied = (name2, file) => {
9130
- if (!file) return void 0;
9131
- const bytes = readFileSync(file.path);
9132
- if (sha256(bytes) !== file.sha256) throw new Error(`${label}: layer ${name2} changed after the manifest was resolved: ${file.path}`);
9133
- return bytes;
9134
- };
9135
- const built = buildLayerSheet(sources, {
9136
- minSide: 32,
9137
- maxSide: LAYER_SHEET_MAX_SIDE,
9138
- columns: layer.columns,
9139
- region: layer.region,
9140
- padding: layer.padding,
9141
- key: layer.key,
9142
- skin: layer.skin,
9143
- reference: layer.clean ? sources.filter((source) => source.still).map((source) => source.png) : [],
9144
- mask: supplied("mask", layer.mask),
9145
- keyed: supplied("keyed sheet", layer.keyed)
9146
- });
9305
+ const built = layerSheetFor(spec, outputs);
9147
9306
  const dir = layerWorkDir(spec);
9148
9307
  mkdirSync(dir, { recursive: true });
9149
9308
  let prepared = built;
@@ -9198,7 +9357,15 @@ var PixelLabProvider = class _PixelLabProvider {
9198
9357
  character: {
9199
9358
  kind: "layer",
9200
9359
  backgroundJobId: res2.background_job_id,
9201
- sheet: { width, height, frames: prepared.frames.length, cleanedPixels: prepared.cleaned }
9360
+ sheet: {
9361
+ width,
9362
+ height,
9363
+ frames: prepared.frames.length,
9364
+ cleanedPixels: prepared.cleaned,
9365
+ // Each frame's neck row in its cell, and the frames whose own narrowest row was overruled; submit prints both.
9366
+ ...prepared.necks ? { necks: prepared.necks.map((neck) => neck?.row ?? null) } : {},
9367
+ ...prepared.necks?.some((neck) => neck?.corrected) ? { neckCorrected: prepared.necks.flatMap((neck, index) => neck?.corrected ? [index] : []) } : {}
9368
+ }
9202
9369
  }
9203
9370
  }
9204
9371
  };
@@ -11261,9 +11428,9 @@ var RetroDiffusionClient = class {
11261
11428
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
11262
11429
  return Buffer.from(await response.arrayBuffer());
11263
11430
  }
11264
- async call(path54, init = {}) {
11431
+ async call(path55, init = {}) {
11265
11432
  if (!this.token) throw new Error("RD_API_KEY is not set");
11266
- const response = await this.request(`${this.baseUrl}${path54}`, {
11433
+ const response = await this.request(`${this.baseUrl}${path55}`, {
11267
11434
  ...init,
11268
11435
  headers: {
11269
11436
  "Content-Type": "application/json",
@@ -14769,6 +14936,7 @@ async function resolveSpecs(loaded, filter) {
14769
14936
  ...keyed ? { keyed } : {},
14770
14937
  ...asset.layer.skin ? { skin: asset.layer.skin } : {},
14771
14938
  ...asset.layer.key ? { key: asset.layer.key } : {},
14939
+ ...asset.layer.cover ? { cover: true } : {},
14772
14940
  clean: asset.layer.clean ?? true,
14773
14941
  ...asset.layer.columns ? { columns: asset.layer.columns } : {},
14774
14942
  region: asset.layer.region ?? "body",
@@ -17072,10 +17240,15 @@ async function buildPlan(specs, lock, opts = {}) {
17072
17240
  } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync14(currentEntryOutputPath(entry, spec, index)))) {
17073
17241
  state = "stale";
17074
17242
  reason = "mirror output missing on disk; flip it again (no generation cost)";
17075
- } else if (spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })) {
17243
+ } else if (
17244
+ // A mirror carries its source's character shape, but it is a flip of
17245
+ // the source's files: whether it is current is the check above, never
17246
+ // the outfit or layer rule its source answers to (#418).
17247
+ !spec.mirror && spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })
17248
+ ) {
17076
17249
  state = "stale";
17077
17250
  reason = `outfit source ${spec.character.parentAssetId} changed; re-clothe the loop again`;
17078
- } else if (spec.character?.kind === "layer" && changedLayerSource(spec, entry, lock)) {
17251
+ } else if (!spec.mirror && spec.character?.kind === "layer" && changedLayerSource(spec, entry, lock)) {
17079
17252
  state = "stale";
17080
17253
  reason = isHeldItem(spec) ? `layer source ${changedLayerSource(spec, entry, lock)} changed; place the item again (no generation cost)` : `layer source ${changedLayerSource(spec, entry, lock)} changed; dress the frames again`;
17081
17254
  } else if (isHeldItem(spec) && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync14(currentEntryOutputPath(entry, spec, index)))) {
@@ -17143,6 +17316,7 @@ async function buildPlan(specs, lock, opts = {}) {
17143
17316
  }
17144
17317
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
17145
17318
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
17319
+ const waiting = /* @__PURE__ */ new Set();
17146
17320
  for (const item of items) {
17147
17321
  if (!isActionable(item)) continue;
17148
17322
  for (const parent of dependencies(item.spec)) {
@@ -17151,11 +17325,35 @@ async function buildPlan(specs, lock, opts = {}) {
17151
17325
  if (parentState && isActionable({ state: parentState })) {
17152
17326
  item.state = "blocked";
17153
17327
  item.reason = `parent ${parentKey} is being generated in this run; this follows in the next wave`;
17328
+ waiting.add(item.key);
17154
17329
  break;
17155
17330
  }
17156
17331
  if ((item.spec.mirror || item.spec.derive || isHeldItem(item.spec)) && (parentState === "recoverable" || parentState === "in-flight")) {
17157
17332
  item.state = "blocked";
17158
17333
  item.reason = `mirror source ${parentKey} is ${parentState}; this follows in the next wave`;
17334
+ waiting.add(item.key);
17335
+ break;
17336
+ }
17337
+ }
17338
+ }
17339
+ const byKey = new Map(items.map((i) => [i.key, i]));
17340
+ for (let changed = true; changed; ) {
17341
+ changed = false;
17342
+ for (const item of items) {
17343
+ if (item.state !== "blocked" || waiting.has(item.key)) continue;
17344
+ for (const parent of dependencies(item.spec)) {
17345
+ const parentKey = lockKey(parent.styleId, parent.assetId);
17346
+ const parentItem = byKey.get(parentKey);
17347
+ if (!parentItem || !item.reason.includes(`${parentKey} is not ready`)) continue;
17348
+ if (isActionable(parentItem)) {
17349
+ item.reason = `waits for ${parentKey}, which this run generates first; follows in a later wave (${item.reason})`;
17350
+ } else if (waiting.has(parentKey)) {
17351
+ item.reason = `waits for ${parentKey}, which itself follows in a later wave of this run (${item.reason})`;
17352
+ } else {
17353
+ continue;
17354
+ }
17355
+ waiting.add(item.key);
17356
+ changed = true;
17159
17357
  break;
17160
17358
  }
17161
17359
  }
@@ -19600,10 +19798,10 @@ function isSha256Hash(value) {
19600
19798
  function parseCache(value) {
19601
19799
  return HashCacheSchema.parse(value);
19602
19800
  }
19603
- async function loadCache(path54) {
19604
- if (!existsSync24(path54)) return { version: 1, hashes: {} };
19801
+ async function loadCache(path55) {
19802
+ if (!existsSync24(path55)) return { version: 1, hashes: {} };
19605
19803
  try {
19606
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile17(path54, "utf8")));
19804
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile17(path55, "utf8")));
19607
19805
  if (!parsed.success) return { version: 1, hashes: {} };
19608
19806
  return {
19609
19807
  version: 1,
@@ -19615,18 +19813,18 @@ async function loadCache(path54) {
19615
19813
  return { version: 1, hashes: {} };
19616
19814
  }
19617
19815
  }
19618
- async function saveCache(path54, cache) {
19816
+ async function saveCache(path55, cache) {
19619
19817
  const sorted = {};
19620
19818
  for (const key3 of Object.keys(cache.hashes).sort()) {
19621
19819
  const hash = cache.hashes[key3];
19622
19820
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
19623
19821
  sorted[key3] = hash;
19624
19822
  }
19625
- await mkdir12(pathModule.dirname(pathModule.resolve(path54)), { recursive: true });
19626
- const tmp = `${path54}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19823
+ await mkdir12(pathModule.dirname(pathModule.resolve(path55)), { recursive: true });
19824
+ const tmp = `${path55}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19627
19825
  try {
19628
19826
  await writeFile12(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
19629
- await rename6(tmp, path54);
19827
+ await rename6(tmp, path55);
19630
19828
  } finally {
19631
19829
  await rm4(tmp, { force: true });
19632
19830
  }
@@ -19872,6 +20070,9 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19872
20070
  if (processed.changed) rawHash = sha256(raw);
19873
20071
  if (processed.moved?.clipped) log(` moved ${path29.relative(process.cwd(), target)}: ${processed.moved.clipped} pixels fell off the canvas; raise layer.padding to keep them`);
19874
20072
  if (processed.removed) log(` cleaned ${path29.relative(process.cwd(), target)} (${processed.removed} ghost pixels)`);
20073
+ if (processed.removed && processed.opaque && processed.removed > processed.opaque * CLEAN_DAMAGE_SHARE) {
20074
+ log(` warning: cleaning took ${processed.removed} of ${processed.opaque} opaque pixels (${(100 * processed.removed / processed.opaque).toFixed(1)}%) from ${path29.relative(process.cwd(), target)}; check the frame for holes, and set clean: false then fetch to restore the provider's bytes`);
20075
+ }
19875
20076
  if (processed.snapped) log(` snapped ${path29.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
19876
20077
  }
19877
20078
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
@@ -21791,6 +21992,21 @@ function renderSheetDocument(format, atlas, opts) {
21791
21992
  return { extension: ".json", document: JSON.stringify(atlas, null, 2) + "\n" };
21792
21993
  }
21793
21994
 
21995
+ // src/pipeline/layer-preview.ts
21996
+ import { mkdir as mkdir14, rm as rm7, writeFile as writeFile14 } from "fs/promises";
21997
+ import path33 from "path";
21998
+ function layerSourceOutputs(spec, lock) {
21999
+ return spec.character.layer.sources.flatMap((source) => {
22000
+ const sourceEntry = lock.entries[lockKey(source.spec.styleId, source.spec.assetId)];
22001
+ return sourceEntry.outputs.map((output, index) => ({
22002
+ path: currentEntryOutputPath(sourceEntry, source.spec, index),
22003
+ role: output.role,
22004
+ assetId: source.assetId,
22005
+ still: source.spec.character?.kind !== "animation"
22006
+ }));
22007
+ });
22008
+ }
22009
+
21794
22010
  // src/pipeline/submit.ts
21795
22011
  var IN_FLIGHT_POLL_MS = 5e3;
21796
22012
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -22073,15 +22289,7 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
22073
22289
  const parentOutputs = spec.character?.kind === "outfit" && parentEntry ? parentEntry.outputs.map((output, index) => ({
22074
22290
  path: currentEntryOutputPath(parentEntry, spec.character.parentSpec, index),
22075
22291
  role: output.role
22076
- })) : spec.character?.kind === "layer" ? spec.character.layer.sources.flatMap((source) => {
22077
- const sourceEntry = lock.entries[lockKey(source.spec.styleId, source.spec.assetId)];
22078
- return sourceEntry.outputs.map((output, index) => ({
22079
- path: currentEntryOutputPath(sourceEntry, source.spec, index),
22080
- role: output.role,
22081
- assetId: source.assetId,
22082
- still: source.spec.character?.kind !== "animation"
22083
- }));
22084
- }) : void 0;
22292
+ })) : spec.character?.kind === "layer" ? layerSourceOutputs(spec, lock) : void 0;
22085
22293
  const referenceSourceImageId = ownedReferenceImageId(spec, lock, provider.id);
22086
22294
  const { jobId, metadata } = await provider.submit(spec, refs, {
22087
22295
  ...previousJobId ? { previousJobId } : {},
@@ -22130,6 +22338,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
22130
22338
  log(
22131
22339
  ` ${key3} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
22132
22340
  );
22341
+ const sheet = metadata?.character?.sheet;
22342
+ if (sheet?.necks) {
22343
+ log(` neck rows by frame: ${sheet.necks.map((row) => row ?? "-").join(" ")}`);
22344
+ if (sheet.neckCorrected?.length) {
22345
+ log(` frame${sheet.neckCorrected.length === 1 ? "" : "s"} ${sheet.neckCorrected.join(", ")}: own narrowest row disagreed; neck taken from the head and the other frames`);
22346
+ }
22347
+ }
22133
22348
  } catch (err) {
22134
22349
  const message6 = err instanceof Error ? err.message : String(err);
22135
22350
  const entry = lock.entries[key3];
@@ -22169,8 +22384,8 @@ function ownedReferenceImageId(spec, lock, providerId) {
22169
22384
 
22170
22385
  // src/pick/candidates.ts
22171
22386
  import { existsSync as existsSync28 } from "fs";
22172
- import { mkdir as mkdir14, readFile as readFile20, rename as rename8, rm as rm7, writeFile as writeFile14 } from "fs/promises";
22173
- import path33 from "path";
22387
+ import { mkdir as mkdir15, readFile as readFile20, rename as rename8, rm as rm8, writeFile as writeFile15 } from "fs/promises";
22388
+ import path34 from "path";
22174
22389
  import { z as z8 } from "zod";
22175
22390
  var REVIEW_STATE_VERSION = 1;
22176
22391
  var CandidateSchema = z8.object({
@@ -22214,12 +22429,12 @@ var ReviewStateSchema = z8.object({
22214
22429
  assets: z8.record(ReviewAssetSchema)
22215
22430
  });
22216
22431
  function candidateCacheDirFor(lockPath) {
22217
- return path33.resolve(path33.dirname(lockPath), ".pixelkiln", "cache");
22432
+ return path34.resolve(path34.dirname(lockPath), ".pixelkiln", "cache");
22218
22433
  }
22219
22434
  function reviewStatePathFor(lockPath) {
22220
- const base = path33.basename(lockPath);
22435
+ const base = path34.basename(lockPath);
22221
22436
  const name = base === "pixelkiln.lock.json" ? "review-state.json" : `${base.replace(/\.json$/, "")}.review-state.json`;
22222
- return path33.resolve(path33.dirname(lockPath), ".pixelkiln", name);
22437
+ return path34.resolve(path34.dirname(lockPath), ".pixelkiln", name);
22223
22438
  }
22224
22439
  async function loadReviewState(file) {
22225
22440
  if (!existsSync28(file)) return { version: REVIEW_STATE_VERSION, assets: {} };
@@ -22231,13 +22446,13 @@ async function loadReviewState(file) {
22231
22446
  return { version: REVIEW_STATE_VERSION, assets: {} };
22232
22447
  }
22233
22448
  async function saveReviewState(file, state) {
22234
- await mkdir14(path33.dirname(file), { recursive: true });
22449
+ await mkdir15(path34.dirname(file), { recursive: true });
22235
22450
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
22236
22451
  try {
22237
- await writeFile14(tmp, JSON.stringify(state, null, 2) + "\n");
22452
+ await writeFile15(tmp, JSON.stringify(state, null, 2) + "\n");
22238
22453
  await rename8(tmp, file);
22239
22454
  } finally {
22240
- await rm7(tmp, { force: true });
22455
+ await rm8(tmp, { force: true });
22241
22456
  }
22242
22457
  }
22243
22458
  async function updateReviewAsset(file, key3, change) {
@@ -22251,7 +22466,7 @@ async function updateReviewAsset(file, key3, change) {
22251
22466
  }
22252
22467
  function cachedCandidatePath(cacheDir, candidate) {
22253
22468
  if (!candidate.sha256 || !candidate.mediaType) return null;
22254
- const file = path33.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22469
+ const file = path34.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22255
22470
  return existsSync28(file) ? file : null;
22256
22471
  }
22257
22472
  function fullyCached(cacheDir, asset) {
@@ -22460,11 +22675,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
22460
22675
  // src/pipeline/doctor.ts
22461
22676
  import { constants, existsSync as existsSync30 } from "fs";
22462
22677
  import { access, stat as stat3 } from "fs/promises";
22463
- import path35 from "path";
22678
+ import path36 from "path";
22464
22679
 
22465
22680
  // src/pipeline/install-check.ts
22466
22681
  import { existsSync as existsSync29, readFileSync as readFileSync9 } from "fs";
22467
- import path34 from "path";
22682
+ import path35 from "path";
22468
22683
  function readJson(file) {
22469
22684
  try {
22470
22685
  return JSON.parse(readFileSync9(file, "utf8"));
@@ -22473,18 +22688,18 @@ function readJson(file) {
22473
22688
  }
22474
22689
  }
22475
22690
  function readInstallFacts(manifestDir, running) {
22476
- let dir = path34.resolve(manifestDir);
22691
+ let dir = path35.resolve(manifestDir);
22477
22692
  for (let depth = 0; depth < 4; depth++) {
22478
- const pkg = readJson(path34.join(dir, "package.json"));
22693
+ const pkg = readJson(path35.join(dir, "package.json"));
22479
22694
  if (pkg) {
22480
22695
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
22481
22696
  if (pinned) {
22482
- const installedPkg = readJson(path34.join(dir, "node_modules", "pixelkiln", "package.json"));
22697
+ const installedPkg = readJson(path35.join(dir, "node_modules", "pixelkiln", "package.json"));
22483
22698
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
22484
22699
  return { pinned, installed, running };
22485
22700
  }
22486
22701
  }
22487
- const parent = path34.dirname(dir);
22702
+ const parent = path35.dirname(dir);
22488
22703
  if (parent === dir || !existsSync29(parent)) break;
22489
22704
  dir = parent;
22490
22705
  }
@@ -22548,12 +22763,12 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22548
22763
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
22549
22764
  );
22550
22765
  }
22551
- const facts = readInstallFacts(path35.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
22766
+ const facts = readInstallFacts(path36.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
22552
22767
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
22553
22768
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
22554
22769
  const dirs = [...new Set(specs.flatMap((spec) => [
22555
- path35.dirname(spec.outFile),
22556
- ...spec.quality ? [path35.dirname(spec.quality.outFile)] : []
22770
+ path36.dirname(spec.outFile),
22771
+ ...spec.quality ? [path36.dirname(spec.quality.outFile)] : []
22557
22772
  ]))];
22558
22773
  const unwritable = [];
22559
22774
  for (const dir of dirs) {
@@ -22576,7 +22791,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22576
22791
  for (let index = 0; index < entry.outputs.length; index++) {
22577
22792
  const output = entry.outputs[index];
22578
22793
  const spec = specByKey.get(key3);
22579
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path35.dirname(lockPath));
22794
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path36.dirname(lockPath));
22580
22795
  const owner = outputOwners.get(absolute);
22581
22796
  if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
22582
22797
  outputOwners.set(absolute, key3);
@@ -22591,7 +22806,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22591
22806
  } else {
22592
22807
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
22593
22808
  }
22594
- const cacheDir = path35.join(path35.dirname(lockPath), ".pixelkiln", "cache");
22809
+ const cacheDir = path36.join(path36.dirname(lockPath), ".pixelkiln", "cache");
22595
22810
  const stranded = [];
22596
22811
  const invalidState = [];
22597
22812
  const staleMapUrls = [];
@@ -22607,7 +22822,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22607
22822
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
22608
22823
  let hasCache = false;
22609
22824
  for (const output of entry.outputs) {
22610
- const cached2 = path35.join(
22825
+ const cached2 = path36.join(
22611
22826
  cacheDir,
22612
22827
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
22613
22828
  );
@@ -22707,7 +22922,7 @@ async function nearestExistingDirectory(start) {
22707
22922
  if ((await stat3(current)).isDirectory()) return current;
22708
22923
  } catch {
22709
22924
  }
22710
- const parent = path35.dirname(current);
22925
+ const parent = path36.dirname(current);
22711
22926
  if (parent === current) return current;
22712
22927
  current = parent;
22713
22928
  }
@@ -22715,8 +22930,8 @@ async function nearestExistingDirectory(start) {
22715
22930
 
22716
22931
  // src/pipeline/adopt.ts
22717
22932
  import { existsSync as existsSync31 } from "fs";
22718
- import { readFile as readFile21, writeFile as writeFile15 } from "fs/promises";
22719
- import path36 from "path";
22933
+ import { readFile as readFile21, writeFile as writeFile16 } from "fs/promises";
22934
+ import path37 from "path";
22720
22935
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
22721
22936
  const log = opts.onProgress ?? (() => {
22722
22937
  });
@@ -22851,7 +23066,7 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
22851
23066
  // src/pipeline/import.ts
22852
23067
  import { existsSync as existsSync32 } from "fs";
22853
23068
  import { readdir as readdir4, readFile as readFile22 } from "fs/promises";
22854
- import path37 from "path";
23069
+ import path38 from "path";
22855
23070
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date(), frames) {
22856
23071
  const png = decodePng(bytes);
22857
23072
  for (const frame of frames ?? []) decodePng(frame.bytes);
@@ -22904,10 +23119,10 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
22904
23119
  var frameRole2 = (index) => `frame-${String(index).padStart(2, "0")}`;
22905
23120
  async function findFrames(spec) {
22906
23121
  const at2 = (index) => memberPath(spec.outFile, frameRole2(index), 0, 2, MediaType.PNG);
22907
- const base = path37.basename(at2(0)).replace(/00\.png$/, "");
23122
+ const base = path38.basename(at2(0)).replace(/00\.png$/, "");
22908
23123
  let names = [];
22909
23124
  try {
22910
- names = await readdir4(path37.dirname(spec.outFile));
23125
+ names = await readdir4(path38.dirname(spec.outFile));
22911
23126
  } catch {
22912
23127
  names = [];
22913
23128
  }
@@ -22937,7 +23152,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22937
23152
  if (opts.objectId && specs.length !== 1) {
22938
23153
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
22939
23154
  }
22940
- const cacheDir = opts.cacheDir === false ? null : path37.resolve(opts.cacheDir ?? path37.join(path37.dirname(lockPath), ".pixelkiln", "cache"));
23155
+ const cacheDir = opts.cacheDir === false ? null : path38.resolve(opts.cacheDir ?? path38.join(path38.dirname(lockPath), ".pixelkiln", "cache"));
22941
23156
  let rawSha256;
22942
23157
  let rawBytes;
22943
23158
  if (opts.raw) {
@@ -22967,7 +23182,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22967
23182
  continue;
22968
23183
  }
22969
23184
  if ("missing" in frames2) {
22970
- skipped.push({ key: key3, reason: `frame set is missing ${frames2.missing.map((file) => path37.basename(file)).join(", ")} (in ${path37.dirname(spec.outFile)})` });
23185
+ skipped.push({ key: key3, reason: `frame set is missing ${frames2.missing.map((file) => path38.basename(file)).join(", ")} (in ${path38.dirname(spec.outFile)})` });
22971
23186
  continue;
22972
23187
  }
22973
23188
  frameFiles = frames2.files;
@@ -23047,9 +23262,9 @@ import { existsSync as existsSync34 } from "fs";
23047
23262
  import { readFile as readFile25 } from "fs/promises";
23048
23263
 
23049
23264
  // src/pipeline/init.ts
23050
- import { readdir as readdir5, readFile as readFile23, writeFile as writeFile16 } from "fs/promises";
23265
+ import { readdir as readdir5, readFile as readFile23, writeFile as writeFile17 } from "fs/promises";
23051
23266
  import { existsSync as existsSync33 } from "fs";
23052
- import path38 from "path";
23267
+ import path39 from "path";
23053
23268
  function pngSize(buf) {
23054
23269
  if (buf.length < 24) return null;
23055
23270
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -23063,7 +23278,7 @@ function slugify(value) {
23063
23278
  async function walk(dir, exclude) {
23064
23279
  const out = [];
23065
23280
  for (const entry of await readdir5(dir, { withFileTypes: true })) {
23066
- const full = path38.join(dir, entry.name);
23281
+ const full = path39.join(dir, entry.name);
23067
23282
  if (exclude.some((x) => full.includes(x))) continue;
23068
23283
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
23069
23284
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -23082,9 +23297,9 @@ async function scanAssets(root, opts = {}) {
23082
23297
  skipped.push(`${file} (not a readable PNG)`);
23083
23298
  continue;
23084
23299
  }
23085
- const rel = path38.relative(root, file);
23086
- const category = path38.dirname(rel) === "." ? "" : path38.dirname(rel);
23087
- let id = slugify(path38.basename(rel));
23300
+ const rel = path39.relative(root, file);
23301
+ const category = path39.dirname(rel) === "." ? "" : path39.dirname(rel);
23302
+ let id = slugify(path39.basename(rel));
23088
23303
  if (seen.has(id)) {
23089
23304
  const n = seen.get(id) + 1;
23090
23305
  seen.set(id, n);
@@ -24591,12 +24806,12 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
24591
24806
  import { createHash as createHash8 } from "crypto";
24592
24807
  import { existsSync as existsSync43 } from "fs";
24593
24808
  import { readFile as readFile35, stat as stat5 } from "fs/promises";
24594
- import path49 from "path";
24809
+ import path50 from "path";
24595
24810
 
24596
24811
  // src/gallery/models.ts
24597
24812
  import { existsSync as existsSync38 } from "fs";
24598
24813
  import { readFile as readFile30, stat as stat4 } from "fs/promises";
24599
- import path43 from "path";
24814
+ import path44 from "path";
24600
24815
  import { z as z12 } from "zod";
24601
24816
 
24602
24817
  // src/glb.ts
@@ -24929,11 +25144,11 @@ function modelItems(json2) {
24929
25144
  }
24930
25145
 
24931
25146
  // src/manifest-edit.ts
24932
- import { readFile as readFile26, rename as rename9, rm as rm8, writeFile as writeFile17 } from "fs/promises";
24933
- import path39 from "path";
25147
+ import { readFile as readFile26, rename as rename9, rm as rm9, writeFile as writeFile18 } from "fs/promises";
25148
+ import path40 from "path";
24934
25149
  import { z as z9 } from "zod";
24935
25150
  var HexSha = z9.string().regex(/^[0-9a-f]{64}$/);
24936
- var ProjectFileSchema = z9.string().min(1).refine((file) => !path39.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
25151
+ var ProjectFileSchema = z9.string().min(1).refine((file) => !path40.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
24937
25152
  var AssetPatchSchema = z9.object({
24938
25153
  prompt: z9.string().optional(),
24939
25154
  /** Per-style override for the style being viewed; null removes it. */
@@ -25354,7 +25569,7 @@ function applyEdit(raw, edit) {
25354
25569
  }
25355
25570
  }
25356
25571
  async function withCandidate(manifestPath, edit, use, unchanged) {
25357
- const absolute = path39.resolve(manifestPath);
25572
+ const absolute = path40.resolve(manifestPath);
25358
25573
  const original = await readFile26(absolute, "utf8");
25359
25574
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
25360
25575
  let raw;
@@ -25368,12 +25583,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
25368
25583
  applyEdit(raw, edit);
25369
25584
  const next = serializeLike(original, raw);
25370
25585
  if (next === original) return unchanged(absolute, original);
25371
- const tmp = path39.join(
25372
- path39.dirname(absolute),
25373
- `.${path39.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
25586
+ const tmp = path40.join(
25587
+ path40.dirname(absolute),
25588
+ `.${path40.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
25374
25589
  );
25375
25590
  try {
25376
- await writeFile17(tmp, next);
25591
+ await writeFile18(tmp, next);
25377
25592
  let specs;
25378
25593
  try {
25379
25594
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -25383,7 +25598,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
25383
25598
  }
25384
25599
  return await use({ absolute, original, next, tmp, specs });
25385
25600
  } finally {
25386
- await rm8(tmp, { force: true });
25601
+ await rm9(tmp, { force: true });
25387
25602
  }
25388
25603
  }
25389
25604
  async function applyManifestEdit(manifestPath, edit) {
@@ -25400,17 +25615,17 @@ async function applyManifestEdit(manifestPath, edit) {
25400
25615
 
25401
25616
  // src/pipeline/hand-edit.ts
25402
25617
  import { existsSync as existsSync35 } from "fs";
25403
- import { copyFile, mkdir as mkdir15, readFile as readFile27, rename as rename10, rm as rm9, writeFile as writeFile18 } from "fs/promises";
25404
- import path40 from "path";
25618
+ import { copyFile, mkdir as mkdir16, readFile as readFile27, rename as rename10, rm as rm10, writeFile as writeFile19 } from "fs/promises";
25619
+ import path41 from "path";
25405
25620
  import { z as z10 } from "zod";
25406
25621
  var HAND_EDIT_DIR = "edits";
25407
25622
  function handEditPath(loaded, spec) {
25408
25623
  const style = loaded.manifest.styles[spec.styleId];
25409
- const outDir = path40.resolve(loaded.root, style?.outDir ?? ".");
25410
- const relative = path40.relative(outDir, spec.outFile);
25411
- const inside2 = relative && !relative.startsWith("..") && !path40.isAbsolute(relative);
25412
- const file = inside2 ? relative : path40.basename(spec.outFile);
25413
- return path40.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
25624
+ const outDir = path41.resolve(loaded.root, style?.outDir ?? ".");
25625
+ const relative = path41.relative(outDir, spec.outFile);
25626
+ const inside2 = relative && !relative.startsWith("..") && !path41.isAbsolute(relative);
25627
+ const file = inside2 ? relative : path41.basename(spec.outFile);
25628
+ return path41.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
25414
25629
  }
25415
25630
  function handEditBases(spec, lock) {
25416
25631
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -25476,7 +25691,7 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
25476
25691
  `${spec.styleId}/${spec.assetId} declares ${spec.source}, one committed file placed for the whole set; clear that source (pixelkiln edit detach) to hand-edit the members one by one`
25477
25692
  );
25478
25693
  }
25479
- const existing = spec.source ? path40.resolve(loaded.root, spec.source) : null;
25694
+ const existing = spec.source ? path41.resolve(loaded.root, spec.source) : null;
25480
25695
  const editPath = existing ?? handEditPath(loaded, spec);
25481
25696
  const members = handEditMembers(loaded, spec, lock, editPath);
25482
25697
  let created = false;
@@ -25487,7 +25702,7 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
25487
25702
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
25488
25703
  );
25489
25704
  }
25490
- await mkdir15(path40.dirname(member.path), { recursive: true });
25705
+ await mkdir16(path41.dirname(member.path), { recursive: true });
25491
25706
  await copyFile(member.base, member.path);
25492
25707
  created = true;
25493
25708
  }
@@ -25626,7 +25841,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
25626
25841
  editor: input.editor,
25627
25842
  protocol: input.protocol,
25628
25843
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
25629
- project: projectPath ? path40.basename(projectPath) : null,
25844
+ project: projectPath ? path41.basename(projectPath) : null,
25630
25845
  outputs: incoming.map((frame, index) => ({
25631
25846
  role: frame.role,
25632
25847
  basedOn: basedOnHash(entry, index),
@@ -25656,10 +25871,10 @@ function basedOnHash(entry, index) {
25656
25871
  async function replaceFile(file, bytes) {
25657
25872
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
25658
25873
  try {
25659
- await writeFile18(tmp, bytes);
25874
+ await writeFile19(tmp, bytes);
25660
25875
  await rename10(tmp, file);
25661
25876
  } finally {
25662
- await rm9(tmp, { force: true });
25877
+ await rm10(tmp, { force: true });
25663
25878
  }
25664
25879
  }
25665
25880
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -25670,8 +25885,8 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
25670
25885
  // src/pipeline/model-edit.ts
25671
25886
  import { spawn as spawn2 } from "child_process";
25672
25887
  import { existsSync as existsSync36, readdirSync as readdirSync2 } from "fs";
25673
- import { mkdir as mkdir16, readdir as readdir6, readFile as readFile28, rename as rename11, rm as rm10, writeFile as writeFile19 } from "fs/promises";
25674
- import path41 from "path";
25888
+ import { mkdir as mkdir17, readdir as readdir6, readFile as readFile28, rename as rename11, rm as rm11, writeFile as writeFile20 } from "fs/promises";
25889
+ import path42 from "path";
25675
25890
  import { z as z11 } from "zod";
25676
25891
 
25677
25892
  // src/jpeg.ts
@@ -26053,7 +26268,7 @@ var MAX_MODELS = 200;
26053
26268
  var MAX_DEPTH = 8;
26054
26269
  var SKIPPED_DIRS = /* @__PURE__ */ new Set([HAND_EDIT_DIR, "node_modules"]);
26055
26270
  async function discoverModels(loaded, opts = {}) {
26056
- const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: path41.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
26271
+ const styles = Object.entries(loaded.manifest.styles).filter(([id]) => !opts.styles?.length || opts.styles.includes(id)).map(([id, style]) => ({ id, outDir: path42.resolve(loaded.root, style.outDir ?? ".") })).sort((a, b) => b.outDir.length - a.outDir.length || a.id.localeCompare(b.id));
26057
26272
  const seen = /* @__PURE__ */ new Set();
26058
26273
  const models = [];
26059
26274
  const walk2 = async (styleId, outDir, dir, depth) => {
@@ -26067,13 +26282,13 @@ async function discoverModels(loaded, opts = {}) {
26067
26282
  entries.sort((a, b) => a.name.localeCompare(b.name));
26068
26283
  for (const entry of entries) {
26069
26284
  if (models.length >= MAX_MODELS) return;
26070
- const full = path41.join(dir, entry.name);
26285
+ const full = path42.join(dir, entry.name);
26071
26286
  if (entry.isDirectory()) {
26072
26287
  if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
26073
26288
  await walk2(styleId, outDir, full, depth + 1);
26074
26289
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith(MODEL_EXTENSION) && !seen.has(full)) {
26075
26290
  seen.add(full);
26076
- models.push({ styleId, file: full, editFile: path41.join(outDir, HAND_EDIT_DIR, path41.relative(outDir, full)) });
26291
+ models.push({ styleId, file: full, editFile: path42.join(outDir, HAND_EDIT_DIR, path42.relative(outDir, full)) });
26077
26292
  }
26078
26293
  }
26079
26294
  };
@@ -26081,12 +26296,12 @@ async function discoverModels(loaded, opts = {}) {
26081
26296
  return models.sort((a, b) => a.styleId.localeCompare(b.styleId) || a.file.localeCompare(b.file));
26082
26297
  }
26083
26298
  async function findModel(loaded, portablePath) {
26084
- const wanted = path41.resolve(loaded.root, portablePath);
26299
+ const wanted = path42.resolve(loaded.root, portablePath);
26085
26300
  const model = (await discoverModels(loaded)).find((candidate) => candidate.file === wanted);
26086
26301
  if (!model) throw new ManifestEditError(`"${portablePath}" is not a model under one of this project's output folders`);
26087
26302
  return model;
26088
26303
  }
26089
- var stem = (editFile) => editFile.slice(0, -path41.extname(editFile).length);
26304
+ var stem = (editFile) => editFile.slice(0, -path42.extname(editFile).length);
26090
26305
  function modelCompanionPath(editFile) {
26091
26306
  return stem(editFile) + ".edit.json";
26092
26307
  }
@@ -26135,13 +26350,13 @@ function modelEditStatus(companion, builtSha256) {
26135
26350
  return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
26136
26351
  }
26137
26352
  async function replaceFile2(file, bytes) {
26138
- await mkdir16(path41.dirname(file), { recursive: true });
26353
+ await mkdir17(path42.dirname(file), { recursive: true });
26139
26354
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
26140
26355
  try {
26141
- await writeFile19(tmp, bytes);
26356
+ await writeFile20(tmp, bytes);
26142
26357
  await rename11(tmp, file);
26143
26358
  } finally {
26144
- await rm10(tmp, { force: true });
26359
+ await rm11(tmp, { force: true });
26145
26360
  }
26146
26361
  }
26147
26362
  async function readModel(file, what) {
@@ -26196,7 +26411,7 @@ async function saveModelTexture(model, input) {
26196
26411
  sha256: sha256(input.png),
26197
26412
  editor: input.editor,
26198
26413
  savedAt,
26199
- project: projectPath ? path41.basename(projectPath) : null
26414
+ project: projectPath ? path42.basename(projectPath) : null
26200
26415
  };
26201
26416
  const companion = {
26202
26417
  version: 2,
@@ -26300,16 +26515,16 @@ function blenderCommand(env = process.env, platform = process.platform, exists =
26300
26515
  const candidates = [];
26301
26516
  if (platform === "darwin") {
26302
26517
  candidates.push("/Applications/Blender.app/Contents/MacOS/Blender");
26303
- if (env.HOME) candidates.push(path41.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
26518
+ if (env.HOME) candidates.push(path42.join(env.HOME, "Applications/Blender.app/Contents/MacOS/Blender"));
26304
26519
  } else if (platform === "win32") {
26305
26520
  for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((value) => Boolean(value))) {
26306
- const foundation = path41.win32.join(root, "Blender Foundation");
26521
+ const foundation = path42.win32.join(root, "Blender Foundation");
26307
26522
  const versions = list(foundation).filter((name) => /^Blender/i.test(name)).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
26308
- for (const version of versions) candidates.push(path41.win32.join(foundation, version, "blender.exe"));
26523
+ for (const version of versions) candidates.push(path42.win32.join(foundation, version, "blender.exe"));
26309
26524
  }
26310
26525
  } else {
26311
26526
  candidates.push("/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/var/lib/flatpak/exports/bin/org.blender.Blender");
26312
- for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(path41.join(dir, "blender"));
26527
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) candidates.push(path42.join(dir, "blender"));
26313
26528
  }
26314
26529
  const found = candidates.find((candidate) => exists(candidate));
26315
26530
  return found ? [found] : null;
@@ -26352,14 +26567,14 @@ function openInBlender(model, opts = {}) {
26352
26567
  child.unref();
26353
26568
  });
26354
26569
  launch(program, args);
26355
- return `${command.join(" ")} (${path41.basename(file)})`;
26570
+ return `${command.join(" ")} (${path42.basename(file)})`;
26356
26571
  }
26357
26572
 
26358
26573
  // src/pipeline/model-normals.ts
26359
26574
  import { createHash as createHash7 } from "crypto";
26360
26575
  import { existsSync as existsSync37 } from "fs";
26361
- import { mkdir as mkdir17, readdir as readdir7, readFile as readFile29, writeFile as writeFile20 } from "fs/promises";
26362
- import path42 from "path";
26576
+ import { mkdir as mkdir18, readdir as readdir7, readFile as readFile29, writeFile as writeFile21 } from "fs/promises";
26577
+ import path43 from "path";
26363
26578
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
26364
26579
  var TILE_MAX = 512;
26365
26580
  function decodeImage(bytes) {
@@ -26451,13 +26666,13 @@ function poseNodes(document, pose) {
26451
26666
  const posed = /* @__PURE__ */ new Map();
26452
26667
  for (const channel of animation.channels) {
26453
26668
  const node = channel.target.node;
26454
- const path54 = channel.target.path;
26455
- if (node === void 0 || !["translation", "rotation", "scale"].includes(path54)) continue;
26669
+ const path55 = channel.target.path;
26670
+ if (node === void 0 || !["translation", "rotation", "scale"].includes(path55)) continue;
26456
26671
  const sampler = animation.samplers[channel.sampler];
26457
26672
  if (!sampler) continue;
26458
26673
  const times = readAccessor(document, sampler.input).data;
26459
26674
  const values = readAccessor(document, sampler.output);
26460
- const width = path54 === "rotation" ? 4 : 3;
26675
+ const width = path55 === "rotation" ? 4 : 3;
26461
26676
  const cubic = sampler.interpolation === "CUBICSPLINE";
26462
26677
  const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
26463
26678
  const last = times.length - 1;
@@ -26469,16 +26684,16 @@ function poseNodes(document, pose) {
26469
26684
  const span = times[key3 + 1] - times[key3];
26470
26685
  const f = span > 0 ? (time - times[key3]) / span : 0;
26471
26686
  const next = valueAt(key3 + 1);
26472
- const sign = path54 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
26687
+ const sign = path55 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
26473
26688
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
26474
26689
  }
26475
- if (path54 === "rotation") {
26690
+ if (path55 === "rotation") {
26476
26691
  const length = Math.hypot(...value) || 1;
26477
26692
  value = value.map((v) => v / length);
26478
26693
  }
26479
26694
  const base = posed.get(node) ?? { ...document.json.nodes?.[node] ?? {} };
26480
26695
  if (base.matrix) delete base.matrix;
26481
- base[path54] = value;
26696
+ base[path55] = value;
26482
26697
  posed.set(node, base);
26483
26698
  }
26484
26699
  return posed;
@@ -27088,9 +27303,9 @@ function modelSpritesDir(modelFile) {
27088
27303
  return modelFile.replace(/\.glb$/i, "") + ".sprites";
27089
27304
  }
27090
27305
  async function readSpriteFolder(dir) {
27091
- const folder = existsSync37(path42.join(dir, "rotations")) ? path42.join(dir, "rotations") : dir;
27306
+ const folder = existsSync37(path43.join(dir, "rotations")) ? path43.join(dir, "rotations") : dir;
27092
27307
  const names = (await readdir7(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
27093
- return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await readFile29(path42.join(folder, name)), file: path42.join(folder, name) })));
27308
+ return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await readFile29(path43.join(folder, name)), file: path43.join(folder, name) })));
27094
27309
  }
27095
27310
  function modelNormalDir(editFile) {
27096
27311
  return editFile.replace(/\.glb$/i, "") + ".normal-map";
@@ -27110,13 +27325,13 @@ async function prepare(model, opts) {
27110
27325
  if (!normalImages.some((image) => image.index === index)) throw new Error(`image ${index} is not one of the model's normal maps`);
27111
27326
  }
27112
27327
  const primitives = restPrimitives(document, opts.pose);
27113
- const dir = path42.join(modelNormalDir(model.editFile), opts.source);
27328
+ const dir = path43.join(modelNormalDir(model.editFile), opts.source);
27114
27329
  const surfaces = /* @__PURE__ */ new Map();
27115
27330
  const tiles = /* @__PURE__ */ new Map();
27116
27331
  const calls = [];
27117
27332
  const images = [];
27118
27333
  const call = (label, png) => {
27119
- const cache = path42.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
27334
+ const cache = path43.join(dir, `${label.replace(/[^a-z0-9]+/gi, "-")}.${requestKey(png, opts)}.normal.png`);
27120
27335
  calls.push({ label, png, cache, cached: existsSync37(cache) });
27121
27336
  };
27122
27337
  for (const index of wanted) {
@@ -27185,15 +27400,15 @@ async function prepare(model, opts) {
27185
27400
  }
27186
27401
  async function planModelNormals(model, opts) {
27187
27402
  const { plan } = await prepare(model, opts);
27188
- await mkdir17(plan.dir, { recursive: true });
27189
- for (const entry of plan.calls) await writeFile20(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27190
- for (const fit of plan.fits ?? []) await writeFile20(path42.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
27403
+ await mkdir18(plan.dir, { recursive: true });
27404
+ for (const entry of plan.calls) await writeFile21(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27405
+ for (const fit of plan.fits ?? []) await writeFile21(path43.join(plan.dir, `${fit.label.replace(/[^a-z0-9]+/gi, "-")}.fit.png`), fit.png);
27191
27406
  return plan;
27192
27407
  }
27193
27408
  async function generateModelNormals(model, opts, mapper, hooks = {}) {
27194
27409
  const prepared = await prepare(model, opts);
27195
27410
  const { plan, document } = prepared;
27196
- await mkdir17(plan.dir, { recursive: true });
27411
+ await mkdir18(plan.dir, { recursive: true });
27197
27412
  const request = {
27198
27413
  ...opts.mode ? { mode: opts.mode } : {},
27199
27414
  ...opts.kind ? { kind: opts.kind } : {},
@@ -27205,14 +27420,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
27205
27420
  let sent = 0;
27206
27421
  for (const entry of plan.calls) {
27207
27422
  hooks.onCall?.(entry.label, entry.cached);
27208
- await writeFile20(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27423
+ await writeFile21(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27209
27424
  if (entry.cached) {
27210
27425
  answers.push(await readFile29(entry.cache));
27211
27426
  continue;
27212
27427
  }
27213
27428
  const answer = await mapper(entry.png, request);
27214
27429
  sent++;
27215
- await writeFile20(entry.cache, answer);
27430
+ await writeFile21(entry.cache, answer);
27216
27431
  answers.push(answer);
27217
27432
  }
27218
27433
  let result = null;
@@ -27230,14 +27445,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
27230
27445
  field = detailFromViews(surface, prepared.views, answers);
27231
27446
  }
27232
27447
  bleed(field);
27233
- const detail = path42.join(plan.dir, `image-${image}.detail.png`);
27234
- await writeFile20(detail, encodeImage(fieldImage(field)));
27448
+ const detail = path43.join(plan.dir, `image-${image}.detail.png`);
27449
+ await writeFile21(detail, encodeImage(fieldImage(field)));
27235
27450
  details.push(detail);
27236
- const basePath = path42.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
27451
+ const basePath = path43.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
27237
27452
  const record = companion?.textures.find((entry) => entry.image === image);
27238
27453
  const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && existsSync37(basePath);
27239
27454
  const existing = ours ? decodeImage(await readFile29(basePath)) : decodeImage(glbImageBytes(document, image).bytes);
27240
- if (!ours) await writeFile20(basePath, encodeImage(existing));
27455
+ if (!ours) await writeFile21(basePath, encodeImage(existing));
27241
27456
  const png = encodeImage(applyDetail(existing, field, opts));
27242
27457
  result = await saveModelTexture(model, {
27243
27458
  image,
@@ -27289,7 +27504,7 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27289
27504
  } catch {
27290
27505
  continue;
27291
27506
  }
27292
- const outDir = path43.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
27507
+ const outDir = path44.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
27293
27508
  let summary = null;
27294
27509
  let error = null;
27295
27510
  if (bytes.length > MAX_MODEL_BYTES) error = `the file is ${bytes.length} bytes; models over ${MAX_MODEL_BYTES} are listed but not opened`;
@@ -27355,12 +27570,12 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27355
27570
  } catch {
27356
27571
  }
27357
27572
  }
27358
- const relative = path43.relative(outDir, model.file).split(path43.sep).join("/");
27573
+ const relative = path44.relative(outDir, model.file).split(path44.sep).join("/");
27359
27574
  models.push({
27360
27575
  id: `model:${model.styleId}/${relative}`,
27361
27576
  project: null,
27362
27577
  styleId: model.styleId,
27363
- name: path43.basename(model.file, path43.extname(model.file)),
27578
+ name: path44.basename(model.file, path44.extname(model.file)),
27364
27579
  file,
27365
27580
  summary,
27366
27581
  error,
@@ -27455,9 +27670,9 @@ function blenderAvailable() {
27455
27670
  }
27456
27671
 
27457
27672
  // src/workspace.ts
27458
- import { mkdir as mkdir18, readFile as readFile31, rename as rename12, rm as rm11, writeFile as writeFile21 } from "fs/promises";
27673
+ import { mkdir as mkdir19, readFile as readFile31, rename as rename12, rm as rm12, writeFile as writeFile22 } from "fs/promises";
27459
27674
  import { existsSync as existsSync39 } from "fs";
27460
- import path44 from "path";
27675
+ import path45 from "path";
27461
27676
  import { z as z13 } from "zod";
27462
27677
  var WorkspaceProjectSchema = z13.object({
27463
27678
  id: z13.string().min(1),
@@ -27499,22 +27714,22 @@ async function saveWorkspace(workspacePath, ws) {
27499
27714
  version: 1,
27500
27715
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
27501
27716
  };
27502
- await mkdir18(path44.dirname(path44.resolve(workspacePath)), { recursive: true });
27717
+ await mkdir19(path45.dirname(path45.resolve(workspacePath)), { recursive: true });
27503
27718
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
27504
27719
  try {
27505
- await writeFile21(tmp, JSON.stringify(sorted, null, 2) + "\n");
27720
+ await writeFile22(tmp, JSON.stringify(sorted, null, 2) + "\n");
27506
27721
  await rename12(tmp, workspacePath);
27507
27722
  } finally {
27508
- await rm11(tmp, { force: true });
27723
+ await rm12(tmp, { force: true });
27509
27724
  }
27510
27725
  }
27511
27726
  function toPortablePath(dir, absolute) {
27512
- return path44.relative(dir, absolute).split(path44.sep).join("/");
27727
+ return path45.relative(dir, absolute).split(path45.sep).join("/");
27513
27728
  }
27514
27729
  function resolveProject(dir, project2) {
27515
27730
  return {
27516
- manifestPath: path44.resolve(dir, project2.manifest.split("/").join(path44.sep)),
27517
- lockPath: path44.resolve(dir, project2.lock.split("/").join(path44.sep))
27731
+ manifestPath: path45.resolve(dir, project2.manifest.split("/").join(path45.sep)),
27732
+ lockPath: path45.resolve(dir, project2.lock.split("/").join(path45.sep))
27518
27733
  };
27519
27734
  }
27520
27735
  function validateWorkspace(ws, dir) {
@@ -27527,7 +27742,7 @@ function validateWorkspace(ws, dir) {
27527
27742
  const { manifestPath, lockPath } = resolveProject(dir, project2);
27528
27743
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project2.id]);
27529
27744
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project2.id]);
27530
- if (path44.isAbsolute(project2.manifest) || path44.isAbsolute(project2.lock)) {
27745
+ if (path45.isAbsolute(project2.manifest) || path45.isAbsolute(project2.lock)) {
27531
27746
  diagnostics.push({
27532
27747
  id: "absolute-path",
27533
27748
  level: "warning",
@@ -27588,14 +27803,14 @@ function validateWorkspace(ws, dir) {
27588
27803
  }
27589
27804
 
27590
27805
  // src/gallery/edit.ts
27591
- import { readFile as readFile34, rename as rename13, writeFile as writeFile25 } from "fs/promises";
27592
- import path48 from "path";
27806
+ import { readFile as readFile34, rename as rename13, writeFile as writeFile26 } from "fs/promises";
27807
+ import path49 from "path";
27593
27808
  import { z as z17 } from "zod";
27594
27809
 
27595
27810
  // src/gallery/upload.ts
27596
27811
  import { existsSync as existsSync40 } from "fs";
27597
- import { mkdir as mkdir19, writeFile as writeFile22 } from "fs/promises";
27598
- import path45 from "path";
27812
+ import { mkdir as mkdir20, writeFile as writeFile23 } from "fs/promises";
27813
+ import path46 from "path";
27599
27814
  import { z as z14 } from "zod";
27600
27815
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
27601
27816
  var UploadImageSchema = z14.object({
@@ -27608,12 +27823,12 @@ var UploadImageSchema = z14.object({
27608
27823
  overwrite: z14.boolean().optional()
27609
27824
  }).strict();
27610
27825
  async function saveProjectImage(root, request) {
27611
- const file = path45.resolve(root, request.path);
27612
- const relative = path45.relative(root, file);
27613
- if (relative.startsWith("..") || path45.isAbsolute(relative)) {
27826
+ const file = path46.resolve(root, request.path);
27827
+ const relative = path46.relative(root, file);
27828
+ if (relative.startsWith("..") || path46.isAbsolute(relative)) {
27614
27829
  throw new ManifestEditError("an upload must stay inside the project");
27615
27830
  }
27616
- const extension = path45.extname(file).toLowerCase();
27831
+ const extension = path46.extname(file).toLowerCase();
27617
27832
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
27618
27833
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
27619
27834
  const bytes = Buffer.from(request.base64, "base64");
@@ -27626,17 +27841,17 @@ async function saveProjectImage(root, request) {
27626
27841
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
27627
27842
  }
27628
27843
  if (existsSync40(file) && !request.overwrite) {
27629
- throw new ManifestEditError(`${relative.split(path45.sep).join("/")} already exists; choose another name, or replace it`);
27844
+ throw new ManifestEditError(`${relative.split(path46.sep).join("/")} already exists; choose another name, or replace it`);
27630
27845
  }
27631
- await mkdir19(path45.dirname(file), { recursive: true });
27632
- await writeFile22(file, bytes);
27633
- return relative.split(path45.sep).join("/");
27846
+ await mkdir20(path46.dirname(file), { recursive: true });
27847
+ await writeFile23(file, bytes);
27848
+ return relative.split(path46.sep).join("/");
27634
27849
  }
27635
27850
 
27636
27851
  // src/gallery/image-revision.ts
27637
27852
  import { existsSync as existsSync41 } from "fs";
27638
- import { readFile as readFile32, rm as rm12, writeFile as writeFile23 } from "fs/promises";
27639
- import path46 from "path";
27853
+ import { readFile as readFile32, rm as rm13, writeFile as writeFile24 } from "fs/promises";
27854
+ import path47 from "path";
27640
27855
  import { z as z15 } from "zod";
27641
27856
  var InpaintRevisionRequestSchema = z15.object({
27642
27857
  action: z15.literal("create-inpaint-revision"),
@@ -27655,14 +27870,14 @@ var InpaintRevisionRequestSchema = z15.object({
27655
27870
  overwrite: z15.boolean().optional()
27656
27871
  }).strict();
27657
27872
  async function createInpaintRevision(manifestPath, request) {
27658
- const root = path46.dirname(path46.resolve(manifestPath));
27659
- if (path46.extname(request.maskPath).toLowerCase() !== ".png") {
27873
+ const root = path47.dirname(path47.resolve(manifestPath));
27874
+ if (path47.extname(request.maskPath).toLowerCase() !== ".png") {
27660
27875
  throw new ManifestEditError("the mask must be a .png path inside the project");
27661
27876
  }
27662
27877
  const bytes = Buffer.from(request.maskBase64, "base64");
27663
27878
  const metadata = imageMetadata(bytes);
27664
27879
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
27665
- const file = path46.resolve(root, request.maskPath);
27880
+ const file = path47.resolve(root, request.maskPath);
27666
27881
  const previous = existsSync41(file) ? await readFile32(file) : null;
27667
27882
  const mask = await saveProjectImage(root, {
27668
27883
  action: "upload-image",
@@ -27682,8 +27897,8 @@ async function createInpaintRevision(manifestPath, request) {
27682
27897
  }
27683
27898
  });
27684
27899
  } catch (error) {
27685
- if (previous) await writeFile23(file, previous);
27686
- else await rm12(file, { force: true });
27900
+ if (previous) await writeFile24(file, previous);
27901
+ else await rm13(file, { force: true });
27687
27902
  throw error;
27688
27903
  }
27689
27904
  return mask;
@@ -27691,8 +27906,8 @@ async function createInpaintRevision(manifestPath, request) {
27691
27906
 
27692
27907
  // src/gallery/skeleton.ts
27693
27908
  import { existsSync as existsSync42 } from "fs";
27694
- import { mkdir as mkdir20, readFile as readFile33, rm as rm13, writeFile as writeFile24 } from "fs/promises";
27695
- import path47 from "path";
27909
+ import { mkdir as mkdir21, readFile as readFile33, rm as rm14, writeFile as writeFile25 } from "fs/promises";
27910
+ import path48 from "path";
27696
27911
  import { z as z16 } from "zod";
27697
27912
  var SkeletonEstimateRequestSchema = z16.object({
27698
27913
  project: z16.string().min(1).optional(),
@@ -27731,10 +27946,10 @@ var SkeletonKeypointsUpdateSchema = z16.object({
27731
27946
  set: SkeletonSetSchema
27732
27947
  }).strict();
27733
27948
  async function createSkeletonAnimation(manifestPath, request) {
27734
- const root = path47.dirname(path47.resolve(manifestPath));
27735
- const file = path47.resolve(root, request.keypointsFile);
27736
- const relative = path47.relative(root, file);
27737
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path47.isAbsolute(relative)) {
27949
+ const root = path48.dirname(path48.resolve(manifestPath));
27950
+ const file = path48.resolve(root, request.keypointsFile);
27951
+ const relative = path48.relative(root, file);
27952
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || path48.isAbsolute(relative)) {
27738
27953
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
27739
27954
  }
27740
27955
  const existed = existsSync42(file);
@@ -27744,8 +27959,8 @@ async function createSkeletonAnimation(manifestPath, request) {
27744
27959
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
27745
27960
  }
27746
27961
  if (existed) previous = await readFile33(file);
27747
- await mkdir20(path47.dirname(file), { recursive: true });
27748
- await writeFile24(file, JSON.stringify(request.set, null, 2) + "\n");
27962
+ await mkdir21(path48.dirname(file), { recursive: true });
27963
+ await writeFile25(file, JSON.stringify(request.set, null, 2) + "\n");
27749
27964
  } else if (!existed) {
27750
27965
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
27751
27966
  }
@@ -27760,7 +27975,7 @@ async function createSkeletonAnimation(manifestPath, request) {
27760
27975
  revision: {
27761
27976
  mode: "animate-skeleton",
27762
27977
  from: request.from,
27763
- keypointsFile: relative.split(path47.sep).join("/"),
27978
+ keypointsFile: relative.split(path48.sep).join("/"),
27764
27979
  direction: request.direction,
27765
27980
  description: request.description,
27766
27981
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -27769,8 +27984,8 @@ async function createSkeletonAnimation(manifestPath, request) {
27769
27984
  });
27770
27985
  } catch (error) {
27771
27986
  if (request.set) {
27772
- if (previous) await writeFile24(file, previous);
27773
- else await rm13(file, { force: true });
27987
+ if (previous) await writeFile25(file, previous);
27988
+ else await rm14(file, { force: true });
27774
27989
  }
27775
27990
  throw error;
27776
27991
  }
@@ -27781,19 +27996,19 @@ async function updateSkeletonKeypoints(ctx, request) {
27781
27996
  if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
27782
27997
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
27783
27998
  if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
27784
- const relative = path47.relative(ctx.loaded.root, file);
27785
- if (relative.startsWith("..") || path47.isAbsolute(relative)) {
27999
+ const relative = path48.relative(ctx.loaded.root, file);
28000
+ if (relative.startsWith("..") || path48.isAbsolute(relative)) {
27786
28001
  throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
27787
28002
  }
27788
28003
  const current = existsSync42(file) ? sha256(await readFile33(file)) : null;
27789
28004
  if (current !== request.expectedSha256) {
27790
28005
  throw Object.assign(
27791
- new Error(`${relative.split(path47.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
28006
+ new Error(`${relative.split(path48.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
27792
28007
  { status: 409 }
27793
28008
  );
27794
28009
  }
27795
- await writeFile24(file, JSON.stringify(request.set, null, 2) + "\n");
27796
- return relative.split(path47.sep).join("/");
28010
+ await writeFile25(file, JSON.stringify(request.set, null, 2) + "\n");
28011
+ return relative.split(path48.sep).join("/");
27797
28012
  }
27798
28013
 
27799
28014
  // src/gallery/edit.ts
@@ -27847,7 +28062,7 @@ function createGalleryEditHandler(opts) {
27847
28062
  const history = /* @__PURE__ */ new Map();
27848
28063
  const manifestOf = async (project2) => {
27849
28064
  try {
27850
- return path48.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
28065
+ return path49.resolve(await opts.manifestFor(typeof project2 === "string" ? project2 : void 0));
27851
28066
  } catch {
27852
28067
  return null;
27853
28068
  }
@@ -27867,10 +28082,10 @@ function createGalleryEditHandler(opts) {
27867
28082
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
27868
28083
  }
27869
28084
  const tmp = manifestPath2 + ".pixelkiln-undo";
27870
- await writeFile25(tmp, last.before);
28085
+ await writeFile26(tmp, last.before);
27871
28086
  await rename13(tmp, manifestPath2);
27872
28087
  stack.pop();
27873
- log(` manifest edit undone in ${path48.relative(process.cwd(), manifestPath2) || manifestPath2}`);
28088
+ log(` manifest edit undone in ${path49.relative(process.cwd(), manifestPath2) || manifestPath2}`);
27874
28089
  return opts.reload();
27875
28090
  }
27876
28091
  const manifestPath = await manifestOf(body?.project);
@@ -27956,7 +28171,7 @@ function createEditApplier(opts, log) {
27956
28171
  } catch (error) {
27957
28172
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
27958
28173
  }
27959
- const written = await saveProjectImage(path48.dirname(path48.resolve(manifestPath2)), upload.data);
28174
+ const written = await saveProjectImage(path49.dirname(path49.resolve(manifestPath2)), upload.data);
27960
28175
  log(` image added: ${written}`);
27961
28176
  return opts.reload();
27962
28177
  }
@@ -28023,7 +28238,7 @@ function createEditApplier(opts, log) {
28023
28238
  }
28024
28239
  const result = await applyManifestEdit(manifestPath, parsed.data);
28025
28240
  if (result.changed) {
28026
- const relative = path48.relative(process.cwd(), result.manifestPath);
28241
+ const relative = path49.relative(process.cwd(), result.manifestPath);
28027
28242
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
28028
28243
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
28029
28244
  }
@@ -28051,7 +28266,7 @@ function describeEdit(edit) {
28051
28266
  // src/gallery/snapshot.ts
28052
28267
  var PROJECT_FILE_TYPE = "application/octet-stream";
28053
28268
  function galleryMediaId(absolutePath) {
28054
- return createHash8("sha256").update(path49.resolve(absolutePath)).digest("hex").slice(0, 24);
28269
+ return createHash8("sha256").update(path50.resolve(absolutePath)).digest("hex").slice(0, 24);
28055
28270
  }
28056
28271
  function galleryMediaRoute(id) {
28057
28272
  return `/media/${id}`;
@@ -28075,7 +28290,7 @@ function describeHistory(media, entry, cacheDir) {
28075
28290
  return (entry.history ?? []).map((generation, i) => {
28076
28291
  const outputs = generation.outputs.map((output) => {
28077
28292
  const mediaType = output.mediaType ?? MediaType.PNG;
28078
- const file = path49.join(cacheDir, cacheFileName(output.sha256, mediaType));
28293
+ const file = path50.join(cacheDir, cacheFileName(output.sha256, mediaType));
28079
28294
  let url = null;
28080
28295
  if (existsSync43(file)) {
28081
28296
  const id = galleryMediaId(file);
@@ -28207,9 +28422,9 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
28207
28422
  async function describeQuality(media, root, inspection) {
28208
28423
  const outputPaths = inspection.outputs ?? [inspection.output];
28209
28424
  const outputs = await Promise.all(
28210
- outputPaths.map((file) => describeOutput(media, root, path49.resolve(root, file)))
28425
+ outputPaths.map((file) => describeOutput(media, root, path50.resolve(root, file)))
28211
28426
  );
28212
- const recordPath = path49.resolve(root, inspection.record);
28427
+ const recordPath = path50.resolve(root, inspection.record);
28213
28428
  const recordExists = existsSync43(recordPath);
28214
28429
  let options = null;
28215
28430
  let check = null;
@@ -28229,7 +28444,7 @@ async function describeQuality(media, root, inspection) {
28229
28444
  return {
28230
28445
  state: inspection.state,
28231
28446
  reason: inspection.reason,
28232
- output: portableOutputPath(path49.resolve(root, inspection.output), root),
28447
+ output: portableOutputPath(path50.resolve(root, inspection.output), root),
28233
28448
  record: portableOutputPath(recordPath, root),
28234
28449
  recordExists,
28235
28450
  outputs,
@@ -28269,7 +28484,7 @@ async function buildGallerySnapshot(opts) {
28269
28484
  const items = [];
28270
28485
  const manifestText = await readFile35(loaded.path, "utf8");
28271
28486
  const manifestSha256 = sha256(manifestText);
28272
- const cacheDir = path49.resolve(path49.dirname(opts.lockPath), ".pixelkiln", "cache");
28487
+ const cacheDir = path50.resolve(path50.dirname(opts.lockPath), ".pixelkiln", "cache");
28273
28488
  let rawStyles = {};
28274
28489
  try {
28275
28490
  const raw = JSON.parse(manifestText);
@@ -28293,7 +28508,7 @@ async function buildGallerySnapshot(opts) {
28293
28508
  )
28294
28509
  );
28295
28510
  if (spec.source) {
28296
- const editPath = path49.resolve(root, spec.source);
28511
+ const editPath = path50.resolve(root, spec.source);
28297
28512
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
28298
28513
  const editShas = await Promise.all(
28299
28514
  Array.from({ length: memberCount }, async (_, index) => {
@@ -28342,7 +28557,7 @@ async function buildGallerySnapshot(opts) {
28342
28557
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
28343
28558
  }
28344
28559
  } else if (spec.source) {
28345
- outputs = [await describeOutput(media, root, path49.resolve(root, spec.source))];
28560
+ outputs = [await describeOutput(media, root, path50.resolve(root, spec.source))];
28346
28561
  } else if (!entry && existsSync43(spec.outFile)) {
28347
28562
  outputs = [await describeOutput(media, root, spec.outFile)];
28348
28563
  } else {
@@ -28547,7 +28762,7 @@ async function buildGallerySnapshot(opts) {
28547
28762
  id: loaded.manifest.name,
28548
28763
  name: loaded.manifest.name,
28549
28764
  manifest: loaded.path,
28550
- lock: path49.resolve(opts.lockPath),
28765
+ lock: path50.resolve(opts.lockPath),
28551
28766
  root,
28552
28767
  provider: loaded.manifest.provider,
28553
28768
  account: null,
@@ -28576,7 +28791,7 @@ async function buildGallerySnapshot(opts) {
28576
28791
  return { snapshot, media };
28577
28792
  }
28578
28793
  async function buildWorkspaceGallerySnapshot(opts) {
28579
- const dir = path49.dirname(path49.resolve(opts.workspacePath));
28794
+ const dir = path50.dirname(path50.resolve(opts.workspacePath));
28580
28795
  const media = /* @__PURE__ */ new Map();
28581
28796
  const projects = [];
28582
28797
  const items = [];
@@ -28621,7 +28836,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
28621
28836
  id: project2.id,
28622
28837
  name: loaded.manifest.name,
28623
28838
  manifest: manifestPath,
28624
- lock: path49.resolve(lockPath),
28839
+ lock: path50.resolve(lockPath),
28625
28840
  root: loaded.root,
28626
28841
  provider: loaded.manifest.provider,
28627
28842
  account: project2.account ?? null,
@@ -28637,8 +28852,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
28637
28852
  id: project2.id,
28638
28853
  name: project2.id,
28639
28854
  manifest: manifestPath,
28640
- lock: path49.resolve(lockPath),
28641
- root: path49.dirname(manifestPath),
28855
+ lock: path50.resolve(lockPath),
28856
+ root: path50.dirname(manifestPath),
28642
28857
  provider: project2.provider,
28643
28858
  account: project2.account ?? null,
28644
28859
  manifestSha256: null,
@@ -28665,7 +28880,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
28665
28880
  version: 1,
28666
28881
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
28667
28882
  project: null,
28668
- workspace: { path: path49.resolve(opts.workspacePath), dir, projects },
28883
+ workspace: { path: path50.resolve(opts.workspacePath), dir, projects },
28669
28884
  filter,
28670
28885
  totals: {
28671
28886
  entries: projects.reduce((sum, project2) => sum + project2.entries, 0),
@@ -28869,9 +29084,9 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
28869
29084
  // src/editor/install.ts
28870
29085
  import { createHash as createHash9 } from "crypto";
28871
29086
  import { existsSync as existsSync45 } from "fs";
28872
- import { mkdir as mkdir21, readFile as readFile36, rename as rename14, rm as rm14, stat as stat6, writeFile as writeFile26 } from "fs/promises";
29087
+ import { mkdir as mkdir22, readFile as readFile36, rename as rename14, rm as rm15, stat as stat6, writeFile as writeFile27 } from "fs/promises";
28873
29088
  import os3 from "os";
28874
- import path50 from "path";
29089
+ import path51 from "path";
28875
29090
  var EditorInstallError = class extends Error {
28876
29091
  constructor(message6, file) {
28877
29092
  super(message6);
@@ -28882,15 +29097,15 @@ var EditorInstallError = class extends Error {
28882
29097
  };
28883
29098
  function editorToolsRoot() {
28884
29099
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
28885
- if (override) return path50.resolve(override);
28886
- if (process.platform === "darwin") return path50.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
29100
+ if (override) return path51.resolve(override);
29101
+ if (process.platform === "darwin") return path51.join(os3.homedir(), "Library", "Caches", "pixelkiln", "tools");
28887
29102
  if (process.platform === "win32") {
28888
- return path50.join(process.env.LOCALAPPDATA ?? path50.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
29103
+ return path51.join(process.env.LOCALAPPDATA ?? path51.join(os3.homedir(), "AppData", "Local"), "pixelkiln", "tools");
28889
29104
  }
28890
- return path50.join(process.env.XDG_CACHE_HOME ?? path50.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
29105
+ return path51.join(process.env.XDG_CACHE_HOME ?? path51.join(os3.homedir(), ".cache"), "pixelkiln", "tools");
28891
29106
  }
28892
29107
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
28893
- return path50.join(root, "pixelorama", pin.release ?? "unpublished");
29108
+ return path51.join(root, "pixelorama", pin.release ?? "unpublished");
28894
29109
  }
28895
29110
  function editorBaseUrl(pin = EDITOR_PIN) {
28896
29111
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -28913,7 +29128,7 @@ async function editorStatus(opts = {}) {
28913
29128
  let totalBytes = 0;
28914
29129
  for (const [name, expected] of Object.entries(pin.files)) {
28915
29130
  totalBytes += expected.bytes;
28916
- const file = path50.join(dir, name);
29131
+ const file = path51.join(dir, name);
28917
29132
  const info = existsSync45(file) ? await stat6(file).catch(() => null) : null;
28918
29133
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
28919
29134
  installedBytes += expected.bytes;
@@ -28943,7 +29158,7 @@ async function installEditor(opts = {}) {
28943
29158
  );
28944
29159
  }
28945
29160
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
28946
- await mkdir21(dir, { recursive: true });
29161
+ await mkdir22(dir, { recursive: true });
28947
29162
  const downloaded = [];
28948
29163
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
28949
29164
  let fetchedBytes = before.installedBytes;
@@ -28971,13 +29186,13 @@ async function installEditor(opts = {}) {
28971
29186
  if (digest2 !== expected.sha256) {
28972
29187
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
28973
29188
  }
28974
- const final = path50.join(dir, name);
29189
+ const final = path51.join(dir, name);
28975
29190
  const tmp = `${final}.${process.pid}.part`;
28976
29191
  try {
28977
- await writeFile26(tmp, bytes);
29192
+ await writeFile27(tmp, bytes);
28978
29193
  await rename14(tmp, final);
28979
29194
  } finally {
28980
- await rm14(tmp, { force: true });
29195
+ await rm15(tmp, { force: true });
28981
29196
  }
28982
29197
  fetchedBytes += bytes.length;
28983
29198
  downloaded.push(name);
@@ -29017,12 +29232,12 @@ var EDITOR_CONTENT_TYPES = {
29017
29232
  ".json": "application/json; charset=utf-8"
29018
29233
  };
29019
29234
  function editorContentType(name) {
29020
- return EDITOR_CONTENT_TYPES[path50.extname(name).toLowerCase()] ?? null;
29235
+ return EDITOR_CONTENT_TYPES[path51.extname(name).toLowerCase()] ?? null;
29021
29236
  }
29022
29237
 
29023
29238
  // src/gallery/editor.ts
29024
29239
  import { readFile as readFile37 } from "fs/promises";
29025
- import path51 from "path";
29240
+ import path52 from "path";
29026
29241
  function editorRoute(release, name = "index.html") {
29027
29242
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
29028
29243
  }
@@ -29095,7 +29310,7 @@ function createGalleryEditorHandlers(opts = {}) {
29095
29310
  if (!status.installed) return null;
29096
29311
  let bytes;
29097
29312
  try {
29098
- bytes = await readFile37(path51.join(dir, name));
29313
+ bytes = await readFile37(path52.join(dir, name));
29099
29314
  } catch {
29100
29315
  verified = null;
29101
29316
  return null;
@@ -29789,7 +30004,7 @@ function createGenerateHandlers(opts) {
29789
30004
  // src/pipeline/salvage.ts
29790
30005
  import { readFile as readFile39 } from "fs/promises";
29791
30006
  import { existsSync as existsSync46 } from "fs";
29792
- import path52 from "path";
30007
+ import path53 from "path";
29793
30008
  function providerClaimId(provider, objectId) {
29794
30009
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
29795
30010
  }
@@ -29903,20 +30118,20 @@ function matchOrphanStyle(prompt, manifest) {
29903
30118
  return matchStyleByPattern(prompt, manifest);
29904
30119
  }
29905
30120
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
29906
- const own = path52.resolve(ownManifestPath);
30121
+ const own = path53.resolve(ownManifestPath);
29907
30122
  const siblingManifestPaths = [
29908
30123
  .../* @__PURE__ */ new Set([
29909
30124
  ...workspaceManifestPaths,
29910
- ...claimPaths.map((c) => path52.join(path52.dirname(path52.resolve(c)), "pixelkiln.manifest.json"))
30125
+ ...claimPaths.map((c) => path53.join(path53.dirname(path53.resolve(c)), "pixelkiln.manifest.json"))
29911
30126
  ])
29912
30127
  ];
29913
30128
  const siblings = [];
29914
30129
  for (const siblingManifestPath of siblingManifestPaths) {
29915
- if (path52.resolve(siblingManifestPath) === own) continue;
30130
+ if (path53.resolve(siblingManifestPath) === own) continue;
29916
30131
  if (!existsSync46(siblingManifestPath)) continue;
29917
30132
  try {
29918
30133
  const { manifest } = await loadManifest(siblingManifestPath);
29919
- siblings.push({ label: path52.basename(path52.dirname(siblingManifestPath)), manifest });
30134
+ siblings.push({ label: path53.basename(path53.dirname(siblingManifestPath)), manifest });
29920
30135
  } catch {
29921
30136
  }
29922
30137
  }
@@ -30036,8 +30251,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
30036
30251
  }
30037
30252
 
30038
30253
  // src/pick/salvage-server.ts
30039
- import { mkdir as mkdir22, writeFile as writeFile27, readFile as readFile40 } from "fs/promises";
30040
- import path53 from "path";
30254
+ import { mkdir as mkdir23, writeFile as writeFile28, readFile as readFile40 } from "fs/promises";
30255
+ import path54 from "path";
30041
30256
 
30042
30257
  // src/pick/salvage-sheet.ts
30043
30258
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -30203,7 +30418,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30203
30418
  });
30204
30419
  const html = renderSalvageSheet(orphans, {
30205
30420
  styleId: ctx.styleId,
30206
- importDir: path53.relative(process.cwd(), ctx.importDir) || "."
30421
+ importDir: path54.relative(process.cwd(), ctx.importDir) || "."
30207
30422
  });
30208
30423
  const byId = new Map(orphans.map((o) => [o.id, o]));
30209
30424
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -30259,10 +30474,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30259
30474
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
30260
30475
  decodePng(buf);
30261
30476
  const assetId = idFromPrompt(orphan.prompt, taken);
30262
- const rel = path53.join("_salvaged", `${assetId}.png`);
30263
- const outFile = path53.resolve(ctx.importDir, rel);
30264
- await mkdir22(path53.dirname(outFile), { recursive: true });
30265
- await writeFile27(outFile, buf);
30477
+ const rel = path54.join("_salvaged", `${assetId}.png`);
30478
+ const outFile = path54.resolve(ctx.importDir, rel);
30479
+ await mkdir23(path54.dirname(outFile), { recursive: true });
30480
+ await writeFile28(outFile, buf);
30266
30481
  ctx.manifest.assets[assetId] = {
30267
30482
  prompt: orphan.prompt,
30268
30483
  promptByStyle: {},
@@ -30294,7 +30509,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30294
30509
  sourceUrl: durableSource,
30295
30510
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
30296
30511
  outputs: [{
30297
- path: portableOutputPath(outFile, path53.dirname(ctx.manifestPath)),
30512
+ path: portableOutputPath(outFile, path54.dirname(ctx.manifestPath)),
30298
30513
  sha256: sha256(buf)
30299
30514
  }],
30300
30515
  submittedAt: orphan.createdAt,
@@ -30320,7 +30535,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30320
30535
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
30321
30536
  const raw = JSON.parse(await readFile40(ctx.manifestPath, "utf8"));
30322
30537
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
30323
- await writeFile27(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
30538
+ await writeFile28(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
30324
30539
  await saveLock(ctx.lockPath, ctx.lock);
30325
30540
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
30326
30541
  return result;