pixelkiln 0.96.1 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ ASSET_KINDS: () => ASSET_KINDS,
33
34
  AssetBatchSchema: () => AssetBatchSchema,
34
35
  AssetDeriveSchema: () => AssetDeriveSchema,
35
36
  AssetExternalSchema: () => AssetExternalSchema,
@@ -56,6 +57,10 @@ __export(index_exports, {
56
57
  EDITOR_PIN: () => EDITOR_PIN,
57
58
  EDITOR_RELEASE_BASE: () => EDITOR_RELEASE_BASE,
58
59
  EXIT_CODES: () => EXIT_CODES,
60
+ EXPAND_DIRECTIONS: () => EXPAND_DIRECTIONS,
61
+ EXPAND_MAX_COST: () => EXPAND_MAX_COST,
62
+ EXPAND_MIN_COST: () => EXPAND_MIN_COST,
63
+ EXPORT_FORMATS: () => EXPORT_FORMATS,
59
64
  EditorInstallError: () => EditorInstallError,
60
65
  FAKE_PNG: () => FAKE_PNG,
61
66
  FONT_COST_GENERATIONS: () => FONT_COST_GENERATIONS,
@@ -70,6 +75,7 @@ __export(index_exports, {
70
75
  HAND_EDIT_DIR: () => HAND_EDIT_DIR,
71
76
  HISTORY_ENV: () => HISTORY_ENV,
72
77
  HandEditCompanionSchema: () => HandEditCompanionSchema,
78
+ IMPORT_MAX_SIDE: () => IMPORT_MAX_SIDE,
73
79
  ImageQualityMetricsSchema: () => ImageQualityMetricsSchema,
74
80
  InheritedStyleSchema: () => InheritedStyleSchema,
75
81
  LockEntrySchema: () => LockEntrySchema,
@@ -82,6 +88,14 @@ __export(index_exports, {
82
88
  MAX_RETRIES: () => MAX_RETRIES,
83
89
  MEMBER_SET_REVISION_MODES: () => MEMBER_SET_REVISION_MODES,
84
90
  MIRRORED_DIRECTION: () => MIRRORED_DIRECTION,
91
+ MIRROR_DIRECTIONS: () => MIRROR_DIRECTIONS,
92
+ MUSIC_COST_GENERATIONS: () => MUSIC_COST_GENERATIONS,
93
+ MUSIC_LOOP_COST_GENERATIONS: () => MUSIC_LOOP_COST_GENERATIONS,
94
+ MUSIC_LOOP_MIN_BODY_SECONDS: () => MUSIC_LOOP_MIN_BODY_SECONDS,
95
+ MUSIC_MAX_BPM: () => MUSIC_MAX_BPM,
96
+ MUSIC_MAX_SECONDS: () => MUSIC_MAX_SECONDS,
97
+ MUSIC_MIN_BPM: () => MUSIC_MIN_BPM,
98
+ MUSIC_MIN_SECONDS: () => MUSIC_MIN_SECONDS,
85
99
  ManifestDriftError: () => ManifestDriftError,
86
100
  ManifestEditError: () => ManifestEditError,
87
101
  ManifestEditSchema: () => ManifestEditSchema,
@@ -99,6 +113,7 @@ __export(index_exports, {
99
113
  OverwriteRefusedError: () => OverwriteRefusedError,
100
114
  PIXELATE_COST_GENERATIONS: () => PIXELATE_COST_GENERATIONS,
101
115
  PIXELATE_MAX_SIDE: () => PIXELATE_MAX_SIDE,
116
+ PIXELATE_PRO_COST_GENERATIONS: () => PIXELATE_PRO_COST_GENERATIONS,
102
117
  PIXELLAB_MCP_URL: () => PIXELLAB_MCP_URL,
103
118
  PIXEL_ART_FIXER_REVISION: () => PIXEL_ART_FIXER_REVISION,
104
119
  PIXEL_ART_FIXER_URL: () => PIXEL_ART_FIXER_URL,
@@ -119,6 +134,8 @@ __export(index_exports, {
119
134
  RevisionDitheringSchema: () => RevisionDitheringSchema,
120
135
  RevisionModeSchema: () => RevisionModeSchema,
121
136
  RevisionSchema: () => RevisionSchema,
137
+ SFX_MAX_SECONDS: () => SFX_MAX_SECONDS,
138
+ SFX_MIN_SECONDS: () => SFX_MIN_SECONDS,
122
139
  SHEET_FORMATS: () => SHEET_FORMATS,
123
140
  ScenarioProvider: () => ScenarioProvider,
124
141
  StyleInputSchema: () => StyleInputSchema,
@@ -127,6 +144,10 @@ __export(index_exports, {
127
144
  TerrainConnectSchema: () => TerrainConnectSchema,
128
145
  TerrainLinkSchema: () => TerrainLinkSchema,
129
146
  TerrainSideSchema: () => TerrainSideSchema,
147
+ UI_STATES_COSTS: () => UI_STATES_COSTS,
148
+ UI_STATES_MAX_COST: () => UI_STATES_MAX_COST,
149
+ UI_STATES_MAX_ELEMENTS: () => UI_STATES_MAX_ELEMENTS,
150
+ UI_STATES_MAX_STATES: () => UI_STATES_MAX_STATES,
130
151
  UNZOOM_MAX_AREA: () => UNZOOM_MAX_AREA,
131
152
  UNZOOM_MIN_SIDE: () => UNZOOM_MIN_SIDE,
132
153
  UiElementSchema: () => UiElementSchema,
@@ -156,8 +177,10 @@ __export(index_exports, {
156
177
  cacheFileName: () => cacheFileName,
157
178
  candidateCount: () => candidateCount,
158
179
  characterDirections: () => characterDirections,
180
+ checkExportBytes: () => checkExportBytes,
159
181
  checkQualityBaseline: () => checkQualityBaseline,
160
182
  checkQualityRecord: () => checkQualityRecord,
183
+ checkUiInsets: () => checkUiInsets,
161
184
  clientFromEnv: () => clientFromEnv,
162
185
  colorDistance: () => colorDistance,
163
186
  countNumberedDescriptions: () => countNumberedDescriptions,
@@ -166,6 +189,7 @@ __export(index_exports, {
166
189
  createGalleryEditorHandlers: () => createGalleryEditorHandlers,
167
190
  createGenerateHandlers: () => createGenerateHandlers,
168
191
  createProvider: () => createProvider,
192
+ createUiStates: () => createUiStates,
169
193
  currentEntryOutputPath: () => currentEntryOutputPath,
170
194
  currentOutputPath: () => currentOutputPath,
171
195
  defaultNormalMapOut: () => defaultNormalMapOut,
@@ -174,6 +198,7 @@ __export(index_exports, {
174
198
  defaultUnzoomOut: () => defaultUnzoomOut,
175
199
  describeVfx: () => describeVfx,
176
200
  detachHandEdit: () => detachHandEdit,
201
+ detectAudioFormat: () => detectAudioFormat,
177
202
  detectMediaType: () => detectMediaType,
178
203
  doctor: () => doctor,
179
204
  editorBaseUrl: () => editorBaseUrl,
@@ -184,7 +209,10 @@ __export(index_exports, {
184
209
  errorCode: () => errorCode,
185
210
  evaluateAudit: () => evaluateAudit,
186
211
  exitCodeFor: () => exitCodeFor,
212
+ expandObject: () => expandObject,
187
213
  expectedOutputPath: () => expectedOutputPath,
214
+ exportAssetFile: () => exportAssetFile,
215
+ exportOutPath: () => exportOutPath,
188
216
  exportTileset: () => exportTileset,
189
217
  fallbackOutputRole: () => fallbackOutputRole,
190
218
  fetchAssets: () => fetchAssets,
@@ -198,6 +226,8 @@ __export(index_exports, {
198
226
  galleryMediaId: () => galleryMediaId,
199
227
  galleryMediaRoute: () => galleryMediaRoute,
200
228
  generateFont: () => generateFont,
229
+ generateMusic: () => generateMusic,
230
+ generateSoundEffect: () => generateSoundEffect,
201
231
  generationCost: () => generationCost,
202
232
  groupOrphansByStyle: () => groupOrphansByStyle,
203
233
  handEditBase: () => handEditBase,
@@ -212,6 +242,7 @@ __export(index_exports, {
212
242
  idFromPrompt: () => idFromPrompt,
213
243
  imageMetadata: () => imageMetadata,
214
244
  importLocal: () => importLocal,
245
+ importObjectFile: () => importObjectFile,
215
246
  inspectCaches: () => inspectCaches,
216
247
  inspectQualityProfile: () => inspectQualityProfile,
217
248
  inspectRevisionReadiness: () => inspectRevisionReadiness,
@@ -243,6 +274,8 @@ __export(index_exports, {
243
274
  mergePalettes: () => mergePalettes,
244
275
  mountSprites: () => mountSprites,
245
276
  mountStyle: () => mountStyle,
277
+ musicCost: () => musicCost,
278
+ musicOutputPaths: () => musicOutputPaths,
246
279
  normalMapFile: () => normalMapFile,
247
280
  normalMapResultPng: () => normalMapResultPng,
248
281
  normalMapSizeProblem: () => normalMapSizeProblem,
@@ -259,10 +292,14 @@ __export(index_exports, {
259
292
  packStyle: () => packStyle,
260
293
  paletteDistance: () => paletteDistance,
261
294
  parentAssetId: () => parentAssetId,
295
+ parseCanvasSize: () => parseCanvasSize,
262
296
  parseLock: () => parseLock,
263
297
  parseMcpBody: () => parseMcpBody,
264
298
  parseProFlashQuote: () => parseProFlashQuote,
265
299
  parseTerrainDescriptions: () => parseTerrainDescriptions,
300
+ parseUiBox: () => parseUiBox,
301
+ parseUiInsets: () => parseUiInsets,
302
+ parseUiState: () => parseUiState,
266
303
  parseVfxArtistResult: () => parseVfxArtistResult,
267
304
  parseVfxExport: () => parseVfxExport,
268
305
  parseVfxRecipe: () => parseVfxRecipe,
@@ -280,6 +317,8 @@ __export(index_exports, {
280
317
  proportionsPayload: () => proportionsPayload,
281
318
  providerCredentialEnvs: () => providerCredentialEnvs,
282
319
  providerFactory: () => providerFactory,
320
+ pullExpansionReview: () => pullExpansionReview,
321
+ pullUiAsset: () => pullUiAsset,
283
322
  pushTags: () => pushTags,
284
323
  qualityFrameOutputPath: () => qualityFrameOutputPath,
285
324
  qualityRecordPath: () => qualityRecordPath,
@@ -345,6 +384,8 @@ __export(index_exports, {
345
384
  slugify: () => slugify,
346
385
  snapshotQualityBaseline: () => snapshotQualityBaseline,
347
386
  snapshotQualityCases: () => snapshotQualityCases,
387
+ soundEffectCost: () => soundEffectCost,
388
+ soundEffectOutputPaths: () => soundEffectOutputPaths,
348
389
  sourceIsStem: () => sourceIsStem,
349
390
  sourceOutputPath: () => sourceOutputPath,
350
391
  specHash: () => specHash,
@@ -364,8 +405,10 @@ __export(index_exports, {
364
405
  toPortablePath: () => toPortablePath,
365
406
  totalSpend: () => totalSpend,
366
407
  uiElementCandidateCount: () => uiElementCandidateCount,
408
+ uiStateElements: () => uiStateElements,
367
409
  unzoomFile: () => unzoomFile,
368
410
  upsert: () => upsert,
411
+ validateAudio: () => validateAudio,
369
412
  validateCostEstimate: () => validateCostEstimate,
370
413
  validateMedia: () => validateMedia,
371
414
  validateWorkspace: () => validateWorkspace,
@@ -492,7 +535,7 @@ function terrainTileCount(transitionSize, mode2, orientation) {
492
535
  return transitionSize === 1 ? 25 : 16;
493
536
  }
494
537
  function terrainCost(mode2, tileSize, orientation) {
495
- if (orientation === "sidescroller") return 3;
538
+ if (orientation === "sidescroller") return mode2 === "pro" ? 15 : 1;
496
539
  if (mode2 === "pro") return tileSize <= 32 ? 15 : 25;
497
540
  return 4;
498
541
  }
@@ -1280,6 +1323,48 @@ var StyleObjectSchema = import_zod.z.object({
1280
1323
  * lower terrain between them.
1281
1324
  */
1282
1325
  terrainConnectDiagonals: import_zod.z.boolean().optional(),
1326
+ /**
1327
+ * `terrain` generator only, standard mode, top-down. Which ragged border
1328
+ * `terrainRaggedness` draws, 0 to 99 (the website's Reshuffle): another
1329
+ * number gives a different boundary at the same raggedness. API default 0.
1330
+ */
1331
+ terrainShapeSeed: import_zod.z.number().int().min(0).max(99).optional(),
1332
+ /**
1333
+ * `terrain` generator only, standard mode, top-down, with
1334
+ * `terrainTransitionSize` above 0. How thick the wall reads on the top
1335
+ * rim and down both sides of the front face, 0 to 1. The website starts
1336
+ * at 0.1.
1337
+ */
1338
+ terrainSideWallThickness: import_zod.z.number().min(0).max(1).optional(),
1339
+ /**
1340
+ * `terrain` generator only, standard mode, top-down, with
1341
+ * `terrainTransitionSize` above 0. Which side of the border the wall sits
1342
+ * on: 0 sticks out past the terrain (the API default), 1 is carved into
1343
+ * it so the shape stays put. The website starts at 0.5.
1344
+ */
1345
+ terrainSideWallPlacement: import_zod.z.number().min(0).max(1).optional(),
1346
+ /**
1347
+ * `terrain` generator only, standard mode. PixelLab rewrites the terrain
1348
+ * descriptions and picks base colors before drawing unless this is
1349
+ * false. On by default upstream; set false to have your wording used as
1350
+ * written.
1351
+ */
1352
+ terrainEnhance: import_zod.z.boolean().optional(),
1353
+ /**
1354
+ * `terrain` generator only, a standard sidescroller set. How thick the
1355
+ * platform body is, 0 thin to 1 thick. Left out, PixelLab fits it to
1356
+ * `terrainTransitionSize`.
1357
+ */
1358
+ terrainPlatformThickness: import_zod.z.number().min(0).max(1).optional(),
1359
+ /**
1360
+ * `terrain` generator only, top-down. Whether each terrain can be walked
1361
+ * on, stored with the set for PixelLab's maps and engine exports (left
1362
+ * out, those guess from the terrain's name). They change no pixel, so
1363
+ * they are sent when the set is generated and are not part of its
1364
+ * identity: changing one later does not make the set stale.
1365
+ */
1366
+ terrainLowerWalkable: import_zod.z.boolean().optional(),
1367
+ terrainUpperWalkable: import_zod.z.boolean().optional(),
1283
1368
  /**
1284
1369
  * `terrain` generator only. Visual height of the step between lower and
1285
1370
  * upper terrain. Without `terrainShapeStyle`, only 0, 0.25, 0.5, or 1 are
@@ -1517,7 +1602,7 @@ var AssetDeriveSchema = import_zod.z.object({
1517
1602
  /** scale: `nearest` (default) keeps hard edges; `box` averages the covered pixels. */
1518
1603
  mode: import_zod.z.enum(["nearest", "box"]).optional()
1519
1604
  }).strict().superRefine((derive, context) => {
1520
- const issue = (message6, path43) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path43] });
1605
+ const issue = (message6, path46) => context.addIssue({ code: import_zod.z.ZodIssueCode.custom, message: message6, path: [path46] });
1521
1606
  if (Boolean(derive.from) === Boolean(derive.file)) {
1522
1607
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
1523
1608
  }
@@ -1672,6 +1757,18 @@ var AssetSchema = import_zod.z.object({
1672
1757
  * (a sword hand, a parted fringe) comes out the other way round.
1673
1758
  */
1674
1759
  mirror: import_zod.z.string().min(1).optional(),
1760
+ /**
1761
+ * `terrain` styles only: a PNG per terrain for PixelLab to take that
1762
+ * terrain's look from, paths relative to the manifest. Top-down sets
1763
+ * take `lower`, `upper` and `transition`. A sidescroller set takes
1764
+ * `lower` (the platform body, pro mode) or `transition` (the surface
1765
+ * layer, standard mode), each a square PNG of the tile size.
1766
+ */
1767
+ terrainReferences: import_zod.z.object({
1768
+ lower: import_zod.z.string().min(1).optional(),
1769
+ upper: import_zod.z.string().min(1).optional(),
1770
+ transition: import_zod.z.string().min(1).optional()
1771
+ }).strict().optional(),
1675
1772
  /** Made from existing pixels by a local transform; see AssetDeriveSchema. Free; the provider is never called. */
1676
1773
  derive: AssetDeriveSchema.optional(),
1677
1774
  /** Built by a tool outside pixelkiln; see AssetExternalSchema. Never generated. */
@@ -2358,6 +2455,69 @@ var UiAssetGetSchema = import_zod3.z.object({
2358
2455
  progress_percent: import_zod3.z.number().nullable().optional(),
2359
2456
  eta_seconds: import_zod3.z.number().nullable().optional()
2360
2457
  }).passthrough();
2458
+ var CanvasChangeSchema = import_zod3.z.object({
2459
+ id: import_zod3.z.string(),
2460
+ previous: import_zod3.z.object({ width: import_zod3.z.number(), height: import_zod3.z.number() }).passthrough(),
2461
+ canvas: import_zod3.z.object({ width: import_zod3.z.number(), height: import_zod3.z.number() }).passthrough(),
2462
+ rotations_moved: import_zod3.z.number().int().default(0),
2463
+ placements_moved: import_zod3.z.number().int().nullable().optional()
2464
+ }).passthrough();
2465
+ var MirrorAnimationSchema = import_zod3.z.object({
2466
+ animation_group_id: import_zod3.z.string(),
2467
+ source_direction: import_zod3.z.string(),
2468
+ target_direction: import_zod3.z.string(),
2469
+ frames_created: import_zod3.z.number().int()
2470
+ }).passthrough();
2471
+ var ImportObjectSchema = import_zod3.z.object({
2472
+ object_id: import_zod3.z.string().min(1),
2473
+ name: import_zod3.z.string().nullable().optional(),
2474
+ size: import_zod3.z.object({ width: import_zod3.z.number(), height: import_zod3.z.number() }).passthrough(),
2475
+ image_url: import_zod3.z.string()
2476
+ }).passthrough();
2477
+ var ExpandRotationsSchema = import_zod3.z.object({
2478
+ object_id: import_zod3.z.string().min(1),
2479
+ background_job_id: import_zod3.z.string().min(1),
2480
+ status: import_zod3.z.string().default("expanding"),
2481
+ min_generations: import_zod3.z.number(),
2482
+ max_generations: import_zod3.z.number()
2483
+ }).passthrough();
2484
+ var UiNineSliceSchema = import_zod3.z.object({ left: import_zod3.z.number().int(), right: import_zod3.z.number().int(), top: import_zod3.z.number().int(), bottom: import_zod3.z.number().int() }).passthrough();
2485
+ var UiSplitBoxSchema = import_zod3.z.object({ label: import_zod3.z.string().default(""), x: import_zod3.z.number().int(), y: import_zod3.z.number().int(), width: import_zod3.z.number().int(), height: import_zod3.z.number().int() }).passthrough();
2486
+ var UiSizeSchema = import_zod3.z.object({ width: import_zod3.z.number().int(), height: import_zod3.z.number().int() }).passthrough();
2487
+ var UiStatePartSchema = import_zod3.z.object({
2488
+ id: import_zod3.z.string().min(1),
2489
+ name: import_zod3.z.string().nullable().optional(),
2490
+ kind: import_zod3.z.string().default("state"),
2491
+ size: UiSizeSchema,
2492
+ image_url: import_zod3.z.string(),
2493
+ nine_slice: UiNineSliceSchema.nullable().optional()
2494
+ }).passthrough();
2495
+ var UiElementPartSchema = UiStatePartSchema.extend({
2496
+ template_box: UiSplitBoxSchema.nullable().optional(),
2497
+ states: import_zod3.z.array(UiStatePartSchema).default([])
2498
+ }).passthrough();
2499
+ var UiAssetDetailSchema = import_zod3.z.object({
2500
+ id: import_zod3.z.string().min(1),
2501
+ name: import_zod3.z.string().nullable().optional(),
2502
+ prompt: import_zod3.z.string().default(""),
2503
+ size: UiSizeSchema,
2504
+ image_url: import_zod3.z.string().nullable().optional(),
2505
+ status: import_zod3.z.string().nullable().optional(),
2506
+ kind: import_zod3.z.string().nullable().optional(),
2507
+ template_id: import_zod3.z.string().nullable().optional(),
2508
+ parent_id: import_zod3.z.string().nullable().optional(),
2509
+ nine_slice: UiNineSliceSchema.nullable().optional(),
2510
+ elements: import_zod3.z.array(UiElementPartSchema).default([]),
2511
+ states: import_zod3.z.array(UiStatePartSchema).default([]),
2512
+ split_preview: import_zod3.z.array(UiSplitBoxSchema).default([])
2513
+ }).passthrough();
2514
+ var UiSplitResponseSchema = import_zod3.z.object({ elements: import_zod3.z.array(UiElementPartSchema) }).passthrough();
2515
+ var UiStatesSubmitSchema = import_zod3.z.object({
2516
+ background_job_id: import_zod3.z.string().min(1),
2517
+ status: import_zod3.z.string().default("processing"),
2518
+ generations: import_zod3.z.number(),
2519
+ count: import_zod3.z.number().int()
2520
+ }).passthrough();
2361
2521
  var RevisionJobSubmitSchema = import_zod3.z.object({
2362
2522
  background_job_id: import_zod3.z.string().min(1),
2363
2523
  status: import_zod3.z.string().default("processing")
@@ -2444,6 +2604,48 @@ var FontJobSchema = import_zod3.z.object({
2444
2604
  download_ttf_url: import_zod3.z.string().nullable().optional(),
2445
2605
  usage: import_zod3.z.unknown().optional()
2446
2606
  }).passthrough();
2607
+ var SongSchema = import_zod3.z.object({
2608
+ id: import_zod3.z.string().min(1),
2609
+ status: import_zod3.z.string(),
2610
+ error: import_zod3.z.string().nullable().optional(),
2611
+ name: import_zod3.z.string().default(""),
2612
+ audio_url: import_zod3.z.string().nullable().optional(),
2613
+ duration_ms: import_zod3.z.number().nullable().optional(),
2614
+ style: import_zod3.z.string().default(""),
2615
+ instrumental: import_zod3.z.boolean().default(true),
2616
+ lyrics: import_zod3.z.string().default(""),
2617
+ take: import_zod3.z.number().int().default(1),
2618
+ request_id: import_zod3.z.string().optional(),
2619
+ loop_of: import_zod3.z.string().nullable().optional(),
2620
+ loop_start_s: import_zod3.z.number().nullable().optional(),
2621
+ loop_end_s: import_zod3.z.number().nullable().optional()
2622
+ }).passthrough();
2623
+ var MusicSubmitSchema = import_zod3.z.object({
2624
+ background_job_id: import_zod3.z.string().min(1),
2625
+ status: import_zod3.z.string().default("processing"),
2626
+ songs: import_zod3.z.array(SongSchema).min(1),
2627
+ quoted_generations: import_zod3.z.number().nullable().optional(),
2628
+ usage: import_zod3.z.unknown().optional()
2629
+ }).passthrough();
2630
+ var SoundEffectSchema = import_zod3.z.object({
2631
+ id: import_zod3.z.string().min(1),
2632
+ status: import_zod3.z.string(),
2633
+ error: import_zod3.z.string().nullable().optional(),
2634
+ name: import_zod3.z.string().default(""),
2635
+ audio_url: import_zod3.z.string().nullable().optional(),
2636
+ duration_ms: import_zod3.z.number().nullable().optional(),
2637
+ prompt: import_zod3.z.string().default(""),
2638
+ seconds: import_zod3.z.number().optional()
2639
+ }).passthrough();
2640
+ var SoundEffectSubmitSchema = import_zod3.z.object({
2641
+ background_job_id: import_zod3.z.string().min(1),
2642
+ status: import_zod3.z.string().default("processing"),
2643
+ sound_effect: SoundEffectSchema,
2644
+ quoted_generations: import_zod3.z.number().nullable().optional(),
2645
+ usage: import_zod3.z.unknown().optional()
2646
+ }).passthrough();
2647
+ var ImproveStyleSchema = import_zod3.z.object({ style: import_zod3.z.string().min(1), usage: import_zod3.z.unknown().optional() }).passthrough();
2648
+ var WriteLyricsSchema = import_zod3.z.object({ lyrics: import_zod3.z.array(import_zod3.z.string()).min(1), usage: import_zod3.z.unknown().optional() }).passthrough();
2447
2649
  var SelectFramesSchema = import_zod3.z.object({ created_object_ids: import_zod3.z.array(import_zod3.z.string()) }).passthrough();
2448
2650
  var EstimateSkeletonResponseSchema = import_zod3.z.object({
2449
2651
  keypoints: import_zod3.z.array(SkeletonKeypointSchema).length(18),
@@ -2586,6 +2788,20 @@ function parseProFlashQuote(raw) {
2586
2788
  if (image !== null || rotations !== null) return { image, rotations, total: (image ?? 0) + (rotations ?? 0) };
2587
2789
  throw new Error(`GET /pro-flash/cost returned no price: ${JSON.stringify(raw).slice(0, 200)}`);
2588
2790
  }
2791
+ function refusalReason(status, body) {
2792
+ if (status < 400 || status >= 500 || !body.startsWith("{")) return "";
2793
+ try {
2794
+ const detail = JSON.parse(body).detail;
2795
+ if (typeof detail === "string" && detail) return `: ${detail.slice(0, 400)}`;
2796
+ if (Array.isArray(detail)) {
2797
+ const messages = detail.map((item) => item && typeof item === "object" && typeof item.msg === "string" ? item.msg : "").filter(Boolean).map((msg) => msg.replace(/^Value error, /, ""));
2798
+ if (messages.length) return `: ${messages.join("; ").slice(0, 400)}`;
2799
+ }
2800
+ return "";
2801
+ } catch {
2802
+ return "";
2803
+ }
2804
+ }
2589
2805
  var PixelLabError = class extends ProviderError {
2590
2806
  constructor(message6, status, body) {
2591
2807
  super("pixellab", message6, { status });
@@ -2624,9 +2840,9 @@ var PixelLabClient = class {
2624
2840
  apiKey;
2625
2841
  http;
2626
2842
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
2627
- async request(path43, init) {
2843
+ async request(path46, init) {
2628
2844
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
2629
- const res = await this.http(`${BASE}${path43}`, {
2845
+ const res = await this.http(`${BASE}${path46}`, {
2630
2846
  ...init,
2631
2847
  headers: {
2632
2848
  Authorization: auth,
@@ -2637,13 +2853,13 @@ var PixelLabClient = class {
2637
2853
  const text = await res.text();
2638
2854
  if (!res.ok) {
2639
2855
  const hint = res.status === 500 && text.includes("Failed to start any animation jobs") ? '; a skeleton-v3 loop needs a character with a stored 3D skeleton (a v3 base), use mode: "template" on a standard one' : "";
2640
- throw new PixelLabError(`${init?.method ?? "GET"} ${path43} \u2192 ${res.status}${hint}`, res.status, text);
2856
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path46} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
2641
2857
  }
2642
2858
  if (!text) return {};
2643
2859
  try {
2644
2860
  return JSON.parse(text);
2645
2861
  } catch {
2646
- throw new Error(`${init?.method ?? "GET"} ${path43} returned invalid JSON`);
2862
+ throw new Error(`${init?.method ?? "GET"} ${path46} returned invalid JSON`);
2647
2863
  }
2648
2864
  }
2649
2865
  async balance() {
@@ -2783,6 +2999,16 @@ var PixelLabClient = class {
2783
2999
  lower_description: args.lowerDescription,
2784
3000
  upper_description: args.upperDescription
2785
3001
  };
3002
+ const image = (value) => ({ type: "base64", base64: value.base64, format: value.format });
3003
+ if (args.shapeSeed != null) body.shape_seed = args.shapeSeed;
3004
+ if (args.sideWallThickness != null) body.side_wall_thickness = args.sideWallThickness;
3005
+ if (args.sideWallPlacement != null) body.side_wall_placement = args.sideWallPlacement;
3006
+ if (args.enhance != null) body.enhance = args.enhance;
3007
+ if (args.lowerWalkable != null) body.lower_walkable = args.lowerWalkable;
3008
+ if (args.upperWalkable != null) body.upper_walkable = args.upperWalkable;
3009
+ if (args.lowerReferenceImage) body.lower_reference_image = image(args.lowerReferenceImage);
3010
+ if (args.upperReferenceImage) body.upper_reference_image = image(args.upperReferenceImage);
3011
+ if (args.transitionReferenceImage) body.transition_reference_image = image(args.transitionReferenceImage);
2786
3012
  if (args.transitionDescription) body.transition_description = args.transitionDescription;
2787
3013
  if (args.lowerBaseTileId) body.lower_base_tile_id = args.lowerBaseTileId;
2788
3014
  if (args.upperBaseTileId) body.upper_base_tile_id = args.upperBaseTileId;
@@ -2820,6 +3046,12 @@ var PixelLabClient = class {
2820
3046
  */
2821
3047
  async createTilesetSidescroller(args) {
2822
3048
  const body = { lower_description: args.lowerDescription };
3049
+ const image = (value) => ({ type: "base64", base64: value.base64, format: value.format });
3050
+ if (args.mode) body.mode = args.mode;
3051
+ if (args.enhance != null) body.enhance = args.enhance;
3052
+ if (args.platformThickness != null) body.platform_thickness = args.platformThickness;
3053
+ if (args.transitionReferenceImage) body.transition_reference_image = image(args.transitionReferenceImage);
3054
+ if (args.lowerReferenceImage) body.lower_reference_image = image(args.lowerReferenceImage);
2823
3055
  if (args.transitionDescription) body.transition_description = args.transitionDescription;
2824
3056
  if (args.lowerBaseTileId) body.lower_base_tile_id = args.lowerBaseTileId;
2825
3057
  if (args.tileSize != null) body.tile_size = { width: args.tileSize, height: args.tileSize };
@@ -2910,6 +3142,57 @@ var PixelLabClient = class {
2910
3142
  );
2911
3143
  return { ui_asset_id: res.ui_asset_id, background_job_id: res.background_job_id, usage: res.usage };
2912
3144
  }
3145
+ /** `GET /ui-assets/{id}` with everything it reports: kind, elements and their states, 9-slice, and the default split boxes. */
3146
+ async getUiAssetDetail(uiAssetId) {
3147
+ return validateResponse(
3148
+ UiAssetDetailSchema,
3149
+ await this.request(`/ui-assets/${encodeURIComponent(uiAssetId)}`),
3150
+ "ui-assets/{id}"
3151
+ );
3152
+ }
3153
+ /**
3154
+ * `POST /ui-assets/{id}/split`: cut a template into one UI asset per shape.
3155
+ * Free; nothing is generated. A template splits once. Without `boxes` it
3156
+ * cuts along the shapes the template was generated from (`split_preview`).
3157
+ */
3158
+ async splitUiAsset(uiAssetId, boxes) {
3159
+ const res = validateResponse(
3160
+ UiSplitResponseSchema,
3161
+ await this.request(`/ui-assets/${encodeURIComponent(uiAssetId)}/split`, {
3162
+ method: "POST",
3163
+ body: JSON.stringify(boxes?.length ? { boxes } : {})
3164
+ }),
3165
+ "ui-assets/{id}/split"
3166
+ );
3167
+ return res.elements;
3168
+ }
3169
+ /**
3170
+ * `POST /ui-assets/states`: draw every listed element in every listed state
3171
+ * in one generation, so the set matches. A background job; the 202 carries
3172
+ * the price (`generations`: 10, 15 or 25 by the size of the grid PixelLab
3173
+ * lays out) and is charged when the states are saved.
3174
+ */
3175
+ async createUiStates(args) {
3176
+ const body = { element_ids: args.elementIds, states: args.states };
3177
+ Object.assign(body, targetPaletteBody(args.targetPalette));
3178
+ return validateResponse(
3179
+ UiStatesSubmitSchema,
3180
+ await this.request("/ui-assets/states", { method: "POST", body: JSON.stringify(body) }),
3181
+ "ui-assets/states"
3182
+ );
3183
+ }
3184
+ /** `PATCH /ui-assets/{id}`: rename, or set or clear the 9-slice insets. Free. */
3185
+ async updateUiAsset(uiAssetId, args) {
3186
+ const body = {};
3187
+ if (args.name) body.name = args.name;
3188
+ if (args.nineSlice) body.nine_slice = args.nineSlice;
3189
+ if (args.clearNineSlice) body.clear_nine_slice = true;
3190
+ return validateResponse(
3191
+ UiAssetDetailSchema,
3192
+ await this.request(`/ui-assets/${encodeURIComponent(uiAssetId)}`, { method: "PATCH", body: JSON.stringify(body) }),
3193
+ "ui-assets/{id}"
3194
+ );
3195
+ }
2913
3196
  async getUiAsset(uiAssetId) {
2914
3197
  const res = await validateResponse(
2915
3198
  UiAssetGetSchema,
@@ -3096,10 +3379,10 @@ var PixelLabClient = class {
3096
3379
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
3097
3380
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3098
3381
  const south = args.reference?.south;
3099
- let path43;
3382
+ let path46;
3100
3383
  let body;
3101
3384
  if (args.mode === "v3") {
3102
- path43 = "/create-character-v3";
3385
+ path46 = "/create-character-v3";
3103
3386
  body = {
3104
3387
  description: args.description,
3105
3388
  image_size: imageSize,
@@ -3113,7 +3396,7 @@ var PixelLabClient = class {
3113
3396
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
3114
3397
  };
3115
3398
  } else if (args.mode === "pro-flash") {
3116
- path43 = "/create-character-pro-flash";
3399
+ path46 = "/create-character-pro-flash";
3117
3400
  const traits = args.styleTraits;
3118
3401
  body = {
3119
3402
  description: args.description,
@@ -3137,7 +3420,7 @@ var PixelLabClient = class {
3137
3420
  } : {}
3138
3421
  };
3139
3422
  } else if (args.mode === "pro") {
3140
- path43 = "/create-character-pro";
3423
+ path46 = "/create-character-pro";
3141
3424
  body = {
3142
3425
  description: args.description,
3143
3426
  image_size: imageSize,
@@ -3151,7 +3434,7 @@ var PixelLabClient = class {
3151
3434
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
3152
3435
  };
3153
3436
  } else {
3154
- path43 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3437
+ path46 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
3155
3438
  body = {
3156
3439
  description: args.description,
3157
3440
  image_size: imageSize,
@@ -3169,8 +3452,8 @@ var PixelLabClient = class {
3169
3452
  };
3170
3453
  }
3171
3454
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
3172
- const raw = await this.request(path43, { method: "POST", body: JSON.stringify(body) });
3173
- return validateResponse(CharacterSubmitSchema, raw, path43.slice(1));
3455
+ const raw = await this.request(path46, { method: "POST", body: JSON.stringify(body) });
3456
+ return validateResponse(CharacterSubmitSchema, raw, path46.slice(1));
3174
3457
  }
3175
3458
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
3176
3459
  async createCharacterState(args) {
@@ -3748,6 +4031,184 @@ var PixelLabClient = class {
3748
4031
  "vfx"
3749
4032
  );
3750
4033
  }
4034
+ /**
4035
+ * `POST /music`: two takes of a song from a style description, instrumental
4036
+ * unless lyrics are sent or `autoLyrics` is set. A background job whose 202
4037
+ * carries the pending takes and `quoted_generations` (10 for the pair);
4038
+ * PixelLab bills when the takes are made. Poll each take with `getMusic`.
4039
+ */
4040
+ async createMusic(args) {
4041
+ const body = { style: args.style };
4042
+ if (args.instrumental !== void 0) body.instrumental = args.instrumental;
4043
+ if (args.lyrics) body.lyrics = args.lyrics;
4044
+ if (args.autoLyrics) body.auto_lyrics = true;
4045
+ if (args.about) body.about = args.about;
4046
+ if (args.lengthS != null) body.length_s = args.lengthS;
4047
+ if (args.bpm != null) body.bpm = args.bpm;
4048
+ if (args.voice) body.voice = args.voice;
4049
+ if (args.exclude) body.exclude = args.exclude;
4050
+ if (args.styleWeight != null) body.style_weight = args.styleWeight;
4051
+ if (args.name) body.name = args.name;
4052
+ if (args.restyleSongId) body.restyle_song_id = args.restyleSongId;
4053
+ return validateResponse(
4054
+ MusicSubmitSchema,
4055
+ await this.request("/music", { method: "POST", body: JSON.stringify(body) }),
4056
+ "music"
4057
+ );
4058
+ }
4059
+ /** `GET /music/{song_id}`: status, then a no-auth MP3 URL and, for a loop, its loop points. */
4060
+ async getMusic(songId) {
4061
+ return validateResponse(SongSchema, await this.request(`/music/${encodeURIComponent(songId)}`), "music/{song_id}");
4062
+ }
4063
+ /**
4064
+ * `POST /music/{song_id}/loop`: a finished instrumental song made again so
4065
+ * the part between its intro and ending repeats without a seam. Two new
4066
+ * takes, each a song with `loop_start_s` and `loop_end_s`; 4 generations.
4067
+ */
4068
+ async loopMusic(songId) {
4069
+ return validateResponse(
4070
+ MusicSubmitSchema,
4071
+ await this.request(`/music/${encodeURIComponent(songId)}/loop`, { method: "POST", body: "{}" }),
4072
+ "music/{song_id}/loop"
4073
+ );
4074
+ }
4075
+ /** `POST /music/improve-style`: a short idea written out as a full style for `createMusic`. Synchronous. */
4076
+ async improveMusicStyle(args) {
4077
+ const body = { style: args.style };
4078
+ if (args.instrumental !== void 0) body.instrumental = args.instrumental;
4079
+ if (args.bpm != null) body.bpm = args.bpm;
4080
+ const res = validateResponse(
4081
+ ImproveStyleSchema,
4082
+ await this.request("/music/improve-style", { method: "POST", body: JSON.stringify(body) }),
4083
+ "music/improve-style"
4084
+ );
4085
+ return { style: res.style, usage: res.usage };
4086
+ }
4087
+ /** `POST /music/lyrics`: two lyric drafts with section tags, for `createMusic`'s `lyrics`. Synchronous. */
4088
+ async writeMusicLyrics(topic) {
4089
+ const res = validateResponse(
4090
+ WriteLyricsSchema,
4091
+ await this.request("/music/lyrics", { method: "POST", body: JSON.stringify({ topic }) }),
4092
+ "music/lyrics"
4093
+ );
4094
+ return { lyrics: res.lyrics, usage: res.usage };
4095
+ }
4096
+ /**
4097
+ * `POST /sound-effects`: one clip (WAV) from a description, 0.5 to 30
4098
+ * seconds. A background job whose 202 carries the pending clip and
4099
+ * `quoted_generations`, priced by length; billed when the clip is made.
4100
+ */
4101
+ async createSoundEffect(args) {
4102
+ const body = { prompt: args.prompt };
4103
+ if (args.seconds != null) body.seconds = args.seconds;
4104
+ if (args.name) body.name = args.name;
4105
+ return validateResponse(
4106
+ SoundEffectSubmitSchema,
4107
+ await this.request("/sound-effects", { method: "POST", body: JSON.stringify(body) }),
4108
+ "sound-effects"
4109
+ );
4110
+ }
4111
+ /** `GET /sound-effects/{id}`: status, then a no-auth WAV URL once completed. */
4112
+ async getSoundEffect(id) {
4113
+ return validateResponse(
4114
+ SoundEffectSchema,
4115
+ await this.request(`/sound-effects/${encodeURIComponent(id)}`),
4116
+ "sound-effects/{id}"
4117
+ );
4118
+ }
4119
+ /**
4120
+ * `POST /image-to-pixelart-pro`: the strongest of the three converters. Like
4121
+ * Pro Flash the output size is picked from the picture; 20 generations at
4122
+ * any source size. A plain background job.
4123
+ */
4124
+ async imageToPixelartPro(args) {
4125
+ const body = { image: args.image };
4126
+ if (args.description) body.description = args.description;
4127
+ if (args.seed != null) body.seed = args.seed;
4128
+ Object.assign(body, targetPaletteBody(args.targetPalette));
4129
+ return validateResponse(
4130
+ RevisionJobSubmitSchema,
4131
+ await this.request("/image-to-pixelart-pro", { method: "POST", body: JSON.stringify(body) }),
4132
+ "image-to-pixelart-pro"
4133
+ );
4134
+ }
4135
+ /**
4136
+ * `POST /{objects|characters}/{id}/canvas`: add or remove transparent margin
4137
+ * around every rotation. Never scales or crops; a size smaller than the art
4138
+ * is refused with the art's bounds. Free.
4139
+ */
4140
+ async setCanvasSize(kind, id, size) {
4141
+ return validateResponse(
4142
+ CanvasChangeSchema,
4143
+ await this.request(`/${kind}s/${encodeURIComponent(id)}/canvas`, { method: "POST", body: JSON.stringify({ image_size: size }) }),
4144
+ `${kind}s/{id}/canvas`
4145
+ );
4146
+ }
4147
+ /** `POST /{objects|characters}/{id}/animations/{group}/mirror`: flip one direction of a loop into its missing opposite. Free. */
4148
+ async mirrorAnimation(kind, id, animationGroupId, sourceDirection) {
4149
+ return validateResponse(
4150
+ MirrorAnimationSchema,
4151
+ await this.request(
4152
+ `/${kind}s/${encodeURIComponent(id)}/animations/${encodeURIComponent(animationGroupId)}/mirror`,
4153
+ { method: "POST", body: JSON.stringify({ source_direction: sourceDirection }) }
4154
+ ),
4155
+ `${kind}s/{id}/animations/{group}/mirror`
4156
+ );
4157
+ }
4158
+ /** `POST /objects/import`: your own PNG (at most 256x256) as a completed 1-direction object. Stored exactly; free. */
4159
+ async importObject(args) {
4160
+ const body = { image: { type: "base64", base64: args.image.base64, format: args.image.format } };
4161
+ if (args.name) body.name = args.name;
4162
+ return validateResponse(
4163
+ ImportObjectSchema,
4164
+ await this.request("/objects/import", { method: "POST", body: JSON.stringify(body) }),
4165
+ "objects/import"
4166
+ );
4167
+ }
4168
+ /**
4169
+ * `POST /objects/{id}/expand-rotations`: draw the 7 missing directions of a
4170
+ * 1-direction object. The object then waits in `review-expansion` until
4171
+ * `acceptObjectExpansion` or `dismissObjectReview`. 10 to 25 generations.
4172
+ */
4173
+ async expandObjectRotations(id, args) {
4174
+ const body = { existing_direction: args.existingDirection };
4175
+ if (args.description) body.description = args.description;
4176
+ return validateResponse(
4177
+ ExpandRotationsSchema,
4178
+ await this.request(`/objects/${encodeURIComponent(id)}/expand-rotations`, { method: "POST", body: JSON.stringify(body) }),
4179
+ "objects/{id}/expand-rotations"
4180
+ );
4181
+ }
4182
+ /** Keep a reviewed 8-direction expansion: `select-frames` with no indices. The object becomes 8-direction. */
4183
+ async acceptObjectExpansion(id) {
4184
+ return this.request(`/objects/${encodeURIComponent(id)}/select-frames`, { method: "POST", body: "{}" });
4185
+ }
4186
+ /** Discard a pending expansion (or a review pack); the object itself is kept as it was. */
4187
+ async dismissObjectReview(id) {
4188
+ return this.request(`/objects/${encodeURIComponent(id)}/dismiss-review`, { method: "POST", body: "{}" });
4189
+ }
4190
+ /**
4191
+ * `GET /{objects|characters}/{id}/{zip|spritesheet|aseprite|gif}`: the
4192
+ * website's exports as bytes. Answers 423 while the asset or one of its
4193
+ * animations is still generating.
4194
+ */
4195
+ async exportAsset(kind, id, format, opts = {}) {
4196
+ const query = new URLSearchParams();
4197
+ if (opts.animationGroupId) query.set("animation_group_id", opts.animationGroupId);
4198
+ if (opts.direction) query.set("direction", opts.direction);
4199
+ const suffix = query.size ? `?${query}` : "";
4200
+ const pathname = `/${kind}s/${encodeURIComponent(id)}/${format}${suffix}`;
4201
+ const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
4202
+ const res = await this.http(`${BASE}${pathname}`, { headers: { Authorization: auth } });
4203
+ if (!res.ok) {
4204
+ const text = await res.text();
4205
+ const hint = res.status === 423 ? "; the asset or one of its animations is still generating, try again shortly" : "";
4206
+ throw new PixelLabError(`GET ${pathname} \u2192 ${res.status}${hint}`, res.status, text);
4207
+ }
4208
+ const bytes = Buffer.from(await res.arrayBuffer());
4209
+ if (bytes.length > MAX_DOWNLOAD_BYTES) throw new Error(`export ${pathname} exceeds the ${MAX_DOWNLOAD_BYTES}-byte safety limit`);
4210
+ return bytes;
4211
+ }
3751
4212
  /** `GET /generate-font-pro/{job_id}`: status, then no-auth atlas and `.ttf` URLs once completed. */
3752
4213
  async getFontJob(jobId) {
3753
4214
  const raw = await this.request(`/generate-font-pro/${encodeURIComponent(jobId)}`);
@@ -4511,10 +4972,10 @@ function normalizeHex(value) {
4511
4972
  function sha256(data) {
4512
4973
  return (0, import_node_crypto.createHash)("sha256").update(data).digest("hex");
4513
4974
  }
4514
- async function sha256File(path43) {
4975
+ async function sha256File(path46) {
4515
4976
  return new Promise((resolve, reject) => {
4516
4977
  const hash = (0, import_node_crypto.createHash)("sha256");
4517
- const stream = (0, import_node_fs.createReadStream)(path43);
4978
+ const stream = (0, import_node_fs.createReadStream)(path46);
4518
4979
  stream.on("data", (chunk2) => hash.update(chunk2));
4519
4980
  stream.on("error", reject);
4520
4981
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -4566,6 +5027,21 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
4566
5027
  terrainBoundarySeed: spec.terrainBoundarySeed,
4567
5028
  terrainStepSlope: spec.terrainStepSlope,
4568
5029
  terrainConnectDiagonals: spec.terrainConnectDiagonals,
5030
+ // Added after the fields above, each only when set, so no terrain entry
5031
+ // written before them changes hash. The walkable flags change no pixel
5032
+ // and are deliberately not here.
5033
+ terrainShapeSeed: spec.terrainShapeSeed,
5034
+ terrainSideWallThickness: spec.terrainSideWallThickness,
5035
+ terrainSideWallPlacement: spec.terrainSideWallPlacement,
5036
+ terrainEnhance: spec.terrainEnhance,
5037
+ terrainPlatformThickness: spec.terrainPlatformThickness,
5038
+ // Reference images enter as their bytes' hashes, never their paths.
5039
+ terrainReferences: spec.terrainReferences && Object.keys(spec.terrainReferences).length ? Object.fromEntries(
5040
+ ["lower", "upper", "transition"].flatMap((side) => {
5041
+ const reference = spec.terrainReferences[side];
5042
+ return reference ? [[side, reference.sha256]] : [];
5043
+ })
5044
+ ) : void 0,
4569
5045
  // "top-down" is the default and draws the same set as leaving it out.
4570
5046
  terrainOrientation: spec.terrainOrientation === "sidescroller" ? spec.terrainOrientation : void 0,
4571
5047
  // Which set and which of its terrains, not that terrain's id: the id
@@ -5401,6 +5877,7 @@ async function generateFont(client2, opts) {
5401
5877
  await sleep3(interval);
5402
5878
  }
5403
5879
  }
5880
+ var PIXELATE_PRO_COST_GENERATIONS = 20;
5404
5881
  var PIXELATE_COST_GENERATIONS = 6;
5405
5882
  var PIXELATE_MAX_SIDE = 2048;
5406
5883
  function defaultPixelateOut(input) {
@@ -5418,11 +5895,16 @@ async function pixelateFile(client2, input, opts = {}) {
5418
5895
  const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
5419
5896
  const interval = opts.intervalMs ?? 5e3;
5420
5897
  const timeout = opts.timeoutMs ?? 10 * 6e4;
5421
- const submitted = await client2.imageToPixelartProFlash({
5422
- image: { base64: bytes.toString("base64"), format },
5898
+ const image = { base64: bytes.toString("base64"), format };
5899
+ if (!opts.pro && (opts.palette?.length || opts.maxColors != null)) {
5900
+ throw new Error("a palette or color cap needs the Pro converter; add --pro");
5901
+ }
5902
+ const submitted = opts.pro ? await client2.imageToPixelartPro({
5903
+ image,
5423
5904
  description: opts.description,
5424
- seed: opts.seed
5425
- });
5905
+ seed: opts.seed,
5906
+ targetPalette: opts.palette?.length || opts.maxColors != null ? { ...opts.palette?.length ? { colors: opts.palette } : {}, ...opts.maxColors != null ? { maxColors: opts.maxColors } : {} } : void 0
5907
+ }) : await client2.imageToPixelartProFlash({ image, description: opts.description, seed: opts.seed });
5426
5908
  const jobId = submitted.background_job_id;
5427
5909
  const started = Date.now();
5428
5910
  for (; ; ) {
@@ -5431,20 +5913,32 @@ async function pixelateFile(client2, input, opts = {}) {
5431
5913
  if (job.status === "failed") throw new Error(`PixelLab pixelate job ${jobId} failed upstream`);
5432
5914
  if (job.status === "completed") {
5433
5915
  const images = job.last_response?.images;
5434
- const first = Array.isArray(images) ? images[0] : void 0;
5916
+ const first = Array.isArray(images) ? images[0] : job.last_response?.image;
5435
5917
  if (!first || typeof first.base64 !== "string" || !first.base64) {
5436
- throw new Error(`PixelLab pixelate job ${jobId} completed without an image at last_response.images[0]`);
5918
+ throw new Error(`PixelLab pixelate job ${jobId} completed without an image at last_response.images[0] or last_response.image`);
5437
5919
  }
5438
5920
  const png = Buffer.from(first.base64, "base64");
5439
5921
  const size = imageMetadata(png);
5440
5922
  await (0, import_promises2.mkdir)(import_node_path2.default.dirname(out), { recursive: true });
5441
5923
  await (0, import_promises2.writeFile)(out, png);
5924
+ const reduced = job.last_response?.quantized_image;
5925
+ const count = (value) => typeof value === "number" ? value : null;
5926
+ let quantized;
5927
+ if (reduced && typeof reduced.base64 === "string" && reduced.base64) {
5928
+ const quantizedOut = out.replace(/(\.png)?$/i, ".quantized.png");
5929
+ if (!(0, import_node_fs3.existsSync)(quantizedOut) || opts.force) {
5930
+ await (0, import_promises2.writeFile)(quantizedOut, Buffer.from(reduced.base64, "base64"));
5931
+ quantized = { out: quantizedOut, colors: count(job.last_response?.quantized_image_n_colors) };
5932
+ }
5933
+ }
5442
5934
  return {
5443
5935
  jobId,
5444
5936
  out,
5445
5937
  original: { width, height },
5446
5938
  pixelated: { width: size?.width ?? Number(first.width), height: size?.height ?? Number(first.height) },
5447
- imageId: submitted.image_id,
5939
+ ...submitted.image_id ? { imageId: submitted.image_id } : {},
5940
+ ...quantized ? { quantized } : {},
5941
+ ...opts.pro ? { colors: count(job.last_response?.original_image_n_colors) } : {},
5448
5942
  usage: job.usage ?? null
5449
5943
  };
5450
5944
  }
@@ -6133,6 +6627,23 @@ var PixelLabProvider = class _PixelLabProvider {
6133
6627
  if (spec.terrainTileSize === 64 && spec.terrainMode !== "pro") {
6134
6628
  throw new Error('PixelLab terrain: a 64px tile needs terrainMode: "pro"');
6135
6629
  }
6630
+ const standardOnly = {
6631
+ terrainShapeSeed: spec.terrainShapeSeed,
6632
+ terrainSideWallThickness: spec.terrainSideWallThickness,
6633
+ terrainSideWallPlacement: spec.terrainSideWallPlacement,
6634
+ terrainEnhance: spec.terrainEnhance
6635
+ };
6636
+ const proSet = Object.entries(standardOnly).filter(([, value]) => value != null).map(([field]) => field);
6637
+ if (pro && proSet.length) {
6638
+ throw new Error(`PixelLab terrain: ${proSet.join(", ")} shape a standard set; terrainMode: "pro" ignores them`);
6639
+ }
6640
+ if ((spec.terrainSideWallThickness != null || spec.terrainSideWallPlacement != null) && !(spec.terrainTransitionSize != null && spec.terrainTransitionSize > 0)) {
6641
+ throw new Error("PixelLab terrain: terrainSideWallThickness and terrainSideWallPlacement shape the wall, which needs a terrainTransitionSize above 0");
6642
+ }
6643
+ if (spec.terrainPlatformThickness != null) {
6644
+ throw new Error("PixelLab terrain: terrainPlatformThickness is a sidescroller control");
6645
+ }
6646
+ this.requireTerrainReferences(spec);
6136
6647
  if (spec.terrainShapeStyle && spec.terrainTransitionSize != null && spec.terrainTransitionSize > 0.5) {
6137
6648
  throw new Error(
6138
6649
  "PixelLab terrain: terrainShapeStyle with terrainTransitionSize above 0.5 uses an extended 32-tile layout pixelkiln does not model; use 0, 0.25, or 0.5"
@@ -6151,7 +6662,6 @@ var PixelLabProvider = class _PixelLabProvider {
6151
6662
  */
6152
6663
  validateSidescrollerTerrain(spec) {
6153
6664
  const topDownOnly = {
6154
- terrainMode: spec.terrainMode,
6155
6665
  terrainShapeStyle: spec.terrainShapeStyle,
6156
6666
  terrainView: spec.terrainView,
6157
6667
  terrainSpreadX: spec.terrainSpreadX,
@@ -6161,7 +6671,12 @@ var PixelLabProvider = class _PixelLabProvider {
6161
6671
  terrainBoundaryAmplitude: spec.terrainBoundaryAmplitude,
6162
6672
  terrainBoundarySeed: spec.terrainBoundarySeed,
6163
6673
  terrainStepSlope: spec.terrainStepSlope,
6164
- terrainConnectDiagonals: spec.terrainConnectDiagonals
6674
+ terrainConnectDiagonals: spec.terrainConnectDiagonals,
6675
+ terrainShapeSeed: spec.terrainShapeSeed,
6676
+ terrainSideWallThickness: spec.terrainSideWallThickness,
6677
+ terrainSideWallPlacement: spec.terrainSideWallPlacement,
6678
+ terrainLowerWalkable: spec.terrainLowerWalkable,
6679
+ terrainUpperWalkable: spec.terrainUpperWalkable
6165
6680
  };
6166
6681
  const set = Object.entries(topDownOnly).filter(([, value]) => value != null).map(([field]) => field);
6167
6682
  if (set.length) {
@@ -6170,9 +6685,26 @@ var PixelLabProvider = class _PixelLabProvider {
6170
6685
  if (spec.terrainTileSize !== 16 && spec.terrainTileSize !== 32) {
6171
6686
  throw new Error(`PixelLab terrain: a sidescroller set's tiles are 16 or 32px, got ${spec.terrainTileSize}`);
6172
6687
  }
6173
- if (spec.terrainTransitionSize != null && ![0, 0.25, 0.5, 1].includes(spec.terrainTransitionSize)) {
6174
- throw new Error("PixelLab terrain: a sidescroller set's terrainTransitionSize must be 0, 0.25, 0.5, or 1");
6688
+ if (spec.terrainTransitionSize != null && ![0, 0.25, 0.5].includes(spec.terrainTransitionSize)) {
6689
+ throw new Error("PixelLab terrain: a sidescroller set's terrainTransitionSize must be 0, 0.25, or 0.5 (the top layer stops at half a tile)");
6690
+ }
6691
+ const pro = spec.terrainMode === "pro";
6692
+ if (pro && (spec.terrainEnhance != null || spec.terrainPlatformThickness != null)) {
6693
+ throw new Error('PixelLab terrain: terrainEnhance and terrainPlatformThickness shape a standard sidescroller set; terrainMode: "pro" ignores them');
6694
+ }
6695
+ if (spec.terrainConnect?.lower && !pro) {
6696
+ throw new Error(`PixelLab terrain: a sidescroller set connects to another set's platform only with terrainMode: "pro"`);
6175
6697
  }
6698
+ if (spec.terrainReferences?.upper) {
6699
+ throw new Error("PixelLab terrain: a sidescroller set's upper terrain is empty air; it takes no upper reference");
6700
+ }
6701
+ if (spec.terrainReferences?.lower && !pro) {
6702
+ throw new Error('PixelLab terrain: a sidescroller set keeps a lower (platform body) reference only with terrainMode: "pro"');
6703
+ }
6704
+ if (spec.terrainReferences?.transition && pro) {
6705
+ throw new Error('PixelLab terrain: a sidescroller set textures its top layer from a transition reference only on standard mode; drop it or terrainMode: "pro"');
6706
+ }
6707
+ this.requireTerrainReferences(spec, spec.terrainTileSize);
6176
6708
  if (spec.terrainConnect?.upper) {
6177
6709
  throw new Error(
6178
6710
  "PixelLab terrain: a sidescroller set's upper terrain is empty air; only its lower (platform) terrain can connect"
@@ -6185,6 +6717,19 @@ var PixelLabProvider = class _PixelLabProvider {
6185
6717
  );
6186
6718
  }
6187
6719
  }
6720
+ /** Reference files must exist; a sidescroller's must be a square PNG of the tile size. */
6721
+ requireTerrainReferences(spec, tileSize) {
6722
+ for (const [side, reference] of Object.entries(spec.terrainReferences ?? {})) {
6723
+ if (!reference?.sha256) {
6724
+ throw new Error(`PixelLab terrain: the ${side} reference is missing or not a PNG: ${reference?.file}`);
6725
+ }
6726
+ if (tileSize != null && (reference.width !== tileSize || reference.height !== tileSize)) {
6727
+ throw new Error(
6728
+ `PixelLab terrain: a sidescroller set's ${side} reference must be a ${tileSize}x${tileSize} PNG; ${reference.file} is ${reference.width}x${reference.height}`
6729
+ );
6730
+ }
6731
+ }
6732
+ }
6188
6733
  validateCharacter(spec, styleImages = []) {
6189
6734
  const character = spec.character;
6190
6735
  if (!character) throw new Error(`${spec.styleId}/${spec.assetId} has no character shape`);
@@ -6962,7 +7507,12 @@ var PixelLabProvider = class _PixelLabProvider {
6962
7507
  outline: spec.outline,
6963
7508
  shading: spec.shading,
6964
7509
  detail: spec.detail,
6965
- seed: spec.seed
7510
+ seed: spec.seed,
7511
+ mode: spec.terrainMode,
7512
+ enhance: spec.terrainEnhance,
7513
+ platformThickness: spec.terrainPlatformThickness,
7514
+ lowerReferenceImage: await terrainReferenceImage(spec, "lower"),
7515
+ transitionReferenceImage: await terrainReferenceImage(spec, "transition")
6966
7516
  });
6967
7517
  return {
6968
7518
  jobId: res2.tileset_id,
@@ -6997,7 +7547,16 @@ var PixelLabProvider = class _PixelLabProvider {
6997
7547
  shading: spec.shading,
6998
7548
  detail: spec.detail,
6999
7549
  seed: spec.seed,
7000
- targetPalette: targetPaletteFor(spec)
7550
+ targetPalette: targetPaletteFor(spec),
7551
+ shapeSeed: spec.terrainShapeSeed,
7552
+ sideWallThickness: spec.terrainSideWallThickness,
7553
+ sideWallPlacement: spec.terrainSideWallPlacement,
7554
+ enhance: spec.terrainEnhance,
7555
+ lowerWalkable: spec.terrainLowerWalkable,
7556
+ upperWalkable: spec.terrainUpperWalkable,
7557
+ lowerReferenceImage: await terrainReferenceImage(spec, "lower"),
7558
+ upperReferenceImage: await terrainReferenceImage(spec, "upper"),
7559
+ transitionReferenceImage: await terrainReferenceImage(spec, "transition")
7001
7560
  });
7002
7561
  return {
7003
7562
  jobId: res2.tileset_id,
@@ -7955,8 +8514,8 @@ var PixelLabProvider = class _PixelLabProvider {
7955
8514
  const sources = [];
7956
8515
  const terrainTiles = [];
7957
8516
  for (const [index, tile] of tileset.tiles.entries()) {
7958
- const slug2 = tile.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "tile";
7959
- const role = `tile-${String(index).padStart(2, "0")}-${slug2}`;
8517
+ const slug3 = tile.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "tile";
8518
+ const role = `tile-${String(index).padStart(2, "0")}-${slug3}`;
7960
8519
  const file = import_node_path3.default.join(_PixelLabProvider.cacheDir(), `${tilesetId}-${index}.png`);
7961
8520
  (0, import_node_fs4.writeFileSync)(file, Buffer.from(tile.image.base64, "base64"));
7962
8521
  sources.push({ url: `file://${file}`, role });
@@ -8176,6 +8735,16 @@ function sendsTargetPalette(spec) {
8176
8735
  return false;
8177
8736
  }
8178
8737
  }
8738
+ async function terrainReferenceImage(spec, side) {
8739
+ const reference = spec.terrainReferences?.[side];
8740
+ if (!reference) return void 0;
8741
+ if (!(0, import_node_fs4.existsSync)(reference.file)) throw new Error(`terrain ${side} reference is missing: ${reference.file}`);
8742
+ const bytes = (0, import_node_fs4.readFileSync)(reference.file);
8743
+ if (sha256(bytes) !== reference.sha256) {
8744
+ throw new Error(`terrain ${side} reference changed after the manifest was resolved: ${reference.file}; run the command again`);
8745
+ }
8746
+ return { base64: bytes.toString("base64"), format: "png" };
8747
+ }
8179
8748
  function targetPaletteFor(spec) {
8180
8749
  if (!sendsTargetPalette(spec)) return void 0;
8181
8750
  if (!spec.palette.length && spec.maxColors == null) return void 0;
@@ -8349,9 +8918,9 @@ var RetroDiffusionClient = class {
8349
8918
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
8350
8919
  return Buffer.from(await response.arrayBuffer());
8351
8920
  }
8352
- async call(path43, init = {}) {
8921
+ async call(path46, init = {}) {
8353
8922
  if (!this.token) throw new Error("RD_API_KEY is not set");
8354
- const response = await this.request(`${this.baseUrl}${path43}`, {
8923
+ const response = await this.request(`${this.baseUrl}${path46}`, {
8355
8924
  ...init,
8356
8925
  headers: {
8357
8926
  "Content-Type": "application/json",
@@ -11458,6 +12027,13 @@ async function resolveSpecs(loaded, filter) {
11458
12027
  terrainBoundarySeed: generator === "terrain" ? style.terrainBoundarySeed : void 0,
11459
12028
  terrainStepSlope: generator === "terrain" ? style.terrainStepSlope : void 0,
11460
12029
  terrainConnectDiagonals: generator === "terrain" ? style.terrainConnectDiagonals : void 0,
12030
+ terrainShapeSeed: generator === "terrain" ? style.terrainShapeSeed : void 0,
12031
+ terrainSideWallThickness: generator === "terrain" ? style.terrainSideWallThickness : void 0,
12032
+ terrainSideWallPlacement: generator === "terrain" ? style.terrainSideWallPlacement : void 0,
12033
+ terrainEnhance: generator === "terrain" ? style.terrainEnhance : void 0,
12034
+ terrainPlatformThickness: generator === "terrain" ? style.terrainPlatformThickness : void 0,
12035
+ terrainLowerWalkable: generator === "terrain" ? style.terrainLowerWalkable : void 0,
12036
+ terrainUpperWalkable: generator === "terrain" ? style.terrainUpperWalkable : void 0,
11461
12037
  terrainTransitionSize: generator === "terrain" ? style.terrainTransitionSize : void 0,
11462
12038
  terrainView: generator === "terrain" ? style.terrainView : void 0,
11463
12039
  terrainOrientation: generator === "terrain" ? style.terrainOrientation : void 0,
@@ -11890,6 +12466,20 @@ async function resolveSpecs(loaded, filter) {
11890
12466
  }
11891
12467
  resolved.terrainConnect = links;
11892
12468
  }
12469
+ if (asset.terrainReferences) {
12470
+ if (resolved.generator !== "terrain") {
12471
+ throw new Error(`assets.${assetId}.terrainReferences: only a terrain set takes terrain references; style "${styleId}" uses "${resolved.generator}"`);
12472
+ }
12473
+ const references = {};
12474
+ for (const side of ["lower", "upper", "transition"]) {
12475
+ const relative = asset.terrainReferences[side];
12476
+ if (!relative) continue;
12477
+ const file = import_node_path8.default.resolve(root, relative);
12478
+ const image = await optionalRevisionImage(file, `terrain ${side} reference`, "png");
12479
+ references[side] = { file, sha256: image?.hash ?? null, width: image?.width ?? null, height: image?.height ?? null };
12480
+ }
12481
+ if (Object.keys(references).length) resolved.terrainReferences = references;
12482
+ }
11893
12483
  if (asset.scene) resolved.scene = await resolveMapScene(root, styleId, assetId, resolved.generator, asset.scene, activeProvider);
11894
12484
  resolved.specHash = specHash(
11895
12485
  resolved,
@@ -14962,16 +15552,552 @@ function hex(c) {
14962
15552
  return `#${[c.r, c.g, c.b].map((v) => v.toString(16).padStart(2, "0")).join("")}`;
14963
15553
  }
14964
15554
 
14965
- // src/pipeline/quality-regression.ts
14966
- var import_node_path21 = __toESM(require("path"), 1);
15555
+ // src/pixellab-audio.ts
14967
15556
  var import_node_fs18 = require("fs");
14968
15557
  var import_promises12 = require("fs/promises");
15558
+ var import_node_path21 = __toESM(require("path"), 1);
15559
+ var MUSIC_COST_GENERATIONS = 10;
15560
+ var MUSIC_LOOP_COST_GENERATIONS = 4;
15561
+ var MUSIC_LOOP_MIN_BODY_SECONDS = 36;
15562
+ var MUSIC_MIN_SECONDS = 10;
15563
+ var MUSIC_MAX_SECONDS = 360;
15564
+ var MUSIC_MIN_BPM = 60;
15565
+ var MUSIC_MAX_BPM = 180;
15566
+ var SFX_MIN_SECONDS = 0.5;
15567
+ var SFX_MAX_SECONDS = 30;
15568
+ function soundEffectCost(seconds) {
15569
+ return Math.max(1, Math.ceil(0.614 * seconds - 1e-9));
15570
+ }
15571
+ function detectAudioFormat(bytes) {
15572
+ if (bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WAVE") {
15573
+ return "wav";
15574
+ }
15575
+ if (bytes.length >= 3 && bytes.subarray(0, 3).toString("ascii") === "ID3") return "mp3";
15576
+ if (bytes.length >= 2 && bytes[0] === 255 && (bytes[1] & 224) === 224) return "mp3";
15577
+ return null;
15578
+ }
15579
+ function validateAudio(bytes, expected) {
15580
+ const actual = detectAudioFormat(bytes);
15581
+ if (actual !== expected) {
15582
+ throw new Error(`PixelLab returned ${actual ?? `${bytes.length} bytes that are not audio`}, expected ${expected}`);
15583
+ }
15584
+ }
15585
+ async function waitFor(what, read, opts, defaults) {
15586
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
15587
+ const interval = opts.intervalMs ?? defaults.intervalMs;
15588
+ const timeout = opts.timeoutMs ?? defaults.timeoutMs;
15589
+ const started = Date.now();
15590
+ for (; ; ) {
15591
+ const item = await read();
15592
+ opts.onProgress?.(item.status);
15593
+ if (item.status === "failed") throw new Error(`PixelLab ${what} failed upstream${item.error ? `: ${item.error}` : ""}`);
15594
+ if (item.status === "completed") return item;
15595
+ if (Date.now() - started > timeout) {
15596
+ throw new Error(
15597
+ `PixelLab ${what} is still ${item.status} after ${Math.round(timeout / 1e3)} s; it keeps running upstream and stays in your PixelLab library, but this command has stopped waiting`
15598
+ );
15599
+ }
15600
+ await sleep3(interval);
15601
+ }
15602
+ }
15603
+ function refusalDetail(error) {
15604
+ const body = error?.body;
15605
+ if (typeof body !== "string" || !body) return null;
15606
+ try {
15607
+ const detail = JSON.parse(body).detail;
15608
+ return typeof detail === "string" ? detail : null;
15609
+ } catch {
15610
+ return null;
15611
+ }
15612
+ }
15613
+ async function billedUsage(client2, jobId) {
15614
+ try {
15615
+ return (await client2.getBackgroundJob(jobId)).usage ?? null;
15616
+ } catch {
15617
+ return null;
15618
+ }
15619
+ }
15620
+ function musicOutputPaths(out) {
15621
+ const base = import_node_path21.default.resolve(out.replace(/\.(music\.json|mp3)$/i, ""));
15622
+ return {
15623
+ takes: [`${base}.mp3`, `${base}.take2.mp3`],
15624
+ loops: [`${base}.loop.mp3`, `${base}.loop.take2.mp3`],
15625
+ record: `${base}.music.json`
15626
+ };
15627
+ }
15628
+ function musicCost(opts) {
15629
+ if (opts.loopOf) return MUSIC_LOOP_COST_GENERATIONS;
15630
+ return MUSIC_COST_GENERATIONS + (opts.loop ? MUSIC_LOOP_COST_GENERATIONS : 0);
15631
+ }
15632
+ async function collectTakes(client2, songs, files, what, opts) {
15633
+ const takes = [];
15634
+ const finished = [];
15635
+ const ordered = [...songs].sort((a, b) => a.take - b.take);
15636
+ for (const [index, pending] of ordered.entries()) {
15637
+ const file = files[index];
15638
+ if (!file) break;
15639
+ const song = await waitFor(`${what} ${pending.id}`, () => client2.getMusic(pending.id), opts, { intervalMs: 1e4, timeoutMs: 6 * 6e4 });
15640
+ if (!song.audio_url) throw new Error(`PixelLab ${what} ${song.id} completed without an audio URL`);
15641
+ const bytes = await client2.download(song.audio_url);
15642
+ validateAudio(bytes, "mp3");
15643
+ await (0, import_promises12.mkdir)(import_node_path21.default.dirname(file), { recursive: true });
15644
+ await (0, import_promises12.writeFile)(file, bytes);
15645
+ finished.push(song);
15646
+ takes.push({
15647
+ songId: song.id,
15648
+ take: song.take,
15649
+ file,
15650
+ sha256: sha256(bytes),
15651
+ durationMs: song.duration_ms ?? null,
15652
+ ...song.loop_start_s != null ? { loopStartS: song.loop_start_s } : {},
15653
+ ...song.loop_end_s != null ? { loopEndS: song.loop_end_s } : {}
15654
+ });
15655
+ }
15656
+ return { takes, finished };
15657
+ }
15658
+ async function generateMusic(client2, opts) {
15659
+ const paths = musicOutputPaths(opts.out);
15660
+ const instrumental = !(opts.lyrics || opts.autoLyrics);
15661
+ const wantsLoop = Boolean(opts.loop || opts.loopOf);
15662
+ if (!opts.loopOf && !opts.style) throw new Error("music needs a style description");
15663
+ if (wantsLoop && !opts.loopOf && !instrumental) throw new Error("PixelLab loops instrumental songs only; drop the lyrics or the loop");
15664
+ if (opts.loop && opts.lengthS != null && opts.lengthS <= MUSIC_LOOP_MIN_BODY_SECONDS) {
15665
+ throw new Error(
15666
+ `a loop needs at least ${MUSIC_LOOP_MIN_BODY_SECONDS} s of music between the intro and the ending, so a ${opts.lengthS} s song cannot be looped; ask for a longer song (60 s or more is safe) or leave the length to PixelLab`
15667
+ );
15668
+ }
15669
+ const writes = [paths.record, ...opts.loopOf ? [] : paths.takes, ...wantsLoop ? paths.loops : []];
15670
+ if (!opts.force) {
15671
+ for (const file of writes) if ((0, import_node_fs18.existsSync)(file)) throw new Error(`${file} already exists; pass --force to replace it`);
15672
+ }
15673
+ const usage = [];
15674
+ let quoted = null;
15675
+ let takes = [];
15676
+ let source;
15677
+ if (!opts.loopOf) {
15678
+ const submitted = await client2.createMusic({
15679
+ style: opts.style,
15680
+ instrumental,
15681
+ lyrics: opts.lyrics,
15682
+ autoLyrics: opts.autoLyrics,
15683
+ about: opts.about,
15684
+ lengthS: opts.lengthS,
15685
+ bpm: opts.bpm,
15686
+ voice: opts.voice,
15687
+ exclude: opts.exclude,
15688
+ styleWeight: opts.styleWeight,
15689
+ name: opts.name,
15690
+ restyleSongId: opts.restyleSongId
15691
+ });
15692
+ quoted = submitted.quoted_generations ?? null;
15693
+ const made = await collectTakes(client2, submitted.songs, paths.takes, "song", opts);
15694
+ takes = made.takes;
15695
+ source = made.finished[0];
15696
+ usage.push(await billedUsage(client2, submitted.background_job_id));
15697
+ }
15698
+ let loops = [];
15699
+ const snapshot = () => ({
15700
+ record: paths.record,
15701
+ takes,
15702
+ loops,
15703
+ style: source?.style ?? opts.style ?? "",
15704
+ instrumental: source?.instrumental ?? instrumental,
15705
+ lyrics: source?.lyrics ?? opts.lyrics ?? "",
15706
+ quotedGenerations: quoted,
15707
+ usage
15708
+ });
15709
+ const relative = (take) => ({ ...take, file: import_node_path21.default.basename(take.file) });
15710
+ const writeRecord = async (result2) => {
15711
+ await (0, import_promises12.mkdir)(import_node_path21.default.dirname(paths.record), { recursive: true });
15712
+ await (0, import_promises12.writeFile)(
15713
+ paths.record,
15714
+ JSON.stringify(
15715
+ {
15716
+ schema: "pixelkiln-music",
15717
+ version: 1,
15718
+ provider: "pixellab",
15719
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
15720
+ request: {
15721
+ ...opts.style ? { style: opts.style } : {},
15722
+ ...opts.bpm != null ? { bpm: opts.bpm } : {},
15723
+ ...opts.lengthS != null ? { lengthS: opts.lengthS } : {},
15724
+ ...opts.exclude ? { exclude: opts.exclude } : {},
15725
+ ...opts.styleWeight != null ? { styleWeight: opts.styleWeight } : {},
15726
+ ...opts.voice ? { voice: opts.voice } : {},
15727
+ ...opts.autoLyrics ? { autoLyrics: true, ...opts.about ? { about: opts.about } : {} } : {},
15728
+ ...opts.restyleSongId ? { restyleSongId: opts.restyleSongId } : {},
15729
+ ...opts.loopOf ? { loopOf: opts.loopOf } : {}
15730
+ },
15731
+ style: result2.style,
15732
+ instrumental: result2.instrumental,
15733
+ ...result2.lyrics ? { lyrics: result2.lyrics } : {},
15734
+ takes: result2.takes.map(relative),
15735
+ loops: result2.loops.map(relative),
15736
+ quotedGenerations: result2.quotedGenerations,
15737
+ usage: result2.usage
15738
+ },
15739
+ null,
15740
+ 2
15741
+ ) + "\n"
15742
+ );
15743
+ };
15744
+ if (takes.length) await writeRecord(snapshot());
15745
+ if (wantsLoop) {
15746
+ const loopSource = opts.loopOf ?? source.id;
15747
+ let submitted;
15748
+ try {
15749
+ submitted = await client2.loopMusic(loopSource);
15750
+ } catch (error) {
15751
+ const detail = refusalDetail(error);
15752
+ const kept = takes.length ? ` The song's takes are saved (${import_node_path21.default.basename(paths.record)}); nothing was charged for the loop.` : "";
15753
+ throw new Error(`PixelLab refused to loop ${loopSource}: ${detail ?? (error instanceof Error ? error.message : String(error))}${kept}`, { cause: error });
15754
+ }
15755
+ quoted = (quoted ?? 0) + (submitted.quoted_generations ?? 0);
15756
+ const made = await collectTakes(client2, submitted.songs, paths.loops, "loop", opts);
15757
+ loops = made.takes;
15758
+ source ??= made.finished[0];
15759
+ usage.push(await billedUsage(client2, submitted.background_job_id));
15760
+ }
15761
+ const result = snapshot();
15762
+ await writeRecord(result);
15763
+ return result;
15764
+ }
15765
+ function soundEffectOutputPaths(out) {
15766
+ const base = import_node_path21.default.resolve(out.replace(/\.(sfx\.json|wav)$/i, ""));
15767
+ return { wav: `${base}.wav`, record: `${base}.sfx.json` };
15768
+ }
15769
+ async function generateSoundEffect(client2, opts) {
15770
+ const { wav, record } = soundEffectOutputPaths(opts.out);
15771
+ if (!opts.force) {
15772
+ for (const file of [wav, record]) if ((0, import_node_fs18.existsSync)(file)) throw new Error(`${file} already exists; pass --force to replace it`);
15773
+ }
15774
+ const seconds = opts.seconds ?? 2;
15775
+ const submitted = await client2.createSoundEffect({ prompt: opts.prompt, seconds, name: opts.name });
15776
+ const id = submitted.sound_effect.id;
15777
+ const clip = await waitFor(`sound effect ${id}`, () => client2.getSoundEffect(id), opts, { intervalMs: 4e3, timeoutMs: 4 * 6e4 });
15778
+ if (!clip.audio_url) throw new Error(`PixelLab sound effect ${id} completed without an audio URL`);
15779
+ const bytes = await client2.download(clip.audio_url);
15780
+ validateAudio(bytes, "wav");
15781
+ await (0, import_promises12.mkdir)(import_node_path21.default.dirname(wav), { recursive: true });
15782
+ await (0, import_promises12.writeFile)(wav, bytes);
15783
+ const result = {
15784
+ soundEffectId: id,
15785
+ file: wav,
15786
+ record,
15787
+ sha256: sha256(bytes),
15788
+ durationMs: clip.duration_ms ?? null,
15789
+ seconds,
15790
+ quotedGenerations: submitted.quoted_generations ?? null,
15791
+ usage: await billedUsage(client2, submitted.background_job_id)
15792
+ };
15793
+ await (0, import_promises12.writeFile)(
15794
+ record,
15795
+ JSON.stringify(
15796
+ {
15797
+ schema: "pixelkiln-sfx",
15798
+ version: 1,
15799
+ provider: "pixellab",
15800
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
15801
+ prompt: opts.prompt,
15802
+ seconds,
15803
+ soundEffectId: id,
15804
+ file: import_node_path21.default.basename(wav),
15805
+ sha256: result.sha256,
15806
+ durationMs: result.durationMs,
15807
+ quotedGenerations: result.quotedGenerations,
15808
+ usage: result.usage
15809
+ },
15810
+ null,
15811
+ 2
15812
+ ) + "\n"
15813
+ );
15814
+ return result;
15815
+ }
15816
+
15817
+ // src/pixellab-ui.ts
15818
+ var import_node_fs19 = require("fs");
15819
+ var import_promises13 = require("fs/promises");
15820
+ var import_node_path22 = __toESM(require("path"), 1);
15821
+ var UI_STATES_COSTS = [10, 15, 25];
15822
+ var UI_STATES_MAX_COST = 25;
15823
+ var UI_STATES_MAX_ELEMENTS = 64;
15824
+ var UI_STATES_MAX_STATES = 16;
15825
+ function parseUiState(text) {
15826
+ const at = text.indexOf("=");
15827
+ const name = at < 0 ? "" : text.slice(0, at).trim();
15828
+ const description = at < 0 ? "" : text.slice(at + 1).trim();
15829
+ if (!name || !description) {
15830
+ throw new Error(`a state is written "name=description", e.g. "pressed=pushed in: darker, face 1 px lower"; got "${text}"`);
15831
+ }
15832
+ return { name, description };
15833
+ }
15834
+ function parseUiBox(text) {
15835
+ const colon = text.lastIndexOf(":");
15836
+ const label = colon < 0 ? "" : text.slice(0, colon).trim();
15837
+ const numbers = (colon < 0 ? text : text.slice(colon + 1)).split(",").map((part) => Number(part.trim()));
15838
+ if (numbers.length !== 4 || numbers.some((n) => !Number.isInteger(n) || n < 0) || numbers[2] < 1 || numbers[3] < 1) {
15839
+ throw new Error(`a box is written "label:x,y,width,height" in template pixels, e.g. "Play:40,30,120,40"; got "${text}"`);
15840
+ }
15841
+ const [x, y, width, height] = numbers;
15842
+ return { ...label ? { label } : {}, x, y, width, height };
15843
+ }
15844
+ function parseUiInsets(text) {
15845
+ const numbers = text.split(",").map((part) => Number(part.trim()));
15846
+ if (numbers.length !== 1 && numbers.length !== 4 || numbers.some((n) => !Number.isInteger(n) || n < 0)) {
15847
+ throw new Error(`insets are one whole number for every side, or "left,right,top,bottom"; got "${text}"`);
15848
+ }
15849
+ const [left, right = left, top = left, bottom = left] = numbers;
15850
+ return { left, right, top, bottom };
15851
+ }
15852
+ function checkUiInsets(insets, size) {
15853
+ if (insets.left + insets.right >= size.width || insets.top + insets.bottom >= size.height) {
15854
+ throw new Error(
15855
+ `insets ${insets.left},${insets.right},${insets.top},${insets.bottom} leave no middle to stretch in a ${size.width}x${size.height} image; left + right must be below the width and top + bottom below the height`
15856
+ );
15857
+ }
15858
+ }
15859
+ function uiStateElements(asset, only) {
15860
+ if (asset.kind === "state") throw new Error(`${asset.id} is a state; states are made for an element or a split template`);
15861
+ if (asset.kind === "element") return [asset.id];
15862
+ if (!asset.elements.length) {
15863
+ throw new Error(`template ${asset.id} has not been split; run pixelkiln ui split --id ${asset.id} first (free)`);
15864
+ }
15865
+ const ids = asset.elements.map((element) => element.id);
15866
+ if (!only?.length) return ids;
15867
+ const unknown = only.filter((id) => !ids.includes(id));
15868
+ if (unknown.length) throw new Error(`not elements of template ${asset.id}: ${unknown.join(", ")}`);
15869
+ return only;
15870
+ }
15871
+ async function createUiStates(client2, opts) {
15872
+ if (!opts.states.length) throw new Error("ui states needs at least one state");
15873
+ if (opts.states.length > UI_STATES_MAX_STATES) throw new Error(`PixelLab takes at most ${UI_STATES_MAX_STATES} states per call`);
15874
+ const before = await client2.getUiAssetDetail(opts.uiAssetId);
15875
+ const elementIds = uiStateElements(before, opts.elementIds);
15876
+ if (elementIds.length > UI_STATES_MAX_ELEMENTS) throw new Error(`PixelLab takes at most ${UI_STATES_MAX_ELEMENTS} elements per call`);
15877
+ const submitted = await client2.createUiStates({ elementIds, states: opts.states, targetPalette: opts.targetPalette });
15878
+ opts.onQuote?.(submitted.generations, submitted.count);
15879
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
15880
+ const interval = opts.intervalMs ?? 8e3;
15881
+ const timeout = opts.timeoutMs ?? 8 * 6e4;
15882
+ const started = Date.now();
15883
+ for (; ; ) {
15884
+ const job = await client2.getBackgroundJob(submitted.background_job_id);
15885
+ opts.onProgress?.(job.status);
15886
+ if (job.status === "failed") throw new Error(`PixelLab UI states job ${submitted.background_job_id} failed upstream`);
15887
+ if (job.status === "completed") {
15888
+ return {
15889
+ jobId: submitted.background_job_id,
15890
+ elementIds,
15891
+ quotedGenerations: submitted.generations,
15892
+ count: submitted.count,
15893
+ usage: job.usage ?? null,
15894
+ asset: await client2.getUiAssetDetail(opts.uiAssetId)
15895
+ };
15896
+ }
15897
+ if (Date.now() - started > timeout) {
15898
+ throw new Error(
15899
+ `PixelLab UI states job ${submitted.background_job_id} is still ${job.status} after ${Math.round(timeout / 1e3)} s; it keeps running upstream, and pixelkiln ui show will list the states once they are saved`
15900
+ );
15901
+ }
15902
+ await sleep3(interval);
15903
+ }
15904
+ }
15905
+ function slug(text, fallback) {
15906
+ const cleaned = (text ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
15907
+ return cleaned || fallback;
15908
+ }
15909
+ async function pullUiAsset(client2, uiAssetId, opts) {
15910
+ const asset = await client2.getUiAssetDetail(uiAssetId);
15911
+ if (asset.status && asset.status !== "completed") throw new Error(`UI asset ${uiAssetId} is ${asset.status}; pull it once it is completed`);
15912
+ if (!asset.image_url) throw new Error(`UI asset ${uiAssetId} has no image yet`);
15913
+ const dir = import_node_path22.default.resolve(opts.out);
15914
+ const record = import_node_path22.default.join(dir, "ui.json");
15915
+ const plan = [];
15916
+ const insets = (part) => part.nine_slice ? { nineSlice: { left: part.nine_slice.left, right: part.nine_slice.right, top: part.nine_slice.top, bottom: part.nine_slice.bottom } } : {};
15917
+ const taken = /* @__PURE__ */ new Set();
15918
+ const unique = (base) => {
15919
+ let name = base;
15920
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
15921
+ taken.add(name);
15922
+ return name;
15923
+ };
15924
+ const kind = asset.kind ?? "template";
15925
+ const rootName = slug(asset.name, kind);
15926
+ plan.push({ id: asset.id, kind, name: rootName, file: `${rootName}.png`, size: asset.size, url: asset.image_url, ...insets(asset) });
15927
+ const addStates = (owner, ownerName, states) => {
15928
+ const stateNames = /* @__PURE__ */ new Set();
15929
+ for (const [i, state] of states.entries()) {
15930
+ let stateName = slug(state.name, `state-${i + 1}`);
15931
+ for (let n = 2; stateNames.has(stateName); n++) stateName = `${slug(state.name, `state-${i + 1}`)}-${n}`;
15932
+ stateNames.add(stateName);
15933
+ plan.push({
15934
+ id: state.id,
15935
+ kind: "state",
15936
+ name: `${ownerName}.${stateName}`,
15937
+ file: `elements/${ownerName}.${stateName}.png`,
15938
+ size: state.size,
15939
+ url: state.image_url,
15940
+ elementId: owner.id,
15941
+ ...insets(state)
15942
+ });
15943
+ }
15944
+ };
15945
+ for (const [i, element] of asset.elements.entries()) {
15946
+ const name = unique(slug(element.name || element.template_box?.label, `element-${i + 1}`));
15947
+ const box = element.template_box;
15948
+ plan.push({
15949
+ id: element.id,
15950
+ kind: "element",
15951
+ name,
15952
+ file: `elements/${name}.png`,
15953
+ size: element.size,
15954
+ url: element.image_url,
15955
+ ...box ? { box: { ...box.label ? { label: box.label } : {}, x: box.x, y: box.y, width: box.width, height: box.height } } : {},
15956
+ ...insets(element)
15957
+ });
15958
+ addStates(element, name, element.states);
15959
+ }
15960
+ if (kind === "element") addStates(asset, rootName, asset.states);
15961
+ if (!opts.force) {
15962
+ for (const file of [record, ...plan.map((item) => import_node_path22.default.join(dir, item.file))]) {
15963
+ if ((0, import_node_fs19.existsSync)(file)) throw new Error(`${file} already exists; pass --force to replace it`);
15964
+ }
15965
+ }
15966
+ const files = [];
15967
+ for (const { url, ...item } of plan) {
15968
+ const bytes = await client2.download(url);
15969
+ validateMedia(bytes, MediaType.PNG);
15970
+ const target = import_node_path22.default.join(dir, item.file);
15971
+ await (0, import_promises13.mkdir)(import_node_path22.default.dirname(target), { recursive: true });
15972
+ await (0, import_promises13.writeFile)(target, bytes);
15973
+ files.push({ ...item, sha256: sha256(bytes) });
15974
+ }
15975
+ await (0, import_promises13.writeFile)(
15976
+ record,
15977
+ JSON.stringify(
15978
+ {
15979
+ schema: "pixelkiln-ui",
15980
+ version: 1,
15981
+ provider: "pixellab",
15982
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
15983
+ uiAssetId: asset.id,
15984
+ kind,
15985
+ prompt: asset.prompt,
15986
+ files
15987
+ },
15988
+ null,
15989
+ 2
15990
+ ) + "\n"
15991
+ );
15992
+ return { dir, record, files };
15993
+ }
15994
+
15995
+ // src/pixellab-assets.ts
15996
+ var import_node_fs20 = require("fs");
15997
+ var import_promises14 = require("fs/promises");
15998
+ var import_node_path23 = __toESM(require("path"), 1);
15999
+ var ASSET_KINDS = ["object", "character"];
16000
+ var EXPORT_FORMATS = ["zip", "spritesheet", "aseprite", "gif"];
16001
+ var MIRROR_DIRECTIONS = ["east", "west", "south-east", "south-west", "north-east", "north-west"];
16002
+ var EXPAND_DIRECTIONS = ["south", "south-east", "east", "north-east", "north", "north-west", "west", "south-west"];
16003
+ var EXPAND_MIN_COST = 10;
16004
+ var EXPAND_MAX_COST = 25;
16005
+ var IMPORT_MAX_SIDE = 256;
16006
+ function parseCanvasSize(text, kind) {
16007
+ const match = /^(\d+)\s*x\s*(\d+)$/i.exec(text.trim());
16008
+ const max = kind === "object" ? 400 : 256;
16009
+ const width = Number(match?.[1]);
16010
+ const height = Number(match?.[2]);
16011
+ if (!match || [width, height].some((side) => side < 8 || side > max || side % 4 !== 0)) {
16012
+ throw new Error(`--size is <width>x<height> in multiples of 4, from 8 to ${max} for a ${kind}, e.g. 64x64; got "${text}"`);
16013
+ }
16014
+ return { width, height };
16015
+ }
16016
+ function exportOutPath(out, format) {
16017
+ const extension = format === "aseprite" ? ".aseprite" : format === "gif" ? ".gif" : ".zip";
16018
+ return import_node_path23.default.extname(out) ? import_node_path23.default.resolve(out) : import_node_path23.default.resolve(`${out}${extension}`);
16019
+ }
16020
+ function checkExportBytes(bytes, format) {
16021
+ const ok = format === "gif" ? bytes.subarray(0, 4).toString("ascii") === "GIF8" : format === "aseprite" ? bytes.length > 6 && bytes.readUInt16LE(4) === 42464 : bytes.subarray(0, 2).toString("ascii") === "PK";
16022
+ if (!ok) throw new Error(`PixelLab's ${format} export was not a ${format === "spritesheet" ? "ZIP" : format} file (${bytes.length} bytes)`);
16023
+ }
16024
+ async function exportAssetFile(client2, kind, id, format, opts) {
16025
+ const out = exportOutPath(opts.out, format);
16026
+ if ((0, import_node_fs20.existsSync)(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
16027
+ const bytes = await client2.exportAsset(kind, id, format, { animationGroupId: opts.animationGroupId, direction: opts.direction });
16028
+ checkExportBytes(bytes, format);
16029
+ await (0, import_promises14.mkdir)(import_node_path23.default.dirname(out), { recursive: true });
16030
+ await (0, import_promises14.writeFile)(out, bytes);
16031
+ return { out, bytes: bytes.length };
16032
+ }
16033
+ async function importObjectFile(client2, file, opts = {}) {
16034
+ const bytes = await (0, import_promises14.readFile)(file);
16035
+ const metadata = imageMetadata(bytes);
16036
+ if (!metadata || metadata.format !== "png") throw new Error(`${file} is not a PNG; PixelLab imports PNG only (JPEG compression would be stored as pixels)`);
16037
+ if (metadata.width > IMPORT_MAX_SIDE || metadata.height > IMPORT_MAX_SIDE) {
16038
+ throw new Error(`${file} is ${metadata.width}x${metadata.height}; PixelLab imports at most ${IMPORT_MAX_SIDE}x${IMPORT_MAX_SIDE}`);
16039
+ }
16040
+ const res = await client2.importObject({ image: { base64: bytes.toString("base64"), format: "png" }, name: opts.name });
16041
+ return { objectId: res.object_id, name: res.name ?? null, size: { width: res.size.width, height: res.size.height }, imageUrl: res.image_url };
16042
+ }
16043
+ async function expandObject(client2, id, opts) {
16044
+ const submitted = await client2.expandObjectRotations(id, { existingDirection: opts.existingDirection, description: opts.description });
16045
+ opts.onQuote?.(submitted.min_generations, submitted.max_generations);
16046
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
16047
+ const interval = opts.intervalMs ?? 1e4;
16048
+ const timeout = opts.timeoutMs ?? 10 * 6e4;
16049
+ const started = Date.now();
16050
+ for (; ; ) {
16051
+ const object = await client2.getObject(id);
16052
+ const status = object.status ?? "unknown";
16053
+ opts.onProgress?.(status);
16054
+ if (status === "failed") throw new Error(`PixelLab could not expand object ${id}`);
16055
+ if (status !== "expanding") {
16056
+ let usage = null;
16057
+ try {
16058
+ usage = (await client2.getBackgroundJob(submitted.background_job_id)).usage ?? null;
16059
+ } catch {
16060
+ usage = null;
16061
+ }
16062
+ return { objectId: id, jobId: submitted.background_job_id, minGenerations: submitted.min_generations, maxGenerations: submitted.max_generations, status, usage };
16063
+ }
16064
+ if (Date.now() - started > timeout) {
16065
+ throw new Error(`object ${id} is still expanding after ${Math.round(timeout / 1e3)} s; it keeps running upstream, and asset expand --keep or --discard finishes it later`);
16066
+ }
16067
+ await sleep3(interval);
16068
+ }
16069
+ }
16070
+ async function pullExpansionReview(client2, id, opts) {
16071
+ const object = await client2.getObject(id);
16072
+ const review = object.expansion_review;
16073
+ if (object.status !== "review-expansion" || !review?.rotation_urls) {
16074
+ throw new Error(`object ${id} is ${object.status ?? "unknown"}; there is no expansion waiting for review`);
16075
+ }
16076
+ const dir = import_node_path23.default.resolve(opts.out);
16077
+ const entries = Object.entries(review.rotation_urls).filter((entry) => typeof entry[1] === "string");
16078
+ const files = entries.map(([direction]) => ({ direction, file: import_node_path23.default.join(dir, `${direction}.png`) }));
16079
+ if (!opts.force) {
16080
+ for (const { file } of files) if ((0, import_node_fs20.existsSync)(file)) throw new Error(`${file} already exists; pass --force to replace it`);
16081
+ }
16082
+ await (0, import_promises14.mkdir)(dir, { recursive: true });
16083
+ for (const [index, [, url]] of entries.entries()) {
16084
+ const bytes = await client2.download(url);
16085
+ validateMedia(bytes, MediaType.PNG);
16086
+ await (0, import_promises14.writeFile)(files[index].file, bytes);
16087
+ }
16088
+ return { dir, existingDirection: review.existing_direction ?? null, files };
16089
+ }
16090
+
16091
+ // src/pipeline/quality-regression.ts
16092
+ var import_node_path24 = __toESM(require("path"), 1);
16093
+ var import_node_fs21 = require("fs");
16094
+ var import_promises15 = require("fs/promises");
14969
16095
  var import_zod5 = require("zod");
14970
16096
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
14971
16097
  var HEX_RE = /^#[0-9a-f]{6}$/;
14972
16098
  var MAX_REDMEAN_DISTANCE = 765;
14973
16099
  var QualityPathSchema = import_zod5.z.string().min(1).refine(
14974
- (value) => !import_node_path21.default.posix.isAbsolute(value) && !value.includes("\\"),
16100
+ (value) => !import_node_path24.default.posix.isAbsolute(value) && !value.includes("\\"),
14975
16101
  "expected a portable relative path"
14976
16102
  );
14977
16103
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -15118,10 +16244,10 @@ function measureDecodedImageQuality(png, digest2) {
15118
16244
  };
15119
16245
  }
15120
16246
  async function measureImageQuality(file) {
15121
- const absolute = import_node_path21.default.resolve(file);
16247
+ const absolute = import_node_path24.default.resolve(file);
15122
16248
  let bytes;
15123
16249
  try {
15124
- bytes = await (0, import_promises12.readFile)(absolute);
16250
+ bytes = await (0, import_promises15.readFile)(absolute);
15125
16251
  } catch (error) {
15126
16252
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
15127
16253
  }
@@ -15140,11 +16266,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
15140
16266
  }
15141
16267
  const ids = parsed.data.map((entry) => entry.id);
15142
16268
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
15143
- const root = import_node_path21.default.dirname(import_node_path21.default.resolve(inputsFilePath));
16269
+ const root = import_node_path24.default.dirname(import_node_path24.default.resolve(inputsFilePath));
15144
16270
  return parsed.data.map((entry) => ({
15145
16271
  id: entry.id,
15146
- file: import_node_path21.default.resolve(root, entry.path),
15147
- ...entry.record ? { record: import_node_path21.default.resolve(root, entry.record) } : {},
16272
+ file: import_node_path24.default.resolve(root, entry.path),
16273
+ ...entry.record ? { record: import_node_path24.default.resolve(root, entry.record) } : {},
15148
16274
  tolerances: QualityToleranceSchema.parse({
15149
16275
  ...DEFAULT_QUALITY_TOLERANCES,
15150
16276
  ...entry.tolerances
@@ -15152,7 +16278,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
15152
16278
  }));
15153
16279
  }
15154
16280
  function portableRelative2(from, to) {
15155
- return import_node_path21.default.relative(from, import_node_path21.default.resolve(to)).split(import_node_path21.default.sep).join("/") || ".";
16281
+ return import_node_path24.default.relative(from, import_node_path24.default.resolve(to)).split(import_node_path24.default.sep).join("/") || ".";
15156
16282
  }
15157
16283
  async function verifyRecordForImage(recordPath, imagePath) {
15158
16284
  const verification = await verifyArtifactBundle(recordPath);
@@ -15167,20 +16293,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
15167
16293
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
15168
16294
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
15169
16295
  }
15170
- const outputs = record.outputs.map((output) => import_node_path21.default.resolve(import_node_path21.default.dirname(recordPath), output.path));
15171
- if (!outputs.includes(import_node_path21.default.resolve(imagePath))) {
16296
+ const outputs = record.outputs.map((output) => import_node_path24.default.resolve(import_node_path24.default.dirname(recordPath), output.path));
16297
+ if (!outputs.includes(import_node_path24.default.resolve(imagePath))) {
15172
16298
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
15173
16299
  }
15174
16300
  }
15175
16301
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
15176
16302
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
15177
- const absolute = import_node_path21.default.resolve(baselinePath);
16303
+ const absolute = import_node_path24.default.resolve(baselinePath);
15178
16304
  for (const input of inputs) {
15179
- if (import_node_path21.default.resolve(input.file) === absolute || input.record && import_node_path21.default.resolve(input.record) === absolute) {
16305
+ if (import_node_path24.default.resolve(input.file) === absolute || input.record && import_node_path24.default.resolve(input.record) === absolute) {
15180
16306
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
15181
16307
  }
15182
16308
  }
15183
- const root = import_node_path21.default.dirname(absolute);
16309
+ const root = import_node_path24.default.dirname(absolute);
15184
16310
  const cases = [];
15185
16311
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
15186
16312
  const expected = await measureImageQuality(input.file);
@@ -15207,8 +16333,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
15207
16333
  cases
15208
16334
  });
15209
16335
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
15210
- if ((0, import_node_fs18.existsSync)(absolute) && !options.force) {
15211
- const current = await (0, import_promises12.readFile)(absolute);
16336
+ if ((0, import_node_fs21.existsSync)(absolute) && !options.force) {
16337
+ const current = await (0, import_promises15.readFile)(absolute);
15212
16338
  if (!current.equals(data)) {
15213
16339
  throw new OverwriteRefusedError(
15214
16340
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -15220,13 +16346,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
15220
16346
  return { baseline, path: absolute, changed: result.changed.length > 0 };
15221
16347
  }
15222
16348
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
15223
- const absolute = import_node_path21.default.resolve(baselinePath);
15224
- if (!(0, import_node_fs18.existsSync)(absolute)) {
16349
+ const absolute = import_node_path24.default.resolve(baselinePath);
16350
+ if (!(0, import_node_fs21.existsSync)(absolute)) {
15225
16351
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
15226
16352
  }
15227
16353
  let raw;
15228
16354
  try {
15229
- raw = JSON.parse(await (0, import_promises12.readFile)(absolute, "utf8"));
16355
+ raw = JSON.parse(await (0, import_promises15.readFile)(absolute, "utf8"));
15230
16356
  } catch (error) {
15231
16357
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
15232
16358
  }
@@ -15236,12 +16362,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
15236
16362
  if (unknown.length) {
15237
16363
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
15238
16364
  }
15239
- const root = import_node_path21.default.dirname(absolute);
16365
+ const root = import_node_path24.default.dirname(absolute);
15240
16366
  const cases = [...raw.cases];
15241
16367
  const report = [];
15242
16368
  for (const id of only) {
15243
16369
  const input = byId.get(id);
15244
- if (import_node_path21.default.resolve(input.file) === absolute || input.record && import_node_path21.default.resolve(input.record) === absolute) {
16370
+ if (import_node_path24.default.resolve(input.file) === absolute || input.record && import_node_path24.default.resolve(input.record) === absolute) {
15245
16371
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
15246
16372
  }
15247
16373
  const expected = await measureImageQuality(input.file);
@@ -15271,16 +16397,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
15271
16397
  }
15272
16398
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
15273
16399
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
15274
- const current = await (0, import_promises12.readFile)(absolute);
16400
+ const current = await (0, import_promises15.readFile)(absolute);
15275
16401
  const changed = !current.equals(data);
15276
16402
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
15277
16403
  return { baseline, path: absolute, changed, cases: report };
15278
16404
  }
15279
16405
  async function readQualityBaseline(baselinePath) {
15280
- const absolute = import_node_path21.default.resolve(baselinePath);
16406
+ const absolute = import_node_path24.default.resolve(baselinePath);
15281
16407
  let raw;
15282
16408
  try {
15283
- raw = JSON.parse(await (0, import_promises12.readFile)(absolute, "utf8"));
16409
+ raw = JSON.parse(await (0, import_promises15.readFile)(absolute, "utf8"));
15284
16410
  } catch (error) {
15285
16411
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
15286
16412
  }
@@ -15302,7 +16428,7 @@ async function readQualityBaseline(baselinePath) {
15302
16428
  throw new Error(
15303
16429
  `Invalid quality baseline ${absolute}:
15304
16430
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
15305
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${import_node_path21.default.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
16431
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${import_node_path24.default.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
15306
16432
  );
15307
16433
  }
15308
16434
  return parsed.data;
@@ -15364,12 +16490,12 @@ function regressionViolations(expected, actual, tolerances) {
15364
16490
  return { violations, warnings };
15365
16491
  }
15366
16492
  async function checkQualityBaseline(baselinePath) {
15367
- const absolute = import_node_path21.default.resolve(baselinePath);
16493
+ const absolute = import_node_path24.default.resolve(baselinePath);
15368
16494
  const baseline = await readQualityBaseline(absolute);
15369
- const root = import_node_path21.default.dirname(absolute);
16495
+ const root = import_node_path24.default.dirname(absolute);
15370
16496
  const cases = [];
15371
16497
  for (const entry of baseline.cases) {
15372
- const file = import_node_path21.default.resolve(root, entry.file);
16498
+ const file = import_node_path24.default.resolve(root, entry.file);
15373
16499
  let actual = null;
15374
16500
  const violations = [];
15375
16501
  const warnings = [];
@@ -15382,7 +16508,7 @@ async function checkQualityBaseline(baselinePath) {
15382
16508
  violations.push(message4(error));
15383
16509
  }
15384
16510
  if (entry.record) {
15385
- const recordPath = import_node_path21.default.resolve(root, entry.record.path);
16511
+ const recordPath = import_node_path24.default.resolve(root, entry.record.path);
15386
16512
  try {
15387
16513
  const recordHash = await sha256File(recordPath);
15388
16514
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -15418,14 +16544,14 @@ async function checkQualityBaseline(baselinePath) {
15418
16544
  }
15419
16545
 
15420
16546
  // src/pipeline/cache-health.ts
15421
- var import_node_fs22 = require("fs");
15422
- var import_promises15 = require("fs/promises");
15423
- var import_node_path25 = __toESM(require("path"), 1);
16547
+ var import_node_fs25 = require("fs");
16548
+ var import_promises18 = require("fs/promises");
16549
+ var import_node_path28 = __toESM(require("path"), 1);
15424
16550
 
15425
16551
  // src/cache.ts
15426
- var import_promises13 = require("fs/promises");
15427
- var import_node_fs19 = require("fs");
15428
- var import_node_path22 = __toESM(require("path"), 1);
16552
+ var import_promises16 = require("fs/promises");
16553
+ var import_node_fs22 = require("fs");
16554
+ var import_node_path25 = __toESM(require("path"), 1);
15429
16555
  var import_zod6 = require("zod");
15430
16556
  var HashCacheSchema = import_zod6.z.object({
15431
16557
  version: import_zod6.z.literal(1),
@@ -15439,10 +16565,10 @@ function isSha256Hash(value) {
15439
16565
  function parseCache(value) {
15440
16566
  return HashCacheSchema.parse(value);
15441
16567
  }
15442
- async function loadCache(path43) {
15443
- if (!(0, import_node_fs19.existsSync)(path43)) return { version: 1, hashes: {} };
16568
+ async function loadCache(path46) {
16569
+ if (!(0, import_node_fs22.existsSync)(path46)) return { version: 1, hashes: {} };
15444
16570
  try {
15445
- const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises13.readFile)(path43, "utf8")));
16571
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await (0, import_promises16.readFile)(path46, "utf8")));
15446
16572
  if (!parsed.success) return { version: 1, hashes: {} };
15447
16573
  return {
15448
16574
  version: 1,
@@ -15454,20 +16580,20 @@ async function loadCache(path43) {
15454
16580
  return { version: 1, hashes: {} };
15455
16581
  }
15456
16582
  }
15457
- async function saveCache(path43, cache) {
16583
+ async function saveCache(path46, cache) {
15458
16584
  const sorted = {};
15459
16585
  for (const key2 of Object.keys(cache.hashes).sort()) {
15460
16586
  const hash = cache.hashes[key2];
15461
16587
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
15462
16588
  sorted[key2] = hash;
15463
16589
  }
15464
- await (0, import_promises13.mkdir)(import_node_path22.default.dirname(import_node_path22.default.resolve(path43)), { recursive: true });
15465
- const tmp = `${path43}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
16590
+ await (0, import_promises16.mkdir)(import_node_path25.default.dirname(import_node_path25.default.resolve(path46)), { recursive: true });
16591
+ const tmp = `${path46}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15466
16592
  try {
15467
- await (0, import_promises13.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
15468
- await (0, import_promises13.rename)(tmp, path43);
16593
+ await (0, import_promises16.writeFile)(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
16594
+ await (0, import_promises16.rename)(tmp, path46);
15469
16595
  } finally {
15470
- await (0, import_promises13.rm)(tmp, { force: true });
16596
+ await (0, import_promises16.rm)(tmp, { force: true });
15471
16597
  }
15472
16598
  }
15473
16599
  function pruneCache(cache, liveIds, namespace = "") {
@@ -15489,20 +16615,20 @@ function cachePathFor(lockPath) {
15489
16615
  }
15490
16616
 
15491
16617
  // src/pipeline/history.ts
15492
- var import_node_fs21 = require("fs");
15493
- var import_node_path24 = __toESM(require("path"), 1);
16618
+ var import_node_fs24 = require("fs");
16619
+ var import_node_path27 = __toESM(require("path"), 1);
15494
16620
 
15495
16621
  // src/pipeline/fetch.ts
15496
- var import_node_fs20 = require("fs");
15497
- var import_promises14 = require("fs/promises");
15498
- var import_node_path23 = __toESM(require("path"), 1);
16622
+ var import_node_fs23 = require("fs");
16623
+ var import_promises17 = require("fs/promises");
16624
+ var import_node_path26 = __toESM(require("path"), 1);
15499
16625
  async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15500
16626
  const log = opts.onProgress ?? (() => {
15501
16627
  });
15502
16628
  const result = { downloaded: 0, skipped: 0, failed: 0, ...opts.refresh ? { unchanged: 0 } : {} };
15503
16629
  const specByKey = new Map(specs.map((s) => [lockKey(s.styleId, s.assetId), s]));
15504
16630
  normalizeLockOutputPaths(lock, specs);
15505
- const cacheDir = opts.cacheDir === false ? null : import_node_path23.default.resolve(opts.cacheDir ?? import_node_path23.default.join(import_node_path23.default.dirname(lockPath), ".pixelkiln", "cache"));
16631
+ const cacheDir = opts.cacheDir === false ? null : import_node_path26.default.resolve(opts.cacheDir ?? import_node_path26.default.join(import_node_path26.default.dirname(lockPath), ".pixelkiln", "cache"));
15506
16632
  const pending = Object.entries(lock.entries).filter(([key2, e]) => {
15507
16633
  if (e.provider !== provider.id || !specByKey.has(key2)) return false;
15508
16634
  if (specByKey.get(key2)?.mirror) return false;
@@ -15514,15 +16640,15 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15514
16640
  if (spec && e.specHash === spec.specHash && e.outputs.length && !postprocessCurrent(e, spec)) {
15515
16641
  return Boolean(opts.force) || e.outputs.every((output) => {
15516
16642
  const file = resolveOutputPath(output.path, spec.root);
15517
- return (0, import_node_fs20.existsSync)(file) && sha256((0, import_node_fs20.readFileSync)(file)) === output.sha256;
16643
+ return (0, import_node_fs23.existsSync)(file) && sha256((0, import_node_fs23.readFileSync)(file)) === output.sha256;
15518
16644
  });
15519
16645
  }
15520
16646
  if (!opts.repair) return false;
15521
16647
  if (e.outputs.length === 0 || !spec) return true;
15522
16648
  return e.outputs.some((output) => {
15523
16649
  const file = resolveOutputPath(output.path, spec.root);
15524
- if (!(0, import_node_fs20.existsSync)(file)) return true;
15525
- const current = sha256((0, import_node_fs20.readFileSync)(file));
16650
+ if (!(0, import_node_fs23.existsSync)(file)) return true;
16651
+ const current = sha256((0, import_node_fs23.readFileSync)(file));
15526
16652
  if (current === output.sha256) return false;
15527
16653
  return Boolean(opts.force) || (e.supersededOutputs ?? []).some((old) => old.sha256 === current);
15528
16654
  });
@@ -15605,21 +16731,21 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15605
16731
  if (!source.url) throw new Error(`no durable source URL to refresh ${source.role ?? "asset"} from`);
15606
16732
  fresh = await provider.download(source.url);
15607
16733
  if (recorded && sha256(fresh) === recordedRaw && !reapply) {
15608
- log(` current ${import_node_path23.default.relative(process.cwd(), target)}`);
16734
+ log(` current ${import_node_path26.default.relative(process.cwd(), target)}`);
15609
16735
  outputs.push({ ...recorded, path: portableOutputPath(target, spec.root) });
15610
16736
  continue;
15611
16737
  }
15612
16738
  }
15613
16739
  let raw = null;
15614
16740
  let final = null;
15615
- if ((0, import_node_fs20.existsSync)(target)) {
16741
+ if ((0, import_node_fs23.existsSync)(target)) {
15616
16742
  const currentHash = await sha256File(target);
15617
16743
  if (recorded && currentHash === recorded.sha256) {
15618
16744
  if (!fresh && !reapply) {
15619
16745
  if (cacheDir) {
15620
16746
  await cacheMedia(
15621
16747
  cacheDir,
15622
- await (0, import_promises14.readFile)(target),
16748
+ await (0, import_promises17.readFile)(target),
15623
16749
  recorded.mediaType ?? MediaType.PNG,
15624
16750
  recorded.sha256
15625
16751
  );
@@ -15628,10 +16754,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15628
16754
  continue;
15629
16755
  }
15630
16756
  if (reapply && !fresh) {
15631
- if (!recorded.raw) raw = await (0, import_promises14.readFile)(target);
15632
- log(` reapply ${import_node_path23.default.relative(process.cwd(), target)}`);
16757
+ if (!recorded.raw) raw = await (0, import_promises17.readFile)(target);
16758
+ log(` reapply ${import_node_path26.default.relative(process.cwd(), target)}`);
15633
16759
  } else {
15634
- log(` changed ${import_node_path23.default.relative(process.cwd(), target)} (upstream)`);
16760
+ log(` changed ${import_node_path26.default.relative(process.cwd(), target)} (upstream)`);
15635
16761
  }
15636
16762
  } else {
15637
16763
  const superseded = (entry.supersededOutputs ?? []).find(
@@ -15652,14 +16778,14 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15652
16778
  }
15653
16779
  if (outgoing && cacheDir) {
15654
16780
  try {
15655
- const oldBytes = await (0, import_promises14.readFile)(target);
16781
+ const oldBytes = await (0, import_promises17.readFile)(target);
15656
16782
  const oldMediaType = detectMediaType(oldBytes);
15657
16783
  if (oldMediaType) await cacheMedia(cacheDir, oldBytes, oldMediaType, currentHash);
15658
16784
  } catch {
15659
16785
  }
15660
16786
  }
15661
16787
  log(
15662
- ` replace ${import_node_path23.default.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
16788
+ ` replace ${import_node_path26.default.relative(process.cwd(), target)}` + (opts.force ? " (--force)" : " (previous tracked generation)")
15663
16789
  );
15664
16790
  }
15665
16791
  }
@@ -15668,7 +16794,7 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15668
16794
  } else if (!raw && recorded && cacheDir) {
15669
16795
  if (!reapply) final = await readCachedMedia(cacheDir, recorded.sha256, expectedMediaType);
15670
16796
  if (!final && recordedRaw) raw = await readCachedMedia(cacheDir, recordedRaw, expectedMediaType);
15671
- if (final || raw) log(` cached ${import_node_path23.default.relative(process.cwd(), target)}`);
16797
+ if (final || raw) log(` cached ${import_node_path26.default.relative(process.cwd(), target)}`);
15672
16798
  }
15673
16799
  if (!final && !raw) {
15674
16800
  if (!source.url) {
@@ -15695,13 +16821,13 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15695
16821
  buf = processed.bytes;
15696
16822
  if (processed.changed) {
15697
16823
  rawHash = sha256(raw);
15698
- log(` snapped ${import_node_path23.default.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
16824
+ log(` snapped ${import_node_path26.default.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
15699
16825
  }
15700
16826
  }
15701
16827
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
15702
- await (0, import_promises14.mkdir)(import_node_path23.default.dirname(target), { recursive: true });
16828
+ await (0, import_promises17.mkdir)(import_node_path26.default.dirname(target), { recursive: true });
15703
16829
  const tmp = `${target}.pixelkiln.tmp`;
15704
- await (0, import_promises14.writeFile)(tmp, buf);
16830
+ await (0, import_promises17.writeFile)(tmp, buf);
15705
16831
  outputs.push({
15706
16832
  path: portableOutputPath(target, spec.root),
15707
16833
  sha256: sha256(buf),
@@ -15711,9 +16837,9 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15711
16837
  });
15712
16838
  upsert(lock, key2, { outputs: mergeOutputs(entry.outputs, outputs) });
15713
16839
  await saveLock(lockPath, lock);
15714
- await (0, import_promises14.rename)(tmp, target);
16840
+ await (0, import_promises17.rename)(tmp, target);
15715
16841
  wrote = true;
15716
- log(` wrote ${import_node_path23.default.relative(process.cwd(), target)}`);
16842
+ log(` wrote ${import_node_path26.default.relative(process.cwd(), target)}`);
15717
16843
  }
15718
16844
  if (opts.refresh && !wrote) {
15719
16845
  if (rotated) {
@@ -15757,10 +16883,10 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
15757
16883
  return result;
15758
16884
  }
15759
16885
  async function readCachedMedia(cacheDir, hash, mediaType) {
15760
- const file = import_node_path23.default.join(cacheDir, cacheFileName(hash, mediaType));
15761
- if (!(0, import_node_fs20.existsSync)(file)) return null;
16886
+ const file = import_node_path26.default.join(cacheDir, cacheFileName(hash, mediaType));
16887
+ if (!(0, import_node_fs23.existsSync)(file)) return null;
15762
16888
  try {
15763
- const buf = await (0, import_promises14.readFile)(file);
16889
+ const buf = await (0, import_promises17.readFile)(file);
15764
16890
  if (sha256(buf) !== hash) return null;
15765
16891
  validateMedia(buf, mediaType);
15766
16892
  return buf;
@@ -15771,17 +16897,17 @@ async function readCachedMedia(cacheDir, hash, mediaType) {
15771
16897
  async function cacheMedia(cacheDir, buf, mediaType, knownHash) {
15772
16898
  const hash = knownHash ?? sha256(buf);
15773
16899
  validateMedia(buf, mediaType);
15774
- const file = import_node_path23.default.join(cacheDir, cacheFileName(hash, mediaType));
16900
+ const file = import_node_path26.default.join(cacheDir, cacheFileName(hash, mediaType));
15775
16901
  if (await readCachedMedia(cacheDir, hash, mediaType)) return;
15776
- await (0, import_promises14.mkdir)(cacheDir, { recursive: true });
16902
+ await (0, import_promises17.mkdir)(cacheDir, { recursive: true });
15777
16903
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
15778
- await (0, import_promises14.writeFile)(tmp, buf);
16904
+ await (0, import_promises17.writeFile)(tmp, buf);
15779
16905
  try {
15780
- await (0, import_promises14.rename)(tmp, file);
16906
+ await (0, import_promises17.rename)(tmp, file);
15781
16907
  } catch (err) {
15782
- if (!(0, import_node_fs20.existsSync)(file)) throw err;
16908
+ if (!(0, import_node_fs23.existsSync)(file)) throw err;
15783
16909
  } finally {
15784
- await (0, import_promises14.rm)(tmp, { force: true });
16910
+ await (0, import_promises17.rm)(tmp, { force: true });
15785
16911
  }
15786
16912
  }
15787
16913
  function mergeOutputs(previous, current) {
@@ -15903,10 +17029,10 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15903
17029
  }
15904
17030
  for (let i = 0; i < entry.outputs.length; i++) {
15905
17031
  const file = currentEntryOutputPath(entry, spec, i);
15906
- if (!(0, import_node_fs21.existsSync)(file)) continue;
17032
+ if (!(0, import_node_fs24.existsSync)(file)) continue;
15907
17033
  if (await sha256File(file) !== entry.outputs[i].sha256 && !opts.force) {
15908
17034
  throw new OverwriteRefusedError(
15909
- `${import_node_path24.default.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
17035
+ `${import_node_path27.default.relative(process.cwd(), file)} was changed after download; keep it with pixelkiln edit, or pass --force to replace it`,
15910
17036
  [file]
15911
17037
  );
15912
17038
  }
@@ -15970,11 +17096,11 @@ async function revertGeneration(provider, spec, lock, lockPath, opts) {
15970
17096
 
15971
17097
  // src/pipeline/cache-health.ts
15972
17098
  async function inspectCaches(lock, lockPath, options = {}) {
15973
- if (options.prune && !(0, import_node_fs22.existsSync)(lockPath)) {
15974
- throw new Error(`Refusing to prune without an existing lockfile at ${import_node_path25.default.resolve(lockPath)}`);
17099
+ if (options.prune && !(0, import_node_fs25.existsSync)(lockPath)) {
17100
+ throw new Error(`Refusing to prune without an existing lockfile at ${import_node_path28.default.resolve(lockPath)}`);
15975
17101
  }
15976
- const contentDir = import_node_path25.default.resolve(import_node_path25.default.dirname(lockPath), ".pixelkiln", "cache");
15977
- const remotePath = import_node_path25.default.resolve(cachePathFor(lockPath));
17102
+ const contentDir = import_node_path28.default.resolve(import_node_path28.default.dirname(lockPath), ".pixelkiln", "cache");
17103
+ const remotePath = import_node_path28.default.resolve(cachePathFor(lockPath));
15978
17104
  const referenced = referencedHashes(lock);
15979
17105
  let content = await inspectContentCache(contentDir, referenced);
15980
17106
  let remoteHashes = await inspectRemoteHashCache(remotePath);
@@ -15986,7 +17112,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15986
17112
  ]);
15987
17113
  for (const name of names) {
15988
17114
  try {
15989
- await (0, import_promises15.rm)(import_node_path25.default.join(contentDir, name), { force: true });
17115
+ await (0, import_promises18.rm)(import_node_path28.default.join(contentDir, name), { force: true });
15990
17116
  removed.contentFiles++;
15991
17117
  } catch {
15992
17118
  }
@@ -15995,7 +17121,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
15995
17121
  await saveCache(remotePath, { version: 1, hashes: {} });
15996
17122
  removed.resetRemoteHashCache = true;
15997
17123
  } else if (remoteHashes.invalidIds.length) {
15998
- const cache = parseCache(JSON.parse(await (0, import_promises15.readFile)(remotePath, "utf8")));
17124
+ const cache = parseCache(JSON.parse(await (0, import_promises18.readFile)(remotePath, "utf8")));
15999
17125
  for (const id of remoteHashes.invalidIds) delete cache.hashes[id];
16000
17126
  removed.remoteHashEntries = remoteHashes.invalidIds.length;
16001
17127
  await saveCache(remotePath, cache);
@@ -16013,7 +17139,7 @@ async function inspectCaches(lock, lockPath, options = {}) {
16013
17139
  async function inspectContentCache(contentDir, referenced) {
16014
17140
  const report = {
16015
17141
  path: contentDir,
16016
- exists: (0, import_node_fs22.existsSync)(contentDir),
17142
+ exists: (0, import_node_fs25.existsSync)(contentDir),
16017
17143
  files: 0,
16018
17144
  bytes: 0,
16019
17145
  valid: 0,
@@ -16027,19 +17153,19 @@ async function inspectContentCache(contentDir, referenced) {
16027
17153
  return report;
16028
17154
  }
16029
17155
  const present = /* @__PURE__ */ new Set();
16030
- const entries = await (0, import_promises15.readdir)(contentDir, { withFileTypes: true });
17156
+ const entries = await (0, import_promises18.readdir)(contentDir, { withFileTypes: true });
16031
17157
  for (const entry of entries) {
16032
17158
  if (!entry.isFile()) {
16033
17159
  report.invalid.push({ name: entry.name, reason: "not a regular file" });
16034
17160
  continue;
16035
17161
  }
16036
17162
  report.files++;
16037
- const file = import_node_path25.default.join(contentDir, entry.name);
17163
+ const file = import_node_path28.default.join(contentDir, entry.name);
16038
17164
  const mediaType = mediaTypeFromExtension(entry.name);
16039
17165
  const expected = mediaType ? entry.name.slice(0, -4) : "";
16040
17166
  let bytes;
16041
17167
  try {
16042
- bytes = await (0, import_promises15.readFile)(file);
17168
+ bytes = await (0, import_promises18.readFile)(file);
16043
17169
  report.bytes += bytes.length;
16044
17170
  } catch (err) {
16045
17171
  report.invalid.push({
@@ -16077,7 +17203,7 @@ async function inspectContentCache(contentDir, referenced) {
16077
17203
  async function inspectRemoteHashCache(remotePath) {
16078
17204
  const report = {
16079
17205
  path: remotePath,
16080
- exists: (0, import_node_fs22.existsSync)(remotePath),
17206
+ exists: (0, import_node_fs25.existsSync)(remotePath),
16081
17207
  entries: 0,
16082
17208
  valid: 0,
16083
17209
  invalidIds: [],
@@ -16086,7 +17212,7 @@ async function inspectRemoteHashCache(remotePath) {
16086
17212
  if (!report.exists) return report;
16087
17213
  let cache;
16088
17214
  try {
16089
- cache = parseCache(JSON.parse(await (0, import_promises15.readFile)(remotePath, "utf8")));
17215
+ cache = parseCache(JSON.parse(await (0, import_promises18.readFile)(remotePath, "utf8")));
16090
17216
  } catch (err) {
16091
17217
  report.error = err instanceof Error ? err.message : String(err);
16092
17218
  return report;
@@ -16101,20 +17227,20 @@ async function inspectRemoteHashCache(remotePath) {
16101
17227
  }
16102
17228
 
16103
17229
  // src/pipeline/pack.ts
16104
- var import_node_fs23 = require("fs");
16105
- var import_node_path26 = __toESM(require("path"), 1);
17230
+ var import_node_fs26 = require("fs");
17231
+ var import_node_path29 = __toESM(require("path"), 1);
16106
17232
  var DEFAULT_FRAME_SET_FPS = 12;
16107
17233
  function resolvePackInputs(raw, inputsFilePath) {
16108
17234
  if (!Array.isArray(raw) || !raw.length) {
16109
17235
  throw new Error("--inputs must be a non-empty JSON array of { id, path }");
16110
17236
  }
16111
- const baseDir = import_node_path26.default.dirname(import_node_path26.default.resolve(inputsFilePath));
17237
+ const baseDir = import_node_path29.default.dirname(import_node_path29.default.resolve(inputsFilePath));
16112
17238
  return raw.map((entry, i) => {
16113
17239
  const e = entry;
16114
17240
  if (typeof e.id !== "string" || typeof e.path !== "string") {
16115
17241
  throw new Error(`--inputs[${i}] needs string "id" and "path"`);
16116
17242
  }
16117
- return { id: e.id, path: import_node_path26.default.resolve(baseDir, e.path) };
17243
+ return { id: e.id, path: import_node_path29.default.resolve(baseDir, e.path) };
16118
17244
  });
16119
17245
  }
16120
17246
  function packSprites(inputs, options = {}) {
@@ -16135,7 +17261,7 @@ function packSprites(inputs, options = {}) {
16135
17261
  for (const input of ordered) {
16136
17262
  let sourceHash = null;
16137
17263
  try {
16138
- const bytes = (0, import_node_fs23.readFileSync)(input.path);
17264
+ const bytes = (0, import_node_fs26.readFileSync)(input.path);
16139
17265
  sourceHash = sha256(bytes);
16140
17266
  const png = decodePng(bytes);
16141
17267
  sprites.push({ id: input.id, width: png.width, height: png.height, pixels: png.pixels });
@@ -16198,7 +17324,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
16198
17324
  }
16199
17325
  const inputs2 = Object.entries(options.sourceOverrides).map(([id, source]) => ({
16200
17326
  id,
16201
- path: import_node_path26.default.resolve(source)
17327
+ path: import_node_path29.default.resolve(source)
16202
17328
  }));
16203
17329
  if (!inputs2.length) throw new Error(`No approved quality outputs for style "${styleId}".`);
16204
17330
  const packed2 = packSprites(inputs2, options);
@@ -16222,7 +17348,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
16222
17348
  let outputs = resolveEntryOutputs(entry, id, manifestDir);
16223
17349
  const source = sources[id];
16224
17350
  if (source && outputs.length <= 1) {
16225
- inputs.push({ id, path: import_node_path26.default.resolve(manifestDir, source) });
17351
+ inputs.push({ id, path: import_node_path29.default.resolve(manifestDir, source) });
16226
17352
  continue;
16227
17353
  }
16228
17354
  if (source && sourceIsStem(source, entry, manifestDir)) {
@@ -16257,7 +17383,7 @@ function packStyle(lock, styleId, manifestDir, options = {}) {
16257
17383
  }
16258
17384
  }
16259
17385
  for (const [id, source] of Object.entries(sources)) {
16260
- if (!locked.has(id)) inputs.push({ id, path: import_node_path26.default.resolve(manifestDir, source) });
17386
+ if (!locked.has(id)) inputs.push({ id, path: import_node_path29.default.resolve(manifestDir, source) });
16261
17387
  }
16262
17388
  if (!inputs.length) {
16263
17389
  throw new Error(`No readable sprites for style "${styleId}"; ${noOutput.length} skipped.`);
@@ -16294,7 +17420,7 @@ function mountSprites(placements, options) {
16294
17420
  for (const p of placements) {
16295
17421
  let sourceHash = null;
16296
17422
  try {
16297
- const bytes = (0, import_node_fs23.readFileSync)(p.path);
17423
+ const bytes = (0, import_node_fs26.readFileSync)(p.path);
16298
17424
  sourceHash = sha256(bytes);
16299
17425
  const png = decodePng(bytes);
16300
17426
  if (png.width > cellWidth || png.height > cellHeight) {
@@ -16365,7 +17491,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
16365
17491
  const source = sources[id];
16366
17492
  const entry = lock.entries[`${styleId}/${id}`];
16367
17493
  if (source && !(entry && sourceIsStem(source, entry, manifestDir))) {
16368
- placements.push({ id, path: import_node_path26.default.resolve(manifestDir, source), cell });
17494
+ placements.push({ id, path: import_node_path29.default.resolve(manifestDir, source), cell });
16369
17495
  continue;
16370
17496
  }
16371
17497
  if (source && entry) {
@@ -16398,7 +17524,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
16398
17524
  `Nothing to mount for style "${styleId}": ${ids.length} asset(s) declare a cell, but none has generated output or a \`source\`. Run \`pixelkiln gen --style ${styleId}\`, or point each at a file.${detail}`
16399
17525
  );
16400
17526
  }
16401
- const basePng = mount.base ? (0, import_node_fs23.readFileSync)(import_node_path26.default.resolve(manifestDir, mount.base)) : void 0;
17527
+ const basePng = mount.base ? (0, import_node_fs26.readFileSync)(import_node_path29.default.resolve(manifestDir, mount.base)) : void 0;
16402
17528
  const mounted = mountSprites(placements, {
16403
17529
  cellWidth: mount.cellWidth,
16404
17530
  cellHeight: mount.cellHeight,
@@ -16408,7 +17534,7 @@ function mountStyle(lock, styleId, manifestDir, mount, cells, sources = {}, outp
16408
17534
  ...mounted,
16409
17535
  sources: mount.base ? [{
16410
17536
  id: "$base",
16411
- path: import_node_path26.default.resolve(manifestDir, mount.base),
17537
+ path: import_node_path29.default.resolve(manifestDir, mount.base),
16412
17538
  sha256: sha256(basePng),
16413
17539
  included: true
16414
17540
  }, ...mounted.sources] : mounted.sources,
@@ -17253,34 +18379,34 @@ async function poll(provider, lock, lockPath, opts = {}) {
17253
18379
  }
17254
18380
 
17255
18381
  // src/pipeline/doctor.ts
17256
- var import_node_fs25 = require("fs");
17257
- var import_promises16 = require("fs/promises");
17258
- var import_node_path28 = __toESM(require("path"), 1);
18382
+ var import_node_fs28 = require("fs");
18383
+ var import_promises19 = require("fs/promises");
18384
+ var import_node_path31 = __toESM(require("path"), 1);
17259
18385
 
17260
18386
  // src/pipeline/install-check.ts
17261
- var import_node_fs24 = require("fs");
17262
- var import_node_path27 = __toESM(require("path"), 1);
18387
+ var import_node_fs27 = require("fs");
18388
+ var import_node_path30 = __toESM(require("path"), 1);
17263
18389
  function readJson(file) {
17264
18390
  try {
17265
- return JSON.parse((0, import_node_fs24.readFileSync)(file, "utf8"));
18391
+ return JSON.parse((0, import_node_fs27.readFileSync)(file, "utf8"));
17266
18392
  } catch {
17267
18393
  return null;
17268
18394
  }
17269
18395
  }
17270
18396
  function readInstallFacts(manifestDir, running) {
17271
- let dir = import_node_path27.default.resolve(manifestDir);
18397
+ let dir = import_node_path30.default.resolve(manifestDir);
17272
18398
  for (let depth = 0; depth < 4; depth++) {
17273
- const pkg = readJson(import_node_path27.default.join(dir, "package.json"));
18399
+ const pkg = readJson(import_node_path30.default.join(dir, "package.json"));
17274
18400
  if (pkg) {
17275
18401
  const pinned = ["dependencies", "devDependencies", "optionalDependencies"].map((field) => pkg[field]?.pixelkiln).find((spec) => typeof spec === "string");
17276
18402
  if (pinned) {
17277
- const installedPkg = readJson(import_node_path27.default.join(dir, "node_modules", "pixelkiln", "package.json"));
18403
+ const installedPkg = readJson(import_node_path30.default.join(dir, "node_modules", "pixelkiln", "package.json"));
17278
18404
  const installed = typeof installedPkg?.version === "string" ? installedPkg.version : void 0;
17279
18405
  return { pinned, installed, running };
17280
18406
  }
17281
18407
  }
17282
- const parent = import_node_path27.default.dirname(dir);
17283
- if (parent === dir || !(0, import_node_fs24.existsSync)(parent)) break;
18408
+ const parent = import_node_path30.default.dirname(dir);
18409
+ if (parent === dir || !(0, import_node_fs27.existsSync)(parent)) break;
17284
18410
  dir = parent;
17285
18411
  }
17286
18412
  return null;
@@ -17343,18 +18469,18 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
17343
18469
  `${entry.kind === "style" ? "styles" : "assets"}.${entry.id} was left out: ${entry.issues.join("; ")}`
17344
18470
  );
17345
18471
  }
17346
- const facts = readInstallFacts(import_node_path28.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
18472
+ const facts = readInstallFacts(import_node_path31.default.dirname(loaded.path), opts.runningVersion !== void 0 ? opts.runningVersion : pixelkilnVersion());
17347
18473
  if (facts) for (const finding of checkInstall(facts)) add("install", finding.level, finding.message);
17348
18474
  add("lock", "ok", `${Object.keys(lock.entries).length} valid v2 lock entr(ies)`);
17349
18475
  const dirs = [...new Set(specs.flatMap((spec) => [
17350
- import_node_path28.default.dirname(spec.outFile),
17351
- ...spec.quality ? [import_node_path28.default.dirname(spec.quality.outFile)] : []
18476
+ import_node_path31.default.dirname(spec.outFile),
18477
+ ...spec.quality ? [import_node_path31.default.dirname(spec.quality.outFile)] : []
17352
18478
  ]))];
17353
18479
  const unwritable = [];
17354
18480
  for (const dir of dirs) {
17355
18481
  const ancestor = await nearestExistingDirectory(dir);
17356
18482
  try {
17357
- await (0, import_promises16.access)(ancestor, import_node_fs25.constants.W_OK);
18483
+ await (0, import_promises19.access)(ancestor, import_node_fs28.constants.W_OK);
17358
18484
  } catch {
17359
18485
  unwritable.push(dir);
17360
18486
  }
@@ -17371,7 +18497,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
17371
18497
  for (let index = 0; index < entry.outputs.length; index++) {
17372
18498
  const output = entry.outputs[index];
17373
18499
  const spec = specByKey.get(key2);
17374
- const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path28.default.dirname(lockPath));
18500
+ const absolute = spec ? currentEntryOutputPath(entry, spec, index) : resolveOutputPath(output.path, import_node_path31.default.dirname(lockPath));
17375
18501
  const owner = outputOwners.get(absolute);
17376
18502
  if (owner && owner !== key2) duplicateOutputs.push(`${output.path} (${owner}, ${key2})`);
17377
18503
  outputOwners.set(absolute, key2);
@@ -17386,7 +18512,7 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
17386
18512
  } else {
17387
18513
  add("lock-outputs", "ok", `${outputOwners.size} recorded output path(s) are uniquely owned`);
17388
18514
  }
17389
- const cacheDir = import_node_path28.default.join(import_node_path28.default.dirname(lockPath), ".pixelkiln", "cache");
18515
+ const cacheDir = import_node_path31.default.join(import_node_path31.default.dirname(lockPath), ".pixelkiln", "cache");
17390
18516
  const stranded = [];
17391
18517
  const invalidState = [];
17392
18518
  const staleMapUrls = [];
@@ -17402,11 +18528,11 @@ async function doctor(loaded, specs, lock, lockPath, opts = {}) {
17402
18528
  const hasSource = Boolean(entry.sourceUrl || entry.sourceUrls?.length);
17403
18529
  let hasCache = false;
17404
18530
  for (const output of entry.outputs) {
17405
- const cached2 = import_node_path28.default.join(
18531
+ const cached2 = import_node_path31.default.join(
17406
18532
  cacheDir,
17407
18533
  cacheFileName(output.sha256, output.mediaType ?? MediaType.PNG)
17408
18534
  );
17409
- if ((0, import_node_fs25.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
18535
+ if ((0, import_node_fs28.existsSync)(cached2) && await sha256File(cached2) === output.sha256) {
17410
18536
  hasCache = true;
17411
18537
  break;
17412
18538
  }
@@ -17499,19 +18625,19 @@ async function nearestExistingDirectory(start) {
17499
18625
  let current = start;
17500
18626
  for (; ; ) {
17501
18627
  try {
17502
- if ((await (0, import_promises16.stat)(current)).isDirectory()) return current;
18628
+ if ((await (0, import_promises19.stat)(current)).isDirectory()) return current;
17503
18629
  } catch {
17504
18630
  }
17505
- const parent = import_node_path28.default.dirname(current);
18631
+ const parent = import_node_path31.default.dirname(current);
17506
18632
  if (parent === current) return current;
17507
18633
  current = parent;
17508
18634
  }
17509
18635
  }
17510
18636
 
17511
18637
  // src/pipeline/adopt.ts
17512
- var import_node_fs26 = require("fs");
17513
- var import_promises17 = require("fs/promises");
17514
- var import_node_path29 = __toESM(require("path"), 1);
18638
+ var import_node_fs29 = require("fs");
18639
+ var import_promises20 = require("fs/promises");
18640
+ var import_node_path32 = __toESM(require("path"), 1);
17515
18641
  async function adopt(provider, specs, lock, lockPath, opts = {}) {
17516
18642
  const log = opts.onProgress ?? (() => {
17517
18643
  });
@@ -17522,11 +18648,11 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
17522
18648
  const localByHash = /* @__PURE__ */ new Map();
17523
18649
  const unmatchedLocal = [];
17524
18650
  for (const spec of specs) {
17525
- if (!(0, import_node_fs26.existsSync)(spec.outFile)) {
18651
+ if (!(0, import_node_fs29.existsSync)(spec.outFile)) {
17526
18652
  unmatchedLocal.push(`${spec.styleId}/${spec.assetId} (no file at ${spec.outFile})`);
17527
18653
  continue;
17528
18654
  }
17529
- const bytes = await (0, import_promises17.readFile)(spec.outFile);
18655
+ const bytes = await (0, import_promises20.readFile)(spec.outFile);
17530
18656
  try {
17531
18657
  decodePng(bytes);
17532
18658
  } catch (err) {
@@ -17644,9 +18770,9 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
17644
18770
  }
17645
18771
 
17646
18772
  // src/pipeline/import.ts
17647
- var import_node_fs27 = require("fs");
17648
- var import_promises18 = require("fs/promises");
17649
- var import_node_path30 = __toESM(require("path"), 1);
18773
+ var import_node_fs30 = require("fs");
18774
+ var import_promises21 = require("fs/promises");
18775
+ var import_node_path33 = __toESM(require("path"), 1);
17650
18776
  function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
17651
18777
  const png = decodePng(bytes);
17652
18778
  const at = now.toISOString();
@@ -17698,13 +18824,13 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
17698
18824
  if (opts.objectId && specs.length !== 1) {
17699
18825
  throw new Error(`--object-id names one object; ${specs.length} assets are selected. Narrow with --only and --style.`);
17700
18826
  }
17701
- const cacheDir = opts.cacheDir === false ? null : import_node_path30.default.resolve(opts.cacheDir ?? import_node_path30.default.join(import_node_path30.default.dirname(lockPath), ".pixelkiln", "cache"));
18827
+ const cacheDir = opts.cacheDir === false ? null : import_node_path33.default.resolve(opts.cacheDir ?? import_node_path33.default.join(import_node_path33.default.dirname(lockPath), ".pixelkiln", "cache"));
17702
18828
  let rawSha256;
17703
18829
  let rawBytes;
17704
18830
  if (opts.raw) {
17705
18831
  if (specs.length !== 1) throw new Error(`--raw names one original; ${specs.length} assets are selected. Narrow with --only and --style.`);
17706
18832
  try {
17707
- rawBytes = await (0, import_promises18.readFile)(opts.raw);
18833
+ rawBytes = await (0, import_promises21.readFile)(opts.raw);
17708
18834
  decodePng(rawBytes);
17709
18835
  } catch (error) {
17710
18836
  throw new Error(`--raw ${opts.raw} is not a readable PNG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
@@ -17720,7 +18846,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
17720
18846
  skipped.push({ key: key2, reason });
17721
18847
  continue;
17722
18848
  }
17723
- if (!(0, import_node_fs27.existsSync)(spec.outFile)) {
18849
+ if (!(0, import_node_fs30.existsSync)(spec.outFile)) {
17724
18850
  skipped.push({ key: key2, reason: `no file at ${spec.outFile}` });
17725
18851
  continue;
17726
18852
  }
@@ -17731,7 +18857,7 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
17731
18857
  let patch;
17732
18858
  let bytes;
17733
18859
  try {
17734
- bytes = await (0, import_promises18.readFile)(spec.outFile);
18860
+ bytes = await (0, import_promises21.readFile)(spec.outFile);
17735
18861
  patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
17736
18862
  } catch (error) {
17737
18863
  skipped.push({ key: key2, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
@@ -17763,7 +18889,7 @@ async function reportSpecHashes(specs, lock) {
17763
18889
  for (const spec of specs) {
17764
18890
  const key2 = lockKey(spec.styleId, spec.assetId);
17765
18891
  let bytes = null;
17766
- if ((0, import_node_fs27.existsSync)(spec.outFile)) bytes = await (0, import_promises18.readFile)(spec.outFile);
18892
+ if ((0, import_node_fs30.existsSync)(spec.outFile)) bytes = await (0, import_promises21.readFile)(spec.outFile);
17767
18893
  let wouldImport = null;
17768
18894
  if (bytes && !unimportable(spec)) {
17769
18895
  try {
@@ -17792,13 +18918,13 @@ async function reportSpecHashes(specs, lock) {
17792
18918
  }
17793
18919
 
17794
18920
  // src/pick/server.ts
17795
- var import_node_fs29 = require("fs");
17796
- var import_promises21 = require("fs/promises");
18921
+ var import_node_fs32 = require("fs");
18922
+ var import_promises24 = require("fs/promises");
17797
18923
 
17798
18924
  // src/pipeline/init.ts
17799
- var import_promises19 = require("fs/promises");
17800
- var import_node_fs28 = require("fs");
17801
- var import_node_path31 = __toESM(require("path"), 1);
18925
+ var import_promises22 = require("fs/promises");
18926
+ var import_node_fs31 = require("fs");
18927
+ var import_node_path34 = __toESM(require("path"), 1);
17802
18928
  function pngSize(buf) {
17803
18929
  if (buf.length < 24) return null;
17804
18930
  const isPng = buf.readUInt32BE(0) === 2303741511 && buf.readUInt32BE(4) === 218765834;
@@ -17811,8 +18937,8 @@ function slugify(value) {
17811
18937
  }
17812
18938
  async function walk(dir, exclude) {
17813
18939
  const out = [];
17814
- for (const entry of await (0, import_promises19.readdir)(dir, { withFileTypes: true })) {
17815
- const full = import_node_path31.default.join(dir, entry.name);
18940
+ for (const entry of await (0, import_promises22.readdir)(dir, { withFileTypes: true })) {
18941
+ const full = import_node_path34.default.join(dir, entry.name);
17816
18942
  if (exclude.some((x) => full.includes(x))) continue;
17817
18943
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
17818
18944
  else if (entry.name.toLowerCase().endsWith(".png")) out.push(full);
@@ -17826,14 +18952,14 @@ async function scanAssets(root, opts = {}) {
17826
18952
  const skipped = [];
17827
18953
  const seen = /* @__PURE__ */ new Map();
17828
18954
  for (const file of files.sort()) {
17829
- const size = pngSize(await (0, import_promises19.readFile)(file));
18955
+ const size = pngSize(await (0, import_promises22.readFile)(file));
17830
18956
  if (!size) {
17831
18957
  skipped.push(`${file} (not a readable PNG)`);
17832
18958
  continue;
17833
18959
  }
17834
- const rel = import_node_path31.default.relative(root, file);
17835
- const category = import_node_path31.default.dirname(rel) === "." ? "" : import_node_path31.default.dirname(rel);
17836
- let id = slugify(import_node_path31.default.basename(rel));
18960
+ const rel = import_node_path34.default.relative(root, file);
18961
+ const category = import_node_path34.default.dirname(rel) === "." ? "" : import_node_path34.default.dirname(rel);
18962
+ let id = slugify(import_node_path34.default.basename(rel));
17837
18963
  if (seen.has(id)) {
17838
18964
  const n = seen.get(id) + 1;
17839
18965
  seen.set(id, n);
@@ -18307,7 +19433,7 @@ document.getElementById('submit').onclick = async () => {
18307
19433
 
18308
19434
  // src/pick/review-server.ts
18309
19435
  var import_node_http = require("http");
18310
- var import_promises20 = require("fs/promises");
19436
+ var import_promises23 = require("fs/promises");
18311
19437
  function serveReviewPage(opts) {
18312
19438
  const log = opts.onProgress ?? (() => {
18313
19439
  });
@@ -18316,7 +19442,7 @@ function serveReviewPage(opts) {
18316
19442
  if (req.method === "GET" && req.url && opts.assets?.has(req.url)) {
18317
19443
  try {
18318
19444
  const asset = opts.assets.get(req.url);
18319
- const bytes = await (0, import_promises20.readFile)(asset.path);
19445
+ const bytes = await (0, import_promises23.readFile)(asset.path);
18320
19446
  res.writeHead(200, {
18321
19447
  "Content-Type": asset.contentType,
18322
19448
  "Cache-Control": "no-store",
@@ -18392,13 +19518,13 @@ async function currentArt(entry, spec) {
18392
19518
  const previous = primaryOutput({ ...entry, outputs: entry.supersededOutputs });
18393
19519
  if (!previous) return null;
18394
19520
  const file = resolveOutputPath(previous.path, spec.root);
18395
- if (!(0, import_node_fs29.existsSync)(file)) return null;
19521
+ if (!(0, import_node_fs32.existsSync)(file)) return null;
18396
19522
  const contentType = previous.mediaType ?? mediaTypeFromExtension(file);
18397
19523
  if (!contentType) return null;
18398
19524
  let width = entry.width;
18399
19525
  let height = entry.height;
18400
19526
  if (contentType === "image/png") {
18401
- const size = pngSize(await (0, import_promises21.readFile)(file));
19527
+ const size = pngSize(await (0, import_promises24.readFile)(file));
18402
19528
  if (size) ({ width, height } = size);
18403
19529
  }
18404
19530
  return { path: file, contentType, width, height };
@@ -18406,7 +19532,7 @@ async function currentArt(entry, spec) {
18406
19532
  async function cachedFrame(url) {
18407
19533
  if (!url.startsWith("file://")) return null;
18408
19534
  const file = url.slice("file://".length);
18409
- const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises21.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
19535
+ const contentType = mediaTypeFromExtension(file) ?? detectMediaType(await (0, import_promises24.readFile)(file).catch(() => Buffer.alloc(0))) ?? "application/octet-stream";
18410
19536
  return { path: file, contentType };
18411
19537
  }
18412
19538
  async function prepareReview(provider, lock, opts = {}) {
@@ -18438,7 +19564,7 @@ async function prepareReview(provider, lock, opts = {}) {
18438
19564
  frameSizes.push(null);
18439
19565
  continue;
18440
19566
  }
18441
- frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises21.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
19567
+ frameSizes.push(cached2.contentType === "image/png" ? pngSize(await (0, import_promises24.readFile)(cached2.path).catch(() => Buffer.alloc(0))) : null);
18442
19568
  const route = `${prefix}/review-frame/${encodeURIComponent(String(groups.length))}/${index}`;
18443
19569
  frameAssets.push([route, cached2]);
18444
19570
  frameUrls.push(route);
@@ -18592,14 +19718,14 @@ async function runPicker(provider, lock, lockPath, opts = {}) {
18592
19718
 
18593
19719
  // src/gallery/snapshot.ts
18594
19720
  var import_node_crypto7 = require("crypto");
18595
- var import_node_fs35 = require("fs");
18596
- var import_promises29 = require("fs/promises");
18597
- var import_node_path39 = __toESM(require("path"), 1);
19721
+ var import_node_fs38 = require("fs");
19722
+ var import_promises32 = require("fs/promises");
19723
+ var import_node_path42 = __toESM(require("path"), 1);
18598
19724
 
18599
19725
  // src/workspace.ts
18600
- var import_promises22 = require("fs/promises");
18601
- var import_node_fs30 = require("fs");
18602
- var import_node_path32 = __toESM(require("path"), 1);
19726
+ var import_promises25 = require("fs/promises");
19727
+ var import_node_fs33 = require("fs");
19728
+ var import_node_path35 = __toESM(require("path"), 1);
18603
19729
  var import_zod7 = require("zod");
18604
19730
  var WorkspaceProjectSchema = import_zod7.z.object({
18605
19731
  id: import_zod7.z.string().min(1),
@@ -18624,10 +19750,10 @@ ${parsed.error.issues.slice(0, 5).map((i) => ` ${i.path.join(".")}: ${i.message
18624
19750
  );
18625
19751
  }
18626
19752
  async function loadWorkspace(workspacePath) {
18627
- if (!(0, import_node_fs30.existsSync)(workspacePath)) return { version: 1, projects: [] };
19753
+ if (!(0, import_node_fs33.existsSync)(workspacePath)) return { version: 1, projects: [] };
18628
19754
  let raw;
18629
19755
  try {
18630
- raw = JSON.parse(await (0, import_promises22.readFile)(workspacePath, "utf8"));
19756
+ raw = JSON.parse(await (0, import_promises25.readFile)(workspacePath, "utf8"));
18631
19757
  } catch (err) {
18632
19758
  throw new ProjectError(
18633
19759
  `Workspace catalog at ${workspacePath} is malformed:
@@ -18641,22 +19767,22 @@ async function saveWorkspace(workspacePath, ws) {
18641
19767
  version: 1,
18642
19768
  projects: [...ws.projects].sort((a, b) => a.id.localeCompare(b.id))
18643
19769
  };
18644
- await (0, import_promises22.mkdir)(import_node_path32.default.dirname(import_node_path32.default.resolve(workspacePath)), { recursive: true });
19770
+ await (0, import_promises25.mkdir)(import_node_path35.default.dirname(import_node_path35.default.resolve(workspacePath)), { recursive: true });
18645
19771
  const tmp = `${workspacePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
18646
19772
  try {
18647
- await (0, import_promises22.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
18648
- await (0, import_promises22.rename)(tmp, workspacePath);
19773
+ await (0, import_promises25.writeFile)(tmp, JSON.stringify(sorted, null, 2) + "\n");
19774
+ await (0, import_promises25.rename)(tmp, workspacePath);
18649
19775
  } finally {
18650
- await (0, import_promises22.rm)(tmp, { force: true });
19776
+ await (0, import_promises25.rm)(tmp, { force: true });
18651
19777
  }
18652
19778
  }
18653
19779
  function toPortablePath(dir, absolute) {
18654
- return import_node_path32.default.relative(dir, absolute).split(import_node_path32.default.sep).join("/");
19780
+ return import_node_path35.default.relative(dir, absolute).split(import_node_path35.default.sep).join("/");
18655
19781
  }
18656
19782
  function resolveProject(dir, project) {
18657
19783
  return {
18658
- manifestPath: import_node_path32.default.resolve(dir, project.manifest.split("/").join(import_node_path32.default.sep)),
18659
- lockPath: import_node_path32.default.resolve(dir, project.lock.split("/").join(import_node_path32.default.sep))
19784
+ manifestPath: import_node_path35.default.resolve(dir, project.manifest.split("/").join(import_node_path35.default.sep)),
19785
+ lockPath: import_node_path35.default.resolve(dir, project.lock.split("/").join(import_node_path35.default.sep))
18660
19786
  };
18661
19787
  }
18662
19788
  function validateWorkspace(ws, dir) {
@@ -18669,21 +19795,21 @@ function validateWorkspace(ws, dir) {
18669
19795
  const { manifestPath, lockPath } = resolveProject(dir, project);
18670
19796
  lockOwners.set(lockPath, [...lockOwners.get(lockPath) ?? [], project.id]);
18671
19797
  manifestOwners.set(manifestPath, [...manifestOwners.get(manifestPath) ?? [], project.id]);
18672
- if (import_node_path32.default.isAbsolute(project.manifest) || import_node_path32.default.isAbsolute(project.lock)) {
19798
+ if (import_node_path35.default.isAbsolute(project.manifest) || import_node_path35.default.isAbsolute(project.lock)) {
18673
19799
  diagnostics.push({
18674
19800
  id: "absolute-path",
18675
19801
  level: "warning",
18676
19802
  message: `project "${project.id}" stores an absolute path; the catalog will not resolve correctly if this tree is cloned or moved elsewhere`
18677
19803
  });
18678
19804
  }
18679
- if (!(0, import_node_fs30.existsSync)(manifestPath)) {
19805
+ if (!(0, import_node_fs33.existsSync)(manifestPath)) {
18680
19806
  diagnostics.push({
18681
19807
  id: "missing-manifest",
18682
19808
  level: "error",
18683
19809
  message: `project "${project.id}" manifest not found: ${manifestPath}`
18684
19810
  });
18685
19811
  }
18686
- if (!(0, import_node_fs30.existsSync)(lockPath)) {
19812
+ if (!(0, import_node_fs33.existsSync)(lockPath)) {
18687
19813
  diagnostics.push({
18688
19814
  id: "missing-lock",
18689
19815
  level: "error",
@@ -18730,16 +19856,16 @@ function validateWorkspace(ws, dir) {
18730
19856
  }
18731
19857
 
18732
19858
  // src/gallery/edit.ts
18733
- var import_promises28 = require("fs/promises");
18734
- var import_node_path38 = __toESM(require("path"), 1);
19859
+ var import_promises31 = require("fs/promises");
19860
+ var import_node_path41 = __toESM(require("path"), 1);
18735
19861
  var import_zod13 = require("zod");
18736
19862
 
18737
19863
  // src/manifest-edit.ts
18738
- var import_promises23 = require("fs/promises");
18739
- var import_node_path33 = __toESM(require("path"), 1);
19864
+ var import_promises26 = require("fs/promises");
19865
+ var import_node_path36 = __toESM(require("path"), 1);
18740
19866
  var import_zod8 = require("zod");
18741
19867
  var HexSha = import_zod8.z.string().regex(/^[0-9a-f]{64}$/);
18742
- var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path33.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
19868
+ var ProjectFileSchema = import_zod8.z.string().min(1).refine((file) => !import_node_path36.default.isAbsolute(file) && !file.split(/[\\/]/).includes(".."), "must be a path inside the project");
18743
19869
  var AssetPatchSchema = import_zod8.z.object({
18744
19870
  prompt: import_zod8.z.string().optional(),
18745
19871
  /** Per-style override for the style being viewed; null removes it. */
@@ -19159,8 +20285,8 @@ function applyEdit(raw, edit) {
19159
20285
  }
19160
20286
  }
19161
20287
  async function withCandidate(manifestPath, edit, use, unchanged) {
19162
- const absolute = import_node_path33.default.resolve(manifestPath);
19163
- const original = await (0, import_promises23.readFile)(absolute, "utf8");
20288
+ const absolute = import_node_path36.default.resolve(manifestPath);
20289
+ const original = await (0, import_promises26.readFile)(absolute, "utf8");
19164
20290
  if (sha256(original) !== edit.expectedSha256) throw new ManifestDriftError(absolute);
19165
20291
  let raw;
19166
20292
  try {
@@ -19173,12 +20299,12 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
19173
20299
  applyEdit(raw, edit);
19174
20300
  const next = serializeLike(original, raw);
19175
20301
  if (next === original) return unchanged(absolute, original);
19176
- const tmp = import_node_path33.default.join(
19177
- import_node_path33.default.dirname(absolute),
19178
- `.${import_node_path33.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
20302
+ const tmp = import_node_path36.default.join(
20303
+ import_node_path36.default.dirname(absolute),
20304
+ `.${import_node_path36.default.basename(absolute)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
19179
20305
  );
19180
20306
  try {
19181
- await (0, import_promises23.writeFile)(tmp, next);
20307
+ await (0, import_promises26.writeFile)(tmp, next);
19182
20308
  let specs;
19183
20309
  try {
19184
20310
  specs = await resolveSpecs(await loadManifest(tmp));
@@ -19188,7 +20314,7 @@ async function withCandidate(manifestPath, edit, use, unchanged) {
19188
20314
  }
19189
20315
  return await use({ absolute, original, next, tmp, specs });
19190
20316
  } finally {
19191
- await (0, import_promises23.rm)(tmp, { force: true });
20317
+ await (0, import_promises26.rm)(tmp, { force: true });
19192
20318
  }
19193
20319
  }
19194
20320
  async function applyManifestEdit(manifestPath, edit) {
@@ -19196,7 +20322,7 @@ async function applyManifestEdit(manifestPath, edit) {
19196
20322
  manifestPath,
19197
20323
  edit,
19198
20324
  async ({ absolute, next, tmp }) => {
19199
- await (0, import_promises23.rename)(tmp, absolute);
20325
+ await (0, import_promises26.rename)(tmp, absolute);
19200
20326
  return { manifestPath: absolute, sha256: sha256(next), changed: true };
19201
20327
  },
19202
20328
  (absolute, original) => ({ manifestPath: absolute, sha256: sha256(original), changed: false })
@@ -19204,18 +20330,18 @@ async function applyManifestEdit(manifestPath, edit) {
19204
20330
  }
19205
20331
 
19206
20332
  // src/pipeline/hand-edit.ts
19207
- var import_node_fs31 = require("fs");
19208
- var import_promises24 = require("fs/promises");
19209
- var import_node_path34 = __toESM(require("path"), 1);
20333
+ var import_node_fs34 = require("fs");
20334
+ var import_promises27 = require("fs/promises");
20335
+ var import_node_path37 = __toESM(require("path"), 1);
19210
20336
  var import_zod9 = require("zod");
19211
20337
  var HAND_EDIT_DIR = "edits";
19212
20338
  function handEditPath(loaded, spec) {
19213
20339
  const style = loaded.manifest.styles[spec.styleId];
19214
- const outDir = import_node_path34.default.resolve(loaded.root, style?.outDir ?? ".");
19215
- const relative = import_node_path34.default.relative(outDir, spec.outFile);
19216
- const inside = relative && !relative.startsWith("..") && !import_node_path34.default.isAbsolute(relative);
19217
- const file = inside ? relative : import_node_path34.default.basename(spec.outFile);
19218
- return import_node_path34.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
20340
+ const outDir = import_node_path37.default.resolve(loaded.root, style?.outDir ?? ".");
20341
+ const relative = import_node_path37.default.relative(outDir, spec.outFile);
20342
+ const inside = relative && !relative.startsWith("..") && !import_node_path37.default.isAbsolute(relative);
20343
+ const file = inside ? relative : import_node_path37.default.basename(spec.outFile);
20344
+ return import_node_path37.default.join(outDir, HAND_EDIT_DIR, file.replace(/\.gif$/i, ".png"));
19219
20345
  }
19220
20346
  function handEditBases(spec, lock) {
19221
20347
  const entry = lock.entries[lockKey(spec.styleId, spec.assetId)];
@@ -19228,10 +20354,10 @@ function handEditBases(spec, lock) {
19228
20354
  }));
19229
20355
  if (members.some((member) => member.mediaType && member.mediaType !== "image/png")) return null;
19230
20356
  if (entry.outputs.length === 1 && !primaryOutput(entry)) return null;
19231
- if (!members.every((member) => (0, import_node_fs31.existsSync)(member.path))) return null;
20357
+ if (!members.every((member) => (0, import_node_fs34.existsSync)(member.path))) return null;
19232
20358
  return members.map(({ role, path: file }) => ({ role, path: file }));
19233
20359
  }
19234
- return (0, import_node_fs31.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
20360
+ return (0, import_node_fs34.existsSync)(spec.outFile) ? [{ role: null, path: spec.outFile }] : null;
19235
20361
  }
19236
20362
  function handEditBase(spec, lock) {
19237
20363
  const bases = handEditBases(spec, lock);
@@ -19281,19 +20407,19 @@ async function startHandEdit(loaded, lock, spec, opts = {}) {
19281
20407
  `${spec.styleId}/${spec.assetId} declares ${spec.source}, one committed file placed for the whole set; clear that source (pixelkiln edit detach) to hand-edit the members one by one`
19282
20408
  );
19283
20409
  }
19284
- const existing = spec.source ? import_node_path34.default.resolve(loaded.root, spec.source) : null;
20410
+ const existing = spec.source ? import_node_path37.default.resolve(loaded.root, spec.source) : null;
19285
20411
  const editPath = existing ?? handEditPath(loaded, spec);
19286
20412
  const members = handEditMembers(loaded, spec, lock, editPath);
19287
20413
  let created = false;
19288
20414
  for (const member of members) {
19289
- if ((0, import_node_fs31.existsSync)(member.path)) continue;
20415
+ if ((0, import_node_fs34.existsSync)(member.path)) continue;
19290
20416
  if (!member.base) {
19291
20417
  throw new ManifestEditError(
19292
20418
  `${spec.styleId}/${spec.assetId} has no generated PNG on disk to start from; generate or restore it first`
19293
20419
  );
19294
20420
  }
19295
- await (0, import_promises24.mkdir)(import_node_path34.default.dirname(member.path), { recursive: true });
19296
- await (0, import_promises24.copyFile)(member.base, member.path);
20421
+ await (0, import_promises27.mkdir)(import_node_path37.default.dirname(member.path), { recursive: true });
20422
+ await (0, import_promises27.copyFile)(member.base, member.path);
19297
20423
  created = true;
19298
20424
  }
19299
20425
  const source = portableOutputPath(editPath, loaded.root);
@@ -19371,7 +20497,7 @@ function handEditProjectPath(editPath) {
19371
20497
  async function readHandEditCompanion(editPath) {
19372
20498
  let text;
19373
20499
  try {
19374
- text = await (0, import_promises24.readFile)(handEditCompanionPath(editPath), "utf8");
20500
+ text = await (0, import_promises27.readFile)(handEditCompanionPath(editPath), "utf8");
19375
20501
  } catch {
19376
20502
  return null;
19377
20503
  }
@@ -19415,7 +20541,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
19415
20541
  }
19416
20542
  });
19417
20543
  const bases = handEditBases(spec, lock);
19418
- const expectedSize = bases?.[0] ? decodePng(await (0, import_promises24.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
20544
+ const expectedSize = bases?.[0] ? decodePng(await (0, import_promises27.readFile)(bases[0].path)) : { width: spec.width, height: spec.height };
19419
20545
  for (const [index, image] of decoded.entries()) {
19420
20546
  if (image.width !== expectedSize.width || image.height !== expectedSize.height) {
19421
20547
  const which = memberSet ? `member ${incoming[index].role ?? index}` : "the edit";
@@ -19431,7 +20557,7 @@ async function saveHandEdit(loaded, lock, spec, input) {
19431
20557
  editor: input.editor,
19432
20558
  protocol: input.protocol,
19433
20559
  savedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
19434
- project: projectPath ? import_node_path34.default.basename(projectPath) : null,
20560
+ project: projectPath ? import_node_path37.default.basename(projectPath) : null,
19435
20561
  outputs: incoming.map((frame, index) => ({
19436
20562
  role: frame.role,
19437
20563
  basedOn: basedOnHash(entry, index),
@@ -19461,10 +20587,10 @@ function basedOnHash(entry, index) {
19461
20587
  async function replaceFile(file, bytes) {
19462
20588
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
19463
20589
  try {
19464
- await (0, import_promises24.writeFile)(tmp, bytes);
19465
- await (0, import_promises24.rename)(tmp, file);
20590
+ await (0, import_promises27.writeFile)(tmp, bytes);
20591
+ await (0, import_promises27.rename)(tmp, file);
19466
20592
  } finally {
19467
- await (0, import_promises24.rm)(tmp, { force: true });
20593
+ await (0, import_promises27.rm)(tmp, { force: true });
19468
20594
  }
19469
20595
  }
19470
20596
  function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
@@ -19473,9 +20599,9 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
19473
20599
  }
19474
20600
 
19475
20601
  // src/gallery/upload.ts
19476
- var import_node_fs32 = require("fs");
19477
- var import_promises25 = require("fs/promises");
19478
- var import_node_path35 = __toESM(require("path"), 1);
20602
+ var import_node_fs35 = require("fs");
20603
+ var import_promises28 = require("fs/promises");
20604
+ var import_node_path38 = __toESM(require("path"), 1);
19479
20605
  var import_zod10 = require("zod");
19480
20606
  var MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
19481
20607
  var UploadImageSchema = import_zod10.z.object({
@@ -19488,12 +20614,12 @@ var UploadImageSchema = import_zod10.z.object({
19488
20614
  overwrite: import_zod10.z.boolean().optional()
19489
20615
  }).strict();
19490
20616
  async function saveProjectImage(root, request) {
19491
- const file = import_node_path35.default.resolve(root, request.path);
19492
- const relative = import_node_path35.default.relative(root, file);
19493
- if (relative.startsWith("..") || import_node_path35.default.isAbsolute(relative)) {
20617
+ const file = import_node_path38.default.resolve(root, request.path);
20618
+ const relative = import_node_path38.default.relative(root, file);
20619
+ if (relative.startsWith("..") || import_node_path38.default.isAbsolute(relative)) {
19494
20620
  throw new ManifestEditError("an upload must stay inside the project");
19495
20621
  }
19496
- const extension = import_node_path35.default.extname(file).toLowerCase();
20622
+ const extension = import_node_path38.default.extname(file).toLowerCase();
19497
20623
  const expected = extension === ".png" ? "png" : extension === ".jpg" || extension === ".jpeg" ? "jpeg" : null;
19498
20624
  if (!expected) throw new ManifestEditError("an upload must be a .png, .jpg, or .jpeg path");
19499
20625
  const bytes = Buffer.from(request.base64, "base64");
@@ -19505,18 +20631,18 @@ async function saveProjectImage(root, request) {
19505
20631
  if (metadata.format !== expected) {
19506
20632
  throw new ManifestEditError(`the upload is a ${metadata.format.toUpperCase()}; name it ${metadata.format === "png" ? ".png" : ".jpg"}`);
19507
20633
  }
19508
- if ((0, import_node_fs32.existsSync)(file) && !request.overwrite) {
19509
- throw new ManifestEditError(`${relative.split(import_node_path35.default.sep).join("/")} already exists; choose another name, or replace it`);
20634
+ if ((0, import_node_fs35.existsSync)(file) && !request.overwrite) {
20635
+ throw new ManifestEditError(`${relative.split(import_node_path38.default.sep).join("/")} already exists; choose another name, or replace it`);
19510
20636
  }
19511
- await (0, import_promises25.mkdir)(import_node_path35.default.dirname(file), { recursive: true });
19512
- await (0, import_promises25.writeFile)(file, bytes);
19513
- return relative.split(import_node_path35.default.sep).join("/");
20637
+ await (0, import_promises28.mkdir)(import_node_path38.default.dirname(file), { recursive: true });
20638
+ await (0, import_promises28.writeFile)(file, bytes);
20639
+ return relative.split(import_node_path38.default.sep).join("/");
19514
20640
  }
19515
20641
 
19516
20642
  // src/gallery/image-revision.ts
19517
- var import_node_fs33 = require("fs");
19518
- var import_promises26 = require("fs/promises");
19519
- var import_node_path36 = __toESM(require("path"), 1);
20643
+ var import_node_fs36 = require("fs");
20644
+ var import_promises29 = require("fs/promises");
20645
+ var import_node_path39 = __toESM(require("path"), 1);
19520
20646
  var import_zod11 = require("zod");
19521
20647
  var InpaintRevisionRequestSchema = import_zod11.z.object({
19522
20648
  action: import_zod11.z.literal("create-inpaint-revision"),
@@ -19535,15 +20661,15 @@ var InpaintRevisionRequestSchema = import_zod11.z.object({
19535
20661
  overwrite: import_zod11.z.boolean().optional()
19536
20662
  }).strict();
19537
20663
  async function createInpaintRevision(manifestPath, request) {
19538
- const root = import_node_path36.default.dirname(import_node_path36.default.resolve(manifestPath));
19539
- if (import_node_path36.default.extname(request.maskPath).toLowerCase() !== ".png") {
20664
+ const root = import_node_path39.default.dirname(import_node_path39.default.resolve(manifestPath));
20665
+ if (import_node_path39.default.extname(request.maskPath).toLowerCase() !== ".png") {
19540
20666
  throw new ManifestEditError("the mask must be a .png path inside the project");
19541
20667
  }
19542
20668
  const bytes = Buffer.from(request.maskBase64, "base64");
19543
20669
  const metadata = imageMetadata(bytes);
19544
20670
  if (!metadata || metadata.format !== "png") throw new ManifestEditError("the mask is not a readable PNG");
19545
- const file = import_node_path36.default.resolve(root, request.maskPath);
19546
- const previous = (0, import_node_fs33.existsSync)(file) ? await (0, import_promises26.readFile)(file) : null;
20671
+ const file = import_node_path39.default.resolve(root, request.maskPath);
20672
+ const previous = (0, import_node_fs36.existsSync)(file) ? await (0, import_promises29.readFile)(file) : null;
19547
20673
  const mask = await saveProjectImage(root, {
19548
20674
  action: "upload-image",
19549
20675
  path: request.maskPath,
@@ -19562,17 +20688,17 @@ async function createInpaintRevision(manifestPath, request) {
19562
20688
  }
19563
20689
  });
19564
20690
  } catch (error) {
19565
- if (previous) await (0, import_promises26.writeFile)(file, previous);
19566
- else await (0, import_promises26.rm)(file, { force: true });
20691
+ if (previous) await (0, import_promises29.writeFile)(file, previous);
20692
+ else await (0, import_promises29.rm)(file, { force: true });
19567
20693
  throw error;
19568
20694
  }
19569
20695
  return mask;
19570
20696
  }
19571
20697
 
19572
20698
  // src/gallery/skeleton.ts
19573
- var import_node_fs34 = require("fs");
19574
- var import_promises27 = require("fs/promises");
19575
- var import_node_path37 = __toESM(require("path"), 1);
20699
+ var import_node_fs37 = require("fs");
20700
+ var import_promises30 = require("fs/promises");
20701
+ var import_node_path40 = __toESM(require("path"), 1);
19576
20702
  var import_zod12 = require("zod");
19577
20703
  var SkeletonEstimateRequestSchema = import_zod12.z.object({
19578
20704
  project: import_zod12.z.string().min(1).optional(),
@@ -19611,21 +20737,21 @@ var SkeletonKeypointsUpdateSchema = import_zod12.z.object({
19611
20737
  set: SkeletonSetSchema
19612
20738
  }).strict();
19613
20739
  async function createSkeletonAnimation(manifestPath, request) {
19614
- const root = import_node_path37.default.dirname(import_node_path37.default.resolve(manifestPath));
19615
- const file = import_node_path37.default.resolve(root, request.keypointsFile);
19616
- const relative = import_node_path37.default.relative(root, file);
19617
- if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path37.default.isAbsolute(relative)) {
20740
+ const root = import_node_path40.default.dirname(import_node_path40.default.resolve(manifestPath));
20741
+ const file = import_node_path40.default.resolve(root, request.keypointsFile);
20742
+ const relative = import_node_path40.default.relative(root, file);
20743
+ if (!request.keypointsFile.endsWith(".json") || relative.startsWith("..") || import_node_path40.default.isAbsolute(relative)) {
19618
20744
  throw new ManifestEditError("the keypoints file must be a .json path inside the project");
19619
20745
  }
19620
- const existed = (0, import_node_fs34.existsSync)(file);
20746
+ const existed = (0, import_node_fs37.existsSync)(file);
19621
20747
  let previous = null;
19622
20748
  if (request.set) {
19623
20749
  if (existed && !request.overwrite) {
19624
20750
  throw new ManifestEditError(`${request.keypointsFile} already exists; choose another path, or replace it`);
19625
20751
  }
19626
- if (existed) previous = await (0, import_promises27.readFile)(file);
19627
- await (0, import_promises27.mkdir)(import_node_path37.default.dirname(file), { recursive: true });
19628
- await (0, import_promises27.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
20752
+ if (existed) previous = await (0, import_promises30.readFile)(file);
20753
+ await (0, import_promises30.mkdir)(import_node_path40.default.dirname(file), { recursive: true });
20754
+ await (0, import_promises30.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
19629
20755
  } else if (!existed) {
19630
20756
  throw new ManifestEditError(`${request.keypointsFile} does not exist; paste poses or estimate them from the sprite`);
19631
20757
  }
@@ -19640,7 +20766,7 @@ async function createSkeletonAnimation(manifestPath, request) {
19640
20766
  revision: {
19641
20767
  mode: "animate-skeleton",
19642
20768
  from: request.from,
19643
- keypointsFile: relative.split(import_node_path37.default.sep).join("/"),
20769
+ keypointsFile: relative.split(import_node_path40.default.sep).join("/"),
19644
20770
  direction: request.direction,
19645
20771
  description: request.description,
19646
20772
  ...request.skeletonTemplate ? { skeletonTemplate: request.skeletonTemplate } : {}
@@ -19649,8 +20775,8 @@ async function createSkeletonAnimation(manifestPath, request) {
19649
20775
  });
19650
20776
  } catch (error) {
19651
20777
  if (request.set) {
19652
- if (previous) await (0, import_promises27.writeFile)(file, previous);
19653
- else await (0, import_promises27.rm)(file, { force: true });
20778
+ if (previous) await (0, import_promises30.writeFile)(file, previous);
20779
+ else await (0, import_promises30.rm)(file, { force: true });
19654
20780
  }
19655
20781
  throw error;
19656
20782
  }
@@ -19661,19 +20787,19 @@ async function updateSkeletonKeypoints(ctx, request) {
19661
20787
  if (!spec) throw new ManifestEditError(`"${key2}" is not declared by the manifest`);
19662
20788
  const file = spec.revision?.mode === "animate-skeleton" ? spec.revision.keypointsFile : void 0;
19663
20789
  if (!file) throw new ManifestEditError(`${key2} is not an animate-skeleton revision`);
19664
- const relative = import_node_path37.default.relative(ctx.loaded.root, file);
19665
- if (relative.startsWith("..") || import_node_path37.default.isAbsolute(relative)) {
20790
+ const relative = import_node_path40.default.relative(ctx.loaded.root, file);
20791
+ if (relative.startsWith("..") || import_node_path40.default.isAbsolute(relative)) {
19666
20792
  throw new ManifestEditError(`${key2}'s keypoints file is outside the project; edit it by hand`);
19667
20793
  }
19668
- const current = (0, import_node_fs34.existsSync)(file) ? sha256(await (0, import_promises27.readFile)(file)) : null;
20794
+ const current = (0, import_node_fs37.existsSync)(file) ? sha256(await (0, import_promises30.readFile)(file)) : null;
19669
20795
  if (current !== request.expectedSha256) {
19670
20796
  throw Object.assign(
19671
- new Error(`${relative.split(import_node_path37.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
20797
+ new Error(`${relative.split(import_node_path40.default.sep).join("/")} changed on disk since this page loaded it; press Refresh and edit again`),
19672
20798
  { status: 409 }
19673
20799
  );
19674
20800
  }
19675
- await (0, import_promises27.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
19676
- return relative.split(import_node_path37.default.sep).join("/");
20801
+ await (0, import_promises30.writeFile)(file, JSON.stringify(request.set, null, 2) + "\n");
20802
+ return relative.split(import_node_path40.default.sep).join("/");
19677
20803
  }
19678
20804
 
19679
20805
  // src/gallery/edit.ts
@@ -19727,7 +20853,7 @@ function createGalleryEditHandler(opts) {
19727
20853
  const history = /* @__PURE__ */ new Map();
19728
20854
  const manifestOf = async (project) => {
19729
20855
  try {
19730
- return import_node_path38.default.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
20856
+ return import_node_path41.default.resolve(await opts.manifestFor(typeof project === "string" ? project : void 0));
19731
20857
  } catch {
19732
20858
  return null;
19733
20859
  }
@@ -19737,7 +20863,7 @@ function createGalleryEditHandler(opts) {
19737
20863
  if (undo.success) {
19738
20864
  const manifestPath2 = await manifestOf(undo.data.project);
19739
20865
  if (!manifestPath2) throw new ManifestEditError("no manifest to undo an edit in");
19740
- const current = await (0, import_promises28.readFile)(manifestPath2, "utf8");
20866
+ const current = await (0, import_promises31.readFile)(manifestPath2, "utf8");
19741
20867
  if (sha256(current) !== undo.data.expectedSha256) throw new ManifestDriftError(manifestPath2);
19742
20868
  const stack = history.get(manifestPath2) ?? [];
19743
20869
  const last = stack[stack.length - 1];
@@ -19747,17 +20873,17 @@ function createGalleryEditHandler(opts) {
19747
20873
  throw Object.assign(new Error("the manifest changed outside the gallery since its last edit; undo would discard that change"), { status: 409 });
19748
20874
  }
19749
20875
  const tmp = manifestPath2 + ".pixelkiln-undo";
19750
- await (0, import_promises28.writeFile)(tmp, last.before);
19751
- await (0, import_promises28.rename)(tmp, manifestPath2);
20876
+ await (0, import_promises31.writeFile)(tmp, last.before);
20877
+ await (0, import_promises31.rename)(tmp, manifestPath2);
19752
20878
  stack.pop();
19753
- log(` manifest edit undone in ${import_node_path38.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
20879
+ log(` manifest edit undone in ${import_node_path41.default.relative(process.cwd(), manifestPath2) || manifestPath2}`);
19754
20880
  return opts.reload();
19755
20881
  }
19756
20882
  const manifestPath = await manifestOf(body?.project);
19757
- const before = manifestPath ? await (0, import_promises28.readFile)(manifestPath, "utf8").catch(() => null) : null;
20883
+ const before = manifestPath ? await (0, import_promises31.readFile)(manifestPath, "utf8").catch(() => null) : null;
19758
20884
  const build = await apply(body);
19759
20885
  if (manifestPath && before !== null) {
19760
- const after = await (0, import_promises28.readFile)(manifestPath, "utf8").catch(() => null);
20886
+ const after = await (0, import_promises31.readFile)(manifestPath, "utf8").catch(() => null);
19761
20887
  if (after !== null && after !== before) {
19762
20888
  const stack = history.get(manifestPath) ?? [];
19763
20889
  stack.push({ before, afterSha: sha256(after) });
@@ -19812,7 +20938,7 @@ function createEditApplier(opts, log) {
19812
20938
  } catch (error) {
19813
20939
  throw new ManifestEditError(error instanceof Error ? error.message : String(error));
19814
20940
  }
19815
- const written = await saveProjectImage(import_node_path38.default.dirname(import_node_path38.default.resolve(manifestPath2)), upload.data);
20941
+ const written = await saveProjectImage(import_node_path41.default.dirname(import_node_path41.default.resolve(manifestPath2)), upload.data);
19816
20942
  log(` image added: ${written}`);
19817
20943
  return opts.reload();
19818
20944
  }
@@ -19879,7 +21005,7 @@ function createEditApplier(opts, log) {
19879
21005
  }
19880
21006
  const result = await applyManifestEdit(manifestPath, parsed.data);
19881
21007
  if (result.changed) {
19882
- const relative = import_node_path38.default.relative(process.cwd(), result.manifestPath);
21008
+ const relative = import_node_path41.default.relative(process.cwd(), result.manifestPath);
19883
21009
  const shown = !relative || relative.startsWith("..") ? result.manifestPath : relative;
19884
21010
  log(` manifest edited: ${describeEdit(parsed.data)} in ${shown}`);
19885
21011
  }
@@ -19907,7 +21033,7 @@ function describeEdit(edit) {
19907
21033
  // src/gallery/snapshot.ts
19908
21034
  var PROJECT_FILE_TYPE = "application/octet-stream";
19909
21035
  function galleryMediaId(absolutePath) {
19910
- return (0, import_node_crypto7.createHash)("sha256").update(import_node_path39.default.resolve(absolutePath)).digest("hex").slice(0, 24);
21036
+ return (0, import_node_crypto7.createHash)("sha256").update(import_node_path42.default.resolve(absolutePath)).digest("hex").slice(0, 24);
19911
21037
  }
19912
21038
  function galleryMediaRoute(id) {
19913
21039
  return `/media/${id}`;
@@ -19931,9 +21057,9 @@ function describeHistory(media, entry, cacheDir) {
19931
21057
  return (entry.history ?? []).map((generation, i) => {
19932
21058
  const outputs = generation.outputs.map((output) => {
19933
21059
  const mediaType = output.mediaType ?? MediaType.PNG;
19934
- const file = import_node_path39.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
21060
+ const file = import_node_path42.default.join(cacheDir, cacheFileName(output.sha256, mediaType));
19935
21061
  let url = null;
19936
- if ((0, import_node_fs35.existsSync)(file)) {
21062
+ if ((0, import_node_fs38.existsSync)(file)) {
19937
21063
  const id = galleryMediaId(file);
19938
21064
  media.set(id, { path: file, contentType: mediaType });
19939
21065
  url = `${galleryMediaRoute(id)}?v=${output.sha256.slice(0, 24)}`;
@@ -19965,7 +21091,7 @@ function describeHistory(media, entry, cacheDir) {
19965
21091
  var MAX_COMPARED_BYTES = 8 * 1024 * 1024;
19966
21092
  async function samePixels(a, b) {
19967
21093
  try {
19968
- const [left, right] = await Promise.all([(0, import_promises29.readFile)(a), (0, import_promises29.readFile)(b)]);
21094
+ const [left, right] = await Promise.all([(0, import_promises32.readFile)(a), (0, import_promises32.readFile)(b)]);
19969
21095
  if (left.length > MAX_COMPARED_BYTES || right.length > MAX_COMPARED_BYTES) return false;
19970
21096
  const x = decodePng(left);
19971
21097
  const y = decodePng(right);
@@ -20031,7 +21157,7 @@ function describeCharacter(spec, entry) {
20031
21157
  }
20032
21158
  async function fileInfo(absolutePath) {
20033
21159
  try {
20034
- const info = await (0, import_promises29.stat)(absolutePath);
21160
+ const info = await (0, import_promises32.stat)(absolutePath);
20035
21161
  return info.isFile() ? { bytes: info.size, modifiedAt: info.mtime.toISOString() } : null;
20036
21162
  } catch {
20037
21163
  return null;
@@ -20063,10 +21189,10 @@ async function describeOutput(media, root, absolutePath, recorded = {}) {
20063
21189
  async function describeQuality(media, root, inspection) {
20064
21190
  const outputPaths = inspection.outputs ?? [inspection.output];
20065
21191
  const outputs = await Promise.all(
20066
- outputPaths.map((file) => describeOutput(media, root, import_node_path39.default.resolve(root, file)))
21192
+ outputPaths.map((file) => describeOutput(media, root, import_node_path42.default.resolve(root, file)))
20067
21193
  );
20068
- const recordPath = import_node_path39.default.resolve(root, inspection.record);
20069
- const recordExists = (0, import_node_fs35.existsSync)(recordPath);
21194
+ const recordPath = import_node_path42.default.resolve(root, inspection.record);
21195
+ const recordExists = (0, import_node_fs38.existsSync)(recordPath);
20070
21196
  let options = null;
20071
21197
  let check = null;
20072
21198
  if (recordExists) {
@@ -20085,7 +21211,7 @@ async function describeQuality(media, root, inspection) {
20085
21211
  return {
20086
21212
  state: inspection.state,
20087
21213
  reason: inspection.reason,
20088
- output: portableOutputPath(import_node_path39.default.resolve(root, inspection.output), root),
21214
+ output: portableOutputPath(import_node_path42.default.resolve(root, inspection.output), root),
20089
21215
  record: portableOutputPath(recordPath, root),
20090
21216
  recordExists,
20091
21217
  outputs,
@@ -20123,9 +21249,9 @@ async function buildGallerySnapshot(opts) {
20123
21249
  const media = /* @__PURE__ */ new Map();
20124
21250
  const plan = await buildPlan(specs, lock);
20125
21251
  const items = [];
20126
- const manifestText = await (0, import_promises29.readFile)(loaded.path, "utf8");
21252
+ const manifestText = await (0, import_promises32.readFile)(loaded.path, "utf8");
20127
21253
  const manifestSha256 = sha256(manifestText);
20128
- const cacheDir = import_node_path39.default.resolve(import_node_path39.default.dirname(opts.lockPath), ".pixelkiln", "cache");
21254
+ const cacheDir = import_node_path42.default.resolve(import_node_path42.default.dirname(opts.lockPath), ".pixelkiln", "cache");
20129
21255
  let rawStyles = {};
20130
21256
  try {
20131
21257
  const raw = JSON.parse(manifestText);
@@ -20149,12 +21275,12 @@ async function buildGallerySnapshot(opts) {
20149
21275
  )
20150
21276
  );
20151
21277
  if (spec.source) {
20152
- const editPath = import_node_path39.default.resolve(root, spec.source);
21278
+ const editPath = import_node_path42.default.resolve(root, spec.source);
20153
21279
  const memberCount = sourceIsStem(spec.source, entry, root) ? entry.outputs.length : 1;
20154
21280
  const editShas = await Promise.all(
20155
21281
  Array.from({ length: memberCount }, async (_, index) => {
20156
21282
  const file = sourceOutputPath(spec.source, entry, index, root);
20157
- return { file, sha256: (0, import_node_fs35.existsSync)(file) ? await sha256File(file) : null };
21283
+ return { file, sha256: (0, import_node_fs38.existsSync)(file) ? await sha256File(file) : null };
20158
21284
  })
20159
21285
  );
20160
21286
  edits = await Promise.all(editShas.map(({ file, sha256: editSha }) => describeOutput(media, root, file, { sha256: editSha })));
@@ -20162,7 +21288,7 @@ async function buildGallerySnapshot(opts) {
20162
21288
  const companion = await readHandEditCompanion(editPath);
20163
21289
  if (companion) {
20164
21290
  const projectPath = handEditProjectPath(editPath);
20165
- const project = companion.project && (0, import_node_fs35.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
21291
+ const project = companion.project && (0, import_node_fs38.existsSync)(projectPath) ? await fileInfo(projectPath) : null;
20166
21292
  let projectUrl = null;
20167
21293
  if (project) {
20168
21294
  const id = galleryMediaId(projectPath);
@@ -20198,8 +21324,8 @@ async function buildGallerySnapshot(opts) {
20198
21324
  editStatus = edits.some((member) => !member.exists) ? "missing" : editChanged.every((changed) => !changed) ? "same" : regenerated ? "regenerated-since" : "edited";
20199
21325
  }
20200
21326
  } else if (spec.source) {
20201
- outputs = [await describeOutput(media, root, import_node_path39.default.resolve(root, spec.source))];
20202
- } else if (!entry && (0, import_node_fs35.existsSync)(spec.outFile)) {
21327
+ outputs = [await describeOutput(media, root, import_node_path42.default.resolve(root, spec.source))];
21328
+ } else if (!entry && (0, import_node_fs38.existsSync)(spec.outFile)) {
20203
21329
  outputs = [await describeOutput(media, root, spec.outFile)];
20204
21330
  } else {
20205
21331
  outputs = [];
@@ -20403,7 +21529,7 @@ async function buildGallerySnapshot(opts) {
20403
21529
  id: loaded.manifest.name,
20404
21530
  name: loaded.manifest.name,
20405
21531
  manifest: loaded.path,
20406
- lock: import_node_path39.default.resolve(opts.lockPath),
21532
+ lock: import_node_path42.default.resolve(opts.lockPath),
20407
21533
  root,
20408
21534
  provider: loaded.manifest.provider,
20409
21535
  account: null,
@@ -20429,7 +21555,7 @@ async function buildGallerySnapshot(opts) {
20429
21555
  return { snapshot, media };
20430
21556
  }
20431
21557
  async function buildWorkspaceGallerySnapshot(opts) {
20432
- const dir = import_node_path39.default.dirname(import_node_path39.default.resolve(opts.workspacePath));
21558
+ const dir = import_node_path42.default.dirname(import_node_path42.default.resolve(opts.workspacePath));
20433
21559
  const media = /* @__PURE__ */ new Map();
20434
21560
  const projects = [];
20435
21561
  const items = [];
@@ -20472,11 +21598,11 @@ async function buildWorkspaceGallerySnapshot(opts) {
20472
21598
  id: project.id,
20473
21599
  name: loaded.manifest.name,
20474
21600
  manifest: manifestPath,
20475
- lock: import_node_path39.default.resolve(lockPath),
21601
+ lock: import_node_path42.default.resolve(lockPath),
20476
21602
  root: loaded.root,
20477
21603
  provider: loaded.manifest.provider,
20478
21604
  account: project.account ?? null,
20479
- manifestSha256: manifestSha256 ?? sha256(await (0, import_promises29.readFile)(manifestPath, "utf8")),
21605
+ manifestSha256: manifestSha256 ?? sha256(await (0, import_promises32.readFile)(manifestPath, "utf8")),
20480
21606
  historyLimit: historyLimit(loaded.manifest),
20481
21607
  entries: Object.keys(lock.entries).length,
20482
21608
  items: projectItems.length,
@@ -20488,8 +21614,8 @@ async function buildWorkspaceGallerySnapshot(opts) {
20488
21614
  id: project.id,
20489
21615
  name: project.id,
20490
21616
  manifest: manifestPath,
20491
- lock: import_node_path39.default.resolve(lockPath),
20492
- root: import_node_path39.default.dirname(manifestPath),
21617
+ lock: import_node_path42.default.resolve(lockPath),
21618
+ root: import_node_path42.default.dirname(manifestPath),
20493
21619
  provider: project.provider,
20494
21620
  account: project.account ?? null,
20495
21621
  manifestSha256: null,
@@ -20516,7 +21642,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
20516
21642
  version: 1,
20517
21643
  generatedAt: (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
20518
21644
  project: null,
20519
- workspace: { path: import_node_path39.default.resolve(opts.workspacePath), dir, projects },
21645
+ workspace: { path: import_node_path42.default.resolve(opts.workspacePath), dir, projects },
20520
21646
  filter,
20521
21647
  totals: {
20522
21648
  entries: projects.reduce((sum, project) => sum + project.entries, 0),
@@ -20533,7 +21659,7 @@ async function buildWorkspaceGallerySnapshot(opts) {
20533
21659
  }
20534
21660
 
20535
21661
  // src/gallery/page.ts
20536
- var import_node_fs36 = require("fs");
21662
+ var import_node_fs39 = require("fs");
20537
21663
 
20538
21664
  // src/gallery/client-bundle.ts
20539
21665
  var import_node_module = require("module");
@@ -20573,8 +21699,8 @@ var client;
20573
21699
  function clientAssets() {
20574
21700
  const prebuilt = new URL("gallery.js", CLIENT_DIR);
20575
21701
  client ??= {
20576
- css: (0, import_node_fs36.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
20577
- js: (0, import_node_fs36.existsSync)(prebuilt) ? (0, import_node_fs36.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
21702
+ css: (0, import_node_fs39.readFileSync)(new URL("gallery.css", CLIENT_DIR), "utf8"),
21703
+ js: (0, import_node_fs39.existsSync)(prebuilt) ? (0, import_node_fs39.readFileSync)(prebuilt, "utf8") : bundleGalleryClient()
20578
21704
  };
20579
21705
  return client;
20580
21706
  }
@@ -20717,10 +21843,10 @@ var EDITOR_RELEASE_BASE = "https://github.com/gfargo/pixelkiln/releases/download
20717
21843
 
20718
21844
  // src/editor/install.ts
20719
21845
  var import_node_crypto8 = require("crypto");
20720
- var import_node_fs37 = require("fs");
20721
- var import_promises30 = require("fs/promises");
21846
+ var import_node_fs40 = require("fs");
21847
+ var import_promises33 = require("fs/promises");
20722
21848
  var import_node_os4 = __toESM(require("os"), 1);
20723
- var import_node_path40 = __toESM(require("path"), 1);
21849
+ var import_node_path43 = __toESM(require("path"), 1);
20724
21850
  var EditorInstallError = class extends Error {
20725
21851
  constructor(message6, file) {
20726
21852
  super(message6);
@@ -20731,15 +21857,15 @@ var EditorInstallError = class extends Error {
20731
21857
  };
20732
21858
  function editorToolsRoot() {
20733
21859
  const override = process.env.PIXELKILN_TOOLS_DIR?.trim();
20734
- if (override) return import_node_path40.default.resolve(override);
20735
- if (process.platform === "darwin") return import_node_path40.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
21860
+ if (override) return import_node_path43.default.resolve(override);
21861
+ if (process.platform === "darwin") return import_node_path43.default.join(import_node_os4.default.homedir(), "Library", "Caches", "pixelkiln", "tools");
20736
21862
  if (process.platform === "win32") {
20737
- return import_node_path40.default.join(process.env.LOCALAPPDATA ?? import_node_path40.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
21863
+ return import_node_path43.default.join(process.env.LOCALAPPDATA ?? import_node_path43.default.join(import_node_os4.default.homedir(), "AppData", "Local"), "pixelkiln", "tools");
20738
21864
  }
20739
- return import_node_path40.default.join(process.env.XDG_CACHE_HOME ?? import_node_path40.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
21865
+ return import_node_path43.default.join(process.env.XDG_CACHE_HOME ?? import_node_path43.default.join(import_node_os4.default.homedir(), ".cache"), "pixelkiln", "tools");
20740
21866
  }
20741
21867
  function editorDir(pin = EDITOR_PIN, root = editorToolsRoot()) {
20742
- return import_node_path40.default.join(root, "pixelorama", pin.release ?? "unpublished");
21868
+ return import_node_path43.default.join(root, "pixelorama", pin.release ?? "unpublished");
20743
21869
  }
20744
21870
  function editorBaseUrl(pin = EDITOR_PIN) {
20745
21871
  const override = process.env.PIXELKILN_EDITOR_URL?.trim();
@@ -20749,7 +21875,7 @@ function editorBaseUrl(pin = EDITOR_PIN) {
20749
21875
  }
20750
21876
  async function sha256Of(file) {
20751
21877
  try {
20752
- return (0, import_node_crypto8.createHash)("sha256").update(await (0, import_promises30.readFile)(file)).digest("hex");
21878
+ return (0, import_node_crypto8.createHash)("sha256").update(await (0, import_promises33.readFile)(file)).digest("hex");
20753
21879
  } catch {
20754
21880
  return null;
20755
21881
  }
@@ -20762,8 +21888,8 @@ async function editorStatus(opts = {}) {
20762
21888
  let totalBytes = 0;
20763
21889
  for (const [name, expected] of Object.entries(pin.files)) {
20764
21890
  totalBytes += expected.bytes;
20765
- const file = import_node_path40.default.join(dir, name);
20766
- const info = (0, import_node_fs37.existsSync)(file) ? await (0, import_promises30.stat)(file).catch(() => null) : null;
21891
+ const file = import_node_path43.default.join(dir, name);
21892
+ const info = (0, import_node_fs40.existsSync)(file) ? await (0, import_promises33.stat)(file).catch(() => null) : null;
20767
21893
  if (info && info.size === expected.bytes && await sha256Of(file) === expected.sha256) {
20768
21894
  installedBytes += expected.bytes;
20769
21895
  } else {
@@ -20792,7 +21918,7 @@ async function installEditor(opts = {}) {
20792
21918
  );
20793
21919
  }
20794
21920
  if (!baseUrl) throw new EditorInstallError("no download location for the editor build");
20795
- await (0, import_promises30.mkdir)(dir, { recursive: true });
21921
+ await (0, import_promises33.mkdir)(dir, { recursive: true });
20796
21922
  const downloaded = [];
20797
21923
  const skipped = Object.keys(pin.files).filter((name) => !before.missing.includes(name));
20798
21924
  let fetchedBytes = before.installedBytes;
@@ -20820,13 +21946,13 @@ async function installEditor(opts = {}) {
20820
21946
  if (digest2 !== expected.sha256) {
20821
21947
  throw new EditorInstallError(`${name}: sha256 ${digest2.slice(0, 12)}\u2026 does not match the pinned ${expected.sha256.slice(0, 12)}\u2026`, name);
20822
21948
  }
20823
- const final = import_node_path40.default.join(dir, name);
21949
+ const final = import_node_path43.default.join(dir, name);
20824
21950
  const tmp = `${final}.${process.pid}.part`;
20825
21951
  try {
20826
- await (0, import_promises30.writeFile)(tmp, bytes);
20827
- await (0, import_promises30.rename)(tmp, final);
21952
+ await (0, import_promises33.writeFile)(tmp, bytes);
21953
+ await (0, import_promises33.rename)(tmp, final);
20828
21954
  } finally {
20829
- await (0, import_promises30.rm)(tmp, { force: true });
21955
+ await (0, import_promises33.rm)(tmp, { force: true });
20830
21956
  }
20831
21957
  fetchedBytes += bytes.length;
20832
21958
  downloaded.push(name);
@@ -20866,12 +21992,12 @@ var EDITOR_CONTENT_TYPES = {
20866
21992
  ".json": "application/json; charset=utf-8"
20867
21993
  };
20868
21994
  function editorContentType(name) {
20869
- return EDITOR_CONTENT_TYPES[import_node_path40.default.extname(name).toLowerCase()] ?? null;
21995
+ return EDITOR_CONTENT_TYPES[import_node_path43.default.extname(name).toLowerCase()] ?? null;
20870
21996
  }
20871
21997
 
20872
21998
  // src/gallery/editor.ts
20873
- var import_promises31 = require("fs/promises");
20874
- var import_node_path41 = __toESM(require("path"), 1);
21999
+ var import_promises34 = require("fs/promises");
22000
+ var import_node_path44 = __toESM(require("path"), 1);
20875
22001
  function editorRoute(release, name = "index.html") {
20876
22002
  return `/editor/${encodeURIComponent(release)}/${encodeURIComponent(name)}`;
20877
22003
  }
@@ -20944,7 +22070,7 @@ function createGalleryEditorHandlers(opts = {}) {
20944
22070
  if (!status.installed) return null;
20945
22071
  let bytes;
20946
22072
  try {
20947
- bytes = await (0, import_promises31.readFile)(import_node_path41.default.join(dir, name));
22073
+ bytes = await (0, import_promises34.readFile)(import_node_path44.default.join(dir, name));
20948
22074
  } catch {
20949
22075
  verified = null;
20950
22076
  return null;
@@ -20961,7 +22087,7 @@ function createGalleryEditorHandlers(opts = {}) {
20961
22087
  // src/gallery/server.ts
20962
22088
  var import_node_crypto9 = require("crypto");
20963
22089
  var import_node_http2 = require("http");
20964
- var import_promises32 = require("fs/promises");
22090
+ var import_promises35 = require("fs/promises");
20965
22091
  var MAX_EDIT_BYTES = 48 * 1024 * 1024;
20966
22092
  var EDITOR_CSP = [
20967
22093
  "default-src 'self'",
@@ -21142,7 +22268,7 @@ async function serveGallery(opts) {
21142
22268
  const asset = reviewAssets.get(jobId)?.get(url2.pathname);
21143
22269
  if (!asset) return fail(404, "no such review asset");
21144
22270
  try {
21145
- const bytes = await (0, import_promises32.readFile)(asset.path);
22271
+ const bytes = await (0, import_promises35.readFile)(asset.path);
21146
22272
  res.writeHead(200, {
21147
22273
  "Content-Type": asset.contentType,
21148
22274
  "Cache-Control": "no-store",
@@ -21225,7 +22351,7 @@ async function serveGallery(opts) {
21225
22351
  if (!asset) return fail(404, "no such gallery media");
21226
22352
  let bytes;
21227
22353
  try {
21228
- bytes = await (0, import_promises32.readFile)(asset.path);
22354
+ bytes = await (0, import_promises35.readFile)(asset.path);
21229
22355
  } catch {
21230
22356
  return fail(404, "gallery media is no longer on disk; refresh the page");
21231
22357
  }
@@ -21635,19 +22761,19 @@ function createGenerateHandlers(opts) {
21635
22761
  }
21636
22762
 
21637
22763
  // src/pipeline/salvage.ts
21638
- var import_promises33 = require("fs/promises");
21639
- var import_node_fs38 = require("fs");
21640
- var import_node_path42 = __toESM(require("path"), 1);
22764
+ var import_promises36 = require("fs/promises");
22765
+ var import_node_fs41 = require("fs");
22766
+ var import_node_path45 = __toESM(require("path"), 1);
21641
22767
  function providerClaimId(provider, objectId) {
21642
22768
  return `${encodeURIComponent(provider)}:${encodeURIComponent(objectId)}`;
21643
22769
  }
21644
22770
  async function loadClaims(lockPaths, opts = {}) {
21645
22771
  const claimed = /* @__PURE__ */ new Set();
21646
22772
  for (const p of lockPaths) {
21647
- if (!(0, import_node_fs38.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
22773
+ if (!(0, import_node_fs41.existsSync)(p)) throw new Error(`Claim lockfile not found: ${p}`);
21648
22774
  let parsed;
21649
22775
  try {
21650
- parsed = parseLock(JSON.parse(await (0, import_promises33.readFile)(p, "utf8")));
22776
+ parsed = parseLock(JSON.parse(await (0, import_promises36.readFile)(p, "utf8")));
21651
22777
  } catch {
21652
22778
  throw new Error(`Claim lockfile is malformed: ${p}`);
21653
22779
  }
@@ -21699,7 +22825,7 @@ function characterSalvageAssets(characters, ctx) {
21699
22825
  assets[baseId] = { prompt: base.prompt || base.name || baseId, remoteId: base.id, ...size, ...common };
21700
22826
  const assetIdOf = /* @__PURE__ */ new Map([[base.id, baseId]]);
21701
22827
  for (const state of ordered.slice(1)) {
21702
- const stateId = uniqueId(`${baseId}_${slug(state.stateName ?? "state")}`, ctx.taken);
22828
+ const stateId = uniqueId(`${baseId}_${slug2(state.stateName ?? "state")}`, ctx.taken);
21703
22829
  assetIdOf.set(state.id, stateId);
21704
22830
  assets[stateId] = { prompt: state.prompt || state.stateName || stateId, state: { of: baseId }, remoteId: state.id, ...common };
21705
22831
  }
@@ -21712,7 +22838,7 @@ function characterSalvageAssets(characters, ctx) {
21712
22838
  skipped.push(`${parentId}: "${label}" ${animation.direction} loop has no animation group id to adopt it by`);
21713
22839
  continue;
21714
22840
  }
21715
- const loopId = uniqueId(`${parentId}.${slug(label)}.${animation.direction}`, ctx.taken);
22841
+ const loopId = uniqueId(`${parentId}.${slug2(label)}.${animation.direction}`, ctx.taken);
21716
22842
  assets[loopId] = {
21717
22843
  prompt: label,
21718
22844
  animation: { of: parentId, direction: animation.direction },
@@ -21723,7 +22849,7 @@ function characterSalvageAssets(characters, ctx) {
21723
22849
  }
21724
22850
  return { assets, skipped };
21725
22851
  }
21726
- function slug(text) {
22852
+ function slug2(text) {
21727
22853
  return text.toLowerCase().replace(/^pixelkiln:.*\//, "").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "loop";
21728
22854
  }
21729
22855
  function uniqueId(base, taken) {
@@ -21751,20 +22877,20 @@ function matchOrphanStyle(prompt, manifest) {
21751
22877
  return matchStyleByPattern(prompt, manifest);
21752
22878
  }
21753
22879
  async function loadSiblingManifests(ownManifestPath, workspaceManifestPaths, claimPaths) {
21754
- const own = import_node_path42.default.resolve(ownManifestPath);
22880
+ const own = import_node_path45.default.resolve(ownManifestPath);
21755
22881
  const siblingManifestPaths = [
21756
22882
  .../* @__PURE__ */ new Set([
21757
22883
  ...workspaceManifestPaths,
21758
- ...claimPaths.map((c) => import_node_path42.default.join(import_node_path42.default.dirname(import_node_path42.default.resolve(c)), "pixelkiln.manifest.json"))
22884
+ ...claimPaths.map((c) => import_node_path45.default.join(import_node_path45.default.dirname(import_node_path45.default.resolve(c)), "pixelkiln.manifest.json"))
21759
22885
  ])
21760
22886
  ];
21761
22887
  const siblings = [];
21762
22888
  for (const siblingManifestPath of siblingManifestPaths) {
21763
- if (import_node_path42.default.resolve(siblingManifestPath) === own) continue;
21764
- if (!(0, import_node_fs38.existsSync)(siblingManifestPath)) continue;
22889
+ if (import_node_path45.default.resolve(siblingManifestPath) === own) continue;
22890
+ if (!(0, import_node_fs41.existsSync)(siblingManifestPath)) continue;
21765
22891
  try {
21766
22892
  const { manifest } = await loadManifest(siblingManifestPath);
21767
- siblings.push({ label: import_node_path42.default.basename(import_node_path42.default.dirname(siblingManifestPath)), manifest });
22893
+ siblings.push({ label: import_node_path45.default.basename(import_node_path45.default.dirname(siblingManifestPath)), manifest });
21768
22894
  } catch {
21769
22895
  }
21770
22896
  }
@@ -21884,8 +23010,8 @@ async function applyTags(provider, decisions, existing, opts = {}) {
21884
23010
  }
21885
23011
 
21886
23012
  // src/pick/salvage-server.ts
21887
- var import_promises34 = require("fs/promises");
21888
- var import_node_path43 = __toESM(require("path"), 1);
23013
+ var import_promises37 = require("fs/promises");
23014
+ var import_node_path46 = __toESM(require("path"), 1);
21889
23015
 
21890
23016
  // src/pick/salvage-sheet.ts
21891
23017
  var escapeHtml3 = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
@@ -22051,7 +23177,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
22051
23177
  });
22052
23178
  const html = renderSalvageSheet(orphans, {
22053
23179
  styleId: ctx.styleId,
22054
- importDir: import_node_path43.default.relative(process.cwd(), ctx.importDir) || "."
23180
+ importDir: import_node_path46.default.relative(process.cwd(), ctx.importDir) || "."
22055
23181
  });
22056
23182
  const byId = new Map(orphans.map((o) => [o.id, o]));
22057
23183
  const existingTags = new Map(orphans.map((o) => [o.id, o.tags]));
@@ -22107,10 +23233,10 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
22107
23233
  if (!buf.subarray(0, 8).equals(PNG_SIGNATURE2)) throw new Error("not a PNG");
22108
23234
  decodePng(buf);
22109
23235
  const assetId = idFromPrompt(orphan.prompt, taken);
22110
- const rel = import_node_path43.default.join("_salvaged", `${assetId}.png`);
22111
- const outFile = import_node_path43.default.resolve(ctx.importDir, rel);
22112
- await (0, import_promises34.mkdir)(import_node_path43.default.dirname(outFile), { recursive: true });
22113
- await (0, import_promises34.writeFile)(outFile, buf);
23236
+ const rel = import_node_path46.default.join("_salvaged", `${assetId}.png`);
23237
+ const outFile = import_node_path46.default.resolve(ctx.importDir, rel);
23238
+ await (0, import_promises37.mkdir)(import_node_path46.default.dirname(outFile), { recursive: true });
23239
+ await (0, import_promises37.writeFile)(outFile, buf);
22114
23240
  ctx.manifest.assets[assetId] = {
22115
23241
  prompt: orphan.prompt,
22116
23242
  promptByStyle: {},
@@ -22142,7 +23268,7 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
22142
23268
  sourceUrl: durableSource,
22143
23269
  sourceUrls: durableSource ? [{ url: durableSource }] : [],
22144
23270
  outputs: [{
22145
- path: portableOutputPath(outFile, import_node_path43.default.dirname(ctx.manifestPath)),
23271
+ path: portableOutputPath(outFile, import_node_path46.default.dirname(ctx.manifestPath)),
22146
23272
  sha256: sha256(buf)
22147
23273
  }],
22148
23274
  submittedAt: orphan.createdAt,
@@ -22166,9 +23292,9 @@ async function runSalvage(provider, orphans, ctx, opts = {}) {
22166
23292
  }
22167
23293
  }
22168
23294
  await applyTags(provider, decisions, existingTags, { onProgress: log, characters: characterMembers });
22169
- const raw = JSON.parse(await (0, import_promises34.readFile)(ctx.manifestPath, "utf8"));
23295
+ const raw = JSON.parse(await (0, import_promises37.readFile)(ctx.manifestPath, "utf8"));
22170
23296
  for (const id of importedAssetIds) raw.assets[id] = ctx.manifest.assets[id];
22171
- await (0, import_promises34.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
23297
+ await (0, import_promises37.writeFile)(ctx.manifestPath, JSON.stringify(raw, null, 2) + "\n");
22172
23298
  await saveLock(ctx.lockPath, ctx.lock);
22173
23299
  if (characterAssetIds.length) result.characterAssetIds = characterAssetIds;
22174
23300
  return result;
@@ -22277,6 +23403,7 @@ async function workspaceStatus(ws, dir) {
22277
23403
  }
22278
23404
  // Annotate the CommonJS export names for ESM import in node:
22279
23405
  0 && (module.exports = {
23406
+ ASSET_KINDS,
22280
23407
  AssetBatchSchema,
22281
23408
  AssetDeriveSchema,
22282
23409
  AssetExternalSchema,
@@ -22303,6 +23430,10 @@ async function workspaceStatus(ws, dir) {
22303
23430
  EDITOR_PIN,
22304
23431
  EDITOR_RELEASE_BASE,
22305
23432
  EXIT_CODES,
23433
+ EXPAND_DIRECTIONS,
23434
+ EXPAND_MAX_COST,
23435
+ EXPAND_MIN_COST,
23436
+ EXPORT_FORMATS,
22306
23437
  EditorInstallError,
22307
23438
  FAKE_PNG,
22308
23439
  FONT_COST_GENERATIONS,
@@ -22317,6 +23448,7 @@ async function workspaceStatus(ws, dir) {
22317
23448
  HAND_EDIT_DIR,
22318
23449
  HISTORY_ENV,
22319
23450
  HandEditCompanionSchema,
23451
+ IMPORT_MAX_SIDE,
22320
23452
  ImageQualityMetricsSchema,
22321
23453
  InheritedStyleSchema,
22322
23454
  LockEntrySchema,
@@ -22329,6 +23461,14 @@ async function workspaceStatus(ws, dir) {
22329
23461
  MAX_RETRIES,
22330
23462
  MEMBER_SET_REVISION_MODES,
22331
23463
  MIRRORED_DIRECTION,
23464
+ MIRROR_DIRECTIONS,
23465
+ MUSIC_COST_GENERATIONS,
23466
+ MUSIC_LOOP_COST_GENERATIONS,
23467
+ MUSIC_LOOP_MIN_BODY_SECONDS,
23468
+ MUSIC_MAX_BPM,
23469
+ MUSIC_MAX_SECONDS,
23470
+ MUSIC_MIN_BPM,
23471
+ MUSIC_MIN_SECONDS,
22332
23472
  ManifestDriftError,
22333
23473
  ManifestEditError,
22334
23474
  ManifestEditSchema,
@@ -22346,6 +23486,7 @@ async function workspaceStatus(ws, dir) {
22346
23486
  OverwriteRefusedError,
22347
23487
  PIXELATE_COST_GENERATIONS,
22348
23488
  PIXELATE_MAX_SIDE,
23489
+ PIXELATE_PRO_COST_GENERATIONS,
22349
23490
  PIXELLAB_MCP_URL,
22350
23491
  PIXEL_ART_FIXER_REVISION,
22351
23492
  PIXEL_ART_FIXER_URL,
@@ -22366,6 +23507,8 @@ async function workspaceStatus(ws, dir) {
22366
23507
  RevisionDitheringSchema,
22367
23508
  RevisionModeSchema,
22368
23509
  RevisionSchema,
23510
+ SFX_MAX_SECONDS,
23511
+ SFX_MIN_SECONDS,
22369
23512
  SHEET_FORMATS,
22370
23513
  ScenarioProvider,
22371
23514
  StyleInputSchema,
@@ -22374,6 +23517,10 @@ async function workspaceStatus(ws, dir) {
22374
23517
  TerrainConnectSchema,
22375
23518
  TerrainLinkSchema,
22376
23519
  TerrainSideSchema,
23520
+ UI_STATES_COSTS,
23521
+ UI_STATES_MAX_COST,
23522
+ UI_STATES_MAX_ELEMENTS,
23523
+ UI_STATES_MAX_STATES,
22377
23524
  UNZOOM_MAX_AREA,
22378
23525
  UNZOOM_MIN_SIDE,
22379
23526
  UiElementSchema,
@@ -22403,8 +23550,10 @@ async function workspaceStatus(ws, dir) {
22403
23550
  cacheFileName,
22404
23551
  candidateCount,
22405
23552
  characterDirections,
23553
+ checkExportBytes,
22406
23554
  checkQualityBaseline,
22407
23555
  checkQualityRecord,
23556
+ checkUiInsets,
22408
23557
  clientFromEnv,
22409
23558
  colorDistance,
22410
23559
  countNumberedDescriptions,
@@ -22413,6 +23562,7 @@ async function workspaceStatus(ws, dir) {
22413
23562
  createGalleryEditorHandlers,
22414
23563
  createGenerateHandlers,
22415
23564
  createProvider,
23565
+ createUiStates,
22416
23566
  currentEntryOutputPath,
22417
23567
  currentOutputPath,
22418
23568
  defaultNormalMapOut,
@@ -22421,6 +23571,7 @@ async function workspaceStatus(ws, dir) {
22421
23571
  defaultUnzoomOut,
22422
23572
  describeVfx,
22423
23573
  detachHandEdit,
23574
+ detectAudioFormat,
22424
23575
  detectMediaType,
22425
23576
  doctor,
22426
23577
  editorBaseUrl,
@@ -22431,7 +23582,10 @@ async function workspaceStatus(ws, dir) {
22431
23582
  errorCode,
22432
23583
  evaluateAudit,
22433
23584
  exitCodeFor,
23585
+ expandObject,
22434
23586
  expectedOutputPath,
23587
+ exportAssetFile,
23588
+ exportOutPath,
22435
23589
  exportTileset,
22436
23590
  fallbackOutputRole,
22437
23591
  fetchAssets,
@@ -22445,6 +23599,8 @@ async function workspaceStatus(ws, dir) {
22445
23599
  galleryMediaId,
22446
23600
  galleryMediaRoute,
22447
23601
  generateFont,
23602
+ generateMusic,
23603
+ generateSoundEffect,
22448
23604
  generationCost,
22449
23605
  groupOrphansByStyle,
22450
23606
  handEditBase,
@@ -22459,6 +23615,7 @@ async function workspaceStatus(ws, dir) {
22459
23615
  idFromPrompt,
22460
23616
  imageMetadata,
22461
23617
  importLocal,
23618
+ importObjectFile,
22462
23619
  inspectCaches,
22463
23620
  inspectQualityProfile,
22464
23621
  inspectRevisionReadiness,
@@ -22490,6 +23647,8 @@ async function workspaceStatus(ws, dir) {
22490
23647
  mergePalettes,
22491
23648
  mountSprites,
22492
23649
  mountStyle,
23650
+ musicCost,
23651
+ musicOutputPaths,
22493
23652
  normalMapFile,
22494
23653
  normalMapResultPng,
22495
23654
  normalMapSizeProblem,
@@ -22506,10 +23665,14 @@ async function workspaceStatus(ws, dir) {
22506
23665
  packStyle,
22507
23666
  paletteDistance,
22508
23667
  parentAssetId,
23668
+ parseCanvasSize,
22509
23669
  parseLock,
22510
23670
  parseMcpBody,
22511
23671
  parseProFlashQuote,
22512
23672
  parseTerrainDescriptions,
23673
+ parseUiBox,
23674
+ parseUiInsets,
23675
+ parseUiState,
22513
23676
  parseVfxArtistResult,
22514
23677
  parseVfxExport,
22515
23678
  parseVfxRecipe,
@@ -22527,6 +23690,8 @@ async function workspaceStatus(ws, dir) {
22527
23690
  proportionsPayload,
22528
23691
  providerCredentialEnvs,
22529
23692
  providerFactory,
23693
+ pullExpansionReview,
23694
+ pullUiAsset,
22530
23695
  pushTags,
22531
23696
  qualityFrameOutputPath,
22532
23697
  qualityRecordPath,
@@ -22592,6 +23757,8 @@ async function workspaceStatus(ws, dir) {
22592
23757
  slugify,
22593
23758
  snapshotQualityBaseline,
22594
23759
  snapshotQualityCases,
23760
+ soundEffectCost,
23761
+ soundEffectOutputPaths,
22595
23762
  sourceIsStem,
22596
23763
  sourceOutputPath,
22597
23764
  specHash,
@@ -22611,8 +23778,10 @@ async function workspaceStatus(ws, dir) {
22611
23778
  toPortablePath,
22612
23779
  totalSpend,
22613
23780
  uiElementCandidateCount,
23781
+ uiStateElements,
22614
23782
  unzoomFile,
22615
23783
  upsert,
23784
+ validateAudio,
22616
23785
  validateCostEstimate,
22617
23786
  validateMedia,
22618
23787
  validateWorkspace,