pixelkiln 0.113.0 → 0.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -188,6 +188,7 @@ var BOOL_FLAGS = [
188
188
  "--write-prompts",
189
189
  "--primary-only",
190
190
  "--prune",
191
+ "--merge-connected",
191
192
  "--edit",
192
193
  "--refresh",
193
194
  "--no-editor",
@@ -536,6 +537,7 @@ function parseArgs(argv) {
536
537
  assets: list("--only"),
537
538
  redrawFrames: list("--frame"),
538
539
  force: rest.includes("--force"),
540
+ mergeConnected: rest.includes("--merge-connected"),
539
541
  yes: rest.includes("--yes") || rest.includes("-y"),
540
542
  budget,
541
543
  providerBudgets,
@@ -893,6 +895,7 @@ Options
893
895
  --game-pack vfx: also download the game-pack ZIP
894
896
  --glyph-px <n> font: native glyph size, 8, 16 (default), 32, or 64
895
897
  --prune cache: remove invalid/unreferenced local cache data
898
+ --merge-connected export: write connected terrain sets as one tileset with every terrain
896
899
  --manifest <path> Default: pixelkiln.manifest.json
897
900
  --lock <path> Default: pixelkiln.lock.json beside the manifest
898
901
  --style a,b Restrict to these styles
@@ -1298,14 +1301,14 @@ function extractPalette(png, topN = 8, alphaThreshold = 128) {
1298
1301
  const alpha = png.pixels[i + 3];
1299
1302
  if (alpha < alphaThreshold) continue;
1300
1303
  opaque2++;
1301
- const key2 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
1302
- counts.set(key2, (counts.get(key2) ?? 0) + 1);
1304
+ const key3 = png.pixels[i] << 16 | png.pixels[i + 1] << 8 | png.pixels[i + 2];
1305
+ counts.set(key3, (counts.get(key3) ?? 0) + 1);
1303
1306
  }
1304
1307
  if (opaque2 === 0) return [];
1305
- return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key2, n]) => ({
1306
- r: key2 >> 16 & 255,
1307
- g: key2 >> 8 & 255,
1308
- b: key2 & 255,
1308
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([key3, n]) => ({
1309
+ r: key3 >> 16 & 255,
1310
+ g: key3 >> 8 & 255,
1311
+ b: key3 & 255,
1309
1312
  weight: n / opaque2
1310
1313
  }));
1311
1314
  }
@@ -2032,24 +2035,24 @@ var AssetVfxSchema = z.object({
2032
2035
  spriteFrames: z.number().int().min(1).max(32).optional(),
2033
2036
  spriteFps: z.number().int().min(1).max(60).optional()
2034
2037
  }).strict().superRefine((vfx, context) => {
2035
- for (const key2 of ["spriteFrames", "spriteFps"]) {
2036
- if (vfx[key2] === void 0) continue;
2038
+ for (const key3 of ["spriteFrames", "spriteFps"]) {
2039
+ if (vfx[key3] === void 0) continue;
2037
2040
  if (vfx.description === void 0) {
2038
- context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} describes the sprite sent to PixelLab's VFX artist; add a description`, path: [key2] });
2041
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key3} describes the sprite sent to PixelLab's VFX artist; add a description`, path: [key3] });
2039
2042
  } else if (!vfx.sprite) {
2040
- context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} describes a sprite strip; add a sprite`, path: [key2] });
2043
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key3} describes a sprite strip; add a sprite`, path: [key3] });
2041
2044
  }
2042
2045
  }
2043
2046
  if (vfx.spriteFps !== void 0 && vfx.sprite && vfx.description !== void 0 && (vfx.spriteFrames ?? 1) < 2) {
2044
2047
  context.addIssue({ code: z.ZodIssueCode.custom, message: "spriteFps is the speed of a sprite strip; set spriteFrames to 2 or more", path: ["spriteFps"] });
2045
2048
  }
2046
2049
  if (vfx.description !== void 0) {
2047
- for (const key2 of ["preset", "recipe", "parts", "fps"]) {
2048
- if (vfx[key2] !== void 0) {
2050
+ for (const key3 of ["preset", "recipe", "parts", "fps"]) {
2051
+ if (vfx[key3] !== void 0) {
2049
2052
  context.addIssue({
2050
2053
  code: z.ZodIssueCode.custom,
2051
- message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key2}; use a description or the workbench's preset/recipe/parts/fps, not both`,
2052
- path: [key2]
2054
+ message: `a vfx description goes to PixelLab's VFX artist, which takes no ${key3}; use a description or the workbench's preset/recipe/parts/fps, not both`,
2055
+ path: [key3]
2053
2056
  });
2054
2057
  }
2055
2058
  }
@@ -2297,18 +2300,18 @@ var CharacterAnimationSchema = z.object({
2297
2300
  context.addIssue({ code: z.ZodIssueCode.custom, message: "a skeleton-v3 loop from a sentence takes 3 to 15 frames", path: ["frames"] });
2298
2301
  }
2299
2302
  const mode2 = animation.mode ?? (animation.template ? "template" : "v3");
2300
- for (const key2 of ["startFrame", "endFrame", "enhancePrompt"]) {
2301
- if (animation[key2] !== void 0 && mode2 !== "v3") {
2303
+ for (const key3 of ["startFrame", "endFrame", "enhancePrompt"]) {
2304
+ if (animation[key3] !== void 0 && mode2 !== "v3") {
2302
2305
  context.addIssue({
2303
2306
  code: z.ZodIssueCode.custom,
2304
- message: `${key2} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
2305
- path: [key2]
2307
+ message: `${key3} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
2308
+ path: [key3]
2306
2309
  });
2307
2310
  }
2308
2311
  }
2309
- for (const key2 of ["outline", "shading", "detail"]) {
2310
- if (animation[key2] !== void 0 && mode2 !== "template") {
2311
- context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} overrides apply to template loops only`, path: [key2] });
2312
+ for (const key3 of ["outline", "shading", "detail"]) {
2313
+ if (animation[key3] !== void 0 && mode2 !== "template") {
2314
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key3} overrides apply to template loops only`, path: [key3] });
2312
2315
  }
2313
2316
  }
2314
2317
  if (animation.template && animation.mode && animation.mode !== "template" && animation.mode !== "skeleton-v3") {
@@ -3861,22 +3864,22 @@ async function writeLockWhileHeld(file, lock) {
3861
3864
  }
3862
3865
  const dirty = dirtyPatches.get(lock) ?? /* @__PURE__ */ new Map();
3863
3866
  const snapshot = /* @__PURE__ */ new Map();
3864
- for (const [key2, patch] of dirty) snapshot.set(key2, { ...patch });
3867
+ for (const [key3, patch] of dirty) snapshot.set(key3, { ...patch });
3865
3868
  const merged = { ...disk.entries };
3866
- for (const [key2, patch] of snapshot) {
3867
- const local = lock.entries[key2];
3869
+ for (const [key3, patch] of snapshot) {
3870
+ const local = lock.entries[key3];
3868
3871
  if (!local) continue;
3869
- merged[key2] = merged[key2] ? { ...merged[key2], ...patch } : local;
3872
+ merged[key3] = merged[key3] ? { ...merged[key3], ...patch } : local;
3870
3873
  }
3871
- for (const [key2, entry] of Object.entries(lock.entries)) {
3872
- if (!merged[key2]) merged[key2] = entry;
3874
+ for (const [key3, entry] of Object.entries(lock.entries)) {
3875
+ if (!merged[key3]) merged[key3] = entry;
3873
3876
  }
3874
3877
  const deletes = dirtyDeletes.get(lock);
3875
3878
  const deleteSnapshot = deletes ? new Set(deletes) : /* @__PURE__ */ new Set();
3876
- for (const key2 of deleteSnapshot) delete merged[key2];
3879
+ for (const key3 of deleteSnapshot) delete merged[key3];
3877
3880
  const sorted = {};
3878
- for (const key2 of Object.keys(merged).sort()) {
3879
- sorted[key2] = merged[key2];
3881
+ for (const key3 of Object.keys(merged).sort()) {
3882
+ sorted[key3] = merged[key3];
3880
3883
  }
3881
3884
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
3882
3885
  try {
@@ -3887,48 +3890,48 @@ async function writeLockWhileHeld(file, lock) {
3887
3890
  }
3888
3891
  const currentDirty = dirtyPatches.get(lock);
3889
3892
  if (currentDirty) {
3890
- for (const [key2, patch] of snapshot) {
3891
- const current = currentDirty.get(key2);
3893
+ for (const [key3, patch] of snapshot) {
3894
+ const current = currentDirty.get(key3);
3892
3895
  if (!current) continue;
3893
3896
  for (const [field, value] of Object.entries(patch)) {
3894
3897
  if (Object.is(current[field], value)) {
3895
3898
  delete current[field];
3896
3899
  }
3897
3900
  }
3898
- if (Object.keys(current).length === 0) currentDirty.delete(key2);
3901
+ if (Object.keys(current).length === 0) currentDirty.delete(key3);
3899
3902
  }
3900
3903
  }
3901
3904
  const stillDirty = dirtyDeletes.get(lock);
3902
3905
  if (stillDirty) {
3903
- for (const key2 of deleteSnapshot) stillDirty.delete(key2);
3906
+ for (const key3 of deleteSnapshot) stillDirty.delete(key3);
3904
3907
  if (stillDirty.size === 0) dirtyDeletes.delete(lock);
3905
3908
  }
3906
3909
  const localAfterWrite = lock.entries;
3907
3910
  lock.entries = { ...merged };
3908
- for (const [key2, patch] of currentDirty ?? []) {
3909
- const base = lock.entries[key2] ?? localAfterWrite[key2];
3910
- if (base) lock.entries[key2] = { ...base, ...patch };
3911
+ for (const [key3, patch] of currentDirty ?? []) {
3912
+ const base = lock.entries[key3] ?? localAfterWrite[key3];
3913
+ if (base) lock.entries[key3] = { ...base, ...patch };
3911
3914
  }
3912
3915
  }
3913
- function upsert(lock, key2, patch) {
3914
- dirtyDeletes.get(lock)?.delete(key2);
3915
- const existing = lock.entries[key2];
3916
+ function upsert(lock, key3, patch) {
3917
+ dirtyDeletes.get(lock)?.delete(key3);
3918
+ const existing = lock.entries[key3];
3916
3919
  const next = { ...existing, ...patch };
3917
- lock.entries[key2] = next;
3920
+ lock.entries[key3] = next;
3918
3921
  let dirty = dirtyPatches.get(lock);
3919
3922
  if (!dirty) {
3920
3923
  dirty = /* @__PURE__ */ new Map();
3921
3924
  dirtyPatches.set(lock, dirty);
3922
3925
  }
3923
- dirty.set(key2, { ...dirty.get(key2) ?? {}, ...patch });
3926
+ dirty.set(key3, { ...dirty.get(key3) ?? {}, ...patch });
3924
3927
  return next;
3925
3928
  }
3926
- function remove(lock, key2) {
3927
- if (!lock.entries[key2]) return false;
3928
- delete lock.entries[key2];
3929
+ function remove(lock, key3) {
3930
+ if (!lock.entries[key3]) return false;
3931
+ delete lock.entries[key3];
3929
3932
  const patches = dirtyPatches.get(lock);
3930
3933
  if (patches) {
3931
- patches.delete(key2);
3934
+ patches.delete(key3);
3932
3935
  if (patches.size === 0) dirtyPatches.delete(lock);
3933
3936
  }
3934
3937
  let deletes = dirtyDeletes.get(lock);
@@ -3936,7 +3939,7 @@ function remove(lock, key2) {
3936
3939
  deletes = /* @__PURE__ */ new Set();
3937
3940
  dirtyDeletes.set(lock, deletes);
3938
3941
  }
3939
- deletes.add(key2);
3942
+ deletes.add(key3);
3940
3943
  return true;
3941
3944
  }
3942
3945
  var FILE_LOCK_TIMEOUT_MS = 1e4;
@@ -4143,8 +4146,8 @@ function currentEntryOutputPath(entry, spec, index) {
4143
4146
  function normalizeLockOutputPaths(lock, specs) {
4144
4147
  const byKey = new Map(specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
4145
4148
  let changed = 0;
4146
- for (const [key2, entry] of Object.entries(lock.entries)) {
4147
- const spec = byKey.get(key2);
4149
+ for (const [key3, entry] of Object.entries(lock.entries)) {
4150
+ const spec = byKey.get(key3);
4148
4151
  if (!spec) continue;
4149
4152
  let entryChanged = false;
4150
4153
  const outputs = entry.outputs.map((output, index) => {
@@ -4155,7 +4158,7 @@ function normalizeLockOutputPaths(lock, specs) {
4155
4158
  entryChanged = true;
4156
4159
  return { ...output, path: portable };
4157
4160
  });
4158
- if (entryChanged) upsert(lock, key2, { outputs });
4161
+ if (entryChanged) upsert(lock, key3, { outputs });
4159
4162
  }
4160
4163
  return changed;
4161
4164
  }
@@ -4261,8 +4264,8 @@ function quantize(png, palette) {
4261
4264
  pixels[i + 2] = 0;
4262
4265
  continue;
4263
4266
  }
4264
- const key2 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
4265
- let nearest = nearestOf.get(key2);
4267
+ const key3 = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
4268
+ let nearest = nearestOf.get(key3);
4266
4269
  if (!nearest) {
4267
4270
  const pixel = { r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] };
4268
4271
  nearest = colors[0];
@@ -4275,7 +4278,7 @@ function quantize(png, palette) {
4275
4278
  distance = candidateDistance;
4276
4279
  }
4277
4280
  }
4278
- nearestOf.set(key2, nearest);
4281
+ nearestOf.set(key3, nearest);
4279
4282
  }
4280
4283
  if (pixels[i] !== nearest.r || pixels[i + 1] !== nearest.g || pixels[i + 2] !== nearest.b) changed++;
4281
4284
  pixels[i] = nearest.r;
@@ -4314,7 +4317,7 @@ var DEFAULT_KEY = "#00ffff";
4314
4317
  var KEY_SATURATION = 0.85;
4315
4318
  function keySkin(png, options = {}) {
4316
4319
  const image = decodePng(png);
4317
- const key2 = parseHex(options.key ?? DEFAULT_KEY);
4320
+ const key3 = parseHex(options.key ?? DEFAULT_KEY);
4318
4321
  const skin = options.skin?.map((hex2) => parseHex(hex2));
4319
4322
  const reach = (options.tolerance ?? 0) ** 2;
4320
4323
  const outlineBelow = options.outlineBelow ?? 46;
@@ -4329,14 +4332,14 @@ function keySkin(png, options = {}) {
4329
4332
  if (!skin.some((c) => (c.r - r) ** 2 + (c.g - g) ** 2 + (c.b - b) ** 2 <= reach)) continue;
4330
4333
  } else if (brightest < outlineBelow) continue;
4331
4334
  const tint = (channel) => Math.floor(brightest * (1 - KEY_SATURATION + KEY_SATURATION * channel / 255));
4332
- out[i] = tint(key2.r);
4333
- out[i + 1] = tint(key2.g);
4334
- out[i + 2] = tint(key2.b);
4335
+ out[i] = tint(key3.r);
4336
+ out[i + 1] = tint(key3.g);
4337
+ out[i + 2] = tint(key3.b);
4335
4338
  }
4336
4339
  return encodeRgbaPng(image.width, image.height, out);
4337
4340
  }
4338
- function isKeyColor(r, g, b, key2 = DEFAULT_KEY) {
4339
- const target = parseHex(key2);
4341
+ function isKeyColor(r, g, b, key3 = DEFAULT_KEY) {
4342
+ const target = parseHex(key3);
4340
4343
  const want = hsv(target.r, target.g, target.b).h;
4341
4344
  const { h, s, v } = hsv(r, g, b);
4342
4345
  const apart = Math.abs(h - want);
@@ -5007,7 +5010,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
5007
5010
  const log2 = opts.onProgress ?? (() => {
5008
5011
  });
5009
5012
  const mirror = spec.mirror;
5010
- const key2 = lockKey(spec.styleId, spec.assetId);
5013
+ const key3 = lockKey(spec.styleId, spec.assetId);
5011
5014
  const sourceKey = lockKey(spec.styleId, mirror.sourceAssetId);
5012
5015
  const source = lock.entries[sourceKey];
5013
5016
  if (!source || source.status !== "downloaded" || !source.outputs.length) {
@@ -5039,7 +5042,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
5039
5042
  }
5040
5043
  const sourceMetadata = source.providerMetadata?.[source.provider] ?? {};
5041
5044
  const character = spec.character;
5042
- const entry = upsert(lock, key2, {
5045
+ const entry = upsert(lock, key3, {
5043
5046
  styleId: spec.styleId,
5044
5047
  assetId: spec.assetId,
5045
5048
  specHash: spec.specHash,
@@ -5082,7 +5085,7 @@ async function deriveMirror(spec, lock, lockPath, opts = {}) {
5082
5085
  postprocess: postprocessFor(spec)
5083
5086
  });
5084
5087
  await saveLock(lockPath, lock);
5085
- log2(` mirror ${key2} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
5088
+ log2(` mirror ${key3} \u2190 ${sourceKey} (${written.length} file${written.length === 1 ? "" : "s"} flipped, no generation cost)`);
5086
5089
  return entry;
5087
5090
  }
5088
5091
 
@@ -5628,9 +5631,9 @@ function canonical(value) {
5628
5631
  if (Array.isArray(value)) return value.map(canonical);
5629
5632
  if (typeof value === "object") {
5630
5633
  const sorted = {};
5631
- for (const key2 of Object.keys(value).sort()) {
5632
- const item = value[key2];
5633
- if (item !== void 0) sorted[key2] = canonical(item);
5634
+ for (const key3 of Object.keys(value).sort()) {
5635
+ const item = value[key3];
5636
+ if (item !== void 0) sorted[key3] = canonical(item);
5634
5637
  }
5635
5638
  return sorted;
5636
5639
  }
@@ -6617,18 +6620,18 @@ async function qualitySource(spec, lock) {
6617
6620
  }
6618
6621
  async function inspectQualityProfile(spec, lock) {
6619
6622
  if (!spec.quality) return null;
6620
- const key2 = lockKey(spec.styleId, spec.assetId);
6623
+ const key3 = lockKey(spec.styleId, spec.assetId);
6621
6624
  const output = spec.quality.outFile;
6622
6625
  const record = qualityRecordPath(output);
6623
6626
  const source = await qualitySource(spec, lock);
6624
6627
  if (!source.items) {
6625
- return { key: key2, state: "blocked", reason: source.reason, source: null, output, record };
6628
+ return { key: key3, state: "blocked", reason: source.reason, source: null, output, record };
6626
6629
  }
6627
6630
  const sourcePaths = source.items.map((item) => item.path);
6628
6631
  const expectedOutputs = spec.generator === "frames" ? source.items.map((item, index) => qualityFrameOutputPath(output, item.role, index)) : [output];
6629
6632
  if (!existsSync5(record)) {
6630
6633
  return {
6631
- key: key2,
6634
+ key: key3,
6632
6635
  state: "needs-refinement",
6633
6636
  reason: "no refinement record",
6634
6637
  source: sourcePaths[0],
@@ -6647,7 +6650,7 @@ async function inspectQualityProfile(spec, lock) {
6647
6650
  const contractChanged = JSON.stringify(check.sources.map((item) => path9.resolve(item))) !== JSON.stringify(sourcePaths.map((item) => path9.resolve(item))) || JSON.stringify(check.outputs.map((item) => path9.resolve(item))) !== JSON.stringify(expectedOutputs.map((item) => path9.resolve(item))) || JSON.stringify(check.options.palette.colors) !== JSON.stringify(expectedPalette) || check.options.nativeGrid.revision !== expectedRevision || check.options.audit.thresholds.minGridConfidence !== spec.quality.minGridConfidence || check.options.audit.thresholds.minTransparency !== expectedTransparency || (expectedFrameSet ? !check.options.frameSet || check.options.frameSet.fps !== expectedFrameSet.fps || check.options.frameSet.count !== expectedFrameSet.count || JSON.stringify(check.options.frameSet.roles) !== JSON.stringify(expectedFrameSet.roles) : check.options.frameSet !== void 0);
6648
6651
  if (contractChanged) {
6649
6652
  return {
6650
- key: key2,
6653
+ key: key3,
6651
6654
  state: "needs-refinement",
6652
6655
  reason: "quality profile changed",
6653
6656
  source: sourcePaths[0],
@@ -6659,7 +6662,7 @@ async function inspectQualityProfile(spec, lock) {
6659
6662
  }
6660
6663
  if (!check.current || !check.auditSafe) {
6661
6664
  return {
6662
- key: key2,
6665
+ key: key3,
6663
6666
  state: "needs-refinement",
6664
6667
  reason: check.reasons.filter((reason) => reason !== "human 1\xD7 review is pending").join("; ") || "refinement record is stale",
6665
6668
  source: sourcePaths[0],
@@ -6671,7 +6674,7 @@ async function inspectQualityProfile(spec, lock) {
6671
6674
  }
6672
6675
  if (!check.approved) {
6673
6676
  return {
6674
- key: key2,
6677
+ key: key3,
6675
6678
  state: "needs-approval",
6676
6679
  reason: "automated checks passed; human 1\xD7 review is pending",
6677
6680
  source: sourcePaths[0],
@@ -6682,7 +6685,7 @@ async function inspectQualityProfile(spec, lock) {
6682
6685
  };
6683
6686
  }
6684
6687
  return {
6685
- key: key2,
6688
+ key: key3,
6686
6689
  state: "approved",
6687
6690
  reason: "refined output and human approval are current",
6688
6691
  source: sourcePaths[0],
@@ -6693,7 +6696,7 @@ async function inspectQualityProfile(spec, lock) {
6693
6696
  };
6694
6697
  } catch (error) {
6695
6698
  return {
6696
- key: key2,
6699
+ key: key3,
6697
6700
  state: "needs-refinement",
6698
6701
  reason: `invalid refinement record: ${error instanceof Error ? error.message : String(error)}`,
6699
6702
  source: sourcePaths[0],
@@ -7045,10 +7048,10 @@ async function requireRevisionReady(spec, lock) {
7045
7048
  if (inspection && !inspection.ready) throw new Error(inspection.reason);
7046
7049
  }
7047
7050
  async function inspectParent(spec, lock, seen) {
7048
- const key2 = lockKey(spec.styleId, spec.assetId);
7049
- if (seen.has(key2)) return { ready: false, reason: `revision dependency cycle at ${key2}` };
7051
+ const key3 = lockKey(spec.styleId, spec.assetId);
7052
+ if (seen.has(key3)) return { ready: false, reason: `revision dependency cycle at ${key3}` };
7050
7053
  const nextSeen = new Set(seen);
7051
- nextSeen.add(key2);
7054
+ nextSeen.add(key3);
7052
7055
  if (spec.mirror) {
7053
7056
  const inputs = await inspectMirror(spec, lock, nextSeen);
7054
7057
  if (!inputs.ready) return inputs;
@@ -7094,7 +7097,7 @@ async function inspectParent(spec, lock, seen) {
7094
7097
  const source = path10.resolve(spec.root, spec.source);
7095
7098
  return existsSync6(source) ? { ready: true, reason: "declared source is present" } : { ready: false, reason: `declared source is missing: ${spec.source}` };
7096
7099
  }
7097
- const entry = lock.entries[key2];
7100
+ const entry = lock.entries[key3];
7098
7101
  if (!entry) return { ready: false, reason: "parent is not in the lockfile" };
7099
7102
  if (entry.specHash !== spec.specHash) {
7100
7103
  return { ready: false, reason: "parent generation spec is stale" };
@@ -7178,15 +7181,15 @@ function resumeCommandForStatus(status) {
7178
7181
  function resumeActions(specs, lock) {
7179
7182
  const grouped = /* @__PURE__ */ new Map();
7180
7183
  for (const spec of specs) {
7181
- const key2 = lockKey(spec.styleId, spec.assetId);
7182
- const entry = lock.entries[key2];
7184
+ const key3 = lockKey(spec.styleId, spec.assetId);
7185
+ const entry = lock.entries[key3];
7183
7186
  if (!entry || entry.specHash !== spec.specHash) continue;
7184
7187
  if (entry.submissionComplete === false) continue;
7185
7188
  const command = resumeCommandForStatus(entry.status) ?? (entry.status === "downloaded" && entry.outputs.length && !postprocessCurrent(entry, spec) ? "fetch" : null);
7186
7189
  if (!command) continue;
7187
7190
  if (command === "poll" && !entry.jobId) continue;
7188
7191
  if (command === "pick" && !entry.reviewObjectId) continue;
7189
- grouped.set(command, [...grouped.get(command) ?? [], key2]);
7192
+ grouped.set(command, [...grouped.get(command) ?? [], key3]);
7190
7193
  }
7191
7194
  return ["poll", "pick", "fetch"].flatMap((command) => {
7192
7195
  const keys = grouped.get(command);
@@ -7196,8 +7199,8 @@ function resumeActions(specs, lock) {
7196
7199
  async function buildPlan(specs, lock, opts = {}) {
7197
7200
  const items = [];
7198
7201
  for (const spec of specs) {
7199
- const key2 = lockKey(spec.styleId, spec.assetId);
7200
- const entry = lock.entries[key2];
7202
+ const key3 = lockKey(spec.styleId, spec.assetId);
7203
+ const entry = lock.entries[key3];
7201
7204
  let state;
7202
7205
  let reason;
7203
7206
  const changedConnection = entry ? changedTerrainConnection(spec, entry, lock) : null;
@@ -7312,7 +7315,7 @@ async function buildPlan(specs, lock, opts = {}) {
7312
7315
  reason = "up to date";
7313
7316
  }
7314
7317
  const quality = await inspectQualityProfile(spec, lock);
7315
- items.push({ spec, key: key2, state, reason, ...quality ? { quality } : {} });
7318
+ items.push({ spec, key: key3, state, reason, ...quality ? { quality } : {} });
7316
7319
  }
7317
7320
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
7318
7321
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
@@ -7529,8 +7532,8 @@ import path12 from "path";
7529
7532
  function loadEnvFiles(dir) {
7530
7533
  const loaded = [];
7531
7534
  for (const [file, vars] of envFiles(dir)) {
7532
- for (const [key2, value] of Object.entries(vars)) {
7533
- if (!(key2 in process.env)) process.env[key2] = value;
7535
+ for (const [key3, value] of Object.entries(vars)) {
7536
+ if (!(key3 in process.env)) process.env[key3] = value;
7534
7537
  }
7535
7538
  loaded.push(file);
7536
7539
  }
@@ -7539,8 +7542,8 @@ function loadEnvFiles(dir) {
7539
7542
  function readEnvFiles(dir) {
7540
7543
  const merged = {};
7541
7544
  for (const [, vars] of envFiles(dir)) {
7542
- for (const [key2, value] of Object.entries(vars)) {
7543
- if (!(key2 in merged)) merged[key2] = value;
7545
+ for (const [key3, value] of Object.entries(vars)) {
7546
+ if (!(key3 in merged)) merged[key3] = value;
7544
7547
  }
7545
7548
  }
7546
7549
  return merged;
@@ -7564,14 +7567,14 @@ function parseEnv(contents) {
7564
7567
  if (!line || line.startsWith("#")) continue;
7565
7568
  const eq = line.indexOf("=");
7566
7569
  if (eq <= 0) continue;
7567
- const key2 = line.slice(0, eq).replace(/^export\s+/, "").trim();
7568
- if (!key2 || key2 in vars) continue;
7570
+ const key3 = line.slice(0, eq).replace(/^export\s+/, "").trim();
7571
+ if (!key3 || key3 in vars) continue;
7569
7572
  let value = line.slice(eq + 1).trim();
7570
7573
  const quote = value[0];
7571
7574
  if ((quote === '"' || quote === "'") && value.endsWith(quote) && value.length >= 2) {
7572
7575
  value = value.slice(1, -1);
7573
7576
  }
7574
- vars[key2] = value;
7577
+ vars[key3] = value;
7575
7578
  }
7576
7579
  return vars;
7577
7580
  }
@@ -8214,7 +8217,7 @@ function parseOptions(value) {
8214
8217
  "workflow",
8215
8218
  "workflowSha256"
8216
8219
  ]);
8217
- const extra = Object.keys(value).filter((key2) => !allowed.has(key2));
8220
+ const extra = Object.keys(value).filter((key3) => !allowed.has(key3));
8218
8221
  if (extra.length) throw new Error(`Unknown ComfyUI option(s): ${extra.join(", ")}`);
8219
8222
  const workflowFile = requiredString(value.workflowFile, "workflowFile");
8220
8223
  const outputNodeId = requiredString(value.outputNodeId, "outputNodeId");
@@ -8250,7 +8253,7 @@ function parseOptions(value) {
8250
8253
  }
8251
8254
  function parseFrames(value) {
8252
8255
  if (!isObject(value)) throw new Error("ComfyUI frames must be an object");
8253
- const extra = Object.keys(value).filter((key2) => key2 !== "vary" && key2 !== "seedStep");
8256
+ const extra = Object.keys(value).filter((key3) => key3 !== "vary" && key3 !== "seedStep");
8254
8257
  if (extra.length) throw new Error(`Unknown ComfyUI frames field(s): ${extra.join(", ")}`);
8255
8258
  const vary = requiredString(value.vary, "frames.vary");
8256
8259
  const seedStep = value.seedStep ?? 0;
@@ -8268,7 +8271,7 @@ function resolvedOptions(spec) {
8268
8271
  }
8269
8272
  function parseBinding(value, name) {
8270
8273
  if (!isObject(value)) throw new Error(`ComfyUI bindings.${name} must be an object`);
8271
- const extra = Object.keys(value).filter((key2) => key2 !== "nodeId" && key2 !== "input");
8274
+ const extra = Object.keys(value).filter((key3) => key3 !== "nodeId" && key3 !== "input");
8272
8275
  if (extra.length) throw new Error(`Unknown ComfyUI bindings.${name} field(s): ${extra.join(", ")}`);
8273
8276
  return {
8274
8277
  nodeId: requiredString(value.nodeId, `bindings.${name}.nodeId`),
@@ -8533,7 +8536,7 @@ function canonical2(value) {
8533
8536
  if (Array.isArray(value)) return value.map(canonical2);
8534
8537
  if (!isObject(value)) return value;
8535
8538
  return Object.fromEntries(
8536
- Object.keys(value).sort().map((key2) => [key2, canonical2(value[key2])])
8539
+ Object.keys(value).sort().map((key3) => [key3, canonical2(value[key3])])
8537
8540
  );
8538
8541
  }
8539
8542
 
@@ -10730,13 +10733,13 @@ var PixelLabClient = class {
10730
10733
  }
10731
10734
  };
10732
10735
  function clientFromEnv() {
10733
- const key2 = process.env.PIXELLAB_API_KEY;
10734
- if (!key2) {
10736
+ const key3 = process.env.PIXELLAB_API_KEY;
10737
+ if (!key3) {
10735
10738
  throw new Error(
10736
10739
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
10737
10740
  );
10738
10741
  }
10739
- return new PixelLabClient(key2);
10742
+ return new PixelLabClient(key3);
10740
10743
  }
10741
10744
 
10742
10745
  // src/pixellab-mcp.ts
@@ -10815,13 +10818,13 @@ var PixelLabMcpClient = class {
10815
10818
  }
10816
10819
  };
10817
10820
  function mcpClientFromEnv() {
10818
- const key2 = process.env.PIXELLAB_API_KEY;
10819
- if (!key2) {
10821
+ const key3 = process.env.PIXELLAB_API_KEY;
10822
+ if (!key3) {
10820
10823
  throw new Error(
10821
10824
  "PIXELLAB_API_KEY is not set.\nLooked in the environment, and in .env.local / .env beside the manifest and in the current directory."
10822
10825
  );
10823
10826
  }
10824
- return new PixelLabMcpClient(key2);
10827
+ return new PixelLabMcpClient(key3);
10825
10828
  }
10826
10829
 
10827
10830
  // src/pixellab-vfx.ts
@@ -11142,27 +11145,27 @@ function vfxArtistFiles(raw) {
11142
11145
  const urlOf = (value) => {
11143
11146
  if (typeof value === "string") return /^https?:\/\//i.test(value) ? value : null;
11144
11147
  if (!value || typeof value !== "object") return null;
11145
- for (const key2 of ["url", "download_url", "href"]) {
11146
- const url = value[key2];
11148
+ for (const key3 of ["url", "download_url", "href"]) {
11149
+ const url = value[key3];
11147
11150
  if (typeof url === "string" && /^https?:\/\//i.test(url)) return url;
11148
11151
  }
11149
11152
  return null;
11150
11153
  };
11151
- const nameOf = (value, url, key2) => {
11154
+ const nameOf = (value, url, key3) => {
11152
11155
  if (value && typeof value === "object") {
11153
11156
  for (const field of ["name", "filename", "file"]) {
11154
11157
  const name = value[field];
11155
11158
  if (typeof name === "string" && name) return name;
11156
11159
  }
11157
11160
  }
11158
- if (key2 && /\.[a-z0-9]+$/i.test(key2)) return key2;
11161
+ if (key3 && /\.[a-z0-9]+$/i.test(key3)) return key3;
11159
11162
  return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
11160
11163
  };
11161
11164
  const entries = Array.isArray(raw) ? raw.map((value) => [void 0, value]) : raw && typeof raw === "object" ? Object.entries(raw) : [];
11162
11165
  const files = [];
11163
- for (const [key2, value] of entries) {
11166
+ for (const [key3, value] of entries) {
11164
11167
  const url = urlOf(value);
11165
- if (url) files.push({ name: nameOf(value, url, key2), url });
11168
+ if (url) files.push({ name: nameOf(value, url, key3), url });
11166
11169
  }
11167
11170
  return files;
11168
11171
  }
@@ -11265,14 +11268,14 @@ async function makeVfxWithArtist(client2, opts) {
11265
11268
  `);
11266
11269
  written.atlas = paths.atlas;
11267
11270
  }
11268
- for (const [file, target, key2] of [
11271
+ for (const [file, target, key3] of [
11269
11272
  [result.gif, paths.gif, "gif"],
11270
11273
  [result.gamePack, paths.gamePack, "gamePack"],
11271
11274
  [result.normals, paths.normals, "normals"]
11272
11275
  ]) {
11273
11276
  if (!file) continue;
11274
11277
  await writeFile5(target, await client2.download(file.url));
11275
- written[key2] = target;
11278
+ written[key3] = target;
11276
11279
  }
11277
11280
  const facts = vfxArtistFrameFacts(result, atlas);
11278
11281
  const usage2 = job.usage ?? null;
@@ -11298,7 +11301,7 @@ async function makeVfxWithArtist(client2, opts) {
11298
11301
  anchor: result.anchor,
11299
11302
  parts: result.parts,
11300
11303
  files: Object.fromEntries(
11301
- ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key2) => written[key2]).map((key2) => [key2, path14.basename(written[key2])])
11304
+ ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key3) => written[key3]).map((key3) => [key3, path14.basename(written[key3])])
11302
11305
  ),
11303
11306
  quotedGenerations: submitted.quoted_generations ?? null,
11304
11307
  usage: usage2,
@@ -11323,8 +11326,8 @@ async function makeVfxWithArtist(client2, opts) {
11323
11326
  };
11324
11327
  }
11325
11328
  function vfxJobFailure(done) {
11326
- for (const key2 of ["error", "detail", "message"]) {
11327
- const value = done?.[key2];
11329
+ for (const key3 of ["error", "detail", "message"]) {
11330
+ const value = done?.[key3];
11328
11331
  if (typeof value === "string" && value) return `: ${value}`;
11329
11332
  }
11330
11333
  return "";
@@ -11359,8 +11362,8 @@ function isSensitiveSourceUrl(value) {
11359
11362
  return false;
11360
11363
  }
11361
11364
  if (parsed.username || parsed.password) return true;
11362
- for (const key2 of parsed.searchParams.keys()) {
11363
- const normalized = key2.toLowerCase();
11365
+ for (const key3 of parsed.searchParams.keys()) {
11366
+ const normalized = key3.toLowerCase();
11364
11367
  if (SENSITIVE_QUERY_KEYS.has(normalized) || normalized.includes("credential") || normalized.includes("signature") || normalized.includes("security-token") || normalized.includes("token")) return true;
11365
11368
  }
11366
11369
  return false;
@@ -11624,14 +11627,14 @@ import path16 from "path";
11624
11627
  function heldFrames(spec, lock) {
11625
11628
  const frames = [];
11626
11629
  for (const source of spec.character.layer.sources) {
11627
- const key2 = lockKey(source.spec.styleId, source.spec.assetId);
11628
- const entry = lock.entries[key2];
11630
+ const key3 = lockKey(source.spec.styleId, source.spec.assetId);
11631
+ const entry = lock.entries[key3];
11629
11632
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
11630
- throw new Error(`held item source ${key2} has no downloaded frames`);
11633
+ throw new Error(`held item source ${key3} has no downloaded frames`);
11631
11634
  }
11632
11635
  for (const [index, output] of entry.outputs.entries()) {
11633
11636
  const direction = isDirection(output.role) ? output.role : source.spec.character?.animation?.direction;
11634
- if (!direction) throw new Error(`cannot tell which way ${key2} frame ${output.role ?? index} faces`);
11637
+ if (!direction) throw new Error(`cannot tell which way ${key3} frame ${output.role ?? index} faces`);
11635
11638
  frames.push({
11636
11639
  assetId: source.assetId,
11637
11640
  role: output.role ?? String(index).padStart(2, "0"),
@@ -11700,7 +11703,7 @@ async function heldItemAsset(spec, lock, lockPath, opts = {}) {
11700
11703
  });
11701
11704
  const layer = spec.character.layer;
11702
11705
  const attach = layer.attach;
11703
- const key2 = lockKey(spec.styleId, spec.assetId);
11706
+ const key3 = lockKey(spec.styleId, spec.assetId);
11704
11707
  const frames = heldFrames(spec, lock);
11705
11708
  const placed = await placeHeldFrames(spec, frames);
11706
11709
  const outputs = [];
@@ -11717,7 +11720,7 @@ async function heldItemAsset(spec, lock, lockPath, opts = {}) {
11717
11720
  outputs.push({ path: portableOutputPath(target, spec.root), sha256: sha256(bytes), role, mediaType: MediaType.PNG });
11718
11721
  }
11719
11722
  const now = (/* @__PURE__ */ new Date()).toISOString();
11720
- const entry = upsert(lock, key2, {
11723
+ const entry = upsert(lock, key3, {
11721
11724
  styleId: spec.styleId,
11722
11725
  assetId: spec.assetId,
11723
11726
  specHash: spec.specHash,
@@ -11756,7 +11759,7 @@ async function heldItemAsset(spec, lock, lockPath, opts = {}) {
11756
11759
  postprocess: void 0
11757
11760
  });
11758
11761
  await saveLock(lockPath, lock);
11759
- log2(` attach ${key2} (${frames.length} frame${frames.length === 1 ? "" : "s"}, ${attach.joint}, no generation cost)`);
11762
+ log2(` attach ${key3} (${frames.length} frame${frames.length === 1 ? "" : "s"}, ${attach.joint}, no generation cost)`);
11760
11763
  if (clipped) log2(` ${clipped} item pixel${clipped === 1 ? "" : "s"} fell outside the canvas; raise layer.padding above ${layer.padding} to keep them`);
11761
11764
  return entry;
11762
11765
  }
@@ -11930,8 +11933,8 @@ function createProFlashQuoter(client2, opts = {}) {
11930
11933
  return async (spec) => {
11931
11934
  const query = proFlashQuoteQuery(spec);
11932
11935
  if (!query) return null;
11933
- const key2 = `${query.operation}:${query.width}x${query.height}:${query.nDirections ?? ""}`;
11934
- let hit = cache.get(key2);
11936
+ const key3 = `${query.operation}:${query.width}x${query.height}:${query.nDirections ?? ""}`;
11937
+ let hit = cache.get(key3);
11935
11938
  if (!hit || now() - hit.at > ttl) {
11936
11939
  let timer;
11937
11940
  const answer = Promise.race([
@@ -11946,9 +11949,9 @@ function createProFlashQuoter(client2, opts = {}) {
11946
11949
  })
11947
11950
  ]).finally(() => clearTimeout(timer));
11948
11951
  hit = { at: now(), answer };
11949
- cache.set(key2, hit);
11952
+ cache.set(key3, hit);
11950
11953
  answer.catch(() => {
11951
- if (cache.get(key2) === hit) cache.delete(key2);
11954
+ if (cache.get(key3) === hit) cache.delete(key3);
11952
11955
  });
11953
11956
  }
11954
11957
  const quote = await hit.answer;
@@ -14343,8 +14346,8 @@ var PixelLabProvider = class _PixelLabProvider {
14343
14346
  billed
14344
14347
  };
14345
14348
  };
14346
- for (const key2 of ["frame_urls", "frames", "images"]) {
14347
- const list = done[key2];
14349
+ for (const key3 of ["frame_urls", "frames", "images"]) {
14350
+ const list = done[key3];
14348
14351
  if (!Array.isArray(list) || !list.length) continue;
14349
14352
  const urls = [];
14350
14353
  for (const [index, item] of list.entries()) {
@@ -14399,15 +14402,15 @@ var PixelLabProvider = class _PixelLabProvider {
14399
14402
  const billed = billedFromUsage(job.usage);
14400
14403
  const done = job.last_response ?? {};
14401
14404
  const urlKeys = ["image_url", "download_url", "url", "output_url"];
14402
- for (const key2 of urlKeys) {
14403
- const url = done[key2];
14405
+ for (const key3 of urlKeys) {
14406
+ const url = done[key3];
14404
14407
  if (typeof url === "string" && url) {
14405
14408
  return { status: "ready", objectId: jobId, sourceUrl: url, sources: [{ url }], billed };
14406
14409
  }
14407
14410
  }
14408
14411
  const imageKeys = ["image", "output_image", "result_image", "edited_image"];
14409
- for (const key2 of imageKeys) {
14410
- const candidate = done[key2];
14412
+ for (const key3 of imageKeys) {
14413
+ const candidate = done[key3];
14411
14414
  const base64 = extractBase64(candidate);
14412
14415
  if (base64) {
14413
14416
  const file = path17.join(_PixelLabProvider.cacheDir(), `${jobId}.png`);
@@ -14876,7 +14879,7 @@ function requirePixelLabOption(generator, name, value, allowed) {
14876
14879
  }
14877
14880
  }
14878
14881
  function tilesInIndexOrder(urls) {
14879
- return Object.entries(urls).map(([key2, url]) => ({ index: Number(key2.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
14882
+ return Object.entries(urls).map(([key3, url]) => ({ index: Number(key3.replace(/^tile_/, "")), url })).filter((tile) => Number.isFinite(tile.index)).sort((a, b) => a.index - b.index);
14880
14883
  }
14881
14884
  function firstUrl(urls) {
14882
14885
  if (!urls) return null;
@@ -15509,8 +15512,8 @@ var ScenarioClient = class {
15509
15512
  throw new Error(`${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not set`);
15510
15513
  }
15511
15514
  const url = new URL(`${this.baseUrl.replace(/\/$/, "")}${pathname}`);
15512
- for (const [key2, value2] of Object.entries(query)) {
15513
- if (value2 != null) url.searchParams.set(key2, value2);
15515
+ for (const [key3, value2] of Object.entries(query)) {
15516
+ if (value2 != null) url.searchParams.set(key3, value2);
15514
15517
  }
15515
15518
  const auth = Buffer.from(`${this.apiKey}:${this.apiSecret}`).toString("base64");
15516
15519
  const response = await this.request(url, {
@@ -15750,12 +15753,12 @@ function readUploadCache() {
15750
15753
  return {};
15751
15754
  }
15752
15755
  }
15753
- function writeUploadCache(key2, assetId) {
15756
+ function writeUploadCache(key3, assetId) {
15754
15757
  try {
15755
15758
  const file = uploadCachePath();
15756
15759
  mkdirSync2(path18.dirname(file), { recursive: true });
15757
15760
  const tmp = `${file}.${process.pid}.tmp`;
15758
- writeFileSync2(tmp, JSON.stringify({ ...readUploadCache(), [key2]: assetId }));
15761
+ writeFileSync2(tmp, JSON.stringify({ ...readUploadCache(), [key3]: assetId }));
15759
15762
  renameSync(tmp, file);
15760
15763
  } catch {
15761
15764
  }
@@ -15805,9 +15808,9 @@ function validateParameters(parameters) {
15805
15808
  if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
15806
15809
  throw new Error("Scenario parameters must be a JSON object");
15807
15810
  }
15808
- for (const key2 of Object.keys(parameters)) {
15809
- if (PROTECTED_PARAMETERS.has(key2)) {
15810
- throw new Error(`Scenario parameters.${key2} is managed by PixelKiln and cannot be overridden`);
15811
+ for (const key3 of Object.keys(parameters)) {
15812
+ if (PROTECTED_PARAMETERS.has(key3)) {
15813
+ throw new Error(`Scenario parameters.${key3} is managed by PixelKiln and cannot be overridden`);
15811
15814
  }
15812
15815
  }
15813
15816
  assertJsonValue(parameters, "Scenario parameters");
@@ -15830,8 +15833,8 @@ function assertJsonValue(value, label, seen = /* @__PURE__ */ new Set()) {
15830
15833
  if (Array.isArray(value)) {
15831
15834
  value.forEach((item, index) => assertJsonValue(item, `${label}[${index}]`, seen));
15832
15835
  } else {
15833
- for (const [key2, item] of Object.entries(value)) {
15834
- assertJsonValue(item, `${label}.${key2}`, seen);
15836
+ for (const [key3, item] of Object.entries(value)) {
15837
+ assertJsonValue(item, `${label}.${key3}`, seen);
15835
15838
  }
15836
15839
  }
15837
15840
  seen.delete(value);
@@ -15932,8 +15935,8 @@ function numericRecord(value) {
15932
15935
  throw new Error("Scenario returned invalid cost details");
15933
15936
  }
15934
15937
  const out = {};
15935
- for (const [key2, amount] of Object.entries(value)) {
15936
- out[key2] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key2}"`);
15938
+ for (const [key3, amount] of Object.entries(value)) {
15939
+ out[key3] = finiteNonnegative(amount, `Scenario returned invalid cost detail "${key3}"`);
15937
15940
  }
15938
15941
  return out;
15939
15942
  }
@@ -16189,10 +16192,10 @@ function culpritEntries(message6) {
16189
16192
  const match = /^ {2}(assets|styles)\.([^.:\s]+)[.:]/.exec(line);
16190
16193
  if (!match) continue;
16191
16194
  const kind = match[1] === "styles" ? "style" : "asset";
16192
- const key2 = `${kind}:${match[2]}`;
16193
- const entry = found.get(key2) ?? { kind, id: match[2], issues: [] };
16195
+ const key3 = `${kind}:${match[2]}`;
16196
+ const entry = found.get(key3) ?? { kind, id: match[2], issues: [] };
16194
16197
  entry.issues.push(line.trim());
16195
- found.set(key2, entry);
16198
+ found.set(key3, entry);
16196
16199
  }
16197
16200
  return [...found.values()];
16198
16201
  }
@@ -17382,8 +17385,8 @@ async function resolveSpecs(loaded, filter) {
17382
17385
  byOutput.set(file, owner);
17383
17386
  };
17384
17387
  for (const spec of specs) {
17385
- const key2 = `${spec.styleId}/${spec.assetId}`;
17386
- claimOutput(spec.outFile, key2);
17388
+ const key3 = `${spec.styleId}/${spec.assetId}`;
17389
+ claimOutput(spec.outFile, key3);
17387
17390
  if (spec.quality) {
17388
17391
  if (spec.generator === "frames") {
17389
17392
  const frameInputs = Object.values(spec.providerInputs ?? {}).find(Array.isArray);
@@ -17398,11 +17401,11 @@ async function resolveSpecs(loaded, filter) {
17398
17401
  count,
17399
17402
  MediaType.PNG
17400
17403
  ),
17401
- `${key2} quality ${role}`
17404
+ `${key3} quality ${role}`
17402
17405
  );
17403
17406
  }
17404
17407
  } else {
17405
- claimOutput(spec.quality.outFile, `${key2} quality output`);
17408
+ claimOutput(spec.quality.outFile, `${key3} quality output`);
17406
17409
  }
17407
17410
  }
17408
17411
  }
@@ -17683,15 +17686,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17683
17686
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
17684
17687
  normalizeLockOutputPaths(lock, specs);
17685
17688
  const cacheDir = opts.cacheDir === false ? null : path20.resolve(opts.cacheDir ?? path20.join(path20.dirname(lockPath), ".pixelkiln", "cache"));
17686
- const pending = Object.entries(lock.entries).filter(([key2, e]) => {
17687
- if (e.provider !== provider.id || !specByKey.has(key2)) return false;
17688
- if (specByKey.get(key2)?.mirror) return false;
17689
- if (specByKey.get(key2)?.derive || specByKey.get(key2)?.external) return false;
17690
- if (specByKey.get(key2) && isHeldItem(specByKey.get(key2))) return false;
17689
+ const pending = Object.entries(lock.entries).filter(([key3, e]) => {
17690
+ if (e.provider !== provider.id || !specByKey.has(key3)) return false;
17691
+ if (specByKey.get(key3)?.mirror) return false;
17692
+ if (specByKey.get(key3)?.derive || specByKey.get(key3)?.external) return false;
17693
+ if (specByKey.get(key3) && isHeldItem(specByKey.get(key3))) return false;
17691
17694
  if (e.status === "selected" || e.status === "download-failed") return true;
17692
17695
  if (e.status !== "downloaded") return false;
17693
17696
  if (opts.refresh) return e.outputs.length > 0 && Boolean(e.sourceUrls?.length || e.sourceUrl);
17694
- const spec = specByKey.get(key2);
17697
+ const spec = specByKey.get(key3);
17695
17698
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
17696
17699
  return Boolean(opts.force) || e.outputs.every((output) => {
17697
17700
  const file = resolveOutputPath(output.path, spec.root);
@@ -17714,15 +17717,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17714
17717
  for (; ; ) {
17715
17718
  const next = pending[cursor++];
17716
17719
  if (!next) return;
17717
- const [key2, entry] = next;
17718
- const spec = specByKey.get(key2);
17720
+ const [key3, entry] = next;
17721
+ const spec = specByKey.get(key3);
17719
17722
  if (!spec) {
17720
- log2(` skip ${key2} (not in current manifest)`);
17723
+ log2(` skip ${key3} (not in current manifest)`);
17721
17724
  result.skipped++;
17722
17725
  continue;
17723
17726
  }
17724
17727
  if (entry.specHash !== spec.specHash) {
17725
- log2(` skip ${key2} (source belongs to a stale spec)`);
17728
+ log2(` skip ${key3} (source belongs to a stale spec)`);
17726
17729
  result.skipped++;
17727
17730
  continue;
17728
17731
  }
@@ -17739,16 +17742,16 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17739
17742
  });
17740
17743
  } catch (err) {
17741
17744
  const message6 = err instanceof Error ? err.message : String(err);
17742
- upsert(lock, key2, { status: "download-failed", error: `download failed: ${message6}` });
17745
+ upsert(lock, key3, { status: "download-failed", error: `download failed: ${message6}` });
17743
17746
  result.failed++;
17744
- log2(` FAILED ${key2}: ${message6}`);
17747
+ log2(` FAILED ${key3}: ${message6}`);
17745
17748
  await saveLock(lockPath, lock);
17746
17749
  continue;
17747
17750
  }
17748
17751
  if (current === null) {
17749
- upsert(lock, key2, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
17752
+ upsert(lock, key3, { status: "download-failed", error: `download failed: ${entry.objectId} no longer exists upstream` });
17750
17753
  result.failed++;
17751
- log2(` FAILED ${key2}: ${entry.objectId} no longer exists upstream`);
17754
+ log2(` FAILED ${key3}: ${entry.objectId} no longer exists upstream`);
17752
17755
  await saveLock(lockPath, lock);
17753
17756
  continue;
17754
17757
  }
@@ -17761,7 +17764,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17761
17764
  }
17762
17765
  }
17763
17766
  if (!sources.length) {
17764
- upsert(lock, key2, {
17767
+ upsert(lock, key3, {
17765
17768
  status: "download-failed",
17766
17769
  error: "no persisted source URL to download; poll the job again if it still exists upstream"
17767
17770
  });
@@ -17778,11 +17781,11 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17778
17781
  const parentSpec = spec.character?.parentSpec;
17779
17782
  const parentEntry = parentSpec ? lock.entries[lockKey(parentSpec.styleId, parentSpec.assetId)] : void 0;
17780
17783
  if (!parentSpec || !parentEntry?.outputs.length) {
17781
- throw new Error(`cannot clean ${key2}: ${wanted.despeckle.of} has no downloaded rotations to judge against`);
17784
+ throw new Error(`cannot clean ${key3}: ${wanted.despeckle.of} has no downloaded rotations to judge against`);
17782
17785
  }
17783
17786
  for (let index = 0; index < parentEntry.outputs.length; index++) {
17784
17787
  const file = currentEntryOutputPath(parentEntry, parentSpec, index);
17785
- if (!existsSync15(file)) throw new Error(`cannot clean ${key2}: ${wanted.despeckle.of}'s rotation is missing on disk: ${file}`);
17788
+ if (!existsSync15(file)) throw new Error(`cannot clean ${key3}: ${wanted.despeckle.of}'s rotation is missing on disk: ${file}`);
17786
17789
  reference.push(await readFile11(file));
17787
17790
  }
17788
17791
  }
@@ -17903,7 +17906,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17903
17906
  mediaType,
17904
17907
  ...rawHash ? { raw: rawHash } : {}
17905
17908
  });
17906
- upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
17909
+ upsert(lock, key3, { outputs: mergeOutputs(entry.outputs, outputs) });
17907
17910
  await saveLock(lockPath, lock);
17908
17911
  await rename6(tmp, target);
17909
17912
  wrote = true;
@@ -17912,13 +17915,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17912
17915
  if (opts.refresh && !wrote) {
17913
17916
  if (rotated) {
17914
17917
  const persistent = sources.filter((source) => shouldPersistSourceUrl(source.url));
17915
- upsert(lock, key2, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
17918
+ upsert(lock, key3, { sourceUrl: persistent[0]?.url ?? null, sourceUrls: persistent });
17916
17919
  }
17917
17920
  result.unchanged = (result.unchanged ?? 0) + 1;
17918
17921
  continue;
17919
17922
  }
17920
17923
  const persistentSources = sources.filter((source) => shouldPersistSourceUrl(source.url));
17921
- upsert(lock, key2, {
17924
+ upsert(lock, key3, {
17922
17925
  status: "downloaded",
17923
17926
  provider: provider.id,
17924
17927
  outputs,
@@ -17935,13 +17938,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
17935
17938
  result.downloaded++;
17936
17939
  } catch (err) {
17937
17940
  const message6 = err instanceof Error ? err.message : String(err);
17938
- upsert(lock, key2, {
17941
+ upsert(lock, key3, {
17939
17942
  status: "download-failed",
17940
17943
  outputs: mergeOutputs(entry.outputs, outputs),
17941
17944
  error: `download failed: ${message6}`
17942
17945
  });
17943
17946
  result.failed++;
17944
- log2(` FAILED ${key2}: ${message6}`);
17947
+ log2(` FAILED ${key3}: ${message6}`);
17945
17948
  }
17946
17949
  await saveLock(lockPath, lock);
17947
17950
  }
@@ -17990,8 +17993,8 @@ async function pushTags(provider, specs, lock, opts = {}) {
17990
17993
  });
17991
17994
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
17992
17995
  let tagged = 0;
17993
- for (const [key2, entry] of Object.entries(lock.entries)) {
17994
- const spec = specByKey.get(key2);
17996
+ for (const [key3, entry] of Object.entries(lock.entries)) {
17997
+ const spec = specByKey.get(key3);
17995
17998
  if (!spec || entry.provider !== provider.id || !entry.objectId) continue;
17996
17999
  if (entry.generator === "pixflux" || entry.generator === "vfx") continue;
17997
18000
  if (!provider.setTags) return tagged;
@@ -17999,7 +18002,7 @@ async function pushTags(provider, specs, lock, opts = {}) {
17999
18002
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
18000
18003
  tagged++;
18001
18004
  } catch (err) {
18002
- log2(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
18005
+ log2(` tag failed ${key3}: ${err instanceof Error ? err.message : String(err)}`);
18003
18006
  }
18004
18007
  }
18005
18008
  return tagged;
@@ -18092,15 +18095,15 @@ function pickHistory(entry, selector) {
18092
18095
  return matches[0];
18093
18096
  }
18094
18097
  async function revertGeneration(provider, spec, lock, lockPath, opts) {
18095
- const key2 = lockKey(spec.styleId, spec.assetId);
18096
- const entry = lock.entries[key2];
18097
- if (!entry) throw new Error(`${key2} is not in the lockfile`);
18098
+ const key3 = lockKey(spec.styleId, spec.assetId);
18099
+ const entry = lock.entries[key3];
18100
+ if (!entry) throw new Error(`${key3} is not in the lockfile`);
18098
18101
  if (entry.status !== "downloaded") {
18099
- throw new Error(`${key2} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
18102
+ throw new Error(`${key3} is ${entry.status}; finish or fetch the current generation before restoring an older one`);
18100
18103
  }
18101
18104
  const { index, generation } = pickHistory(entry, opts.generation);
18102
18105
  if (generation.provider !== provider.id) {
18103
- throw new Error(`${key2}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
18106
+ throw new Error(`${key3}'s previous generation #${index} came from ${generation.provider}, not ${provider.id}`);
18104
18107
  }
18105
18108
  for (let i = 0; i < entry.outputs.length; i++) {
18106
18109
  const file = currentEntryOutputPath(entry, spec, i);
@@ -18115,7 +18118,7 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
18115
18118
  const now = (/* @__PURE__ */ new Date()).toISOString();
18116
18119
  const remaining = (entry.history ?? []).filter((_, i) => i !== index - 1);
18117
18120
  const history = [retireGeneration(entry, now), ...remaining];
18118
- upsert(lock, key2, {
18121
+ upsert(lock, key3, {
18119
18122
  specHash: generation.specHash,
18120
18123
  generator: generation.generator,
18121
18124
  tileFeature: generation.tileFeature,
@@ -18237,18 +18240,18 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
18237
18240
  const imported = [];
18238
18241
  const skipped = [];
18239
18242
  for (const spec of specs) {
18240
- const key2 = lockKey(spec.styleId, spec.assetId);
18243
+ const key3 = lockKey(spec.styleId, spec.assetId);
18241
18244
  const reason = unimportable(spec);
18242
18245
  if (reason) {
18243
- skipped.push({ key: key2, reason });
18246
+ skipped.push({ key: key3, reason });
18244
18247
  continue;
18245
18248
  }
18246
18249
  if (!existsSync17(spec.outFile)) {
18247
- skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
18250
+ skipped.push({ key: key3, reason: `no file at ${spec.outFile}` });
18248
18251
  continue;
18249
18252
  }
18250
- if (lock.entries[key2] && !opts.force) {
18251
- skipped.push({ key: key2, reason: "already in the lockfile (use --force to replace it)" });
18253
+ if (lock.entries[key3] && !opts.force) {
18254
+ skipped.push({ key: key3, reason: "already in the lockfile (use --force to replace it)" });
18252
18255
  continue;
18253
18256
  }
18254
18257
  let patch;
@@ -18257,20 +18260,20 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
18257
18260
  bytes = await readFile12(spec.outFile);
18258
18261
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
18259
18262
  } catch (error) {
18260
- skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
18263
+ skipped.push({ key: key3, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
18261
18264
  continue;
18262
18265
  }
18263
18266
  if (opts.dryRun) {
18264
- imported.push({ key: key2, entry: patch });
18267
+ imported.push({ key: key3, entry: patch });
18265
18268
  continue;
18266
18269
  }
18267
- const existing = lock.entries[key2];
18270
+ const existing = lock.entries[key3];
18268
18271
  const history = existing?.outputs[0]?.sha256 === sha256(bytes) ? existing.history : historyAfterReplacing(existing, opts.historyLimit ?? DEFAULT_HISTORY_LIMIT, patch.downloadedAt ?? (/* @__PURE__ */ new Date()).toISOString());
18269
18272
  if (cacheDir) {
18270
18273
  await cacheMedia(cacheDir, bytes, MediaType.PNG);
18271
18274
  if (rawBytes) await cacheMedia(cacheDir, rawBytes, MediaType.PNG);
18272
18275
  }
18273
- imported.push({ key: key2, entry: upsert(lock, key2, {
18276
+ imported.push({ key: key3, entry: upsert(lock, key3, {
18274
18277
  ...patch,
18275
18278
  // An import replaces the whole record: clear what the entry held that
18276
18279
  // an import never has, or a regenerated entry would keep stale links.
@@ -18284,7 +18287,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
18284
18287
  async function reportSpecHashes(specs, lock) {
18285
18288
  const reports = [];
18286
18289
  for (const spec of specs) {
18287
- const key2 = lockKey(spec.styleId, spec.assetId);
18290
+ const key3 = lockKey(spec.styleId, spec.assetId);
18288
18291
  let bytes = null;
18289
18292
  if (existsSync17(spec.outFile)) bytes = await readFile12(spec.outFile);
18290
18293
  let wouldImport = null;
@@ -18295,11 +18298,11 @@ async function reportSpecHashes(specs, lock) {
18295
18298
  wouldImport = null;
18296
18299
  }
18297
18300
  }
18298
- const entry = lock.entries[key2];
18301
+ const entry = lock.entries[key3];
18299
18302
  const fileSha256 = bytes ? sha256(bytes) : null;
18300
18303
  const outputSha256 = entry?.outputs[0]?.sha256 ?? null;
18301
18304
  reports.push({
18302
- key: key2,
18305
+ key: key3,
18303
18306
  specHash: spec.specHash,
18304
18307
  file: spec.outFile,
18305
18308
  fileSha256,
@@ -18353,10 +18356,10 @@ async function loadCache(path76) {
18353
18356
  }
18354
18357
  async function saveCache(path76, cache) {
18355
18358
  const sorted = {};
18356
- for (const key2 of Object.keys(cache.hashes).sort()) {
18357
- const hash = cache.hashes[key2];
18358
- if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
18359
- sorted[key2] = hash;
18359
+ for (const key3 of Object.keys(cache.hashes).sort()) {
18360
+ const hash = cache.hashes[key3];
18361
+ if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key3}`);
18362
+ sorted[key3] = hash;
18360
18363
  }
18361
18364
  await mkdir9(pathModule.dirname(pathModule.resolve(path76)), { recursive: true });
18362
18365
  const tmp = `${path76}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
@@ -18369,12 +18372,12 @@ async function saveCache(path76, cache) {
18369
18372
  }
18370
18373
  function pruneCache(cache, liveIds, namespace = "") {
18371
18374
  let removed = 0;
18372
- for (const key2 of Object.keys(cache.hashes)) {
18373
- const owned = namespace ? key2.startsWith(namespace) : !key2.includes(":");
18375
+ for (const key3 of Object.keys(cache.hashes)) {
18376
+ const owned = namespace ? key3.startsWith(namespace) : !key3.includes(":");
18374
18377
  if (!owned) continue;
18375
- const id = namespace ? key2.slice(namespace.length) : key2;
18378
+ const id = namespace ? key3.slice(namespace.length) : key3;
18376
18379
  if (!liveIds.has(id)) {
18377
- delete cache.hashes[key2];
18380
+ delete cache.hashes[key3];
18378
18381
  removed++;
18379
18382
  }
18380
18383
  }
@@ -18445,14 +18448,14 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
18445
18448
  if (!hits?.length) continue;
18446
18449
  matchedRemote.add(obj.id);
18447
18450
  for (const spec of hits) {
18448
- const key2 = lockKey(spec.styleId, spec.assetId);
18449
- const existing = lock.entries[key2];
18451
+ const key3 = lockKey(spec.styleId, spec.assetId);
18452
+ const existing = lock.entries[key3];
18450
18453
  if (existing?.objectId && existing.objectId !== obj.id) {
18451
- ambiguous.push(`${key2}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
18454
+ ambiguous.push(`${key3}: already mapped to ${existing.objectId}, also matches ${obj.id}`);
18452
18455
  continue;
18453
18456
  }
18454
18457
  const durableSource = shouldPersistSourceUrl(url) ? url : null;
18455
- upsert(lock, key2, {
18458
+ upsert(lock, key3, {
18456
18459
  styleId: spec.styleId,
18457
18460
  assetId: spec.assetId,
18458
18461
  // Deliberately the CURRENT spec hash: adoption declares "the file on
@@ -18479,7 +18482,7 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
18479
18482
  provider: provider.id
18480
18483
  });
18481
18484
  matched++;
18482
- log2(` adopted ${key2} \u2190 ${obj.id}`);
18485
+ log2(` adopted ${key3} \u2190 ${obj.id}`);
18483
18486
  }
18484
18487
  }
18485
18488
  }
@@ -18503,15 +18506,15 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
18503
18506
  });
18504
18507
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
18505
18508
  let count = 0;
18506
- for (const [key2, entry] of Object.entries(lock.entries)) {
18507
- const spec = specByKey.get(key2);
18509
+ for (const [key3, entry] of Object.entries(lock.entries)) {
18510
+ const spec = specByKey.get(key3);
18508
18511
  if (!spec || !entry.objectId) continue;
18509
18512
  if (!provider.setTags) return count;
18510
18513
  try {
18511
18514
  await provider.setTags(entry.objectId, spec.tags, entry.generator);
18512
18515
  count++;
18513
18516
  } catch (err) {
18514
- log2(` tag failed ${key2}: ${err instanceof Error ? err.message : String(err)}`);
18517
+ log2(` tag failed ${key3}: ${err instanceof Error ? err.message : String(err)}`);
18515
18518
  }
18516
18519
  }
18517
18520
  return count;
@@ -18628,13 +18631,13 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18628
18631
  const wave = current.filter((spec) => spec.character?.kind === kind);
18629
18632
  let adoptedThisWave = 0;
18630
18633
  for (const spec of wave) {
18631
- const key2 = lockKey(spec.styleId, spec.assetId);
18632
- if (lock.entries[key2]?.status === "downloaded" && lock.entries[key2]?.objectId) continue;
18634
+ const key3 = lockKey(spec.styleId, spec.assetId);
18635
+ if (lock.entries[key3]?.status === "downloaded" && lock.entries[key3]?.objectId) continue;
18633
18636
  try {
18634
- const adopted = kind === "animation" ? await adoptAnimation(spec, key2) : await adoptCharacter(spec, key2);
18637
+ const adopted = kind === "animation" ? await adoptAnimation(spec, key3) : await adoptCharacter(spec, key3);
18635
18638
  if (adopted) adoptedThisWave++;
18636
18639
  } catch (err) {
18637
- result.unmatched.push(`${key2}: ${err instanceof Error ? err.message : String(err)}`);
18640
+ result.unmatched.push(`${key3}: ${err instanceof Error ? err.message : String(err)}`);
18638
18641
  }
18639
18642
  }
18640
18643
  if (adoptedThisWave) {
@@ -18642,7 +18645,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18642
18645
  current = await opts.resolve();
18643
18646
  }
18644
18647
  }
18645
- async function adoptCharacter(spec, key2) {
18648
+ async function adoptCharacter(spec, key3) {
18646
18649
  let match;
18647
18650
  if (spec.remoteId) {
18648
18651
  match = remote.find((c) => c.id === spec.remoteId);
@@ -18650,7 +18653,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18650
18653
  } else {
18651
18654
  const south = expectedOutputPath(spec, "south", 0, spec.character.directions);
18652
18655
  if (!existsSync20(south)) {
18653
- result.unmatched.push(`${key2}: no remoteId and no ${path24.relative(process.cwd(), south)} to match by`);
18656
+ result.unmatched.push(`${key3}: no remoteId and no ${path24.relative(process.cwd(), south)} to match by`);
18654
18657
  return false;
18655
18658
  }
18656
18659
  const localHash = sha256(await readFile15(south));
@@ -18662,7 +18665,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18662
18665
  }
18663
18666
  }
18664
18667
  if (!match) {
18665
- result.unmatched.push(`${key2}: no character's south rotation has the bytes of ${path24.relative(process.cwd(), south)}`);
18668
+ result.unmatched.push(`${key3}: no character's south rotation has the bytes of ${path24.relative(process.cwd(), south)}`);
18666
18669
  return false;
18667
18670
  }
18668
18671
  }
@@ -18670,7 +18673,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18670
18673
  if (!full.rotations.length) throw new Error(`character ${match.id} has no rotations yet (${full.status})`);
18671
18674
  const outputs = await materialize(spec, full.rotations);
18672
18675
  const durable = full.rotations.filter((source) => shouldPersistSourceUrl(source.url));
18673
- upsert(lock, key2, {
18676
+ upsert(lock, key3, {
18674
18677
  styleId: spec.styleId,
18675
18678
  assetId: spec.assetId,
18676
18679
  specHash: spec.specHash,
@@ -18708,16 +18711,16 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18708
18711
  });
18709
18712
  claimed.add(full.id);
18710
18713
  result.matched++;
18711
- log2(` adopted ${key2} \u2190 character ${full.id}${full.stateName && full.stateName !== "Idle" ? ` (${full.stateName})` : ""}`);
18714
+ log2(` adopted ${key3} \u2190 character ${full.id}${full.stateName && full.stateName !== "Idle" ? ` (${full.stateName})` : ""}`);
18712
18715
  return true;
18713
18716
  }
18714
- async function adoptAnimation(spec, key2) {
18717
+ async function adoptAnimation(spec, key3) {
18715
18718
  const character = spec.character;
18716
18719
  const animation = character.animation;
18717
18720
  const parentKey = lockKey(spec.styleId, character.parentAssetId);
18718
18721
  const parentId = spec.remoteId?.split("#")[0] ?? lock.entries[parentKey]?.objectId;
18719
18722
  if (!parentId) {
18720
- result.unmatched.push(`${key2}: its parent ${parentKey} is not adopted yet`);
18723
+ result.unmatched.push(`${key3}: its parent ${parentKey} is not adopted yet`);
18721
18724
  return false;
18722
18725
  }
18723
18726
  const full = await detail(parentId);
@@ -18732,7 +18735,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18732
18735
  if (!existsSync20(first)) {
18733
18736
  const byName = candidates.find((a) => a.name === characterAnimationName(spec));
18734
18737
  if (!byName) {
18735
- result.unmatched.push(`${key2}: no remoteId and no ${path24.relative(process.cwd(), first)} to match by`);
18738
+ result.unmatched.push(`${key3}: no remoteId and no ${path24.relative(process.cwd(), first)} to match by`);
18736
18739
  return false;
18737
18740
  }
18738
18741
  match = byName;
@@ -18745,7 +18748,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18745
18748
  }
18746
18749
  }
18747
18750
  if (!match) {
18748
- result.unmatched.push(`${key2}: no ${animation.direction} animation of character ${parentId} starts with the bytes of ${path24.relative(process.cwd(), first)}`);
18751
+ result.unmatched.push(`${key3}: no ${animation.direction} animation of character ${parentId} starts with the bytes of ${path24.relative(process.cwd(), first)}`);
18749
18752
  return false;
18750
18753
  }
18751
18754
  }
@@ -18754,7 +18757,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18754
18757
  const outputs = await materialize(spec, sources);
18755
18758
  const durable = sources.filter((source) => shouldPersistSourceUrl(source.url));
18756
18759
  const animationId = /\/animations\/([^/]+)\//.exec(match.frames[0])?.[1] ?? null;
18757
- upsert(lock, key2, {
18760
+ upsert(lock, key3, {
18758
18761
  styleId: spec.styleId,
18759
18762
  assetId: spec.assetId,
18760
18763
  specHash: spec.specHash,
@@ -18792,7 +18795,7 @@ async function adoptCharacters(provider, specs, lock, lockPath, opts) {
18792
18795
  provider: provider.id
18793
18796
  });
18794
18797
  result.matched++;
18795
- log2(` adopted ${key2} \u2190 ${animation.direction} animation ${match.groupId ?? animationId ?? match.type} of ${parentId}`);
18798
+ log2(` adopted ${key3} \u2190 ${animation.direction} animation ${match.groupId ?? animationId ?? match.type} of ${parentId}`);
18796
18799
  return true;
18797
18800
  }
18798
18801
  await saveLock(lockPath, lock);
@@ -18865,8 +18868,8 @@ async function findOrphanCharacters(provider, claimed, opts = {}) {
18865
18868
  const isClaimed = (id) => claimed.has(id) || claimed.has(providerClaimId(provider.id, id));
18866
18869
  const groups = /* @__PURE__ */ new Map();
18867
18870
  for (const character of all) {
18868
- const key2 = character.groupId ?? character.id;
18869
- groups.set(key2, [...groups.get(key2) ?? [], character]);
18871
+ const key3 = character.groupId ?? character.id;
18872
+ groups.set(key3, [...groups.get(key3) ?? [], character]);
18870
18873
  }
18871
18874
  let partlyClaimed = 0;
18872
18875
  const orphans = [];
@@ -19017,10 +19020,10 @@ function groupOrphansByStyle(orphans, manifest, siblings = []) {
19017
19020
  }
19018
19021
  const sibling = siblings.find((s) => matchStyleByPattern(o.prompt, s.manifest));
19019
19022
  if (sibling) {
19020
- const key2 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
19021
- const list = elsewhere.get(key2) ?? [];
19023
+ const key3 = `${sibling.label}: ${matchStyleByPattern(o.prompt, sibling.manifest)}`;
19024
+ const list = elsewhere.get(key3) ?? [];
19022
19025
  list.push(o);
19023
- elsewhere.set(key2, list);
19026
+ elsewhere.set(key3, list);
19024
19027
  continue;
19025
19028
  }
19026
19029
  if (ownStyleIds.length <= 1 && ownStyleIds[0]) matched.get(ownStyleIds[0]).push(o);
@@ -19678,11 +19681,11 @@ async function openProject(manifestPath = "pixelkiln.manifest.json", opts = {})
19678
19681
  reload: () => openProject(absolute, { ...opts, env: false }),
19679
19682
  providers: () => [...new Set(specs.map((spec) => spec.provider))].sort(),
19680
19683
  provider: (id, mode2 = "online") => {
19681
- const key2 = `${mode2}:${id}`;
19682
- let adapter = adapters.get(key2);
19684
+ const key3 = `${mode2}:${id}`;
19685
+ let adapter = adapters.get(key3);
19683
19686
  if (!adapter) {
19684
19687
  adapter = createProvider(id, mode2);
19685
- adapters.set(key2, adapter);
19688
+ adapters.set(key3, adapter);
19686
19689
  }
19687
19690
  return adapter;
19688
19691
  }
@@ -19816,8 +19819,8 @@ function manifestProviderIds(manifest) {
19816
19819
  function specsByRecordedProvider(specs, lock) {
19817
19820
  const grouped = /* @__PURE__ */ new Map();
19818
19821
  for (const spec of specs) {
19819
- const key2 = lockKey(spec.styleId, spec.assetId);
19820
- const provider = lock.entries[key2]?.provider ?? spec.provider;
19822
+ const key3 = lockKey(spec.styleId, spec.assetId);
19823
+ const provider = lock.entries[key3]?.provider ?? spec.provider;
19821
19824
  grouped.set(provider, [...grouped.get(provider) ?? [], spec]);
19822
19825
  }
19823
19826
  return grouped;
@@ -19970,15 +19973,15 @@ async function runAdoptLocal(args) {
19970
19973
  if (args.json) {
19971
19974
  log(JSON.stringify({
19972
19975
  dryRun: args.dryRun,
19973
- imported: result.imported.map(({ key: key2, entry }) => ({ key: key2, entry })),
19976
+ imported: result.imported.map(({ key: key3, entry }) => ({ key: key3, entry })),
19974
19977
  skipped: result.skipped
19975
19978
  }, null, 2));
19976
19979
  return;
19977
19980
  }
19978
- for (const { key: key2, entry } of result.imported) {
19979
- log(` ${args.dryRun ? "would import" : "imported"} ${key2} ${entry.outputs?.[0]?.sha256.slice(0, 12)}`);
19981
+ for (const { key: key3, entry } of result.imported) {
19982
+ log(` ${args.dryRun ? "would import" : "imported"} ${key3} ${entry.outputs?.[0]?.sha256.slice(0, 12)}`);
19980
19983
  }
19981
- for (const { key: key2, reason } of result.skipped) log(` skipped ${key2}: ${reason}`);
19984
+ for (const { key: key3, reason } of result.skipped) log(` skipped ${key3}: ${reason}`);
19982
19985
  log(`
19983
19986
  ${result.imported.length} ${args.dryRun ? "to import" : "imported"}, ${result.skipped.length} skipped (offline; no provider contacted)`);
19984
19987
  }
@@ -20059,9 +20062,9 @@ async function runAdopt(args) {
20059
20062
  })).filter((spec) => spec.provider === provider.id);
20060
20063
  let n = 0;
20061
20064
  for (const spec of rebased) {
20062
- const key2 = lockKey(spec.styleId, spec.assetId);
20063
- if (lock.entries[key2]?.status !== "downloaded") continue;
20064
- upsert(lock, key2, { specHash: spec.specHash });
20065
+ const key3 = lockKey(spec.styleId, spec.assetId);
20066
+ if (lock.entries[key3]?.status !== "downloaded") continue;
20067
+ upsert(lock, key3, { specHash: spec.specHash });
20065
20068
  n++;
20066
20069
  }
20067
20070
  await saveLock(args.lock, lock);
@@ -20203,10 +20206,10 @@ async function runSalvage2(args) {
20203
20206
  const rebased = (await resolveSpecs(reloaded)).filter((spec) => spec.provider === provider.id);
20204
20207
  let n = 0;
20205
20208
  for (const spec of rebased) {
20206
- const key2 = lockKey(spec.styleId, spec.assetId);
20207
- const entry = lock.entries[key2];
20209
+ const key3 = lockKey(spec.styleId, spec.assetId);
20210
+ const entry = lock.entries[key3];
20208
20211
  if (entry?.status !== "downloaded" || entry.specHash !== SALVAGED_SPEC_HASH) continue;
20209
- upsert(lock, key2, { specHash: spec.specHash });
20212
+ upsert(lock, key3, { specHash: spec.specHash });
20210
20213
  n++;
20211
20214
  }
20212
20215
  await saveLock(args.lock, lock);
@@ -20634,9 +20637,9 @@ function styleProvider(raw, styleId, seen = /* @__PURE__ */ new Set()) {
20634
20637
  seen.add(styleId);
20635
20638
  return style.extends ? styleProvider(raw, style.extends, seen) : raw.provider ?? "pixellab";
20636
20639
  }
20637
- function setOrDelete(target, key2, value) {
20638
- if (value === null || value === void 0) delete target[key2];
20639
- else target[key2] = value;
20640
+ function setOrDelete(target, key3, value) {
20641
+ if (value === null || value === void 0) delete target[key3];
20642
+ else target[key3] = value;
20640
20643
  }
20641
20644
  function assetStyles(raw, asset) {
20642
20645
  const own = Array.isArray(asset.styles) ? asset.styles : [];
@@ -20850,14 +20853,14 @@ async function priceManifestEdit(manifestPath, edit, opts = {}) {
20850
20853
  const items = [];
20851
20854
  const totals = {};
20852
20855
  priced.forEach((spec, index) => {
20853
- const key2 = `${spec.styleId}/${spec.assetId}`;
20856
+ const key3 = `${spec.styleId}/${spec.assetId}`;
20854
20857
  const quoted = live[index];
20855
20858
  const cost = quoted ?? spec.cost;
20856
20859
  items.push({
20857
- key: key2,
20860
+ key: key3,
20858
20861
  styleId: spec.styleId,
20859
20862
  assetId: spec.assetId,
20860
- change: before.has(key2) ? "changed" : "new",
20863
+ change: before.has(key3) ? "changed" : "new",
20861
20864
  provider: spec.provider,
20862
20865
  cost,
20863
20866
  costUnit: spec.costUnit,
@@ -20911,21 +20914,21 @@ function handEditMembers(loaded, spec, lock, editPath) {
20911
20914
  return [{ role: null, path: editPath, base: bases?.[0]?.path ?? null }];
20912
20915
  }
20913
20916
  function refuseUneditable(spec) {
20914
- const key2 = `${spec.styleId}/${spec.assetId}`;
20917
+ const key3 = `${spec.styleId}/${spec.assetId}`;
20915
20918
  if (spec.derive) {
20916
20919
  const from = spec.derive.source.kind === "asset" ? spec.derive.source.assetId : spec.derive.source.file;
20917
20920
  throw new ManifestEditError(
20918
- `${key2} is derived from ${from} (${spec.derive.transform}), so it has no hand edit of its own; edit its source, or change the derive transform in the manifest`
20921
+ `${key3} is derived from ${from} (${spec.derive.transform}), so it has no hand edit of its own; edit its source, or change the derive transform in the manifest`
20919
20922
  );
20920
20923
  }
20921
20924
  if (spec.external) {
20922
20925
  throw new ManifestEditError(
20923
- `${key2} is built outside pixelkiln (${spec.external.builder}); change it there, then run pixelkiln adopt --local --force to record the new file`
20926
+ `${key3} is built outside pixelkiln (${spec.external.builder}); change it there, then run pixelkiln adopt --local --force to record the new file`
20924
20927
  );
20925
20928
  }
20926
20929
  if (spec.mirror) {
20927
20930
  throw new ManifestEditError(
20928
- `${key2} is a flip of ${spec.mirror.sourceAssetId}, so it has no hand edit of its own; edit ${spec.mirror.sourceAssetId} and flip it again`
20931
+ `${key3} is a flip of ${spec.mirror.sourceAssetId}, so it has no hand edit of its own; edit ${spec.mirror.sourceAssetId} and flip it again`
20929
20932
  );
20930
20933
  }
20931
20934
  }
@@ -21572,11 +21575,11 @@ function uvGuide(document, imageIndex) {
21572
21575
  for (let vertex = 0; vertex < uv.count; vertex++) {
21573
21576
  const u = uv.data[vertex * uv.size];
21574
21577
  const v = uv.data[vertex * uv.size + 1];
21575
- const key2 = Math.round(u * WELD) * (WELD * 4) + Math.round(v * WELD);
21576
- let point = pointOf.get(key2);
21578
+ const key3 = Math.round(u * WELD) * (WELD * 4) + Math.round(v * WELD);
21579
+ let point = pointOf.get(key3);
21577
21580
  if (point === void 0) {
21578
21581
  point = us.length;
21579
- pointOf.set(key2, point);
21582
+ pointOf.set(key3, point);
21580
21583
  us.push(u);
21581
21584
  vs.push(v);
21582
21585
  parent.push(point);
@@ -21617,8 +21620,8 @@ function uvGuide(document, imageIndex) {
21617
21620
  group.triangles.push(triangle);
21618
21621
  for (const [from, to] of [[triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a]]) {
21619
21622
  if (from === to) continue;
21620
- const key2 = Math.min(from, to) * points + Math.max(from, to);
21621
- group.edges.set(key2, (group.edges.get(key2) ?? 0) + 1);
21623
+ const key3 = Math.min(from, to) * points + Math.max(from, to);
21624
+ group.edges.set(key3, (group.edges.get(key3) ?? 0) + 1);
21622
21625
  }
21623
21626
  }
21624
21627
  const pieces = [];
@@ -21653,10 +21656,10 @@ function uvGuide(document, imageIndex) {
21653
21656
  };
21654
21657
  const anchor = group.triangles.some((triangle) => inside2(triangle, centre)) ? centre : [(us[largest.a] + us[largest.b] + us[largest.c]) / 3, (vs[largest.a] + vs[largest.b] + vs[largest.c]) / 3];
21655
21658
  const outline = [];
21656
- for (const [key2, count] of group.edges) {
21659
+ for (const [key3, count] of group.edges) {
21657
21660
  if (count !== 1) continue;
21658
- const from = Math.floor(key2 / points);
21659
- const to = key2 - from * points;
21661
+ const from = Math.floor(key3 / points);
21662
+ const to = key3 - from * points;
21660
21663
  outline.push(us[from], vs[from], us[to], vs[to]);
21661
21664
  }
21662
21665
  let bone = null;
@@ -22294,8 +22297,8 @@ async function adoptModelExport(model, opts = {}) {
22294
22297
  for (const [index, material] of (exported.document.json.materials ?? []).entries()) {
22295
22298
  for (const slot of slots) {
22296
22299
  const image = slotImage(exported.document, index, slot);
22297
- const key2 = `${material.name}\0${slot}`;
22298
- if (material.name && image !== void 0 && !exportedByName.has(key2)) exportedByName.set(key2, image);
22300
+ const key3 = `${material.name}\0${slot}`;
22301
+ if (material.name && image !== void 0 && !exportedByName.has(key3)) exportedByName.set(key3, image);
22299
22302
  }
22300
22303
  }
22301
22304
  let document = original.document;
@@ -22603,16 +22606,16 @@ function poseNodes(document, pose) {
22603
22606
  const values = readAccessor(document, sampler.output);
22604
22607
  const width = path76 === "rotation" ? 4 : 3;
22605
22608
  const cubic = sampler.interpolation === "CUBICSPLINE";
22606
- const valueAt = (key3) => Array.from(values.data.subarray((cubic ? key3 * 3 + 1 : key3) * width, (cubic ? key3 * 3 + 1 : key3) * width + width));
22609
+ const valueAt = (key4) => Array.from(values.data.subarray((cubic ? key4 * 3 + 1 : key4) * width, (cubic ? key4 * 3 + 1 : key4) * width + width));
22607
22610
  const last = times.length - 1;
22608
22611
  const time = Math.min(Math.max(pose.time, times[0] ?? 0), times[last] ?? 0);
22609
- let key2 = 0;
22610
- while (key2 < last && times[key2 + 1] <= time) key2++;
22611
- let value = valueAt(key2);
22612
- if (key2 < last && sampler.interpolation !== "STEP" && !cubic) {
22613
- const span = times[key2 + 1] - times[key2];
22614
- const f = span > 0 ? (time - times[key2]) / span : 0;
22615
- const next = valueAt(key2 + 1);
22612
+ let key3 = 0;
22613
+ while (key3 < last && times[key3 + 1] <= time) key3++;
22614
+ let value = valueAt(key3);
22615
+ if (key3 < last && sampler.interpolation !== "STEP" && !cubic) {
22616
+ const span = times[key3 + 1] - times[key3];
22617
+ const f = span > 0 ? (time - times[key3]) / span : 0;
22618
+ const next = valueAt(key3 + 1);
22616
22619
  const sign = path76 === "rotation" && value.reduce((sum, v, k) => sum + v * next[k], 0) < 0 ? -1 : 1;
22617
22620
  value = value.map((v, k) => v * (1 - f) + next[k] * sign * f);
22618
22621
  }
@@ -23767,16 +23770,16 @@ function createGallerySkeletonHandlers(opts) {
23767
23770
  if (!parsed.success) throw new ManifestEditError(`invalid estimate request: ${parsed.error.issues[0]?.message}`);
23768
23771
  const request = parsed.data;
23769
23772
  const ctx = await opts.loadProject(request.project);
23770
- const key2 = lockKey(request.styleId, request.assetId);
23771
- const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key2);
23772
- if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
23773
+ const key3 = lockKey(request.styleId, request.assetId);
23774
+ const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key3);
23775
+ if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
23773
23776
  const file = skeletonSourceFile(spec);
23774
- if (!existsSync31(file)) throw new ManifestEditError(`${key2} has no image on disk to estimate from`);
23777
+ if (!existsSync31(file)) throw new ManifestEditError(`${key3} has no image on disk to estimate from`);
23775
23778
  const bytes = await readFile26(file);
23776
23779
  const metadata = imageMetadata(bytes);
23777
23780
  if (!metadata) throw new ManifestEditError(`${path39.basename(file)} is not a readable PNG or JPEG`);
23778
23781
  const problem = estimateSkeletonSizeProblem(metadata.width, metadata.height);
23779
- if (problem) throw new ManifestEditError(`${key2} is ${problem}`);
23782
+ if (problem) throw new ManifestEditError(`${key3} is ${problem}`);
23780
23783
  if (used >= limit) {
23781
23784
  throw Object.assign(
23782
23785
  new Error(`this gallery has made its ${limit} skeleton estimate${limit === 1 ? "" : "s"}; restart it with --estimate-limit to allow more`),
@@ -23788,7 +23791,7 @@ function createGallerySkeletonHandlers(opts) {
23788
23791
  const res = await client2.estimateSkeleton({ image: { base64: bytes.toString("base64"), format: metadata.format } });
23789
23792
  const billed = billedAmount(res.usage);
23790
23793
  if (billed) spent[billed.unit] = (spent[billed.unit] ?? 0) + billed.amount;
23791
- log2(` estimated a skeleton for ${key2} (PixelLab estimate-skeleton, ${used}/${limit} this session${billed ? `, billed ${billed.amount} ${billed.unit}` : ""})`);
23794
+ log2(` estimated a skeleton for ${key3} (PixelLab estimate-skeleton, ${used}/${limit} this session${billed ? `, billed ${billed.amount} ${billed.unit}` : ""})`);
23792
23795
  return {
23793
23796
  set: scaffoldSkeletonSet(res.keypoints, request.frames ?? DEFAULT_SCAFFOLD_FRAMES),
23794
23797
  source: path39.relative(ctx.loaded.root, file).split(path39.sep).join("/"),
@@ -23850,14 +23853,14 @@ async function createSkeletonAnimation(manifestPath, request) {
23850
23853
  }
23851
23854
  }
23852
23855
  async function updateSkeletonKeypoints(ctx, request) {
23853
- const key2 = lockKey(request.styleId, request.assetId);
23854
- const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key2);
23855
- if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
23856
+ const key3 = lockKey(request.styleId, request.assetId);
23857
+ const spec = ctx.specs.find((candidate) => lockKey(candidate.styleId, candidate.assetId) === key3);
23858
+ if (!spec) throw new ManifestEditError(`"${key3}" is not declared by the manifest`);
23856
23859
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
23857
- if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
23860
+ if (!file) throw new ManifestEditError(`${key3} is not an animate-skeleton revision`);
23858
23861
  const relative = path39.relative(ctx.loaded.root, file);
23859
23862
  if (relative.startsWith("..") || path39.isAbsolute(relative)) {
23860
- throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
23863
+ throw new ManifestEditError(`${key3}'s keypoints file is outside the project; edit it by hand`);
23861
23864
  }
23862
23865
  const current = existsSync31(file) ? sha256(await readFile26(file)) : null;
23863
23866
  if (current !== request.expectedSha256) {
@@ -24376,8 +24379,8 @@ async function buildGallerySnapshot(opts) {
24376
24379
  } catch {
24377
24380
  }
24378
24381
  for (const planItem of plan.items) {
24379
- const { spec, key: key2 } = planItem;
24380
- const entry = lock.entries[key2];
24382
+ const { spec, key: key3 } = planItem;
24383
+ const entry = lock.entries[key3];
24381
24384
  const asset = loaded.manifest.assets[spec.assetId] ?? null;
24382
24385
  let outputs;
24383
24386
  let edit = null;
@@ -24449,9 +24452,9 @@ async function buildGallerySnapshot(opts) {
24449
24452
  }
24450
24453
  const quality = planItem.quality ? await describeQuality(media, root, planItem.quality) : null;
24451
24454
  items.push({
24452
- id: key2,
24455
+ id: key3,
24453
24456
  project: null,
24454
- key: key2,
24457
+ key: key3,
24455
24458
  styleId: spec.styleId,
24456
24459
  assetId: spec.assetId,
24457
24460
  declared: true,
@@ -24509,8 +24512,8 @@ async function buildGallerySnapshot(opts) {
24509
24512
  });
24510
24513
  }
24511
24514
  const shown2 = new Set(items.map((item) => item.key));
24512
- for (const [key2, entry] of Object.entries(lock.entries)) {
24513
- if (shown2.has(key2)) continue;
24515
+ for (const [key3, entry] of Object.entries(lock.entries)) {
24516
+ if (shown2.has(key3)) continue;
24514
24517
  if (isDeclared(loaded, entry.styleId, entry.assetId)) continue;
24515
24518
  if (!matchesFilter(filter, entry.styleId, entry.assetId)) continue;
24516
24519
  const outputs = await Promise.all(
@@ -24519,9 +24522,9 @@ async function buildGallerySnapshot(opts) {
24519
24522
  )
24520
24523
  );
24521
24524
  items.push({
24522
- id: key2,
24525
+ id: key3,
24523
24526
  project: null,
24524
- key: key2,
24527
+ key: key3,
24525
24528
  styleId: entry.styleId,
24526
24529
  assetId: entry.assetId,
24527
24530
  declared: false,
@@ -24622,7 +24625,7 @@ async function buildGallerySnapshot(opts) {
24622
24625
  } : null,
24623
24626
  tags: style?.tags ?? [],
24624
24627
  extends: typeof rawStyle?.extends === "string" ? rawStyle.extends : null,
24625
- ownFields: rawStyle ? Object.keys(rawStyle).filter((key2) => key2 !== "extends") : [],
24628
+ ownFields: rawStyle ? Object.keys(rawStyle).filter((key3) => key3 !== "extends") : [],
24626
24629
  items: styleItems.length,
24627
24630
  spendByUnit: spend,
24628
24631
  regenerate: {
@@ -24856,7 +24859,7 @@ function renderGuide(guide, width, height) {
24856
24859
  }
24857
24860
  }
24858
24861
  }
24859
- const key2 = [
24862
+ const key3 = [
24860
24863
  "# Regions: the number drawn on each piece, its outline colour, and what it is",
24861
24864
  ...guide.regions.map((region, index) => {
24862
24865
  const [r, g, b] = colours[index];
@@ -24873,7 +24876,7 @@ function renderGuide(guide, width, height) {
24873
24876
  ].join(" ")),
24874
24877
  ""
24875
24878
  ].join("\n");
24876
- return { png: encodeRgbaPng(width, height, pixels), key: key2 };
24879
+ return { png: encodeRgbaPng(width, height, pixels), key: key3 };
24877
24880
  }
24878
24881
 
24879
24882
  // src/cli/commands/model.ts
@@ -24889,7 +24892,7 @@ async function runModel(args) {
24889
24892
  if (sub === "list") {
24890
24893
  const models = await describeModels(loaded, { set: () => void 0 }, galleryMediaId, styles);
24891
24894
  if (args.json) {
24892
- log(JSON.stringify(models, (key2, value) => key2 === "url" || key2 === "projectUrl" ? void 0 : value, 2));
24895
+ log(JSON.stringify(models, (key3, value) => key3 === "url" || key3 === "projectUrl" ? void 0 : value, 2));
24893
24896
  return;
24894
24897
  }
24895
24898
  if (!models.length) {
@@ -25567,14 +25570,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
25567
25570
  const selectedKeys = opts.specs ? new Set(specByKey.keys()) : null;
25568
25571
  const result = { review: 0, completed: 0, failed: 0, stillRunning: 0 };
25569
25572
  const incompleteSubmissions = Object.entries(lock.entries).filter(
25570
- ([key2, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
25573
+ ([key3, entry]) => entry.provider === provider.id && (!selectedKeys || selectedKeys.has(key3)) && entry.jobId && entry.submissionComplete === false && (entry.status === "pending" || entry.status === "processing")
25571
25574
  );
25572
- for (const [key2] of incompleteSubmissions) {
25573
- log2(` incomplete submission ${key2}; rerun \`pixelkiln submit\` to resume`);
25575
+ for (const [key3] of incompleteSubmissions) {
25576
+ log2(` incomplete submission ${key3}; rerun \`pixelkiln submit\` to resume`);
25574
25577
  }
25575
25578
  result.stillRunning = incompleteSubmissions.length;
25576
25579
  const pending = () => Object.entries(lock.entries).filter(
25577
- ([key2, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key2)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
25580
+ ([key3, e]) => e.provider === provider.id && (!selectedKeys || selectedKeys.has(key3)) && e.jobId && e.submissionComplete !== false && (e.status === "pending" || e.status === "processing")
25578
25581
  );
25579
25582
  while (pending().length > 0) {
25580
25583
  if (Date.now() - started > timeout) {
@@ -25582,16 +25585,16 @@ async function poll(provider, lock, lockPath, opts = {}) {
25582
25585
  log2(` timed out with ${result.stillRunning} job(s) still running; re-run \`poll\` to resume`);
25583
25586
  break;
25584
25587
  }
25585
- for (const [key2, entry] of pending()) {
25588
+ for (const [key3, entry] of pending()) {
25586
25589
  try {
25587
- const currentSpec = specByKey.get(key2);
25590
+ const currentSpec = specByKey.get(key3);
25588
25591
  const state = await provider.poll(entry.jobId, entry.generator, {
25589
25592
  tileFeature: entry.tileFeature ?? currentSpec?.tileFeature,
25590
25593
  spec: currentSpec,
25591
25594
  metadata: entry.providerMetadata?.[provider.id]
25592
25595
  });
25593
25596
  if (state.status === "review" || state.status === "review-set") {
25594
- upsert(lock, key2, {
25597
+ upsert(lock, key3, {
25595
25598
  status: "review",
25596
25599
  reviewObjectId: entry.jobId,
25597
25600
  providerMetadata: state.metadata ? {
@@ -25605,11 +25608,11 @@ async function poll(provider, lock, lockPath, opts = {}) {
25605
25608
  });
25606
25609
  result.review++;
25607
25610
  log2(
25608
- state.status === "review-set" ? ` review ${key2} (${state.frameUrls.length} ordered frames)` : ` review ${key2} (${state.candidateUrls.length} candidates)`
25611
+ state.status === "review-set" ? ` review ${key3} (${state.frameUrls.length} ordered frames)` : ` review ${key3} (${state.candidateUrls.length} candidates)`
25609
25612
  );
25610
25613
  } else if (state.status === "ready") {
25611
25614
  const sourceUrls = state.sources?.length ? state.sources : state.sourceUrl ? [{ url: state.sourceUrl }] : [];
25612
- upsert(lock, key2, {
25615
+ upsert(lock, key3, {
25613
25616
  status: "selected",
25614
25617
  objectId: state.objectId,
25615
25618
  sourceUrl: sourceUrls[0]?.url ?? null,
@@ -25625,14 +25628,14 @@ async function poll(provider, lock, lockPath, opts = {}) {
25625
25628
  billed: state.billed ?? entry.billed
25626
25629
  });
25627
25630
  result.completed++;
25628
- log2(` ready ${key2}`);
25631
+ log2(` ready ${key3}`);
25629
25632
  } else if (state.status === "failed") {
25630
- upsert(lock, key2, { status: "failed", error: state.error });
25633
+ upsert(lock, key3, { status: "failed", error: state.error });
25631
25634
  result.failed++;
25632
- log2(` FAILED ${key2}: ${state.error}`);
25635
+ log2(` FAILED ${key3}: ${state.error}`);
25633
25636
  }
25634
25637
  } catch (err) {
25635
- log2(` error polling ${key2}: ${err instanceof Error ? err.message : String(err)}`);
25638
+ log2(` error polling ${key3}: ${err instanceof Error ? err.message : String(err)}`);
25636
25639
  }
25637
25640
  }
25638
25641
  await saveLock(lockPath, lock);
@@ -25755,8 +25758,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25755
25758
  }
25756
25759
  }
25757
25760
  }
25758
- for (const { spec, key: key2 } of items) {
25759
- const estimate = estimates.get(key2);
25761
+ for (const { spec, key: key3 } of items) {
25762
+ const estimate = estimates.get(key3);
25760
25763
  if (spec.batch?.role === "member") {
25761
25764
  continue;
25762
25765
  }
@@ -25770,7 +25773,7 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25770
25773
  } catch (err) {
25771
25774
  const message6 = err instanceof Error ? err.message : String(err);
25772
25775
  failed++;
25773
- upsert(lock, key2, {
25776
+ upsert(lock, key3, {
25774
25777
  styleId: spec.styleId,
25775
25778
  assetId: spec.assetId,
25776
25779
  specHash: spec.specHash,
@@ -25780,13 +25783,13 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25780
25783
  height: spec.height,
25781
25784
  status: "failed",
25782
25785
  error: message6,
25783
- outputs: lock.entries[key2]?.outputs ?? [],
25786
+ outputs: lock.entries[key3]?.outputs ?? [],
25784
25787
  cost: 0,
25785
25788
  costUnit: spec.costUnit,
25786
25789
  provider: provider.id
25787
25790
  });
25788
25791
  await saveLock(lockPath, lock);
25789
- log2(` FAILED ${key2}: ${message6}`);
25792
+ log2(` FAILED ${key3}: ${message6}`);
25790
25793
  }
25791
25794
  continue;
25792
25795
  }
@@ -25798,11 +25801,11 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25798
25801
  const missing = (spec.batch.memberAssetIds ?? []).filter((id) => !byKey.has(lockKey(spec.styleId, id)));
25799
25802
  if (missing.length) {
25800
25803
  throw new Error(
25801
- `${key2}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
25804
+ `${key3}: batch member(s) ${missing.join(", ")} must be submitted in the same run as this leader; run without --only, or include every sibling`
25802
25805
  );
25803
25806
  }
25804
25807
  }
25805
- const previousEntry = lock.entries[key2];
25808
+ const previousEntry = lock.entries[key3];
25806
25809
  const resumesCheckpoint = Boolean(
25807
25810
  previousEntry?.specHash === spec.specHash && previousEntry.provider === provider.id && previousEntry.generator === spec.generator && previousEntry.submissionComplete === false && previousEntry.jobId
25808
25811
  );
@@ -25832,9 +25835,9 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25832
25835
  const leaderGroup = motionLeader ? recordedAnimationGroup(lock.entries[lockKey(motionLeader.spec.styleId, motionLeader.spec.assetId)]) : void 0;
25833
25836
  const motionGroup = leaderGroup?.animationGroupId && leaderGroup.animationName ? { animationGroupId: leaderGroup.animationGroupId, animationName: leaderGroup.animationName } : void 0;
25834
25837
  if (motionLeader && !motionGroup) {
25835
- log2(` ${key2}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
25838
+ log2(` ${key3}: ${motionLeader.assetId} has no animation group recorded; drawing this direction on its own`);
25836
25839
  }
25837
- upsert(lock, key2, {
25840
+ upsert(lock, key3, {
25838
25841
  styleId: spec.styleId,
25839
25842
  assetId: spec.assetId,
25840
25843
  specHash: spec.specHash,
@@ -25946,8 +25949,8 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25946
25949
  ...previousMetadata ? { previousMetadata } : {},
25947
25950
  checkpoint: async (checkpoint) => {
25948
25951
  if (!checkpoint.jobId) throw new Error("Provider checkpoint returned an empty job id");
25949
- const entry = lock.entries[key2];
25950
- upsert(lock, key2, {
25952
+ const entry = lock.entries[key3];
25953
+ upsert(lock, key3, {
25951
25954
  jobId: checkpoint.jobId,
25952
25955
  submissionComplete: checkpoint.complete,
25953
25956
  reviewObjectId: checkpoint.complete && (spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature) ? checkpoint.jobId : null,
@@ -25964,41 +25967,41 @@ async function submit(provider, loaded, items, lock, lockPath, opts = {}) {
25964
25967
  await saveLock(lockPath, lock);
25965
25968
  }
25966
25969
  });
25967
- upsert(lock, key2, {
25970
+ upsert(lock, key3, {
25968
25971
  jobId,
25969
25972
  submissionComplete: true,
25970
25973
  // A multi-candidate generator routes through review; record the parent
25971
25974
  // so `pick` knows where to look.
25972
25975
  reviewObjectId: spec.generator === "frames" || estimate.candidates > 1 && !spec.tileFeature ? jobId : null,
25973
25976
  status: "processing",
25974
- providerMetadata: metadata ? { ...lock.entries[key2].providerMetadata, [provider.id]: metadata } : lock.entries[key2].providerMetadata
25977
+ providerMetadata: metadata ? { ...lock.entries[key3].providerMetadata, [provider.id]: metadata } : lock.entries[key3].providerMetadata
25975
25978
  });
25976
25979
  inFlight.set(jobId, spec);
25977
25980
  submitted++;
25978
25981
  spent += estimate.amount;
25979
- writeBatchMembers(spec, key2, null);
25982
+ writeBatchMembers(spec, key3, null);
25980
25983
  log2(
25981
- ` ${key2} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
25984
+ ` ${key3} \u2192 ${jobId} (${spec.width}x${spec.height}` + (estimate.candidates > 1 ? `, ${estimate.candidates} ${spec.tileFeature ? "outputs" : "candidates"}` : "") + `, ${estimate.amount})`
25982
25985
  );
25983
25986
  } catch (err) {
25984
25987
  const message6 = err instanceof Error ? err.message : String(err);
25985
- const entry = lock.entries[key2];
25988
+ const entry = lock.entries[key3];
25986
25989
  if (entry.jobId && entry.submissionComplete === true) {
25987
- upsert(lock, key2, { status: "processing", error: null });
25990
+ upsert(lock, key3, { status: "processing", error: null });
25988
25991
  inFlight.set(entry.jobId, spec);
25989
25992
  submitted++;
25990
25993
  spent += estimate.amount;
25991
- writeBatchMembers(spec, key2, null);
25992
- log2(` ${key2} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
25994
+ writeBatchMembers(spec, key3, null);
25995
+ log2(` ${key3} \u2192 ${entry.jobId} (recovered from completed checkpoint)`);
25993
25996
  } else {
25994
25997
  failed++;
25995
- upsert(lock, key2, {
25998
+ upsert(lock, key3, {
25996
25999
  status: "failed",
25997
26000
  error: message6,
25998
26001
  cost: entry.jobId ? estimate.amount : 0
25999
26002
  });
26000
- writeBatchMembers(spec, key2, message6);
26001
- log2(` FAILED ${key2}: ${message6}`);
26003
+ writeBatchMembers(spec, key3, message6);
26004
+ log2(` FAILED ${key3}: ${message6}`);
26002
26005
  }
26003
26006
  }
26004
26007
  await saveLock(lockPath, lock);
@@ -26571,11 +26574,11 @@ async function prepareReview(provider, lock, opts = {}) {
26571
26574
  const prefix = opts.routePrefix ?? "";
26572
26575
  const providerUrls = /* @__PURE__ */ new Map();
26573
26576
  const groups = [];
26574
- for (const [key2, entry] of Object.entries(lock.entries)) {
26575
- if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key2)) continue;
26577
+ for (const [key3, entry] of Object.entries(lock.entries)) {
26578
+ if (entry.provider !== provider.id || selectedKeys && !selectedKeys.has(key3)) continue;
26576
26579
  if (entry.status !== "review" || !entry.reviewObjectId) continue;
26577
26580
  try {
26578
- const spec = specByKey.get(key2);
26581
+ const spec = specByKey.get(key3);
26579
26582
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
26580
26583
  if (state.status !== "review" && state.status !== "review-set" || (state.status === "review" ? !state.candidateUrls.length : !state.frameUrls.length)) continue;
26581
26584
  const urls = state.status === "review" ? state.candidateUrls : state.frameUrls;
@@ -26607,9 +26610,9 @@ async function prepareReview(provider, lock, opts = {}) {
26607
26610
  reviewAssets.set(currentRoute, { path: current.path, contentType: current.contentType });
26608
26611
  }
26609
26612
  for (const [route, asset] of frameAssets) reviewAssets.set(route, asset);
26610
- providerUrls.set(key2, urls);
26613
+ providerUrls.set(key3, urls);
26611
26614
  groups.push({
26612
- key: key2,
26615
+ key: key3,
26613
26616
  assetId: entry.assetId,
26614
26617
  styleId: entry.styleId,
26615
26618
  prompt: entry.prompt,
@@ -26639,7 +26642,7 @@ async function prepareReview(provider, lock, opts = {}) {
26639
26642
  ...entry.batch?.index != null ? { recommendedIndex: entry.batch.index } : {}
26640
26643
  });
26641
26644
  } catch (err) {
26642
- log2(` could not load candidates for ${key2}: ${err instanceof Error ? err.message : String(err)}`);
26645
+ log2(` could not load candidates for ${key3}: ${err instanceof Error ? err.message : String(err)}`);
26643
26646
  }
26644
26647
  }
26645
26648
  if (groups.length === 0) return null;
@@ -26651,18 +26654,18 @@ async function prepareReview(provider, lock, opts = {}) {
26651
26654
  apply: async (body, lockPath) => {
26652
26655
  const { selections } = body;
26653
26656
  let selected = 0;
26654
- for (const { key: key2, index } of selections) {
26655
- const group = byKey.get(key2);
26656
- const entry = lock.entries[key2];
26657
+ for (const { key: key3, index } of selections) {
26658
+ const group = byKey.get(key3);
26659
+ const entry = lock.entries[key3];
26657
26660
  if (!group || !entry?.reviewObjectId) continue;
26658
26661
  if (!Number.isInteger(index) || index < 0 || index >= group.frameUrls.length) continue;
26659
26662
  if (group.mode === "frame-set") {
26660
- const spec = specByKey.get(key2);
26663
+ const spec = specByKey.get(key3);
26661
26664
  const state = await provider.poll(entry.reviewObjectId, entry.generator, { spec, metadata: entry.providerMetadata?.[provider.id] });
26662
26665
  if (state.status !== "review-set") {
26663
- throw new Error(`Frame set ${key2} is no longer ready for review`);
26666
+ throw new Error(`Frame set ${key3} is no longer ready for review`);
26664
26667
  }
26665
- upsert(lock, key2, {
26668
+ upsert(lock, key3, {
26666
26669
  status: "selected",
26667
26670
  objectId: state.objectId,
26668
26671
  candidateIndex: null,
@@ -26678,7 +26681,7 @@ async function prepareReview(provider, lock, opts = {}) {
26678
26681
  } : entry.providerMetadata
26679
26682
  });
26680
26683
  selected++;
26681
- log2(` accepted ${key2} \u2192 ${state.sources.length} ordered frames`);
26684
+ log2(` accepted ${key3} \u2192 ${state.sources.length} ordered frames`);
26682
26685
  continue;
26683
26686
  }
26684
26687
  const { objectId, sourceUrl, metadata } = await requireSelectCandidate(provider)(
@@ -26687,11 +26690,11 @@ async function prepareReview(provider, lock, opts = {}) {
26687
26690
  `asset:${entry.assetId}`,
26688
26691
  entry.generator
26689
26692
  );
26690
- upsert(lock, key2, {
26693
+ upsert(lock, key3, {
26691
26694
  status: "selected",
26692
26695
  objectId,
26693
26696
  candidateIndex: index,
26694
- sourceUrl: sourceUrl ?? providerUrls.get(key2)?.[index] ?? null,
26697
+ sourceUrl: sourceUrl ?? providerUrls.get(key3)?.[index] ?? null,
26695
26698
  sourceUrls: [],
26696
26699
  provider: provider.id,
26697
26700
  providerMetadata: metadata ? {
@@ -26703,7 +26706,7 @@ async function prepareReview(provider, lock, opts = {}) {
26703
26706
  } : entry.providerMetadata
26704
26707
  });
26705
26708
  selected++;
26706
- log2(` picked ${key2} \u2192 candidate ${index + 1}`);
26709
+ log2(` picked ${key3} \u2192 candidate ${index + 1}`);
26707
26710
  }
26708
26711
  await saveLock(lockPath, lock);
26709
26712
  return { selected, skipped: groups.length - selected };
@@ -26804,7 +26807,7 @@ function createGenerateHandlers(opts) {
26804
26807
  const busy = /* @__PURE__ */ new Map();
26805
26808
  for (const job of jobs.values()) {
26806
26809
  if (job.phase === "done" || job.phase === "failed") continue;
26807
- for (const key2 of job.keys) busy.set(`${job.project ?? ""}:${key2}`, job.id);
26810
+ for (const key3 of job.keys) busy.set(`${job.project ?? ""}:${key3}`, job.id);
26808
26811
  }
26809
26812
  return busy;
26810
26813
  };
@@ -26847,7 +26850,7 @@ function createGenerateHandlers(opts) {
26847
26850
  });
26848
26851
  say(job, `${providerId}: ${res.completed} completed, ${res.review} awaiting review, ${res.failed} failed, ${res.stillRunning} still running`);
26849
26852
  }
26850
- job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key2) => ctx.lock.entries[key2]?.status === "review");
26853
+ job.review = specs.map((spec) => lockKey(spec.styleId, spec.assetId)).filter((key3) => ctx.lock.entries[key3]?.status === "review");
26851
26854
  job.phase = "fetching";
26852
26855
  for (const [providerId, providerSpecs] of groupByRecordedProvider(specs, ctx.lock)) {
26853
26856
  const provider = opts.providerFor(job.project ?? void 0, providerId);
@@ -26932,7 +26935,7 @@ function createGenerateHandlers(opts) {
26932
26935
  job.finishedAt = null;
26933
26936
  const next = await opts.loadProject(job.project ?? void 0);
26934
26937
  const byKey = new Map(next.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
26935
- const nextSpecs = job.keys.map((key2) => byKey.get(key2)).filter((spec) => Boolean(spec));
26938
+ const nextSpecs = job.keys.map((key3) => byKey.get(key3)).filter((spec) => Boolean(spec));
26936
26939
  const plan = await buildPlan(nextSpecs, next.lock);
26937
26940
  if (!plan.actionable.length) return finish();
26938
26941
  for (const group of plan.groups) {
@@ -26999,21 +27002,21 @@ function createGenerateHandlers(opts) {
26999
27002
  const ctx = await opts.loadProject(request.project);
27000
27003
  const byKey = new Map(ctx.specs.map((spec) => [lockKey(spec.styleId, spec.assetId), spec]));
27001
27004
  const specs = [];
27002
- for (const key2 of request.keys) {
27003
- const spec = byKey.get(key2);
27004
- if (!spec) throw new GenerateRequestError(`"${key2}" is not declared by the manifest`);
27005
+ for (const key3 of request.keys) {
27006
+ const spec = byKey.get(key3);
27007
+ if (!spec) throw new GenerateRequestError(`"${key3}" is not declared by the manifest`);
27005
27008
  specs.push(spec);
27006
27009
  }
27007
27010
  const busy = busyKeys();
27008
- for (const key2 of request.keys) {
27009
- const holder = busy.get(`${request.project ?? ""}:${key2}`);
27010
- if (holder) throw new GenerateRequestError(`"${key2}" is already being worked on by job ${holder}`, 409);
27011
+ for (const key3 of request.keys) {
27012
+ const holder = busy.get(`${request.project ?? ""}:${key3}`);
27013
+ if (holder) throw new GenerateRequestError(`"${key3}" is already being worked on by job ${holder}`, 409);
27011
27014
  }
27012
27015
  if (request.restore) {
27013
- for (const key2 of request.keys) {
27014
- const entry = ctx.lock.entries[key2];
27016
+ for (const key3 of request.keys) {
27017
+ const entry = ctx.lock.entries[key3];
27015
27018
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) {
27016
- throw new GenerateRequestError(`"${key2}" has no downloaded output recorded to restore`);
27019
+ throw new GenerateRequestError(`"${key3}" has no downloaded output recorded to restore`);
27017
27020
  }
27018
27021
  }
27019
27022
  }
@@ -27342,7 +27345,7 @@ function createGalleryEditorHandlers(opts = {}) {
27342
27345
  }
27343
27346
  return checking;
27344
27347
  };
27345
- const describe = (status) => ({
27348
+ const describe2 = (status) => ({
27346
27349
  ...status,
27347
27350
  pixelorama: pin.pixelorama,
27348
27351
  protocol: pin.protocol,
@@ -27352,7 +27355,7 @@ function createGalleryEditorHandlers(opts = {}) {
27352
27355
  });
27353
27356
  return {
27354
27357
  release: pin.release,
27355
- status: async () => describe(verified ?? await check()),
27358
+ status: async () => describe2(verified ?? await check()),
27356
27359
  install: async () => {
27357
27360
  if (!running) {
27358
27361
  error = null;
@@ -27379,7 +27382,7 @@ function createGalleryEditorHandlers(opts = {}) {
27379
27382
  running = null;
27380
27383
  });
27381
27384
  }
27382
- return describe(verified ?? await check());
27385
+ return describe2(verified ?? await check());
27383
27386
  },
27384
27387
  file: async (release, name) => {
27385
27388
  if (!pin.release || release !== pin.release) return null;
@@ -27448,12 +27451,12 @@ async function serveUntilStopped(initial, reload, args, access2) {
27448
27451
  const quoters = /* @__PURE__ */ new Map();
27449
27452
  const quoteFor = async (project2) => {
27450
27453
  loadProjectEnv(path46.dirname(path46.resolve(await access2.manifestFor(project2))));
27451
- const key2 = process.env.PIXELLAB_API_KEY;
27452
- if (!key2) return null;
27453
- let quoter = quoters.get(key2);
27454
+ const key3 = process.env.PIXELLAB_API_KEY;
27455
+ if (!key3) return null;
27456
+ let quoter = quoters.get(key3);
27454
27457
  if (!quoter) {
27455
- quoter = createProFlashQuoter(new PixelLabClient(key2));
27456
- quoters.set(key2, quoter);
27458
+ quoter = createProFlashQuoter(new PixelLabClient(key3));
27459
+ quoters.set(key3, quoter);
27457
27460
  }
27458
27461
  return quoter;
27459
27462
  };
@@ -27826,9 +27829,9 @@ async function runHistory(args) {
27826
27829
  for (const { spec, entry } of selected) {
27827
27830
  if (!entry?.history?.length) continue;
27828
27831
  shown2++;
27829
- const key2 = lockKey(spec.styleId, spec.assetId);
27832
+ const key3 = lockKey(spec.styleId, spec.assetId);
27830
27833
  log(`
27831
- ${key2}`);
27834
+ ${key3}`);
27832
27835
  log(` current ${entry.outputs[0]?.sha256.slice(0, 12) ?? "\u2014"} ${entry.downloadedAt ?? ""} ${entry.objectId ?? ""}${billedNote(entry.cost, entry.costUnit, entry.billed)}${importedNote(entry)}`);
27833
27836
  for (const [i, generation] of entry.history.entries()) {
27834
27837
  const changed = generation.prompt !== entry.prompt ? " (different prompt)" : "";
@@ -28069,17 +28072,17 @@ async function runPrune(args) {
28069
28072
  );
28070
28073
  }
28071
28074
  const declared = new Set((await resolveSpecs(loaded)).map((s) => lockKey(s.styleId, s.assetId)));
28072
- const orphans = Object.keys(lock.entries).filter((key2) => !declared.has(key2)).sort();
28075
+ const orphans = Object.keys(lock.entries).filter((key3) => !declared.has(key3)).sort();
28073
28076
  if (!orphans.length) {
28074
28077
  log(` every lock entry is declared by the manifest; nothing to prune`);
28075
28078
  return;
28076
28079
  }
28077
28080
  log(`
28078
28081
  ${orphans.length} lock entr(ies) the manifest no longer declares:`);
28079
- for (const key2 of orphans.slice(0, 20)) {
28080
- const outputs = lock.entries[key2]?.outputs ?? [];
28082
+ for (const key3 of orphans.slice(0, 20)) {
28083
+ const outputs = lock.entries[key3]?.outputs ?? [];
28081
28084
  const where = outputs[0]?.path ?? "no recorded output";
28082
- log(` ${key2.padEnd(44)} ${where}`);
28085
+ log(` ${key3.padEnd(44)} ${where}`);
28083
28086
  }
28084
28087
  if (orphans.length > 20) log(` \u2026 and ${orphans.length - 20} more`);
28085
28088
  if (args.dryRun) {
@@ -28097,7 +28100,7 @@ This drops their provenance from the lockfile. The art on disk is`);
28097
28100
  return;
28098
28101
  }
28099
28102
  let removed = 0;
28100
- for (const key2 of orphans) if (remove(lock, key2)) removed++;
28103
+ for (const key3 of orphans) if (remove(lock, key3)) removed++;
28101
28104
  await saveLock(args.lock, lock);
28102
28105
  log(` removed ${removed} lock entr(ies); ${Object.keys(lock.entries).length} remain`);
28103
28106
  }
@@ -28250,14 +28253,14 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
28250
28253
  const outputOwners = /* @__PURE__ */ new Map();
28251
28254
  const duplicateOutputs = [];
28252
28255
  const specByKey = new Map(specs.map((spec) => [`${spec.styleId}/${spec.assetId}`, spec]));
28253
- for (const [key2, entry] of Object.entries(lock.entries)) {
28256
+ for (const [key3, entry] of Object.entries(lock.entries)) {
28254
28257
  for (let index = 0; index < entry.outputs.length; index++) {
28255
28258
  const output = entry.outputs[index];
28256
- const spec = specByKey.get(key2);
28259
+ const spec = specByKey.get(key3);
28257
28260
  const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, path50.dirname(lockPath));
28258
28261
  const owner = outputOwners.get(absolute);
28259
- if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
28260
- outputOwners.set(absolute, key2);
28262
+ if (owner && owner !== key3) duplicateOutputs.push(`${output.path} (${owner}, ${key3})`);
28263
+ outputOwners.set(absolute, key3);
28261
28264
  }
28262
28265
  }
28263
28266
  if (duplicateOutputs.length) {
@@ -28274,12 +28277,12 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
28274
28277
  const invalidState = [];
28275
28278
  const staleMapUrls = [];
28276
28279
  const now = Date.now();
28277
- for (const [key2, entry] of Object.entries(lock.entries)) {
28280
+ for (const [key3, entry] of Object.entries(lock.entries)) {
28278
28281
  if ((entry.status === "pending" || entry.status === "processing") && !entry.jobId) {
28279
- invalidState.push(`${key2} (${entry.status} without job id)`);
28282
+ invalidState.push(`${key3} (${entry.status} without job id)`);
28280
28283
  }
28281
28284
  if (entry.status === "review" && !entry.reviewObjectId) {
28282
- invalidState.push(`${key2} (review without review object id)`);
28285
+ invalidState.push(`${key3} (review without review object id)`);
28283
28286
  }
28284
28287
  if (entry.status !== "selected" && entry.status !== "download-failed") continue;
28285
28288
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
@@ -28294,9 +28297,9 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
28294
28297
  break;
28295
28298
  }
28296
28299
  }
28297
- if (!hasSource && !hasCache) stranded.push(key2);
28300
+ if (!hasSource && !hasCache) stranded.push(key3);
28298
28301
  if (entry.generator === "map" && entry.submittedAt && now - Date.parse(entry.submittedAt) > 8 * 60 * 60 * 1e3) {
28299
- staleMapUrls.push(key2);
28302
+ staleMapUrls.push(key3);
28300
28303
  }
28301
28304
  }
28302
28305
  add(
@@ -28411,10 +28414,10 @@ function mergePalettes(palettes, topN = 24) {
28411
28414
  const totals = /* @__PURE__ */ new Map();
28412
28415
  for (const palette of palettes) {
28413
28416
  for (const color of palette) {
28414
- const key2 = `${color.r},${color.g},${color.b}`;
28415
- const existing = totals.get(key2);
28417
+ const key3 = `${color.r},${color.g},${color.b}`;
28418
+ const existing = totals.get(key3);
28416
28419
  if (existing) existing.weight += color.weight;
28417
- else totals.set(key2, { ...color });
28420
+ else totals.set(key3, { ...color });
28418
28421
  }
28419
28422
  }
28420
28423
  const merged = [...totals.values()].sort((a, b) => b.weight - a.weight).slice(0, topN);
@@ -28611,11 +28614,11 @@ async function runPlan(args) {
28611
28614
  actionable: group.actionable.map((item) => item.key)
28612
28615
  })),
28613
28616
  actionable: plan.actionable.map((i) => i.key),
28614
- items: plan.items.map(({ key: key2, state, reason, quality, spec }) => {
28615
- const entry = lock.entries[key2];
28617
+ items: plan.items.map(({ key: key3, state, reason, quality, spec }) => {
28618
+ const entry = lock.entries[key3];
28616
28619
  const billedDiffers = entry?.billed && (entry.billed.unit !== entry.costUnit || entry.billed.amount !== entry.cost);
28617
28620
  return {
28618
- key: key2,
28621
+ key: key3,
28619
28622
  state,
28620
28623
  reason,
28621
28624
  ...spec.revision ? {
@@ -28825,7 +28828,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
28825
28828
  return { ...packed2, atlas: { ...packed2.atlas, style: styleId } };
28826
28829
  }
28827
28830
  const prefix = `${styleId}/`;
28828
- const entries = Object.entries(lock.entries).filter(([key2]) => key2.startsWith(prefix));
28831
+ const entries = Object.entries(lock.entries).filter(([key3]) => key3.startsWith(prefix));
28829
28832
  const sources = options.sources ?? {};
28830
28833
  if (!entries.length && !Object.keys(sources).length) {
28831
28834
  throw new Error(
@@ -28844,8 +28847,8 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
28844
28847
  return parent ? layerSources(parent, seen.add(id)) : void 0;
28845
28848
  };
28846
28849
  const layered = [];
28847
- for (const [key2, entry] of entries) {
28848
- const id = key2.slice(prefix.length);
28850
+ for (const [key3, entry] of entries) {
28851
+ const id = key3.slice(prefix.length);
28849
28852
  locked.add(id);
28850
28853
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
28851
28854
  const source = sources[id];
@@ -28936,14 +28939,14 @@ function mountSprites(placements, options) {
28936
28939
  }
28937
28940
  const byCell = /* @__PURE__ */ new Map();
28938
28941
  for (const p of placements) {
28939
- const key2 = `${p.cell[0]},${p.cell[1]}`;
28940
- const owner = byCell.get(key2);
28942
+ const key3 = `${p.cell[0]},${p.cell[1]}`;
28943
+ const owner = byCell.get(key3);
28941
28944
  if (owner) {
28942
28945
  throw new Error(
28943
- `mountSprites: "${p.id}" and "${owner}" both claim cell ${key2}; a cell has exactly one owner`
28946
+ `mountSprites: "${p.id}" and "${owner}" both claim cell ${key3}; a cell has exactly one owner`
28944
28947
  );
28945
28948
  }
28946
- byCell.set(key2, p.id);
28949
+ byCell.set(key3, p.id);
28947
28950
  }
28948
28951
  const loaded = [];
28949
28952
  const skipped = [];
@@ -29074,13 +29077,169 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
29074
29077
  };
29075
29078
  }
29076
29079
 
29080
+ // src/pipeline/connected-sets.ts
29081
+ var key2 = (spec) => `${spec.styleId}/${spec.assetId}`;
29082
+ var SIDES = ["lower", "upper"];
29083
+ function connectedGroup(start, specs) {
29084
+ const byKey = new Map(specs.map((spec) => [key2(spec), spec]));
29085
+ const neighbours = /* @__PURE__ */ new Map();
29086
+ const link = (a, b) => {
29087
+ if (!neighbours.has(a)) neighbours.set(a, /* @__PURE__ */ new Set());
29088
+ neighbours.get(a).add(b);
29089
+ };
29090
+ for (const spec of specs) {
29091
+ for (const side of SIDES) {
29092
+ const other = spec.terrainConnect?.[side];
29093
+ if (!other) continue;
29094
+ link(key2(spec), key2(other.spec));
29095
+ link(key2(other.spec), key2(spec));
29096
+ }
29097
+ }
29098
+ const seen = /* @__PURE__ */ new Set();
29099
+ const queue = [key2(start)];
29100
+ while (queue.length) {
29101
+ const next = queue.pop();
29102
+ if (seen.has(next)) continue;
29103
+ seen.add(next);
29104
+ for (const other of neighbours.get(next) ?? []) queue.push(other);
29105
+ }
29106
+ const members = [...seen].map((id) => byKey.get(id)).filter((spec) => spec !== void 0).sort((a, b) => a.assetId.localeCompare(b.assetId));
29107
+ const ordered = [];
29108
+ const placed = /* @__PURE__ */ new Set();
29109
+ const place = (spec) => {
29110
+ if (placed.has(key2(spec))) return;
29111
+ placed.add(key2(spec));
29112
+ for (const side of SIDES) {
29113
+ const other = spec.terrainConnect?.[side];
29114
+ const parent = other ? byKey.get(key2(other.spec)) : void 0;
29115
+ if (parent) place(parent);
29116
+ }
29117
+ ordered.push(spec);
29118
+ };
29119
+ for (const spec of members) place(spec);
29120
+ return ordered;
29121
+ }
29122
+ function describe(prompt, side) {
29123
+ const parsed = prompt ? parseTerrainDescriptions(prompt) : null;
29124
+ const text = parsed?.[side];
29125
+ if (!text) return void 0;
29126
+ const clause = text.split(/[,;.]/)[0].replace(/\s+/g, " ").trim().toLowerCase();
29127
+ return clause ? clause.slice(0, 32).trim() : void 0;
29128
+ }
29129
+ function sideOf(name, terrainTypes) {
29130
+ const index = terrainTypes.indexOf(name);
29131
+ if (index === 0) return "lower";
29132
+ if (index === 1) return "upper";
29133
+ if (name === "transition") return "upper";
29134
+ throw new Error(`a tile corner is "${name}", which is not one of the set's terrains (${terrainTypes.join(", ")})`);
29135
+ }
29136
+ function mergeConnectedTerrain(members, manifestDir) {
29137
+ const ids = members.map((member) => member.spec.assetId);
29138
+ if (members.length < 2) throw new Error("a connected tileset needs at least two sets");
29139
+ for (const { spec } of members) {
29140
+ if (spec.terrainOrientation === "sidescroller") {
29141
+ throw new Error(
29142
+ `${key2(spec)} is a sidescroller set, which connects only its platform; export it on its own, without --merge-connected`
29143
+ );
29144
+ }
29145
+ }
29146
+ const tileTypes = new Set(members.map((member) => member.spec.tileType ?? ""));
29147
+ if (tileTypes.size > 1) {
29148
+ throw new Error(`connected sets ${ids.join(", ")} use different tile shapes; export them one at a time`);
29149
+ }
29150
+ const parent = /* @__PURE__ */ new Map();
29151
+ const find = (node) => {
29152
+ if (!parent.has(node)) parent.set(node, node);
29153
+ const above = parent.get(node);
29154
+ if (above === node) return node;
29155
+ const root = find(above);
29156
+ parent.set(node, root);
29157
+ return root;
29158
+ };
29159
+ const nodeOf = (assetId, side) => `${assetId}:${side}`;
29160
+ for (const { spec } of members) {
29161
+ for (const side of SIDES) {
29162
+ const other = spec.terrainConnect?.[side];
29163
+ if (other) parent.set(find(nodeOf(spec.assetId, side)), find(nodeOf(other.assetId, other.terrain)));
29164
+ }
29165
+ }
29166
+ const indexOfClass = /* @__PURE__ */ new Map();
29167
+ const names = [];
29168
+ const taken = /* @__PURE__ */ new Set();
29169
+ const defining = /* @__PURE__ */ new Map();
29170
+ for (const { spec } of members) {
29171
+ for (const side of SIDES) {
29172
+ const root = find(nodeOf(spec.assetId, side));
29173
+ if (!indexOfClass.has(root)) {
29174
+ indexOfClass.set(root, names.length);
29175
+ names.push("");
29176
+ }
29177
+ if (!spec.terrainConnect?.[side] && !defining.has(root)) defining.set(root, nodeOf(spec.assetId, side));
29178
+ }
29179
+ }
29180
+ for (const [root, index] of indexOfClass) {
29181
+ const node = defining.get(root) ?? root;
29182
+ const [assetId, side] = node.split(":");
29183
+ const member = members.find((candidate) => candidate.spec.assetId === assetId);
29184
+ const base = describe(member.spec.prompt, side) ?? `${assetId}_${side}`;
29185
+ let name = base;
29186
+ for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
29187
+ taken.add(name);
29188
+ names[index] = name;
29189
+ }
29190
+ const tiles = [];
29191
+ const providerRules = {};
29192
+ for (const { spec, entry } of members) {
29193
+ const metadata = entry.providerMetadata?.[entry.provider];
29194
+ const terrainTypes = Array.isArray(metadata?.terrainTypes) ? metadata.terrainTypes.filter((item) => typeof item === "string") : [];
29195
+ const terrainTiles = Array.isArray(metadata?.terrainTiles) ? metadata.terrainTiles : [];
29196
+ if (terrainTypes.length < 2 || !terrainTiles.length) {
29197
+ throw new Error(`${key2(spec)} has no terrain tile data; regenerate it before merging`);
29198
+ }
29199
+ providerRules[spec.assetId] = metadata;
29200
+ let outputs = resolveSpecEntryOutputs(entry, spec);
29201
+ if (!outputs.length) throw new Error(`${key2(spec)} has no downloaded outputs`);
29202
+ if (spec.source && sourceIsStem(spec.source, entry, manifestDir)) {
29203
+ outputs = outputs.map((output) => ({ ...output, absolutePath: sourceOutputPath(spec.source, entry, output.index, manifestDir) }));
29204
+ }
29205
+ for (const output of outputs) {
29206
+ const tile = (output.role ? terrainTiles.find((item) => isRecord2(item) && item.role === output.role) : void 0) ?? terrainTiles[output.index];
29207
+ if (!isRecord2(tile) || !isRecord2(tile.corners)) continue;
29208
+ const corner = (position) => {
29209
+ const name = tile.corners && tile.corners[position];
29210
+ if (typeof name !== "string") throw new Error(`${key2(spec)}: ${output.role ?? output.index} has no ${position} corner`);
29211
+ return indexOfClass.get(find(nodeOf(spec.assetId, sideOf(name, terrainTypes))));
29212
+ };
29213
+ tiles.push({
29214
+ id: `${spec.assetId}/${output.role ?? `tile-${String(output.index).padStart(2, "0")}`}`,
29215
+ assetId: spec.assetId,
29216
+ path: output.absolutePath,
29217
+ corners: [corner("NW"), corner("NE"), corner("SW"), corner("SE")]
29218
+ });
29219
+ }
29220
+ }
29221
+ if (!tiles.length) throw new Error(`connected sets ${ids.join(", ")} have no tiles with corner data`);
29222
+ return { assets: ids, terrains: names, tiles, tileType: members[0].spec.tileType, providerRules };
29223
+ }
29224
+ function tileCorners(rules, tile) {
29225
+ if (tile.corners) return tile.corners;
29226
+ if (rules.ruleType !== "corner" || tile.bitmask === void 0) return null;
29227
+ const mask = tile.bitmask;
29228
+ const corner = (bit) => (mask & 1 << bit) !== 0 ? 0 : 1;
29229
+ return [corner(3), corner(2), corner(1), corner(0)];
29230
+ }
29231
+ var TERRAIN_PALETTE = ["#5ab552", "#4c78a8", "#e0a458", "#a0522d", "#9b6bd1", "#d9534f", "#4fb8b8", "#8c8c8c"];
29232
+ var terrainColor = (index) => TERRAIN_PALETTE[index % TERRAIN_PALETTE.length];
29233
+ function isRecord2(value) {
29234
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29235
+ }
29236
+
29077
29237
  // src/pipeline/ldtk-export.ts
29078
29238
  import { createHash as createHash7 } from "crypto";
29079
29239
  var LDTK_JSON_VERSION = "1.5.3";
29080
29240
  var FIRST = 1;
29081
29241
  var SECOND = 2;
29082
- var DEMO_WIDTH = 12;
29083
- var DEMO_HEIGHT = 9;
29242
+ var DEMO_SIZE = { small: [12, 9], large: [16, 12] };
29084
29243
  function ldtkRuleMatches(rule, grid, cx, cy) {
29085
29244
  const radius = Math.floor(rule.size / 2);
29086
29245
  for (let py = 0; py < rule.size; py++) {
@@ -29126,6 +29285,14 @@ function ldtkPattern(rules, mask) {
29126
29285
  pattern[3] = value(3);
29127
29286
  return pattern;
29128
29287
  }
29288
+ function ldtkCornerPattern(corners) {
29289
+ const pattern = new Array(9).fill(0);
29290
+ pattern[4] = corners[0] + 1;
29291
+ pattern[5] = corners[1] + 1;
29292
+ pattern[7] = corners[2] + 1;
29293
+ pattern[8] = corners[3] + 1;
29294
+ return pattern;
29295
+ }
29129
29296
  function resolveLdtkTiles(rules, grid) {
29130
29297
  const out = [];
29131
29298
  for (let cy = 0; cy < grid.height; cy++) {
@@ -29136,16 +29303,16 @@ function resolveLdtkTiles(rules, grid) {
29136
29303
  }
29137
29304
  return out;
29138
29305
  }
29139
- function demoGrid(rules, wanted) {
29306
+ function demoGrid(rules, wanted, width, height) {
29140
29307
  let best = null;
29141
29308
  let bestCovered = -1;
29142
29309
  for (let seed = 1; seed <= 400; seed++) {
29143
29310
  let state = seed * 2654435761 >>> 0;
29144
- const cells = Array.from({ length: DEMO_WIDTH * DEMO_HEIGHT }, () => {
29311
+ const cells = Array.from({ length: width * height }, () => {
29145
29312
  state = Math.imul(state, 1664525) + 1013904223 >>> 0;
29146
29313
  return (state >>> 16) % 100 < 52 ? FIRST : SECOND;
29147
29314
  });
29148
- const grid = { width: DEMO_WIDTH, height: DEMO_HEIGHT, cells };
29315
+ const grid = { width, height, cells };
29149
29316
  const covered = new Set(resolveLdtkTiles(rules, grid).map((hit) => hit.rule.uid)).size;
29150
29317
  if (covered > bestCovered) {
29151
29318
  best = grid;
@@ -29155,7 +29322,63 @@ function demoGrid(rules, wanted) {
29155
29322
  }
29156
29323
  return best;
29157
29324
  }
29158
- var TERRAIN_COLORS = ["#5AB552", "#4C78A8"];
29325
+ function constrainedDemoGrid(rules, combos, count, outside, width, height) {
29326
+ const stride = width + 1;
29327
+ const comboList = [...combos].map((combo) => combo.split(",").map(Number));
29328
+ let best = null;
29329
+ let bestCovered = -1;
29330
+ for (let seed = 1; seed <= 600; seed++) {
29331
+ let state = seed * 2654435761 >>> 0;
29332
+ const random = () => {
29333
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
29334
+ return (state >>> 8) / 16777216;
29335
+ };
29336
+ const vertices = new Array(stride * (height + 1)).fill(0);
29337
+ for (let x = 0; x <= width; x++) vertices[height * stride + x] = outside;
29338
+ for (let y = 0; y <= height; y++) vertices[y * stride + width] = outside;
29339
+ const at2 = (x, y) => vertices[y * stride + x];
29340
+ const comboAt = (x, y) => {
29341
+ if (x < 0 || y < 0 || x >= width || y >= height) return void 0;
29342
+ const painted = [at2(x, y), at2(x + 1, y), at2(x, y + 1), at2(x + 1, y + 1)];
29343
+ if (!comboList.some((combo) => combo.every((terrain, corner) => !painted[corner] || painted[corner] === terrain + 1))) return null;
29344
+ return painted.every(Boolean) ? painted.map((value) => value - 1).join(",") : void 0;
29345
+ };
29346
+ const around = (x, y) => [comboAt(x - 1, y - 1), comboAt(x, y - 1), comboAt(x - 1, y), comboAt(x, y)];
29347
+ const seen = /* @__PURE__ */ new Set();
29348
+ let ok = true;
29349
+ for (let y = 0; y < height && ok; y++) {
29350
+ for (let x = 0; x < width && ok; x++) {
29351
+ const options = [];
29352
+ for (let value = 1; value <= count; value++) {
29353
+ vertices[y * stride + x] = value;
29354
+ const made = around(x, y);
29355
+ if (made.includes(null)) continue;
29356
+ options.push({ value, fresh: made.filter((combo) => combo !== void 0 && !seen.has(combo)).length });
29357
+ }
29358
+ if (!options.length) {
29359
+ ok = false;
29360
+ break;
29361
+ }
29362
+ const best2 = Math.max(...options.map((option) => option.fresh));
29363
+ const pool = best2 > 0 && random() < 0.85 ? options.filter((option) => option.fresh === best2) : options;
29364
+ vertices[y * stride + x] = pool[Math.floor(random() * pool.length)].value;
29365
+ for (const combo of around(x, y)) if (combo) seen.add(combo);
29366
+ }
29367
+ }
29368
+ if (!ok) continue;
29369
+ const cells = [];
29370
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) cells.push(at2(x, y));
29371
+ const grid = { width, height, cells };
29372
+ const covered = new Set(resolveLdtkTiles(rules, grid).map((hit) => hit.rule.uid)).size;
29373
+ if (covered > bestCovered) {
29374
+ best = grid;
29375
+ bestCovered = covered;
29376
+ }
29377
+ if (covered >= rules.length) break;
29378
+ }
29379
+ if (!best) throw new Error("ldtk export could not paint a preview level for these connected sets");
29380
+ return best;
29381
+ }
29159
29382
  function buildLdtk(generic, tileType) {
29160
29383
  const rules = generic.rules;
29161
29384
  if (!rules || rules.ruleType === "outline") {
@@ -29173,20 +29396,27 @@ function buildLdtk(generic, tileType) {
29173
29396
  const corner = rules.ruleType === "corner";
29174
29397
  const base = identifier(generic.name.replace("/", "_"), "Tileset");
29175
29398
  const name = base.charAt(0).toUpperCase() + base.slice(1);
29176
- const terrainNames = [rules.terrains[0] ?? "feature", rules.terrains[1] ?? "background"];
29399
+ const merged = rules.terrains.length > 2;
29400
+ const terrainNames = merged ? rules.terrains : [rules.terrains[0] ?? "feature", rules.terrains[1] ?? "background"];
29401
+ const [demoWidth, demoHeight] = merged ? DEMO_SIZE.large : DEMO_SIZE.small;
29177
29402
  const columns = generic.sheet.columns;
29178
29403
  const rows = Math.ceil(generic.tiles.length / columns);
29179
- const byMask = /* @__PURE__ */ new Map();
29404
+ const byAdjacency = /* @__PURE__ */ new Map();
29180
29405
  for (const tile of generic.tiles) {
29181
- if (tile.bitmask === void 0) continue;
29182
- byMask.set(tile.bitmask, [...byMask.get(tile.bitmask) ?? [], tile.id]);
29183
- }
29184
- if (!byMask.size) throw new Error("ldtk export found no tiles with adjacency masks; use --format generic");
29406
+ const corners = corner ? tileCorners(rules, tile) : null;
29407
+ if (corner ? !corners : tile.bitmask === void 0) continue;
29408
+ const adjacency = corners ? corners.join(",") : String(tile.bitmask);
29409
+ const known = byAdjacency.get(adjacency);
29410
+ if (known) known.ids.push(tile.id);
29411
+ else byAdjacency.set(adjacency, { pattern: corners ? ldtkCornerPattern(corners) : ldtkPattern(rules, tile.bitmask), ids: [tile.id] });
29412
+ }
29413
+ if (!byAdjacency.size) throw new Error("ldtk export found no tiles with adjacency rules; use --format generic");
29414
+ const outside = merged ? FIRST : SECOND;
29185
29415
  const tilesetUid = 1;
29186
29416
  const sourceUid = 2;
29187
29417
  const autoUid = 3;
29188
29418
  const groupUid = 4;
29189
- const ruleList = [...byMask.entries()].map(([mask, ids], index) => ({
29419
+ const ruleList = [...byAdjacency.values()].map(({ pattern, ids }, index) => ({
29190
29420
  uid: 5 + index,
29191
29421
  active: true,
29192
29422
  size: 3,
@@ -29194,7 +29424,7 @@ function buildLdtk(generic, tileType) {
29194
29424
  alpha: 1,
29195
29425
  chance: 1,
29196
29426
  breakOnMatch: true,
29197
- pattern: ldtkPattern(rules, mask),
29427
+ pattern,
29198
29428
  flipX: false,
29199
29429
  flipY: false,
29200
29430
  xModulo: 1,
@@ -29211,7 +29441,7 @@ function buildLdtk(generic, tileType) {
29211
29441
  tileMode: "Single",
29212
29442
  pivotX: 0,
29213
29443
  pivotY: 0,
29214
- outOfBoundsValue: SECOND,
29444
+ outOfBoundsValue: outside,
29215
29445
  invalidated: false,
29216
29446
  perlinActive: false,
29217
29447
  perlinSeed: 1,
@@ -29225,9 +29455,10 @@ function buildLdtk(generic, tileType) {
29225
29455
  return tile ? { tilesetUid, x: tile.x, y: tile.y, w: tile.width, h: tile.height } : null;
29226
29456
  };
29227
29457
  const full = (1 << rules.arity) - 1;
29228
- const representative = (terrain) => generic.tiles.find((tile) => tile.bitmask === (terrain === 0 ? full : 0))?.id;
29458
+ const representative = (terrain) => corner ? generic.tiles.find((tile) => tileCorners(rules, tile)?.every((value) => value === terrain))?.id : generic.tiles.find((tile) => tile.bitmask === (terrain === 0 ? full : 0))?.id;
29229
29459
  const shift = corner ? -Math.floor(grid / 2) : 0;
29230
29460
  const sourceName = `${name}_${corner ? "corners" : "cells"}`;
29461
+ const paintList = terrainNames.map((terrainName, index) => `${terrainName} (${index + 1})`).join(", ");
29231
29462
  const autoName = name;
29232
29463
  const layerBase = {
29233
29464
  guideGridWid: 0,
@@ -29256,16 +29487,16 @@ function buildLdtk(generic, tileType) {
29256
29487
  identifier: sourceName,
29257
29488
  type: "IntGrid",
29258
29489
  uid: sourceUid,
29259
- doc: corner ? `Paint ${terrainNames[0]} (1) and ${terrainNames[1]} (2). Each cell is a corner where four tiles meet, so it is drawn half a tile up and left of the tiles it controls.` : `Paint ${terrainNames[0]} (1) and ${terrainNames[1]} (2). Each tile looks at its own cell and the four around it.`,
29260
- uiColor: TERRAIN_COLORS[0],
29490
+ doc: `Paint ${paintList}. ` + (corner ? "Each cell is a corner where four tiles meet, so it is drawn half a tile up and left of the tiles it controls." : "Each tile looks at its own cell and the four around it."),
29491
+ uiColor: terrainColor(0).toUpperCase(),
29261
29492
  ...layerBase,
29262
29493
  renderInWorldView: true,
29263
29494
  pxOffsetX: shift,
29264
29495
  pxOffsetY: shift,
29265
- intGridValues: [FIRST, SECOND].map((value, index) => ({
29266
- value,
29267
- identifier: identifier(terrainNames[index], `terrain${value}`),
29268
- color: TERRAIN_COLORS[index],
29496
+ intGridValues: terrainNames.map((terrainName, index) => ({
29497
+ value: index + 1,
29498
+ identifier: identifier(terrainName, `terrain${index + 1}`),
29499
+ color: terrainColor(index).toUpperCase(),
29269
29500
  tile: tileRect(representative(index)),
29270
29501
  groupUid: 0
29271
29502
  })),
@@ -29278,8 +29509,8 @@ function buildLdtk(generic, tileType) {
29278
29509
  identifier: autoName,
29279
29510
  type: "AutoLayer",
29280
29511
  uid: autoUid,
29281
- doc: `Drawn by rules from ${sourceName}: one rule for each way the two terrains can meet.`,
29282
- uiColor: TERRAIN_COLORS[1],
29512
+ doc: `Drawn by rules from ${sourceName}: one rule for each way the ${merged ? "terrains" : "two terrains"} can meet.`,
29513
+ uiColor: terrainColor(1).toUpperCase(),
29283
29514
  ...layerBase,
29284
29515
  renderInWorldView: true,
29285
29516
  pxOffsetX: 0,
@@ -29300,14 +29531,21 @@ function buildLdtk(generic, tileType) {
29300
29531
  }],
29301
29532
  autoSourceLayerDefUid: sourceUid
29302
29533
  };
29303
- const level = demoGrid(ruleList, ruleList.length);
29534
+ const level = merged ? constrainedDemoGrid(
29535
+ ruleList,
29536
+ new Set(generic.tiles.flatMap((tile) => tile.corners ? [tile.corners.join(",")] : [])),
29537
+ terrainNames.length,
29538
+ outside,
29539
+ demoWidth,
29540
+ demoHeight
29541
+ ) : demoGrid(ruleList, ruleList.length, demoWidth, demoHeight);
29304
29542
  const hits = resolveLdtkTiles(ruleList, level);
29305
29543
  const tileAt = (id) => ({ x: id % columns * grid, y: Math.floor(id / columns) * grid });
29306
29544
  const instanceBase = (layerDef, offset) => ({
29307
29545
  __identifier: layerDef.identifier,
29308
29546
  __type: layerDef.__type,
29309
- __cWid: DEMO_WIDTH,
29310
- __cHei: DEMO_HEIGHT,
29547
+ __cWid: demoWidth,
29548
+ __cHei: demoHeight,
29311
29549
  __gridSize: grid,
29312
29550
  __opacity: 1,
29313
29551
  __pxTotalOffsetX: offset,
@@ -29345,8 +29583,8 @@ function buildLdtk(generic, tileType) {
29345
29583
  worldLayout: "LinearHorizontal",
29346
29584
  worldGridWidth: 256,
29347
29585
  worldGridHeight: 256,
29348
- defaultLevelWidth: DEMO_WIDTH * grid,
29349
- defaultLevelHeight: DEMO_HEIGHT * grid,
29586
+ defaultLevelWidth: demoWidth * grid,
29587
+ defaultLevelHeight: demoHeight * grid,
29350
29588
  defaultPivotX: 0,
29351
29589
  defaultPivotY: 0,
29352
29590
  defaultGridSize: grid,
@@ -29386,7 +29624,7 @@ function buildLdtk(generic, tileType) {
29386
29624
  tags: [],
29387
29625
  tagsSourceEnumUid: null,
29388
29626
  enumTags: [],
29389
- customData: generic.tiles.filter((tile) => tile.bitmask !== void 0).map((tile) => ({ tileId: tile.id, data: `mask=${tile.bitmask}` })),
29627
+ customData: generic.tiles.filter((tile) => tile.bitmask !== void 0 || tile.corners !== void 0).map((tile) => ({ tileId: tile.id, data: tile.corners ? `corners=${tile.corners.join(",")}` : `mask=${tile.bitmask}` })),
29390
29628
  savedSelections: [],
29391
29629
  cachedPixelData: null
29392
29630
  }],
@@ -29402,8 +29640,8 @@ function buildLdtk(generic, tileType) {
29402
29640
  worldX: -1,
29403
29641
  worldY: -1,
29404
29642
  worldDepth: 0,
29405
- pxWid: DEMO_WIDTH * grid,
29406
- pxHei: DEMO_HEIGHT * grid,
29643
+ pxWid: demoWidth * grid,
29644
+ pxHei: demoHeight * grid,
29407
29645
  __bgColor: "#474B67",
29408
29646
  bgColor: null,
29409
29647
  useAutoIdentifier: false,
@@ -29424,7 +29662,7 @@ function buildLdtk(generic, tileType) {
29424
29662
  src: [tileAt(hit.tile).x, tileAt(hit.tile).y],
29425
29663
  f: 0,
29426
29664
  t: hit.tile,
29427
- d: [hit.rule.uid, hit.cy * DEMO_WIDTH + hit.cx],
29665
+ d: [hit.rule.uid, hit.cy * demoWidth + hit.cx],
29428
29666
  a: 1
29429
29667
  }))
29430
29668
  },
@@ -29444,16 +29682,16 @@ function buildLdtk(generic, tileType) {
29444
29682
 
29445
29683
  // src/pipeline/tileset-export.ts
29446
29684
  function normalizeTileRules(raw) {
29447
- if (!isRecord2(raw)) return null;
29685
+ if (!isRecord3(raw)) return null;
29448
29686
  const ruleType = raw.rule_type;
29449
29687
  const arity = raw.arity;
29450
29688
  if (ruleType !== "edge" && ruleType !== "corner" && ruleType !== "outline") return null;
29451
29689
  if (arity !== 4 && arity !== 6) return null;
29452
29690
  const masks = {};
29453
- if (isRecord2(raw.tiles)) {
29454
- for (const [key2, value] of Object.entries(raw.tiles)) {
29455
- const index = tileIndex(key2);
29456
- const mask = typeof value === "number" ? value : isRecord2(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord2(value) && typeof value.mask === "number" ? value.mask : null;
29691
+ if (isRecord3(raw.tiles)) {
29692
+ for (const [key3, value] of Object.entries(raw.tiles)) {
29693
+ const index = tileIndex(key3);
29694
+ const mask = typeof value === "number" ? value : isRecord3(value) && typeof value.bitmask === "number" ? value.bitmask : isRecord3(value) && typeof value.mask === "number" ? value.mask : null;
29457
29695
  if (index !== null && mask !== null && Number.isInteger(mask) && mask >= 0) masks[index] = mask;
29458
29696
  }
29459
29697
  }
@@ -29469,12 +29707,12 @@ function normalizeTileRules(raw) {
29469
29707
  };
29470
29708
  }
29471
29709
  function normalizeTerrainTiles(metadata) {
29472
- if (!isRecord2(metadata) || !Array.isArray(metadata.terrainTiles)) return null;
29710
+ if (!isRecord3(metadata) || !Array.isArray(metadata.terrainTiles)) return null;
29473
29711
  const terrains = Array.isArray(metadata.terrainTypes) ? metadata.terrainTypes.filter((item) => typeof item === "string") : [];
29474
29712
  if (terrains.length < 2) return null;
29475
29713
  const masks = {};
29476
29714
  metadata.terrainTiles.forEach((tile, index) => {
29477
- if (!isRecord2(tile) || !isRecord2(tile.corners)) return;
29715
+ if (!isRecord3(tile) || !isRecord3(tile.corners)) return;
29478
29716
  const corners = tile.corners;
29479
29717
  const bit = (corner) => corners[corner] === terrains[0] ? 1 : 0;
29480
29718
  masks[index] = bit("NW") << 3 | bit("NE") << 2 | bit("SW") << 1 | bit("SE");
@@ -29506,13 +29744,13 @@ function exportTileset(entry, spec, options) {
29506
29744
  );
29507
29745
  }
29508
29746
  const metadata = entry.providerMetadata?.[entry.provider];
29509
- const rawRules = isRecord2(metadata) ? metadata.tileRules : void 0;
29747
+ const rawRules = isRecord3(metadata) ? metadata.tileRules : void 0;
29510
29748
  const terrainRules = normalizeTerrainTiles(metadata);
29511
29749
  const rules = normalizeTileRules(rawRules) ?? terrainRules;
29512
- const providerRules = isRecord2(rawRules) ? rawRules : terrainRules ? metadata : null;
29750
+ const providerRules = isRecord3(rawRules) ? rawRules : terrainRules ? metadata : null;
29513
29751
  const frames = packed.atlas.frames;
29514
29752
  const generic = buildGeneric(
29515
- spec,
29753
+ { name: `${spec.styleId}/${spec.assetId}`, style: spec.styleId, asset: spec.assetId },
29516
29754
  options.imageName,
29517
29755
  packed.atlas,
29518
29756
  frames,
@@ -29549,6 +29787,9 @@ function exportTileset(entry, spec, options) {
29549
29787
  "godot export does not yet map edge/side adjacency onto an isometric or oblique tile's diagonal peering bits safely; use --format generic or --format tiled"
29550
29788
  );
29551
29789
  }
29790
+ return renderTileset(generic, packed, spec.tileType, options);
29791
+ }
29792
+ function renderTileset(generic, packed, tileType, options) {
29552
29793
  if (options.format === "tiled") {
29553
29794
  return {
29554
29795
  png: packed.png,
@@ -29562,7 +29803,7 @@ function exportTileset(entry, spec, options) {
29562
29803
  return {
29563
29804
  png: packed.png,
29564
29805
  extension: ".ldtk",
29565
- document: buildLdtk(generic, spec.tileType),
29806
+ document: buildLdtk(generic, tileType),
29566
29807
  generic,
29567
29808
  sources: packed.sources
29568
29809
  };
@@ -29570,23 +29811,67 @@ function exportTileset(entry, spec, options) {
29570
29811
  return {
29571
29812
  png: packed.png,
29572
29813
  extension: ".tres",
29573
- document: buildGodot(generic, spec),
29814
+ document: buildGodot(generic, tileType),
29574
29815
  generic,
29575
29816
  sources: packed.sources
29576
29817
  };
29577
29818
  }
29578
- function buildGeneric(spec, imageName, atlas, frames, providerRules, rules) {
29819
+ function exportMergedTilesets(members, options) {
29820
+ const merged = mergeConnectedTerrain(members, options.manifestDir);
29821
+ const packed = packSprites(
29822
+ merged.tiles.map((tile) => ({ id: tile.id, path: tile.path })),
29823
+ { columns: options.columns, order: "input" }
29824
+ );
29825
+ if (packed.skipped.length) {
29826
+ throw new Error(
29827
+ `Cannot export ${merged.assets.join(" + ")}: ` + packed.skipped.map((item) => `${item.id}: ${item.reason}`).join("; ")
29828
+ );
29829
+ }
29830
+ const rules = {
29831
+ ruleType: "corner",
29832
+ arity: 4,
29833
+ terrains: merged.terrains,
29834
+ masks: {},
29835
+ corners: Object.fromEntries(merged.tiles.map((tile, index) => [index, tile.corners])),
29836
+ raw: merged.providerRules
29837
+ };
29838
+ const styleId = members[0].spec.styleId;
29839
+ const asset = merged.assets.join("+");
29840
+ const generic = buildGeneric(
29841
+ { name: `${styleId}/${asset}`, style: styleId, asset, sets: merged.assets },
29842
+ options.imageName,
29843
+ packed.atlas,
29844
+ packed.atlas.frames,
29845
+ merged.providerRules,
29846
+ rules,
29847
+ new Map(merged.tiles.map((tile, index) => [tile.id, index]))
29848
+ );
29849
+ if (options.format === "generic") {
29850
+ return {
29851
+ png: packed.png,
29852
+ extension: ".json",
29853
+ document: JSON.stringify(generic, null, 2) + "\n",
29854
+ generic,
29855
+ sources: packed.sources
29856
+ };
29857
+ }
29858
+ assertUniformTiles(generic);
29859
+ return renderTileset(generic, packed, merged.tileType, options);
29860
+ }
29861
+ function buildGeneric(identity2, imageName, atlas, frames, providerRules, rules, indexOf) {
29579
29862
  return {
29580
29863
  format: "pixelkiln-tileset",
29581
29864
  version: 1,
29582
- name: `${spec.styleId}/${spec.assetId}`,
29583
- style: spec.styleId,
29584
- asset: spec.assetId,
29865
+ name: identity2.name,
29866
+ style: identity2.style,
29867
+ asset: identity2.asset,
29868
+ ...identity2.sets ? { sets: identity2.sets } : {},
29585
29869
  image: imageName,
29586
29870
  tile: { ...atlas.cell },
29587
29871
  sheet: { ...atlas.sheet, columns: atlas.columns },
29588
29872
  tiles: frames.map((frame, index) => {
29589
- const sourceIndex = tileIndex(frame.id) ?? index;
29873
+ const sourceIndex = indexOf?.get(frame.id) ?? tileIndex(frame.id) ?? index;
29874
+ const corners = rules?.corners?.[sourceIndex];
29590
29875
  return {
29591
29876
  id: index,
29592
29877
  sourceIndex,
@@ -29596,7 +29881,8 @@ function buildGeneric(spec, imageName, atlas, frames, providerRules, rules) {
29596
29881
  width: frame.width,
29597
29882
  height: frame.height,
29598
29883
  ...rules?.masks[sourceIndex] !== void 0 ? { bitmask: rules.masks[sourceIndex] } : {},
29599
- stampOnly: rules ? rules.masks[sourceIndex] === void 0 : true
29884
+ ...corners ? { corners } : {},
29885
+ stampOnly: rules ? rules.masks[sourceIndex] === void 0 && !corners : true
29600
29886
  };
29601
29887
  }),
29602
29888
  providerRules,
@@ -29628,25 +29914,28 @@ function buildTiled(generic) {
29628
29914
  tile: representativeTile(generic, 0),
29629
29915
  colors: terrainNames.map((name, index) => ({
29630
29916
  name,
29631
- color: index === 0 ? "#5ab552" : "#4c78a8",
29917
+ color: terrainColor(index),
29632
29918
  tile: representativeTile(generic, index),
29633
29919
  probability: 1
29634
29920
  })),
29635
29921
  properties: rules.connectivity ? [{ name: "pixelkiln:connectivity", type: "string", value: rules.connectivity }] : [],
29636
- wangtiles: generic.tiles.filter((tile) => tile.bitmask !== void 0).map((tile) => ({ tileid: tile.id, wangid: tiledWangId(rules, tile.bitmask) }))
29922
+ wangtiles: generic.tiles.filter((tile) => tile.bitmask !== void 0 || tile.corners !== void 0).map((tile) => ({ tileid: tile.id, wangid: tiledWangId(rules, tile) }))
29637
29923
  }];
29638
29924
  return tiled;
29639
29925
  }
29640
- function tiledWangId(rules, mask) {
29641
- const bitColor = (bit) => (mask & 1 << bit) !== 0 ? 1 : 2;
29642
- if (rules.ruleType === "corner") {
29643
- return [0, bitColor(2), 0, bitColor(0), 0, bitColor(1), 0, bitColor(3)];
29926
+ function tiledWangId(rules, tile) {
29927
+ const corners = tileCorners(rules, tile);
29928
+ if (corners) {
29929
+ const [nw, ne, sw, se] = corners;
29930
+ return [0, ne + 1, 0, se + 1, 0, sw + 1, 0, nw + 1];
29644
29931
  }
29932
+ const mask = tile.bitmask;
29933
+ const bitColor = (bit) => (mask & 1 << bit) !== 0 ? 1 : 2;
29645
29934
  return [bitColor(0), 0, bitColor(1), 0, bitColor(2), 0, bitColor(3), 0];
29646
29935
  }
29647
- function buildGodot(generic, spec) {
29936
+ function buildGodot(generic, tileType) {
29648
29937
  const rules = generic.rules;
29649
- const shape = godotTileShape(spec.tileType ?? "isometric");
29938
+ const shape = godotTileShape(tileType ?? "isometric");
29650
29939
  const lines = [
29651
29940
  `[gd_resource type="TileSet" load_steps=3 format=3]`,
29652
29941
  "",
@@ -29660,8 +29949,8 @@ function buildGodot(generic, spec) {
29660
29949
  const x = tile.id % generic.sheet.columns;
29661
29950
  const y = Math.floor(tile.id / generic.sheet.columns);
29662
29951
  lines.push(`${x}:${y}/0 = 0`);
29663
- if (!rules || tile.bitmask === void 0 || rules.ruleType === "outline") continue;
29664
- const values = godotTerrainBits(rules, tile.bitmask, shape);
29952
+ if (!rules || tile.bitmask === void 0 && tile.corners === void 0 || rules.ruleType === "outline") continue;
29953
+ const values = godotTerrainBits(rules, tile, shape);
29665
29954
  lines.push(`${x}:${y}/0/terrain_set = 0`);
29666
29955
  lines.push(`${x}:${y}/0/terrain = ${dominantTerrain(values)}`);
29667
29956
  for (const [side, value] of Object.entries(values)) {
@@ -29675,32 +29964,23 @@ function buildGodot(generic, spec) {
29675
29964
  lines.push(`terrain_set_0/mode = ${rules.ruleType === "corner" ? 1 : 2}`);
29676
29965
  for (const [index, name] of terrainNamesFor(rules).entries()) {
29677
29966
  lines.push(`terrain_set_0/terrain_${index}/name = ${JSON.stringify(name)}`);
29678
- lines.push(
29679
- `terrain_set_0/terrain_${index}/color = ` + (index === 0 ? "Color(0.3529, 0.7098, 0.3216, 1)" : "Color(0.298, 0.4706, 0.6588, 1)")
29680
- );
29967
+ lines.push(`terrain_set_0/terrain_${index}/color = ${godotColor(terrainColor(index))}`);
29681
29968
  }
29682
29969
  }
29683
29970
  lines.push(`sources/0 = SubResource("TileSetAtlasSource_pixelkiln")`, "");
29684
29971
  return lines.join("\n");
29685
29972
  }
29686
- function godotTerrainBits(rules, mask, shape) {
29687
- const terrain = (bit) => (mask & 1 << bit) !== 0 ? 0 : 1;
29688
- if (rules.ruleType === "corner") {
29973
+ function godotTerrainBits(rules, tile, shape) {
29974
+ const corners = tileCorners(rules, tile);
29975
+ if (corners) {
29976
+ const [nw, ne, sw, se] = corners;
29689
29977
  if (shape === 1) {
29690
- return {
29691
- top_corner: terrain(3),
29692
- right_corner: terrain(2),
29693
- left_corner: terrain(1),
29694
- bottom_corner: terrain(0)
29695
- };
29978
+ return { top_corner: nw, right_corner: ne, left_corner: sw, bottom_corner: se };
29696
29979
  }
29697
- return {
29698
- top_left_corner: terrain(3),
29699
- top_right_corner: terrain(2),
29700
- bottom_left_corner: terrain(1),
29701
- bottom_right_corner: terrain(0)
29702
- };
29980
+ return { top_left_corner: nw, top_right_corner: ne, bottom_left_corner: sw, bottom_right_corner: se };
29703
29981
  }
29982
+ const mask = tile.bitmask;
29983
+ const terrain = (bit) => (mask & 1 << bit) !== 0 ? 0 : 1;
29704
29984
  return {
29705
29985
  top_side: terrain(0),
29706
29986
  right_side: terrain(1),
@@ -29709,8 +29989,17 @@ function godotTerrainBits(rules, mask, shape) {
29709
29989
  };
29710
29990
  }
29711
29991
  function dominantTerrain(values) {
29712
- const terrainZero = Object.values(values).filter((value) => value === 0).length;
29713
- return terrainZero * 2 >= Object.keys(values).length ? 0 : 1;
29992
+ const counts = /* @__PURE__ */ new Map();
29993
+ for (const value of Object.values(values)) counts.set(value, (counts.get(value) ?? 0) + 1);
29994
+ let best = 0;
29995
+ let bestCount = -1;
29996
+ for (const [terrain, count] of [...counts].sort(([a], [b]) => a - b)) {
29997
+ if (count > bestCount) {
29998
+ best = terrain;
29999
+ bestCount = count;
30000
+ }
30001
+ }
30002
+ return best;
29714
30003
  }
29715
30004
  function godotTileShape(tileType) {
29716
30005
  if (tileType === "isometric" || tileType === "oblique") return 1;
@@ -29719,13 +30008,21 @@ function godotTileShape(tileType) {
29719
30008
  }
29720
30009
  function representativeTile(generic, terrainIndex) {
29721
30010
  const rules = generic.rules;
30011
+ if (rules.ruleType === "corner") {
30012
+ return generic.tiles.find((tile) => tileCorners(rules, tile)?.every((corner) => corner === terrainIndex))?.id ?? -1;
30013
+ }
29722
30014
  const full = (1 << rules.arity) - 1;
29723
30015
  const wanted = terrainIndex === 0 ? full : 0;
29724
30016
  return generic.tiles.find((tile) => tile.bitmask === wanted)?.id ?? -1;
29725
30017
  }
29726
30018
  function terrainNamesFor(rules) {
30019
+ if (rules.terrains.length > 2) return rules.terrains;
29727
30020
  return [rules.terrains[0] ?? "feature", rules.terrains[1] ?? "background"];
29728
30021
  }
30022
+ function godotColor(hex2) {
30023
+ const channel = (at2) => Number((parseInt(hex2.slice(at2, at2 + 2), 16) / 255).toFixed(4));
30024
+ return `Color(${channel(1)}, ${channel(3)}, ${channel(5)}, 1)`;
30025
+ }
29729
30026
  function assertUniformTiles(generic) {
29730
30027
  const mismatched = generic.tiles.filter(
29731
30028
  (tile) => tile.width !== generic.tile.width || tile.height !== generic.tile.height
@@ -29736,11 +30033,11 @@ function assertUniformTiles(generic) {
29736
30033
  );
29737
30034
  }
29738
30035
  }
29739
- function tileIndex(key2) {
29740
- const match = key2.match(/(?:^|[_-])(\d+)$/);
30036
+ function tileIndex(key3) {
30037
+ const match = key3.match(/(?:^|[_-])(\d+)$/);
29741
30038
  return match ? Number(match[1]) : null;
29742
30039
  }
29743
- function isRecord2(value) {
30040
+ function isRecord3(value) {
29744
30041
  return typeof value === "object" && value !== null && !Array.isArray(value);
29745
30042
  }
29746
30043
 
@@ -30019,20 +30316,48 @@ async function runExport(args) {
30019
30316
  if (!selected.length) {
30020
30317
  throw new Error("No downloaded tiles/terrain entries match the requested --style/--only filters.");
30021
30318
  }
30022
- if (args.out && selected.length > 1) {
30319
+ if (args.out && selected.length > 1 && !args.mergeConnected) {
30320
+ throw new Error("--out can name one tileset only; add --style/--only to select one asset.");
30321
+ }
30322
+ const jobs = [];
30323
+ if (args.mergeConnected) {
30324
+ const terrainSpecs = (await resolveSpecs(loaded)).filter((spec) => spec.generator === "terrain");
30325
+ const taken = /* @__PURE__ */ new Set();
30326
+ for (const spec of selected) {
30327
+ if (taken.has(lockKey(spec.styleId, spec.assetId))) continue;
30328
+ const group = spec.generator === "terrain" ? connectedGroup(spec, terrainSpecs) : [spec];
30329
+ for (const member of group) taken.add(lockKey(member.styleId, member.assetId));
30330
+ const missing = group.filter((member) => !lock.entries[lockKey(member.styleId, member.assetId)]);
30331
+ if (missing.length) {
30332
+ throw new Error(
30333
+ `${spec.styleId}/${spec.assetId} is connected to ${missing.map((member) => member.assetId).join(", ")}, which has not been generated; run gen first, or export without --merge-connected`
30334
+ );
30335
+ }
30336
+ jobs.push(group);
30337
+ }
30338
+ } else {
30339
+ for (const spec of selected) jobs.push([spec]);
30340
+ }
30341
+ if (args.out && jobs.length > 1) {
30023
30342
  throw new Error("--out can name one tileset only; add --style/--only to select one asset.");
30024
30343
  }
30025
- for (const spec of selected) {
30026
- const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
30344
+ for (const group of jobs) {
30345
+ const spec = group[0];
30346
+ const merged = group.length > 1;
30027
30347
  const style = loaded.manifest.styles[spec.styleId];
30028
- const defaultBase = path53.resolve(manifestDir, style.outDir, `${spec.assetId}-tileset`);
30348
+ const assetName = group.map((member) => member.assetId).join("-");
30349
+ const defaultBase = path53.resolve(manifestDir, style.outDir, `${assetName}-tileset`);
30029
30350
  const base = args.out ? path53.resolve(args.out.replace(/\.(?:png|json|tsj|tres|ldtk)$/i, "")) : defaultBase;
30030
- const result = exportTileset(entry, spec, {
30351
+ const exportOptions = {
30031
30352
  format,
30032
30353
  manifestDir,
30033
30354
  imageName: path53.basename(`${base}.png`),
30034
30355
  columns: args.columns
30035
- });
30356
+ };
30357
+ const result = merged ? exportMergedTilesets(
30358
+ group.map((member) => ({ spec: member, entry: lock.entries[lockKey(member.styleId, member.assetId)] })),
30359
+ exportOptions
30360
+ ) : exportTileset(lock.entries[lockKey(spec.styleId, spec.assetId)], spec, exportOptions);
30036
30361
  const outputs = [
30037
30362
  { path: `${base}.png`, data: result.png },
30038
30363
  { path: `${base}${result.extension}`, data: result.document }
@@ -30045,17 +30370,18 @@ async function runExport(args) {
30045
30370
  ...result.sources
30046
30371
  ],
30047
30372
  options: {
30048
- asset: spec.assetId,
30373
+ asset: result.generic.asset,
30049
30374
  columns: args.columns ?? null,
30050
30375
  format,
30051
30376
  image: path53.basename(`${base}.png`),
30052
30377
  providerRules: result.generic.providerRules,
30378
+ ...merged ? { sets: result.generic.sets } : {},
30053
30379
  style: spec.styleId,
30054
30380
  tileType: spec.tileType ?? null
30055
30381
  }
30056
30382
  }, { force: args.force });
30057
30383
  log(
30058
- ` ${spec.styleId}/${spec.assetId}: ${result.generic.tiles.length} tile(s), ${result.generic.sheet.width}x${result.generic.sheet.height} (${format})`
30384
+ ` ${spec.styleId}/${merged ? group.map((member) => member.assetId).join(" + ") : spec.assetId}: ${result.generic.tiles.length} tile(s), ` + (merged ? `${result.generic.rules.terrains.length} terrains (${result.generic.rules.terrains.join(", ")}), ` : "") + `${result.generic.sheet.width}x${result.generic.sheet.height} (${format})`
30059
30385
  );
30060
30386
  log(
30061
30387
  ` ${path53.relative(process.cwd(), base)}.png + ${path53.basename(base)}${result.extension} + .pixelkiln.json`
@@ -30254,7 +30580,7 @@ function listCodexEffects(lib) {
30254
30580
  ...entry,
30255
30581
  loopSeconds: def.loop,
30256
30582
  params: Object.fromEntries(
30257
- Object.entries(def.params ?? {}).map(([key2, param]) => [key2, { label: param.en ?? key2, min: param.min, max: param.max, value: param.value }])
30583
+ Object.entries(def.params ?? {}).map(([key3, param]) => [key3, { label: param.en ?? key3, min: param.min, max: param.max, value: param.value }])
30258
30584
  )
30259
30585
  };
30260
30586
  });
@@ -30295,19 +30621,19 @@ function checkCodexRecipe(lib, recipe) {
30295
30621
  if (hue !== void 0 && (typeof hue !== "number" || !Number.isFinite(hue) || hue < -360 || hue > 360)) {
30296
30622
  throw new UsageError(`codex hue is degrees from -360 to 360, got ${JSON.stringify(hue)}`);
30297
30623
  }
30298
- for (const [key2, value] of Object.entries(params)) {
30299
- const param = info.params[key2];
30624
+ for (const [key3, value] of Object.entries(params)) {
30625
+ const param = info.params[key3];
30300
30626
  if (!param) {
30301
30627
  const known = Object.keys(info.params);
30302
- throw new UsageError(`${recipe.effect} has no parameter "${key2}"${known.length ? `; it has ${known.join(", ")}` : " (it takes none)"}`);
30628
+ throw new UsageError(`${recipe.effect} has no parameter "${key3}"${known.length ? `; it has ${known.join(", ")}` : " (it takes none)"}`);
30303
30629
  }
30304
30630
  if (typeof value !== "number" || !Number.isFinite(value) || value < param.min || value > param.max) {
30305
- throw new UsageError(`${recipe.effect} ${key2} is a number from ${param.min} to ${param.max}, got ${JSON.stringify(value)}`);
30631
+ throw new UsageError(`${recipe.effect} ${key3} is a number from ${param.min} to ${param.max}, got ${JSON.stringify(value)}`);
30306
30632
  }
30307
30633
  }
30308
- for (const [key2, value] of Object.entries(tune)) {
30309
- if (!CODEX_TUNE_KEYS.includes(key2)) throw new UsageError(`unknown tune knob "${key2}"; they are ${CODEX_TUNE_KEYS.join(", ")}`);
30310
- if (typeof value !== "number" || !Number.isFinite(value)) throw new UsageError(`tune ${key2} is a number, got ${JSON.stringify(value)}`);
30634
+ for (const [key3, value] of Object.entries(tune)) {
30635
+ if (!CODEX_TUNE_KEYS.includes(key3)) throw new UsageError(`unknown tune knob "${key3}"; they are ${CODEX_TUNE_KEYS.join(", ")}`);
30636
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new UsageError(`tune ${key3} is a number, got ${JSON.stringify(value)}`);
30311
30637
  }
30312
30638
  return info;
30313
30639
  }
@@ -30393,12 +30719,12 @@ async function readCodexRecipe(file, opts = {}) {
30393
30719
  }
30394
30720
  const recipe = { effect: raw.effect };
30395
30721
  if (raw.camera !== void 0) recipe.camera = raw.camera;
30396
- for (const key2 of ["fps", "margin", "hue"]) if (raw[key2] !== void 0) recipe[key2] = raw[key2];
30397
- for (const key2 of ["params", "tune"]) {
30398
- const value = raw[key2];
30722
+ for (const key3 of ["fps", "margin", "hue"]) if (raw[key3] !== void 0) recipe[key3] = raw[key3];
30723
+ for (const key3 of ["params", "tune"]) {
30724
+ const value = raw[key3];
30399
30725
  if (value === void 0) continue;
30400
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${file}: a codex recipe's ${key2} is an object`);
30401
- recipe[key2] = value;
30726
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${file}: a codex recipe's ${key3} is an object`);
30727
+ recipe[key3] = value;
30402
30728
  }
30403
30729
  const library = record ? parsed.library : void 0;
30404
30730
  return {
@@ -30874,12 +31200,12 @@ function pixelfxOnly(args) {
30874
31200
  function numberPairs(flag, pairs) {
30875
31201
  const out = {};
30876
31202
  for (const pair of pairs) {
30877
- const [key2, raw, ...rest] = pair.split("=");
31203
+ const [key3, raw, ...rest] = pair.split("=");
30878
31204
  const value = Number(raw);
30879
- if (!key2 || raw === void 0 || rest.length || raw.trim() === "" || !Number.isFinite(value)) {
31205
+ if (!key3 || raw === void 0 || rest.length || raw.trim() === "" || !Number.isFinite(value)) {
30880
31206
  throw new UsageError(`${flag} takes name=number, got "${pair}"`);
30881
31207
  }
30882
- out[key2] = value;
31208
+ out[key3] = value;
30883
31209
  }
30884
31210
  return out;
30885
31211
  }
@@ -32006,7 +32332,7 @@ function tilesetSheetReadings(width, height) {
32006
32332
  }
32007
32333
  function chooseTilesetSheetReading(file, width, height, tileSize) {
32008
32334
  const readings = tilesetSheetReadings(width, height);
32009
- const describe = (reading) => `${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"})`;
32335
+ const describe2 = (reading) => `${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"})`;
32010
32336
  if (readings.length === 0) {
32011
32337
  throw new Error(
32012
32338
  `${file} is ${width}x${height}, not a PixelLab tileset sheet: it takes a square sheet 4 or 8 tiles wide (or twice as tall, for a set with transitions) of 16, 24, 32, 48 or 64px tiles`
@@ -32015,13 +32341,13 @@ function chooseTilesetSheetReading(file, width, height, tileSize) {
32015
32341
  if (tileSize === void 0) {
32016
32342
  if (readings.length > 1) {
32017
32343
  throw new Error(
32018
- `${file} is ${width}x${height}, which reads as ${readings.map(describe).join(" or ")}; say which with --size ${readings.map((reading) => reading.tileSize).join(" or --size ")}`
32344
+ `${file} is ${width}x${height}, which reads as ${readings.map(describe2).join(" or ")}; say which with --size ${readings.map((reading) => reading.tileSize).join(" or --size ")}`
32019
32345
  );
32020
32346
  }
32021
32347
  return readings[0];
32022
32348
  }
32023
32349
  const chosen = readings.find((reading) => reading.tileSize === tileSize);
32024
- if (!chosen) throw new Error(`${file} is ${width}x${height}, which holds ${readings.map(describe).join(" or ")}, not ${tileSize}px tiles`);
32350
+ if (!chosen) throw new Error(`${file} is ${width}x${height}, which holds ${readings.map(describe2).join(" or ")}, not ${tileSize}px tiles`);
32025
32351
  return chosen;
32026
32352
  }
32027
32353
  function readPng(bytes, file) {
@@ -32847,8 +33173,8 @@ function measureDecodedImageQuality(png, digest2) {
32847
33173
  const index = offset / 4;
32848
33174
  const x = index % png.width;
32849
33175
  const y = Math.floor(index / png.width);
32850
- const key2 = pixelKey(png.pixels, offset);
32851
- const hasSameNeighbor = x > 0 && pixelKey(png.pixels, offset - 4) === key2 || x + 1 < png.width && pixelKey(png.pixels, offset + 4) === key2 || y > 0 && pixelKey(png.pixels, offset - png.width * 4) === key2 || y + 1 < png.height && pixelKey(png.pixels, offset + png.width * 4) === key2;
33176
+ const key3 = pixelKey(png.pixels, offset);
33177
+ const hasSameNeighbor = x > 0 && pixelKey(png.pixels, offset - 4) === key3 || x + 1 < png.width && pixelKey(png.pixels, offset + 4) === key3 || y > 0 && pixelKey(png.pixels, offset - png.width * 4) === key3 || y + 1 < png.height && pixelKey(png.pixels, offset + png.width * 4) === key3;
32852
33178
  if (!hasSameNeighbor) {
32853
33179
  isolated++;
32854
33180
  }
@@ -33436,9 +33762,9 @@ function canonical3(value) {
33436
33762
  if (Array.isArray(value)) return value.map(canonical3);
33437
33763
  if (typeof value === "object") {
33438
33764
  const sorted = {};
33439
- for (const key2 of Object.keys(value).sort()) {
33440
- const item = value[key2];
33441
- if (item !== void 0) sorted[key2] = canonical3(item);
33765
+ for (const key3 of Object.keys(value).sort()) {
33766
+ const item = value[key3];
33767
+ if (item !== void 0) sorted[key3] = canonical3(item);
33442
33768
  }
33443
33769
  return sorted;
33444
33770
  }
@@ -33577,7 +33903,7 @@ function renderStyle(style, destination, cwd) {
33577
33903
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
33578
33904
  if (Array.isArray(value)) return value.map(replace);
33579
33905
  if (value && typeof value === "object") {
33580
- return Object.fromEntries(Object.entries(value).map(([key2, item]) => [key2, replace(item)]));
33906
+ return Object.fromEntries(Object.entries(value).map(([key3, item]) => [key3, replace(item)]));
33581
33907
  }
33582
33908
  return value;
33583
33909
  };
@@ -33905,8 +34231,8 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
33905
34231
  `${label} is a held item, placed rather than drawn; move it with attach or a place override in its anchors file` + (layer.attach.grasp ? ", or generate its grip again with gen --force" : "")
33906
34232
  );
33907
34233
  }
33908
- const key2 = lockKey(spec.styleId, spec.assetId);
33909
- const entry = lock.entries[key2];
34234
+ const key3 = lockKey(spec.styleId, spec.assetId);
34235
+ const entry = lock.entries[key3];
33910
34236
  if (!entry || entry.status !== "downloaded" || !entry.outputs.length) throw new Error(`${label} has no downloaded frames to redraw; generate it first`);
33911
34237
  if (entry.specHash !== spec.specHash) throw new Error(`${label} changed in the manifest since it was generated; generate it again instead of redrawing a frame`);
33912
34238
  const sourceIds = layer.sources.map((source) => source.assetId);
@@ -34013,7 +34339,7 @@ async function redrawLayerFrames(spec, lock, painter, opts) {
34013
34339
  const { raw: _raw, ...kept } = outputs[at2];
34014
34340
  outputs[at2] = { ...kept, sha256: sha256(processed.bytes), ...processed.changed ? { raw: sha256(raw) } : {} };
34015
34341
  }
34016
- upsert(lock, key2, {
34342
+ upsert(lock, key3, {
34017
34343
  outputs,
34018
34344
  cost: entry.cost + cost,
34019
34345
  billed: result.billed ? { amount: (entry.billed?.unit === result.billed.unit ? entry.billed.amount : 0) + result.billed.amount, unit: result.billed.unit } : entry.billed