pixelkiln 0.148.1 → 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);
@@ -7117,23 +7207,55 @@ function buildLayerSheet(sources, options) {
7117
7207
  }
7118
7208
  return png;
7119
7209
  };
7120
- 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 });
7121
7213
  return {
7122
7214
  sheet: sheetPng,
7123
- 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,
7124
7216
  mask,
7125
7217
  frames,
7126
- cleaned
7218
+ cleaned,
7219
+ ...computed ? { necks: computed.necks } : {},
7220
+ ...keyed ? { closed: keyed.closed } : {}
7127
7221
  };
7128
7222
  }
7129
7223
  function keyInsideMask(sheet, mask, options) {
7130
7224
  const original = decodePng(sheet);
7131
- const keyed = decodePng(keySkin(sheet, options));
7132
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
+ };
7133
7236
  for (let i = 0; i < keyed.pixels.length; i += 4) {
7134
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;
7135
7257
  }
7136
- return encodeRgbaPng(keyed.width, keyed.height, keyed.pixels);
7258
+ return { png: encodeRgbaPng(keyed.width, keyed.height, keyed.pixels), closed };
7137
7259
  }
7138
7260
  var SPECK = 8;
7139
7261
  var BLEED = 20;
@@ -8258,6 +8380,37 @@ var GRASP_PROMPT = "Every cyan mannequin on this spritesheet carries the same it
8258
8380
  function layerWorkDir(spec) {
8259
8381
  return path7.join(spec.root, ".pixelkiln", "layers", spec.styleId, spec.assetId);
8260
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
+ }
8261
8414
  var PixelLabProvider = class _PixelLabProvider {
8262
8415
  /**
8263
8416
  * `mcp` reaches the tools PixelLab offers only over MCP (the VFX
@@ -9149,31 +9302,7 @@ var PixelLabProvider = class _PixelLabProvider {
9149
9302
  const layer = character.layer;
9150
9303
  const label = `${spec.styleId}/${spec.assetId}`;
9151
9304
  const outputs = context?.parentOutputs ?? [];
9152
- if (!outputs.length) throw new Error(`${label}: its layer sources have no downloaded frames`);
9153
- const sources = outputs.map((output) => ({
9154
- assetId: output.assetId ?? character.parentAssetId,
9155
- ...output.role ? { role: output.role } : {},
9156
- png: readFileSync(output.path),
9157
- still: output.still === true
9158
- }));
9159
- const supplied = (name2, file) => {
9160
- if (!file) return void 0;
9161
- const bytes = readFileSync(file.path);
9162
- if (sha256(bytes) !== file.sha256) throw new Error(`${label}: layer ${name2} changed after the manifest was resolved: ${file.path}`);
9163
- return bytes;
9164
- };
9165
- const built = buildLayerSheet(sources, {
9166
- minSide: 32,
9167
- maxSide: LAYER_SHEET_MAX_SIDE,
9168
- columns: layer.columns,
9169
- region: layer.region,
9170
- padding: layer.padding,
9171
- key: layer.key,
9172
- skin: layer.skin,
9173
- reference: layer.clean ? sources.filter((source) => source.still).map((source) => source.png) : [],
9174
- mask: supplied("mask", layer.mask),
9175
- keyed: supplied("keyed sheet", layer.keyed)
9176
- });
9305
+ const built = layerSheetFor(spec, outputs);
9177
9306
  const dir = layerWorkDir(spec);
9178
9307
  mkdirSync(dir, { recursive: true });
9179
9308
  let prepared = built;
@@ -9228,7 +9357,15 @@ var PixelLabProvider = class _PixelLabProvider {
9228
9357
  character: {
9229
9358
  kind: "layer",
9230
9359
  backgroundJobId: res2.background_job_id,
9231
- 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
+ }
9232
9369
  }
9233
9370
  }
9234
9371
  };
@@ -11291,9 +11428,9 @@ var RetroDiffusionClient = class {
11291
11428
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
11292
11429
  return Buffer.from(await response.arrayBuffer());
11293
11430
  }
11294
- async call(path54, init = {}) {
11431
+ async call(path55, init = {}) {
11295
11432
  if (!this.token) throw new Error("RD_API_KEY is not set");
11296
- const response = await this.request(`${this.baseUrl}${path54}`, {
11433
+ const response = await this.request(`${this.baseUrl}${path55}`, {
11297
11434
  ...init,
11298
11435
  headers: {
11299
11436
  "Content-Type": "application/json",
@@ -14799,6 +14936,7 @@ async function resolveSpecs(loaded, filter) {
14799
14936
  ...keyed ? { keyed } : {},
14800
14937
  ...asset.layer.skin ? { skin: asset.layer.skin } : {},
14801
14938
  ...asset.layer.key ? { key: asset.layer.key } : {},
14939
+ ...asset.layer.cover ? { cover: true } : {},
14802
14940
  clean: asset.layer.clean ?? true,
14803
14941
  ...asset.layer.columns ? { columns: asset.layer.columns } : {},
14804
14942
  region: asset.layer.region ?? "body",
@@ -19660,10 +19798,10 @@ function isSha256Hash(value) {
19660
19798
  function parseCache(value) {
19661
19799
  return HashCacheSchema.parse(value);
19662
19800
  }
19663
- async function loadCache(path54) {
19664
- if (!existsSync24(path54)) return { version: 1, hashes: {} };
19801
+ async function loadCache(path55) {
19802
+ if (!existsSync24(path55)) return { version: 1, hashes: {} };
19665
19803
  try {
19666
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile17(path54, "utf8")));
19804
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile17(path55, "utf8")));
19667
19805
  if (!parsed.success) return { version: 1, hashes: {} };
19668
19806
  return {
19669
19807
  version: 1,
@@ -19675,18 +19813,18 @@ async function loadCache(path54) {
19675
19813
  return { version: 1, hashes: {} };
19676
19814
  }
19677
19815
  }
19678
- async function saveCache(path54, cache) {
19816
+ async function saveCache(path55, cache) {
19679
19817
  const sorted = {};
19680
19818
  for (const key3 of Object.keys(cache.hashes).sort()) {
19681
19819
  const hash = cache.hashes[key3];
19682
19820
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
19683
19821
  sorted[key3] = hash;
19684
19822
  }
19685
- await mkdir12(pathModule.dirname(pathModule.resolve(path54)), { recursive: true });
19686
- 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`;
19687
19825
  try {
19688
19826
  await writeFile12(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
19689
- await rename6(tmp, path54);
19827
+ await rename6(tmp, path55);
19690
19828
  } finally {
19691
19829
  await rm4(tmp, { force: true });
19692
19830
  }
@@ -21854,6 +21992,21 @@ function renderSheetDocument(format, atlas, opts) {
21854
21992
  return { extension: ".json", document: JSON.stringify(atlas, null, 2) + "\n" };
21855
21993
  }
21856
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
+
21857
22010
  // src/pipeline/submit.ts
21858
22011
  var IN_FLIGHT_POLL_MS = 5e3;
21859
22012
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -22136,15 +22289,7 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
22136
22289
  const parentOutputs = spec.character?.kind === "outfit" && parentEntry ? parentEntry.outputs.map((output, index) => ({
22137
22290
  path: currentEntryOutputPath(parentEntry, spec.character.parentSpec, index),
22138
22291
  role: output.role
22139
- })) : spec.character?.kind === "layer" ? spec.character.layer.sources.flatMap((source) => {
22140
- const sourceEntry = lock.entries[lockKey(source.spec.styleId, source.spec.assetId)];
22141
- return sourceEntry.outputs.map((output, index) => ({
22142
- path: currentEntryOutputPath(sourceEntry, source.spec, index),
22143
- role: output.role,
22144
- assetId: source.assetId,
22145
- still: source.spec.character?.kind !== "animation"
22146
- }));
22147
- }) : void 0;
22292
+ })) : spec.character?.kind === "layer" ? layerSourceOutputs(spec, lock) : void 0;
22148
22293
  const referenceSourceImageId = ownedReferenceImageId(spec, lock, provider.id);
22149
22294
  const { jobId, metadata } = await provider.submit(spec, refs, {
22150
22295
  ...previousJobId ? { previousJobId } : {},
@@ -22193,6 +22338,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
22193
22338
  log(
22194
22339
  ` ${key3} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
22195
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
+ }
22196
22348
  } catch (err) {
22197
22349
  const message6 = err instanceof Error ? err.message : String(err);
22198
22350
  const entry = lock.entries[key3];
@@ -22232,8 +22384,8 @@ function ownedReferenceImageId(spec, lock, providerId) {
22232
22384
 
22233
22385
  // src/pick/candidates.ts
22234
22386
  import { existsSync as existsSync28 } from "fs";
22235
- import { mkdir as mkdir14, readFile as readFile20, rename as rename8, rm as rm7, writeFile as writeFile14 } from "fs/promises";
22236
- 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";
22237
22389
  import { z as z8 } from "zod";
22238
22390
  var REVIEW_STATE_VERSION = 1;
22239
22391
  var CandidateSchema = z8.object({
@@ -22277,12 +22429,12 @@ var ReviewStateSchema = z8.object({
22277
22429
  assets: z8.record(ReviewAssetSchema)
22278
22430
  });
22279
22431
  function candidateCacheDirFor(lockPath) {
22280
- return path33.resolve(path33.dirname(lockPath), ".pixelkiln", "cache");
22432
+ return path34.resolve(path34.dirname(lockPath), ".pixelkiln", "cache");
22281
22433
  }
22282
22434
  function reviewStatePathFor(lockPath) {
22283
- const base = path33.basename(lockPath);
22435
+ const base = path34.basename(lockPath);
22284
22436
  const name = base === "pixelkiln.lock.json" ? "review-state.json" : `${base.replace(/\.json$/, "")}.review-state.json`;
22285
- return path33.resolve(path33.dirname(lockPath), ".pixelkiln", name);
22437
+ return path34.resolve(path34.dirname(lockPath), ".pixelkiln", name);
22286
22438
  }
22287
22439
  async function loadReviewState(file) {
22288
22440
  if (!existsSync28(file)) return { version: REVIEW_STATE_VERSION, assets: {} };
@@ -22294,13 +22446,13 @@ async function loadReviewState(file) {
22294
22446
  return { version: REVIEW_STATE_VERSION, assets: {} };
22295
22447
  }
22296
22448
  async function saveReviewState(file, state) {
22297
- await mkdir14(path33.dirname(file), { recursive: true });
22449
+ await mkdir15(path34.dirname(file), { recursive: true });
22298
22450
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
22299
22451
  try {
22300
- await writeFile14(tmp, JSON.stringify(state, null, 2) + "\n");
22452
+ await writeFile15(tmp, JSON.stringify(state, null, 2) + "\n");
22301
22453
  await rename8(tmp, file);
22302
22454
  } finally {
22303
- await rm7(tmp, { force: true });
22455
+ await rm8(tmp, { force: true });
22304
22456
  }
22305
22457
  }
22306
22458
  async function updateReviewAsset(file, key3, change) {
@@ -22314,7 +22466,7 @@ async function updateReviewAsset(file, key3, change) {
22314
22466
  }
22315
22467
  function cachedCandidatePath(cacheDir, candidate) {
22316
22468
  if (!candidate.sha256 || !candidate.mediaType) return null;
22317
- const file = path33.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22469
+ const file = path34.join(cacheDir, cacheFileName(candidate.sha256, candidate.mediaType));
22318
22470
  return existsSync28(file) ? file : null;
22319
22471
  }
22320
22472
  function fullyCached(cacheDir, asset) {
@@ -22523,11 +22675,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
22523
22675
  // src/pipeline/doctor.ts
22524
22676
  import { constants, existsSync as existsSync30 } from "fs";
22525
22677
  import { access, stat as stat3 } from "fs/promises";
22526
- import path35 from "path";
22678
+ import path36 from "path";
22527
22679
 
22528
22680
  // src/pipeline/install-check.ts
22529
22681
  import { existsSync as existsSync29, readFileSync as readFileSync9 } from "fs";
22530
- import path34 from "path";
22682
+ import path35 from "path";
22531
22683
  function readJson(file) {
22532
22684
  try {
22533
22685
  return JSON.parse(readFileSync9(file, "utf8"));
@@ -22536,18 +22688,18 @@ function readJson(file) {
22536
22688
  }
22537
22689
  }
22538
22690
  function readInstallFacts(manifestDir, running) {
22539
- let dir = path34.resolve(manifestDir);
22691
+ let dir = path35.resolve(manifestDir);
22540
22692
  for (let depth = 0; depth < 4; depth++) {
22541
- const pkg = readJson(path34.join(dir, "package.json"));
22693
+ const pkg = readJson(path35.join(dir, "package.json"));
22542
22694
  if (pkg) {
22543
22695
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
22544
22696
  if (pinned) {
22545
- const installedPkg = readJson(path34.join(dir, "node_modules", "pixelkiln", "package.json"));
22697
+ const installedPkg = readJson(path35.join(dir, "node_modules", "pixelkiln", "package.json"));
22546
22698
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
22547
22699
  return { pinned, installed, running };
22548
22700
  }
22549
22701
  }
22550
- const parent = path34.dirname(dir);
22702
+ const parent = path35.dirname(dir);
22551
22703
  if (parent === dir || !existsSync29(parent)) break;
22552
22704
  dir = parent;
22553
22705
  }
@@ -22611,12 +22763,12 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22611
22763
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
22612
22764
  );
22613
22765
  }
22614
- 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());
22615
22767
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
22616
22768
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
22617
22769
  const dirs = [...new Set(specs.flatMap((spec) => [
22618
- path35.dirname(spec.outFile),
22619
- ...spec.quality ? [path35.dirname(spec.quality.outFile)] : []
22770
+ path36.dirname(spec.outFile),
22771
+ ...spec.quality ? [path36.dirname(spec.quality.outFile)] : []
22620
22772
  ]))];
22621
22773
  const unwritable = [];
22622
22774
  for (const dir of dirs) {
@@ -22639,7 +22791,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22639
22791
  for (let index = 0; index < entry.outputs.length; index++) {
22640
22792
  const output = entry.outputs[index];
22641
22793
  const spec = specByKey.get(key3);
22642
- 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));
22643
22795
  const owner = outputOwners.get(absolute);
22644
22796
  if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
22645
22797
  outputOwners.set(absolute, key3);
@@ -22654,7 +22806,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22654
22806
  } else {
22655
22807
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
22656
22808
  }
22657
- const cacheDir = path35.join(path35.dirname(lockPath), ".pixelkiln", "cache");
22809
+ const cacheDir = path36.join(path36.dirname(lockPath), ".pixelkiln", "cache");
22658
22810
  const stranded = [];
22659
22811
  const invalidState = [];
22660
22812
  const staleMapUrls = [];
@@ -22670,7 +22822,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
22670
22822
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
22671
22823
  let hasCache = false;
22672
22824
  for (const output of entry.outputs) {
22673
- const cached2 = path35.join(
22825
+ const cached2 = path36.join(
22674
22826
  cacheDir,
22675
22827
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
22676
22828
  );
@@ -22770,7 +22922,7 @@ async function nearestExistingDirectory(start) {
22770
22922
  if ((await stat3(current)).isDirectory()) return current;
22771
22923
  } catch {
22772
22924
  }
22773
- const parent = path35.dirname(current);
22925
+ const parent = path36.dirname(current);
22774
22926
  if (parent === current) return current;
22775
22927
  current = parent;
22776
22928
  }
@@ -22778,8 +22930,8 @@ async function nearestExistingDirectory(start) {
22778
22930
 
22779
22931
  // src/pipeline/adopt.ts
22780
22932
  import { existsSync as existsSync31 } from "fs";
22781
- import { readFile as readFile21, writeFile as writeFile15 } from "fs/promises";
22782
- import path36 from "path";
22933
+ import { readFile as readFile21, writeFile as writeFile16 } from "fs/promises";
22934
+ import path37 from "path";
22783
22935
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
22784
22936
  const log = opts.onProgress ?? (() => {
22785
22937
  });
@@ -22914,7 +23066,7 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
22914
23066
  // src/pipeline/import.ts
22915
23067
  import { existsSync as existsSync32 } from "fs";
22916
23068
  import { readdir as readdir4, readFile as readFile22 } from "fs/promises";
22917
- import path37 from "path";
23069
+ import path38 from "path";
22918
23070
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date(), frames) {
22919
23071
  const png = decodePng(bytes);
22920
23072
  for (const frame of frames ?? []) decodePng(frame.bytes);
@@ -22967,10 +23119,10 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
22967
23119
  var frameRole2 = (index) => `frame-${String(index).padStart(2, "0")}`;
22968
23120
  async function findFrames(spec) {
22969
23121
  const at2 = (index) => memberPath(spec.outFile, frameRole2(index), 0, 2, MediaType.PNG);
22970
- const base = path37.basename(at2(0)).replace(/00\.png$/, "");
23122
+ const base = path38.basename(at2(0)).replace(/00\.png$/, "");
22971
23123
  let names = [];
22972
23124
  try {
22973
- names = await readdir4(path37.dirname(spec.outFile));
23125
+ names = await readdir4(path38.dirname(spec.outFile));
22974
23126
  } catch {
22975
23127
  names = [];
22976
23128
  }
@@ -23000,7 +23152,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
23000
23152
  if (opts.objectId && specs.length !== 1) {
23001
23153
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
23002
23154
  }
23003
- 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"));
23004
23156
  let rawSha256;
23005
23157
  let rawBytes;
23006
23158
  if (opts.raw) {
@@ -23030,7 +23182,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
23030
23182
  continue;
23031
23183
  }
23032
23184
  if ("missing" in frames2) {
23033
- 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)})` });
23034
23186
  continue;
23035
23187
  }
23036
23188
  frameFiles = frames2.files;
@@ -23110,9 +23262,9 @@ import { existsSync as existsSync34 } from "fs";
23110
23262
  import { readFile as readFile25 } from "fs/promises";
23111
23263
 
23112
23264
  // src/pipeline/init.ts
23113
- 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";
23114
23266
  import { existsSync as existsSync33 } from "fs";
23115
- import path38 from "path";
23267
+ import path39 from "path";
23116
23268
  function pngSize(buf) {
23117
23269
  if (buf.length < 24) return null;
23118
23270
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -23126,7 +23278,7 @@ function slugify(value) {
23126
23278
  async function walk(dir, exclude) {
23127
23279
  const out = [];
23128
23280
  for (const entry of await readdir5(dir, { withFileTypes: true })) {
23129
- const full = path38.join(dir, entry.name);
23281
+ const full = path39.join(dir, entry.name);
23130
23282
  if (exclude.some((x) => full.includes(x))) continue;
23131
23283
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
23132
23284
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -23145,9 +23297,9 @@ async function scanAssets(root, opts = {}) {
23145
23297
  skipped.push(`${file} (not a readable PNG)`);
23146
23298
  continue;
23147
23299
  }
23148
- const rel = path38.relative(root, file);
23149
- const category = path38.dirname(rel) === "." ? "" : path38.dirname(rel);
23150
- 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));
23151
23303
  if (seen.has(id)) {
23152
23304
  const n = seen.get(id) + 1;
23153
23305
  seen.set(id, n);
@@ -24654,12 +24806,12 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
24654
24806
  import { createHash as createHash8 } from "crypto";
24655
24807
  import { existsSync as existsSync43 } from "fs";
24656
24808
  import { readFile as readFile35, stat as stat5 } from "fs/promises";
24657
- import path49 from "path";
24809
+ import path50 from "path";
24658
24810
 
24659
24811
  // src/gallery/models.ts
24660
24812
  import { existsSync as existsSync38 } from "fs";
24661
24813
  import { readFile as readFile30, stat as stat4 } from "fs/promises";
24662
- import path43 from "path";
24814
+ import path44 from "path";
24663
24815
  import { z as z12 } from "zod";
24664
24816
 
24665
24817
  // src/glb.ts
@@ -24992,11 +25144,11 @@ function modelItems(json2) {
24992
25144
  }
24993
25145
 
24994
25146
  // src/manifest-edit.ts
24995
- import { readFile as readFile26, rename as rename9, rm as rm8, writeFile as writeFile17 } from "fs/promises";
24996
- 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";
24997
25149
  import { z as z9 } from "zod";
24998
25150
  var HexSha = z9.string().regex(/^[0-9a-f]{64}$/);
24999
- 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");
25000
25152
  var AssetPatchSchema = z9.object({
25001
25153
  prompt: z9.string().optional(),
25002
25154
  /** Per-style override for the style being viewed; null removes it. */
@@ -25417,7 +25569,7 @@ function applyEdit(raw, edit) {
25417
25569
  }
25418
25570
  }
25419
25571
  async function withCandidate(manifestPath, edit, use, unchanged) {
25420
- const absolute = path39.resolve(manifestPath);
25572
+ const absolute = path40.resolve(manifestPath);
25421
25573
  const original = await readFile26(absolute, "utf8");
25422
25574
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
25423
25575
  let raw;
@@ -25431,12 +25583,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
25431
25583
  applyEdit(raw, edit);
25432
25584
  const next = serializeLike(original, raw);
25433
25585
  if (next === original) return unchanged(absolute, original);
25434
- const tmp = path39.join(
25435
- path39.dirname(absolute),
25436
- `.${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`
25437
25589
  );
25438
25590
  try {
25439
- await writeFile17(tmp, next);
25591
+ await writeFile18(tmp, next);
25440
25592
  let specs;
25441
25593
  try {
25442
25594
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -25446,7 +25598,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
25446
25598
  }
25447
25599
  return await use({ absolute, original, next, tmp, specs });
25448
25600
  } finally {
25449
- await rm8(tmp, { force: true });
25601
+ await rm9(tmp, { force: true });
25450
25602
  }
25451
25603
  }
25452
25604
  async function applyManifestEdit(manifestPath, edit) {
@@ -25463,17 +25615,17 @@ async function applyManifestEdit(manifestPath, edit) {
25463
25615
 
25464
25616
  // src/pipeline/hand-edit.ts
25465
25617
  import { existsSync as existsSync35 } from "fs";
25466
- import { copyFile, mkdir as mkdir15, readFile as readFile27, rename as rename10, rm as rm9, writeFile as writeFile18 } from "fs/promises";
25467
- 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";
25468
25620
  import { z as z10 } from "zod";
25469
25621
  var HAND_EDIT_DIR = "edits";
25470
25622
  function handEditPath(loaded, spec) {
25471
25623
  const style = loaded.manifest.styles[spec.styleId];
25472
- const outDir = path40.resolve(loaded.root, style?.outDir ?? ".");
25473
- const relative = path40.relative(outDir, spec.outFile);
25474
- const inside2 = relative && !relative.startsWith("..") && !path40.isAbsolute(relative);
25475
- const file = inside2 ? relative : path40.basename(spec.outFile);
25476
- 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"));
25477
25629
  }
25478
25630
  function handEditBases(spec, lock) {
25479
25631
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -25539,7 +25691,7 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
25539
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`
25540
25692
  );
25541
25693
  }
25542
- const existing = spec.source ? path40.resolve(loaded.root, spec.source) : null;
25694
+ const existing = spec.source ? path41.resolve(loaded.root, spec.source) : null;
25543
25695
  const editPath = existing ?? handEditPath(loaded, spec);
25544
25696
  const members = handEditMembers(loaded, spec, lock, editPath);
25545
25697
  let created = false;
@@ -25550,7 +25702,7 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
25550
25702
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
25551
25703
  );
25552
25704
  }
25553
- await mkdir15(path40.dirname(member.path), { recursive: true });
25705
+ await mkdir16(path41.dirname(member.path), { recursive: true });
25554
25706
  await copyFile(member.base, member.path);
25555
25707
  created = true;
25556
25708
  }
@@ -25689,7 +25841,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
25689
25841
  editor: input.editor,
25690
25842
  protocol: input.protocol,
25691
25843
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
25692
- project: projectPath ? path40.basename(projectPath) : null,
25844
+ project: projectPath ? path41.basename(projectPath) : null,
25693
25845
  outputs: incoming.map((frame, index) => ({
25694
25846
  role: frame.role,
25695
25847
  basedOn: basedOnHash(entry, index),
@@ -25719,10 +25871,10 @@ function basedOnHash(entry, index) {
25719
25871
  async function replaceFile(file, bytes) {
25720
25872
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
25721
25873
  try {
25722
- await writeFile18(tmp, bytes);
25874
+ await writeFile19(tmp, bytes);
25723
25875
  await rename10(tmp, file);
25724
25876
  } finally {
25725
- await rm9(tmp, { force: true });
25877
+ await rm10(tmp, { force: true });
25726
25878
  }
25727
25879
  }
25728
25880
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -25733,8 +25885,8 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
25733
25885
  // src/pipeline/model-edit.ts
25734
25886
  import { spawn as spawn2 } from "child_process";
25735
25887
  import { existsSync as existsSync36, readdirSync as readdirSync2 } from "fs";
25736
- import { mkdir as mkdir16, readdir as readdir6, readFile as readFile28, rename as rename11, rm as rm10, writeFile as writeFile19 } from "fs/promises";
25737
- 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";
25738
25890
  import { z as z11 } from "zod";
25739
25891
 
25740
25892
  // src/jpeg.ts
@@ -26116,7 +26268,7 @@ var MAX_MODELS = 200;
26116
26268
  var MAX_DEPTH = 8;
26117
26269
  var SKIPPED_DIRS = /* @__PURE__ */ new Set([HAND_EDIT_DIR, "node_modules"]);
26118
26270
  async function discoverModels(loaded, opts = {}) {
26119
- 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));
26120
26272
  const seen = /* @__PURE__ */ new Set();
26121
26273
  const models = [];
26122
26274
  const walk2 = async (styleId, outDir, dir, depth) => {
@@ -26130,13 +26282,13 @@ async function discoverModels(loaded, opts = {}) {
26130
26282
  entries.sort((a, b) => a.name.localeCompare(b.name));
26131
26283
  for (const entry of entries) {
26132
26284
  if (models.length >= MAX_MODELS) return;
26133
- const full = path41.join(dir, entry.name);
26285
+ const full = path42.join(dir, entry.name);
26134
26286
  if (entry.isDirectory()) {
26135
26287
  if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
26136
26288
  await walk2(styleId, outDir, full, depth + 1);
26137
26289
  } else if (entry.isFile() && entry.name.toLowerCase().endsWith(MODEL_EXTENSION) && !seen.has(full)) {
26138
26290
  seen.add(full);
26139
- 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)) });
26140
26292
  }
26141
26293
  }
26142
26294
  };
@@ -26144,12 +26296,12 @@ async function discoverModels(loaded, opts = {}) {
26144
26296
  return models.sort((a, b) => a.styleId.localeCompare(b.styleId) || a.file.localeCompare(b.file));
26145
26297
  }
26146
26298
  async function findModel(loaded, portablePath) {
26147
- const wanted = path41.resolve(loaded.root, portablePath);
26299
+ const wanted = path42.resolve(loaded.root, portablePath);
26148
26300
  const model = (await discoverModels(loaded)).find((candidate) => candidate.file === wanted);
26149
26301
  if (!model) throw new ManifestEditError(`"${portablePath}" is not a model under one of this project's output folders`);
26150
26302
  return model;
26151
26303
  }
26152
- var stem = (editFile) => editFile.slice(0, -path41.extname(editFile).length);
26304
+ var stem = (editFile) => editFile.slice(0, -path42.extname(editFile).length);
26153
26305
  function modelCompanionPath(editFile) {
26154
26306
  return stem(editFile) + ".edit.json";
26155
26307
  }
@@ -26198,13 +26350,13 @@ function modelEditStatus(companion, builtSha256) {
26198
26350
  return companion.outputs[0].basedOn === builtSha256 ? "edited" : "rebuilt-since";
26199
26351
  }
26200
26352
  async function replaceFile2(file, bytes) {
26201
- await mkdir16(path41.dirname(file), { recursive: true });
26353
+ await mkdir17(path42.dirname(file), { recursive: true });
26202
26354
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
26203
26355
  try {
26204
- await writeFile19(tmp, bytes);
26356
+ await writeFile20(tmp, bytes);
26205
26357
  await rename11(tmp, file);
26206
26358
  } finally {
26207
- await rm10(tmp, { force: true });
26359
+ await rm11(tmp, { force: true });
26208
26360
  }
26209
26361
  }
26210
26362
  async function readModel(file, what) {
@@ -26259,7 +26411,7 @@ async function saveModelTexture(model, input) {
26259
26411
  sha256: sha256(input.png),
26260
26412
  editor: input.editor,
26261
26413
  savedAt,
26262
- project: projectPath ? path41.basename(projectPath) : null
26414
+ project: projectPath ? path42.basename(projectPath) : null
26263
26415
  };
26264
26416
  const companion = {
26265
26417
  version: 2,
@@ -26363,16 +26515,16 @@ function blenderCommand(env = process.env, platform = process.platform, exists =
26363
26515
  const candidates = [];
26364
26516
  if (platform === "darwin") {
26365
26517
  candidates.push("/Applications/Blender.app/Contents/MacOS/Blender");
26366
- 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"));
26367
26519
  } else if (platform === "win32") {
26368
26520
  for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((value) => Boolean(value))) {
26369
- const foundation = path41.win32.join(root, "Blender Foundation");
26521
+ const foundation = path42.win32.join(root, "Blender Foundation");
26370
26522
  const versions = list(foundation).filter((name) => /^Blender/i.test(name)).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
26371
- 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"));
26372
26524
  }
26373
26525
  } else {
26374
26526
  candidates.push("/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender", "/var/lib/flatpak/exports/bin/org.blender.Blender");
26375
- 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"));
26376
26528
  }
26377
26529
  const found = candidates.find((candidate) => exists(candidate));
26378
26530
  return found ? [found] : null;
@@ -26415,14 +26567,14 @@ function openInBlender(model, opts = {}) {
26415
26567
  child.unref();
26416
26568
  });
26417
26569
  launch(program, args);
26418
- return `${command.join(" ")} (${path41.basename(file)})`;
26570
+ return `${command.join(" ")} (${path42.basename(file)})`;
26419
26571
  }
26420
26572
 
26421
26573
  // src/pipeline/model-normals.ts
26422
26574
  import { createHash as createHash7 } from "crypto";
26423
26575
  import { existsSync as existsSync37 } from "fs";
26424
- import { mkdir as mkdir17, readdir as readdir7, readFile as readFile29, writeFile as writeFile20 } from "fs/promises";
26425
- 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";
26426
26578
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
26427
26579
  var TILE_MAX = 512;
26428
26580
  function decodeImage(bytes) {
@@ -26514,13 +26666,13 @@ function poseNodes(document, pose) {
26514
26666
  const posed = /* @__PURE__ */ new Map();
26515
26667
  for (const channel of animation.channels) {
26516
26668
  const node = channel.target.node;
26517
- const path54 = channel.target.path;
26518
- 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;
26519
26671
  const sampler = animation.samplers[channel.sampler];
26520
26672
  if (!sampler) continue;
26521
26673
  const times = readAccessor(document, sampler.input).data;
26522
26674
  const values = readAccessor(document, sampler.output);
26523
- const width = path54 === "rotation" ? 4 : 3;
26675
+ const width = path55 === "rotation" ? 4 : 3;
26524
26676
  const cubic = sampler.interpolation === "CUBICSPLINE";
26525
26677
  const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
26526
26678
  const last = times.length - 1;
@@ -26532,16 +26684,16 @@ function poseNodes(document, pose) {
26532
26684
  const span = times[key3 + 1] - times[key3];
26533
26685
  const f = span > 0 ? (time - times[key3]) / span : 0;
26534
26686
  const next = valueAt(key3 + 1);
26535
- 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;
26536
26688
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
26537
26689
  }
26538
- if (path54 === "rotation") {
26690
+ if (path55 === "rotation") {
26539
26691
  const length = Math.hypot(...value) || 1;
26540
26692
  value = value.map((v) => v / length);
26541
26693
  }
26542
26694
  const base = posed.get(node) ?? { ...document.json.nodes?.[node] ?? {} };
26543
26695
  if (base.matrix) delete base.matrix;
26544
- base[path54] = value;
26696
+ base[path55] = value;
26545
26697
  posed.set(node, base);
26546
26698
  }
26547
26699
  return posed;
@@ -27151,9 +27303,9 @@ function modelSpritesDir(modelFile) {
27151
27303
  return modelFile.replace(/\.glb$/i, "") + ".sprites";
27152
27304
  }
27153
27305
  async function readSpriteFolder(dir) {
27154
- 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;
27155
27307
  const names = (await readdir7(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
27156
- 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) })));
27157
27309
  }
27158
27310
  function modelNormalDir(editFile) {
27159
27311
  return editFile.replace(/\.glb$/i, "") + ".normal-map";
@@ -27173,13 +27325,13 @@ async function prepare(model, opts) {
27173
27325
  if (!normalImages.some((image) => image.index === index)) throw new Error(`image ${index} is not one of the model's normal maps`);
27174
27326
  }
27175
27327
  const primitives = restPrimitives(document, opts.pose);
27176
- const dir = path42.join(modelNormalDir(model.editFile), opts.source);
27328
+ const dir = path43.join(modelNormalDir(model.editFile), opts.source);
27177
27329
  const surfaces = /* @__PURE__ */ new Map();
27178
27330
  const tiles = /* @__PURE__ */ new Map();
27179
27331
  const calls = [];
27180
27332
  const images = [];
27181
27333
  const call = (label, png) => {
27182
- 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`);
27183
27335
  calls.push({ label, png, cache, cached: existsSync37(cache) });
27184
27336
  };
27185
27337
  for (const index of wanted) {
@@ -27248,15 +27400,15 @@ async function prepare(model, opts) {
27248
27400
  }
27249
27401
  async function planModelNormals(model, opts) {
27250
27402
  const { plan } = await prepare(model, opts);
27251
- await mkdir17(plan.dir, { recursive: true });
27252
- for (const entry of plan.calls) await writeFile20(entry.cache.replace(/\.[0-9a-f]{16}\.normal\.png$/, ".png"), entry.png);
27253
- 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);
27254
27406
  return plan;
27255
27407
  }
27256
27408
  async function generateModelNormals(model, opts, mapper, hooks = {}) {
27257
27409
  const prepared = await prepare(model, opts);
27258
27410
  const { plan, document } = prepared;
27259
- await mkdir17(plan.dir, { recursive: true });
27411
+ await mkdir18(plan.dir, { recursive: true });
27260
27412
  const request = {
27261
27413
  ...opts.mode ? { mode: opts.mode } : {},
27262
27414
  ...opts.kind ? { kind: opts.kind } : {},
@@ -27268,14 +27420,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
27268
27420
  let sent = 0;
27269
27421
  for (const entry of plan.calls) {
27270
27422
  hooks.onCall?.(entry.label, entry.cached);
27271
- 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);
27272
27424
  if (entry.cached) {
27273
27425
  answers.push(await readFile29(entry.cache));
27274
27426
  continue;
27275
27427
  }
27276
27428
  const answer = await mapper(entry.png, request);
27277
27429
  sent++;
27278
- await writeFile20(entry.cache, answer);
27430
+ await writeFile21(entry.cache, answer);
27279
27431
  answers.push(answer);
27280
27432
  }
27281
27433
  let result = null;
@@ -27293,14 +27445,14 @@ async function generateModelNormals(model, opts, mapper, hooks = {}) {
27293
27445
  field = detailFromViews(surface, prepared.views, answers);
27294
27446
  }
27295
27447
  bleed(field);
27296
- const detail = path42.join(plan.dir, `image-${image}.detail.png`);
27297
- await writeFile20(detail, encodeImage(fieldImage(field)));
27448
+ const detail = path43.join(plan.dir, `image-${image}.detail.png`);
27449
+ await writeFile21(detail, encodeImage(fieldImage(field)));
27298
27450
  details.push(detail);
27299
- const basePath = path42.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
27451
+ const basePath = path43.join(modelNormalDir(model.editFile), `image-${image}.base.png`);
27300
27452
  const record = companion?.textures.find((entry) => entry.image === image);
27301
27453
  const ours = record?.editor.startsWith(PIXELLAB_EDITOR) === true && existsSync37(basePath);
27302
27454
  const existing = ours ? decodeImage(await readFile29(basePath)) : decodeImage(glbImageBytes(document, image).bytes);
27303
- if (!ours) await writeFile20(basePath, encodeImage(existing));
27455
+ if (!ours) await writeFile21(basePath, encodeImage(existing));
27304
27456
  const png = encodeImage(applyDetail(existing, field, opts));
27305
27457
  result = await saveModelTexture(model, {
27306
27458
  image,
@@ -27352,7 +27504,7 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27352
27504
  } catch {
27353
27505
  continue;
27354
27506
  }
27355
- const outDir = path43.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
27507
+ const outDir = path44.resolve(root, loaded.manifest.styles[model.styleId]?.outDir ?? ".");
27356
27508
  let summary = null;
27357
27509
  let error = null;
27358
27510
  if (bytes.length > MAX_MODEL_BYTES) error = `the file is ${bytes.length} bytes; models over ${MAX_MODEL_BYTES} are listed but not opened`;
@@ -27418,12 +27570,12 @@ async function describeModels(loaded, media, mediaId, opts = {}) {
27418
27570
  } catch {
27419
27571
  }
27420
27572
  }
27421
- const relative = path43.relative(outDir, model.file).split(path43.sep).join("/");
27573
+ const relative = path44.relative(outDir, model.file).split(path44.sep).join("/");
27422
27574
  models.push({
27423
27575
  id: `model:${model.styleId}/${relative}`,
27424
27576
  project: null,
27425
27577
  styleId: model.styleId,
27426
- name: path43.basename(model.file, path43.extname(model.file)),
27578
+ name: path44.basename(model.file, path44.extname(model.file)),
27427
27579
  file,
27428
27580
  summary,
27429
27581
  error,
@@ -27518,9 +27670,9 @@ function blenderAvailable() {
27518
27670
  }
27519
27671
 
27520
27672
  // src/workspace.ts
27521
- 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";
27522
27674
  import { existsSync as existsSync39 } from "fs";
27523
- import path44 from "path";
27675
+ import path45 from "path";
27524
27676
  import { z as z13 } from "zod";
27525
27677
  var WorkspaceProjectSchema = z13.object({
27526
27678
  id: z13.string().min(1),
@@ -27562,22 +27714,22 @@ async function saveWorkspace(workspacePath, ws) {
27562
27714
  version: 1,
27563
27715
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
27564
27716
  };
27565
- await mkdir18(path44.dirname(path44.resolve(workspacePath)), { recursive: true });
27717
+ await mkdir19(path45.dirname(path45.resolve(workspacePath)), { recursive: true });
27566
27718
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
27567
27719
  try {
27568
- await writeFile21(tmp, JSON.stringify(sorted, null, 2) + "\n");
27720
+ await writeFile22(tmp, JSON.stringify(sorted, null, 2) + "\n");
27569
27721
  await rename12(tmp, workspacePath);
27570
27722
  } finally {
27571
- await rm11(tmp, { force: true });
27723
+ await rm12(tmp, { force: true });
27572
27724
  }
27573
27725
  }
27574
27726
  function toPortablePath(dir, absolute) {
27575
- return path44.relative(dir, absolute).split(path44.sep).join("/");
27727
+ return path45.relative(dir, absolute).split(path45.sep).join("/");
27576
27728
  }
27577
27729
  function resolveProject(dir, project2) {
27578
27730
  return {
27579
- manifestPath: path44.resolve(dir, project2.manifest.split("/").join(path44.sep)),
27580
- 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))
27581
27733
  };
27582
27734
  }
27583
27735
  function validateWorkspace(ws, dir) {
@@ -27590,7 +27742,7 @@ function validateWorkspace(ws, dir) {
27590
27742
  const { manifestPath, lockPath } = resolveProject(dir, project2);
27591
27743
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project2.id]);
27592
27744
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project2.id]);
27593
- if (path44.isAbsolute(project2.manifest) || path44.isAbsolute(project2.lock)) {
27745
+ if (path45.isAbsolute(project2.manifest) || path45.isAbsolute(project2.lock)) {
27594
27746
  diagnostics.push({
27595
27747
  id: "absolute-path",
27596
27748
  level: "warning",
@@ -27651,14 +27803,14 @@ function validateWorkspace(ws, dir) {
27651
27803
  }
27652
27804
 
27653
27805
  // src/gallery/edit.ts
27654
- import { readFile as readFile34, rename as rename13, writeFile as writeFile25 } from "fs/promises";
27655
- import path48 from "path";
27806
+ import { readFile as readFile34, rename as rename13, writeFile as writeFile26 } from "fs/promises";
27807
+ import path49 from "path";
27656
27808
  import { z as z17 } from "zod";
27657
27809
 
27658
27810
  // src/gallery/upload.ts
27659
27811
  import { existsSync as existsSync40 } from "fs";
27660
- import { mkdir as mkdir19, writeFile as writeFile22 } from "fs/promises";
27661
- import path45 from "path";
27812
+ import { mkdir as mkdir20, writeFile as writeFile23 } from "fs/promises";
27813
+ import path46 from "path";
27662
27814
  import { z as z14 } from "zod";
27663
27815
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
27664
27816
  var UploadImageSchema = z14.object({
@@ -27671,12 +27823,12 @@ var UploadImageSchema = z14.object({
27671
27823
  overwrite: z14.boolean().optional()
27672
27824
  }).strict();
27673
27825
  async function saveProjectImage(root, request) {
27674
- const file = path45.resolve(root, request.path);
27675
- const relative = path45.relative(root, file);
27676
- 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)) {
27677
27829
  throw new ManifestEditError("an upload must stay inside the project");
27678
27830
  }
27679
- const extension = path45.extname(file).toLowerCase();
27831
+ const extension = path46.extname(file).toLowerCase();
27680
27832
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
27681
27833
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
27682
27834
  const bytes = Buffer.from(request.base64, "base64");
@@ -27689,17 +27841,17 @@ async function saveProjectImage(root, request) {
27689
27841
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
27690
27842
  }
27691
27843
  if (existsSync40(file) && !request.overwrite) {
27692
- 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`);
27693
27845
  }
27694
- await mkdir19(path45.dirname(file), { recursive: true });
27695
- await writeFile22(file, bytes);
27696
- 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("/");
27697
27849
  }
27698
27850
 
27699
27851
  // src/gallery/image-revision.ts
27700
27852
  import { existsSync as existsSync41 } from "fs";
27701
- import { readFile as readFile32, rm as rm12, writeFile as writeFile23 } from "fs/promises";
27702
- import path46 from "path";
27853
+ import { readFile as readFile32, rm as rm13, writeFile as writeFile24 } from "fs/promises";
27854
+ import path47 from "path";
27703
27855
  import { z as z15 } from "zod";
27704
27856
  var InpaintRevisionRequestSchema = z15.object({
27705
27857
  action: z15.literal("create-inpaint-revision"),
@@ -27718,14 +27870,14 @@ var InpaintRevisionRequestSchema = z15.object({
27718
27870
  overwrite: z15.boolean().optional()
27719
27871
  }).strict();
27720
27872
  async function createInpaintRevision(manifestPath, request) {
27721
- const root = path46.dirname(path46.resolve(manifestPath));
27722
- if (path46.extname(request.maskPath).toLowerCase() !== ".png") {
27873
+ const root = path47.dirname(path47.resolve(manifestPath));
27874
+ if (path47.extname(request.maskPath).toLowerCase() !== ".png") {
27723
27875
  throw new ManifestEditError("the mask must be a .png path inside the project");
27724
27876
  }
27725
27877
  const bytes = Buffer.from(request.maskBase64, "base64");
27726
27878
  const metadata = imageMetadata(bytes);
27727
27879
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
27728
- const file = path46.resolve(root, request.maskPath);
27880
+ const file = path47.resolve(root, request.maskPath);
27729
27881
  const previous = existsSync41(file) ? await readFile32(file) : null;
27730
27882
  const mask = await saveProjectImage(root, {
27731
27883
  action: "upload-image",
@@ -27745,8 +27897,8 @@ async function createInpaintRevision(manifestPath, request) {
27745
27897
  }
27746
27898
  });
27747
27899
  } catch (error) {
27748
- if (previous) await writeFile23(file, previous);
27749
- else await rm12(file, { force: true });
27900
+ if (previous) await writeFile24(file, previous);
27901
+ else await rm13(file, { force: true });
27750
27902
  throw error;
27751
27903
  }
27752
27904
  return mask;
@@ -27754,8 +27906,8 @@ async function createInpaintRevision(manifestPath, request) {
27754
27906
 
27755
27907
  // src/gallery/skeleton.ts
27756
27908
  import { existsSync as existsSync42 } from "fs";
27757
- import { mkdir as mkdir20, readFile as readFile33, rm as rm13, writeFile as writeFile24 } from "fs/promises";
27758
- 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";
27759
27911
  import { z as z16 } from "zod";
27760
27912
  var SkeletonEstimateRequestSchema = z16.object({
27761
27913
  project: z16.string().min(1).optional(),
@@ -27794,10 +27946,10 @@ var SkeletonKeypointsUpdateSchema = z16.object({
27794
27946
  set: SkeletonSetSchema
27795
27947
  }).strict();
27796
27948
  async function createSkeletonAnimation(manifestPath, request) {
27797
- const root = path47.dirname(path47.resolve(manifestPath));
27798
- const file = path47.resolve(root, request.keypointsFile);
27799
- const relative = path47.relative(root, file);
27800
- 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)) {
27801
27953
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
27802
27954
  }
27803
27955
  const existed = existsSync42(file);
@@ -27807,8 +27959,8 @@ async function createSkeletonAnimation(manifestPath, request) {
27807
27959
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
27808
27960
  }
27809
27961
  if (existed) previous = await readFile33(file);
27810
- await mkdir20(path47.dirname(file), { recursive: true });
27811
- 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");
27812
27964
  } else if (!existed) {
27813
27965
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
27814
27966
  }
@@ -27823,7 +27975,7 @@ async function createSkeletonAnimation(manifestPath, request) {
27823
27975
  revision: {
27824
27976
  mode: "animate-skeleton",
27825
27977
  from: request.from,
27826
- keypointsFile: relative.split(path47.sep).join("/"),
27978
+ keypointsFile: relative.split(path48.sep).join("/"),
27827
27979
  direction: request.direction,
27828
27980
  description: request.description,
27829
27981
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -27832,8 +27984,8 @@ async function createSkeletonAnimation(manifestPath, request) {
27832
27984
  });
27833
27985
  } catch (error) {
27834
27986
  if (request.set) {
27835
- if (previous) await writeFile24(file, previous);
27836
- else await rm13(file, { force: true });
27987
+ if (previous) await writeFile25(file, previous);
27988
+ else await rm14(file, { force: true });
27837
27989
  }
27838
27990
  throw error;
27839
27991
  }
@@ -27844,19 +27996,19 @@ async function updateSkeletonKeypoints(ctx, request) {
27844
27996
  if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
27845
27997
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
27846
27998
  if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
27847
- const relative = path47.relative(ctx.loaded.root, file);
27848
- if (relative.startsWith("..") || path47.isAbsolute(relative)) {
27999
+ const relative = path48.relative(ctx.loaded.root, file);
28000
+ if (relative.startsWith("..") || path48.isAbsolute(relative)) {
27849
28001
  throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
27850
28002
  }
27851
28003
  const current = existsSync42(file) ? sha256(await readFile33(file)) : null;
27852
28004
  if (current !== request.expectedSha256) {
27853
28005
  throw Object.assign(
27854
- 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`),
27855
28007
  { status: 409 }
27856
28008
  );
27857
28009
  }
27858
- await writeFile24(file, JSON.stringify(request.set, null, 2) + "\n");
27859
- return relative.split(path47.sep).join("/");
28010
+ await writeFile25(file, JSON.stringify(request.set, null, 2) + "\n");
28011
+ return relative.split(path48.sep).join("/");
27860
28012
  }
27861
28013
 
27862
28014
  // src/gallery/edit.ts
@@ -27910,7 +28062,7 @@ function createGalleryEditHandler(opts) {
27910
28062
  const history = /* @__PURE__ */ new Map();
27911
28063
  const manifestOf = async (project2) => {
27912
28064
  try {
27913
- 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));
27914
28066
  } catch {
27915
28067
  return null;
27916
28068
  }
@@ -27930,10 +28082,10 @@ function createGalleryEditHandler(opts) {
27930
28082
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
27931
28083
  }
27932
28084
  const tmp = manifestPath2 + ".pixelkiln-undo";
27933
- await writeFile25(tmp, last.before);
28085
+ await writeFile26(tmp, last.before);
27934
28086
  await rename13(tmp, manifestPath2);
27935
28087
  stack.pop();
27936
- log(` manifest edit undone in ${path48.relative(process.cwd(), manifestPath2) || manifestPath2}`);
28088
+ log(` manifest edit undone in ${path49.relative(process.cwd(), manifestPath2) || manifestPath2}`);
27937
28089
  return opts.reload();
27938
28090
  }
27939
28091
  const manifestPath = await manifestOf(body?.project);
@@ -28019,7 +28171,7 @@ function createEditApplier(opts, log) {
28019
28171
  } catch (error) {
28020
28172
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
28021
28173
  }
28022
- const written = await saveProjectImage(path48.dirname(path48.resolve(manifestPath2)), upload.data);
28174
+ const written = await saveProjectImage(path49.dirname(path49.resolve(manifestPath2)), upload.data);
28023
28175
  log(` image added: ${written}`);
28024
28176
  return opts.reload();
28025
28177
  }
@@ -28086,7 +28238,7 @@ function createEditApplier(opts, log) {
28086
28238
  }
28087
28239
  const result = await applyManifestEdit(manifestPath, parsed.data);
28088
28240
  if (result.changed) {
28089
- const relative = path48.relative(process.cwd(), result.manifestPath);
28241
+ const relative = path49.relative(process.cwd(), result.manifestPath);
28090
28242
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
28091
28243
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
28092
28244
  }
@@ -28114,7 +28266,7 @@ function describeEdit(edit) {
28114
28266
  // src/gallery/snapshot.ts
28115
28267
  var PROJECT_FILE_TYPE = "application/octet-stream";
28116
28268
  function galleryMediaId(absolutePath) {
28117
- 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);
28118
28270
  }
28119
28271
  function galleryMediaRoute(id) {
28120
28272
  return `/media/${id}`;
@@ -28138,7 +28290,7 @@ function describeHistory(media, entry, cacheDir) {
28138
28290
  return (entry.history ?? []).map((generation, i) => {
28139
28291
  const outputs = generation.outputs.map((output) => {
28140
28292
  const mediaType = output.mediaType ?? MediaType.PNG;
28141
- const file = path49.join(cacheDir, cacheFileName(output.sha256, mediaType));
28293
+ const file = path50.join(cacheDir, cacheFileName(output.sha256, mediaType));
28142
28294
  let url = null;
28143
28295
  if (existsSync43(file)) {
28144
28296
  const id = galleryMediaId(file);
@@ -28270,9 +28422,9 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
28270
28422
  async function describeQuality(media, root, inspection) {
28271
28423
  const outputPaths = inspection.outputs ?? [inspection.output];
28272
28424
  const outputs = await Promise.all(
28273
- outputPaths.map((file) => describeOutput(media, root, path49.resolve(root, file)))
28425
+ outputPaths.map((file) => describeOutput(media, root, path50.resolve(root, file)))
28274
28426
  );
28275
- const recordPath = path49.resolve(root, inspection.record);
28427
+ const recordPath = path50.resolve(root, inspection.record);
28276
28428
  const recordExists = existsSync43(recordPath);
28277
28429
  let options = null;
28278
28430
  let check = null;
@@ -28292,7 +28444,7 @@ async function describeQuality(media, root, inspection) {
28292
28444
  return {
28293
28445
  state: inspection.state,
28294
28446
  reason: inspection.reason,
28295
- output: portableOutputPath(path49.resolve(root, inspection.output), root),
28447
+ output: portableOutputPath(path50.resolve(root, inspection.output), root),
28296
28448
  record: portableOutputPath(recordPath, root),
28297
28449
  recordExists,
28298
28450
  outputs,
@@ -28332,7 +28484,7 @@ async function buildGallerySnapshot(opts) {
28332
28484
  const items = [];
28333
28485
  const manifestText = await readFile35(loaded.path, "utf8");
28334
28486
  const manifestSha256 = sha256(manifestText);
28335
- const cacheDir = path49.resolve(path49.dirname(opts.lockPath), ".pixelkiln", "cache");
28487
+ const cacheDir = path50.resolve(path50.dirname(opts.lockPath), ".pixelkiln", "cache");
28336
28488
  let rawStyles = {};
28337
28489
  try {
28338
28490
  const raw = JSON.parse(manifestText);
@@ -28356,7 +28508,7 @@ async function buildGallerySnapshot(opts) {
28356
28508
  )
28357
28509
  );
28358
28510
  if (spec.source) {
28359
- const editPath = path49.resolve(root, spec.source);
28511
+ const editPath = path50.resolve(root, spec.source);
28360
28512
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
28361
28513
  const editShas = await Promise.all(
28362
28514
  Array.from({ length: memberCount }, async (_, index) => {
@@ -28405,7 +28557,7 @@ async function buildGallerySnapshot(opts) {
28405
28557
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
28406
28558
  }
28407
28559
  } else if (spec.source) {
28408
- outputs = [await describeOutput(media, root, path49.resolve(root, spec.source))];
28560
+ outputs = [await describeOutput(media, root, path50.resolve(root, spec.source))];
28409
28561
  } else if (!entry && existsSync43(spec.outFile)) {
28410
28562
  outputs = [await describeOutput(media, root, spec.outFile)];
28411
28563
  } else {
@@ -28610,7 +28762,7 @@ async function buildGallerySnapshot(opts) {
28610
28762
  id: loaded.manifest.name,
28611
28763
  name: loaded.manifest.name,
28612
28764
  manifest: loaded.path,
28613
- lock: path49.resolve(opts.lockPath),
28765
+ lock: path50.resolve(opts.lockPath),
28614
28766
  root,
28615
28767
  provider: loaded.manifest.provider,
28616
28768
  account: null,
@@ -28639,7 +28791,7 @@ async function buildGallerySnapshot(opts) {
28639
28791
  return { snapshot, media };
28640
28792
  }
28641
28793
  async function buildWorkspaceGallerySnapshot(opts) {
28642
- const dir = path49.dirname(path49.resolve(opts.workspacePath));
28794
+ const dir = path50.dirname(path50.resolve(opts.workspacePath));
28643
28795
  const media = /* @__PURE__ */ new Map();
28644
28796
  const projects = [];
28645
28797
  const items = [];
@@ -28684,7 +28836,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
28684
28836
  id: project2.id,
28685
28837
  name: loaded.manifest.name,
28686
28838
  manifest: manifestPath,
28687
- lock: path49.resolve(lockPath),
28839
+ lock: path50.resolve(lockPath),
28688
28840
  root: loaded.root,
28689
28841
  provider: loaded.manifest.provider,
28690
28842
  account: project2.account ?? null,
@@ -28700,8 +28852,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
28700
28852
  id: project2.id,
28701
28853
  name: project2.id,
28702
28854
  manifest: manifestPath,
28703
- lock: path49.resolve(lockPath),
28704
- root: path49.dirname(manifestPath),
28855
+ lock: path50.resolve(lockPath),
28856
+ root: path50.dirname(manifestPath),
28705
28857
  provider: project2.provider,
28706
28858
  account: project2.account ?? null,
28707
28859
  manifestSha256: null,
@@ -28728,7 +28880,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
28728
28880
  version: 1,
28729
28881
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
28730
28882
  project: null,
28731
- workspace: { path: path49.resolve(opts.workspacePath), dir, projects },
28883
+ workspace: { path: path50.resolve(opts.workspacePath), dir, projects },
28732
28884
  filter,
28733
28885
  totals: {
28734
28886
  entries: projects.reduce((sum, project2) => sum + project2.entries, 0),
@@ -28932,9 +29084,9 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
28932
29084
  // src/editor/install.ts
28933
29085
  import { createHash as createHash9 } from "crypto";
28934
29086
  import { existsSync as existsSync45 } from "fs";
28935
- 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";
28936
29088
  import os3 from "os";
28937
- import path50 from "path";
29089
+ import path51 from "path";
28938
29090
  var EditorInstallError = class extends Error {
28939
29091
  constructor(message6, file) {
28940
29092
  super(message6);
@@ -28945,15 +29097,15 @@ var EditorInstallError = class extends Error {
28945
29097
  };
28946
29098
  function editorToolsRoot() {
28947
29099
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
28948
- if (override) return path50.resolve(override);
28949
- 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");
28950
29102
  if (process.platform === "win32") {
28951
- 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");
28952
29104
  }
28953
- 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");
28954
29106
  }
28955
29107
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
28956
- return path50.join(root, "pixelorama", pin.release ?? "unpublished");
29108
+ return path51.join(root, "pixelorama", pin.release ?? "unpublished");
28957
29109
  }
28958
29110
  function editorBaseUrl(pin = EDITOR_PIN) {
28959
29111
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -28976,7 +29128,7 @@ async function editorStatus(opts = {}) {
28976
29128
  let totalBytes = 0;
28977
29129
  for (const [name, expected] of Object.entries(pin.files)) {
28978
29130
  totalBytes += expected.bytes;
28979
- const file = path50.join(dir, name);
29131
+ const file = path51.join(dir, name);
28980
29132
  const info = existsSync45(file) ? await stat6(file).catch(() => null) : null;
28981
29133
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
28982
29134
  installedBytes += expected.bytes;
@@ -29006,7 +29158,7 @@ async function installEditor(opts = {}) {
29006
29158
  );
29007
29159
  }
29008
29160
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
29009
- await mkdir21(dir, { recursive: true });
29161
+ await mkdir22(dir, { recursive: true });
29010
29162
  const downloaded = [];
29011
29163
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
29012
29164
  let fetchedBytes = before.installedBytes;
@@ -29034,13 +29186,13 @@ async function installEditor(opts = {}) {
29034
29186
  if (digest2 !== expected.sha256) {
29035
29187
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
29036
29188
  }
29037
- const final = path50.join(dir, name);
29189
+ const final = path51.join(dir, name);
29038
29190
  const tmp = `${final}.${process.pid}.part`;
29039
29191
  try {
29040
- await writeFile26(tmp, bytes);
29192
+ await writeFile27(tmp, bytes);
29041
29193
  await rename14(tmp, final);
29042
29194
  } finally {
29043
- await rm14(tmp, { force: true });
29195
+ await rm15(tmp, { force: true });
29044
29196
  }
29045
29197
  fetchedBytes += bytes.length;
29046
29198
  downloaded.push(name);
@@ -29080,12 +29232,12 @@ var EDITOR_CONTENT_TYPES = {
29080
29232
  ".json": "application/json; charset=utf-8"
29081
29233
  };
29082
29234
  function editorContentType(name) {
29083
- return EDITOR_CONTENT_TYPES[path50.extname(name).toLowerCase()] ?? null;
29235
+ return EDITOR_CONTENT_TYPES[path51.extname(name).toLowerCase()] ?? null;
29084
29236
  }
29085
29237
 
29086
29238
  // src/gallery/editor.ts
29087
29239
  import { readFile as readFile37 } from "fs/promises";
29088
- import path51 from "path";
29240
+ import path52 from "path";
29089
29241
  function editorRoute(release, name = "index.html") {
29090
29242
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
29091
29243
  }
@@ -29158,7 +29310,7 @@ function createGalleryEditorHandlers(opts = {}) {
29158
29310
  if (!status.installed) return null;
29159
29311
  let bytes;
29160
29312
  try {
29161
- bytes = await readFile37(path51.join(dir, name));
29313
+ bytes = await readFile37(path52.join(dir, name));
29162
29314
  } catch {
29163
29315
  verified = null;
29164
29316
  return null;
@@ -29852,7 +30004,7 @@ function createGenerateHandlers(opts) {
29852
30004
  // src/pipeline/salvage.ts
29853
30005
  import { readFile as readFile39 } from "fs/promises";
29854
30006
  import { existsSync as existsSync46 } from "fs";
29855
- import path52 from "path";
30007
+ import path53 from "path";
29856
30008
  function providerClaimId(provider, objectId) {
29857
30009
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
29858
30010
  }
@@ -29966,20 +30118,20 @@ function matchOrphanStyle(prompt, manifest) {
29966
30118
  return matchStyleByPattern(prompt, manifest);
29967
30119
  }
29968
30120
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
29969
- const own = path52.resolve(ownManifestPath);
30121
+ const own = path53.resolve(ownManifestPath);
29970
30122
  const siblingManifestPaths = [
29971
30123
  .../* @__PURE__ */ new Set([
29972
30124
  ...workspaceManifestPaths,
29973
- ...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"))
29974
30126
  ])
29975
30127
  ];
29976
30128
  const siblings = [];
29977
30129
  for (const siblingManifestPath of siblingManifestPaths) {
29978
- if (path52.resolve(siblingManifestPath) === own) continue;
30130
+ if (path53.resolve(siblingManifestPath) === own) continue;
29979
30131
  if (!existsSync46(siblingManifestPath)) continue;
29980
30132
  try {
29981
30133
  const { manifest } = await loadManifest(siblingManifestPath);
29982
- siblings.push({ label: path52.basename(path52.dirname(siblingManifestPath)), manifest });
30134
+ siblings.push({ label: path53.basename(path53.dirname(siblingManifestPath)), manifest });
29983
30135
  } catch {
29984
30136
  }
29985
30137
  }
@@ -30099,8 +30251,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
30099
30251
  }
30100
30252
 
30101
30253
  // src/pick/salvage-server.ts
30102
- import { mkdir as mkdir22, writeFile as writeFile27, readFile as readFile40 } from "fs/promises";
30103
- import path53 from "path";
30254
+ import { mkdir as mkdir23, writeFile as writeFile28, readFile as readFile40 } from "fs/promises";
30255
+ import path54 from "path";
30104
30256
 
30105
30257
  // src/pick/salvage-sheet.ts
30106
30258
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -30266,7 +30418,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30266
30418
  });
30267
30419
  const html = renderSalvageSheet(orphans, {
30268
30420
  styleId: ctx.styleId,
30269
- importDir: path53.relative(process.cwd(), ctx.importDir) || "."
30421
+ importDir: path54.relative(process.cwd(), ctx.importDir) || "."
30270
30422
  });
30271
30423
  const byId = new Map(orphans.map((o) => [o.id, o]));
30272
30424
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -30322,10 +30474,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30322
30474
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
30323
30475
  decodePng(buf);
30324
30476
  const assetId = idFromPrompt(orphan.prompt, taken);
30325
- const rel = path53.join("_salvaged", `${assetId}.png`);
30326
- const outFile = path53.resolve(ctx.importDir, rel);
30327
- await mkdir22(path53.dirname(outFile), { recursive: true });
30328
- 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);
30329
30481
  ctx.manifest.assets[assetId] = {
30330
30482
  prompt: orphan.prompt,
30331
30483
  promptByStyle: {},
@@ -30357,7 +30509,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30357
30509
  sourceUrl: durableSource,
30358
30510
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
30359
30511
  outputs: [{
30360
- path: portableOutputPath(outFile, path53.dirname(ctx.manifestPath)),
30512
+ path: portableOutputPath(outFile, path54.dirname(ctx.manifestPath)),
30361
30513
  sha256: sha256(buf)
30362
30514
  }],
30363
30515
  submittedAt: orphan.createdAt,
@@ -30383,7 +30535,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
30383
30535
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
30384
30536
  const raw = JSON.parse(await readFile40(ctx.manifestPath, "utf8"));
30385
30537
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
30386
- await writeFile27(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
30538
+ await writeFile28(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
30387
30539
  await saveLock(ctx.lockPath, ctx.lock);
30388
30540
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
30389
30541
  return result;