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/README.md +1 -1
- package/dist/cli.js +1796 -172
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1527 -358
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3948 -101
- package/dist/index.d.ts +3948 -101
- package/dist/index.js +1456 -330
- package/dist/index.js.map +1 -1
- package/docs/CLI.md +211 -2
- package/docs/ENDPOINTS.md +221 -15
- package/docs/GENERATORS.md +2 -2
- package/docs/MANIFEST.md +7 -0
- package/docs/PIXELLAB.md +5 -2
- package/docs/TILES.md +29 -0
- package/package.json +1 -1
- package/schema/manifest.schema.json +76 -0
- package/schema/recipe.schema.json +29 -0
- package/skills/pixelkiln/references/pixellab.md +1 -1
package/dist/cli.js
CHANGED
|
@@ -67,8 +67,8 @@ function exitCodeFor(err) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
// src/cli/main.ts
|
|
70
|
-
import { existsSync as
|
|
71
|
-
import { readFile as
|
|
70
|
+
import { existsSync as existsSync47 } from "fs";
|
|
71
|
+
import { readFile as readFile40 } from "fs/promises";
|
|
72
72
|
|
|
73
73
|
// src/cli/args.ts
|
|
74
74
|
import path from "path";
|
|
@@ -125,7 +125,24 @@ var VALUE_FLAGS = [
|
|
|
125
125
|
"--sprite",
|
|
126
126
|
"--fps",
|
|
127
127
|
"--artist",
|
|
128
|
-
"--convention"
|
|
128
|
+
"--convention",
|
|
129
|
+
"--id",
|
|
130
|
+
"--state",
|
|
131
|
+
"--element",
|
|
132
|
+
"--insets",
|
|
133
|
+
"--box",
|
|
134
|
+
"--kind",
|
|
135
|
+
"--size",
|
|
136
|
+
"--animation",
|
|
137
|
+
"--direction",
|
|
138
|
+
"--bpm",
|
|
139
|
+
"--seconds",
|
|
140
|
+
"--lyrics",
|
|
141
|
+
"--about",
|
|
142
|
+
"--voice",
|
|
143
|
+
"--style-weight",
|
|
144
|
+
"--loop-of",
|
|
145
|
+
"--restyle"
|
|
129
146
|
];
|
|
130
147
|
var BOOL_FLAGS = [
|
|
131
148
|
"--force",
|
|
@@ -145,7 +162,14 @@ var BOOL_FLAGS = [
|
|
|
145
162
|
"--no-editor",
|
|
146
163
|
"--game-pack",
|
|
147
164
|
"--local",
|
|
148
|
-
"--strict"
|
|
165
|
+
"--strict",
|
|
166
|
+
"--auto-lyrics",
|
|
167
|
+
"--loop",
|
|
168
|
+
"--improve",
|
|
169
|
+
"--clear",
|
|
170
|
+
"--keep",
|
|
171
|
+
"--discard",
|
|
172
|
+
"--pro"
|
|
149
173
|
];
|
|
150
174
|
var COMMANDS = [
|
|
151
175
|
"init",
|
|
@@ -186,6 +210,10 @@ var COMMANDS = [
|
|
|
186
210
|
"normal-map",
|
|
187
211
|
"vfx",
|
|
188
212
|
"font",
|
|
213
|
+
"music",
|
|
214
|
+
"sfx",
|
|
215
|
+
"ui",
|
|
216
|
+
"asset",
|
|
189
217
|
"help",
|
|
190
218
|
"--help",
|
|
191
219
|
"-h",
|
|
@@ -200,6 +228,9 @@ var EDIT_SUBCOMMANDS = ["start", "detach"];
|
|
|
200
228
|
var TOOLS_SUBCOMMANDS = ["status", "install"];
|
|
201
229
|
var TOOLS = ["editor"];
|
|
202
230
|
var VFX_SUBCOMMANDS = ["make", "presets", "parts"];
|
|
231
|
+
var MUSIC_SUBCOMMANDS = ["make", "style", "lyrics"];
|
|
232
|
+
var ASSET_SUBCOMMANDS = ["canvas", "mirror", "import", "expand", "review", "export"];
|
|
233
|
+
var UI_SUBCOMMANDS = ["show", "split", "states", "nine-slice", "pull"];
|
|
203
234
|
function parseArgs(argv) {
|
|
204
235
|
const [command = "help"] = argv;
|
|
205
236
|
if (!COMMANDS.includes(command)) {
|
|
@@ -295,6 +326,30 @@ function parseArgs(argv) {
|
|
|
295
326
|
throw new UsageError(`Unknown vfx subcommand "${subcommand}". Known: ${VFX_SUBCOMMANDS.join(", ")}`);
|
|
296
327
|
}
|
|
297
328
|
if (rest[0] === subcommand) rest = rest.slice(1);
|
|
329
|
+
} else if (command === "asset") {
|
|
330
|
+
subcommand = rest[0];
|
|
331
|
+
if (subcommand === void 0 || subcommand.startsWith("-")) {
|
|
332
|
+
throw new UsageError(`asset needs a subcommand: ${ASSET_SUBCOMMANDS.join(", ")}`);
|
|
333
|
+
}
|
|
334
|
+
if (!ASSET_SUBCOMMANDS.includes(subcommand)) {
|
|
335
|
+
throw new UsageError(`Unknown asset subcommand "${subcommand}". Known: ${ASSET_SUBCOMMANDS.join(", ")}`);
|
|
336
|
+
}
|
|
337
|
+
rest = rest.slice(1);
|
|
338
|
+
} else if (command === "ui") {
|
|
339
|
+
subcommand = rest[0];
|
|
340
|
+
if (subcommand === void 0 || subcommand.startsWith("-")) {
|
|
341
|
+
throw new UsageError(`ui needs a subcommand: ${UI_SUBCOMMANDS.join(", ")}`);
|
|
342
|
+
}
|
|
343
|
+
if (!UI_SUBCOMMANDS.includes(subcommand)) {
|
|
344
|
+
throw new UsageError(`Unknown ui subcommand "${subcommand}". Known: ${UI_SUBCOMMANDS.join(", ")}`);
|
|
345
|
+
}
|
|
346
|
+
rest = rest.slice(1);
|
|
347
|
+
} else if (command === "music") {
|
|
348
|
+
subcommand = rest[0]?.startsWith("-") || rest[0] === void 0 ? "make" : rest[0];
|
|
349
|
+
if (!MUSIC_SUBCOMMANDS.includes(subcommand)) {
|
|
350
|
+
throw new UsageError(`Unknown music subcommand "${subcommand}". Known: ${MUSIC_SUBCOMMANDS.join(", ")}`);
|
|
351
|
+
}
|
|
352
|
+
if (rest[0] === subcommand) rest = rest.slice(1);
|
|
298
353
|
} else if (command === "refine") {
|
|
299
354
|
subcommand = rest[0]?.startsWith("-") || rest[0] === void 0 ? "run" : rest[0];
|
|
300
355
|
if (!REFINE_SUBCOMMANDS.includes(subcommand)) {
|
|
@@ -386,7 +441,7 @@ function parseArgs(argv) {
|
|
|
386
441
|
}
|
|
387
442
|
const manifest = get("--manifest") ?? "pixelkiln.manifest.json";
|
|
388
443
|
const rawFormat = get("--format");
|
|
389
|
-
const formats = command === "export" ? ["generic", "tiled", "godot"] : ["generic", "aseprite", "godot"];
|
|
444
|
+
const formats = command === "export" ? ["generic", "tiled", "godot"] : command === "asset" ? ["zip", "spritesheet", "aseprite", "gif"] : ["generic", "aseprite", "godot"];
|
|
390
445
|
if (rawFormat && !formats.includes(rawFormat)) {
|
|
391
446
|
throw new UsageError(`--format must be ${formats.slice(0, -1).join(", ")}, or ${formats.at(-1)}, got "${rawFormat}"`);
|
|
392
447
|
}
|
|
@@ -482,7 +537,32 @@ function parseArgs(argv) {
|
|
|
482
537
|
parts: list("--part"),
|
|
483
538
|
sprite: get("--sprite"),
|
|
484
539
|
fps: numberOption("--fps", { min: 1, max: 60, integer: true }),
|
|
485
|
-
gamePack: rest.includes("--game-pack")
|
|
540
|
+
gamePack: rest.includes("--game-pack"),
|
|
541
|
+
kind: get("--kind"),
|
|
542
|
+
size: get("--size"),
|
|
543
|
+
animation: get("--animation"),
|
|
544
|
+
direction: get("--direction"),
|
|
545
|
+
keep: rest.includes("--keep"),
|
|
546
|
+
discard: rest.includes("--discard"),
|
|
547
|
+
pro: rest.includes("--pro"),
|
|
548
|
+
id: get("--id"),
|
|
549
|
+
// Free text with commas and "=" of its own, so neither is split.
|
|
550
|
+
uiStates: rest.flatMap((token, i) => token === "--state" && rest[i + 1] ? [rest[i + 1].trim()] : []),
|
|
551
|
+
elements: list("--element"),
|
|
552
|
+
insets: get("--insets"),
|
|
553
|
+
clear: rest.includes("--clear"),
|
|
554
|
+
boxes: rest.flatMap((token, i) => token === "--box" && rest[i + 1] ? [rest[i + 1].trim()] : []),
|
|
555
|
+
bpm: numberOption("--bpm", { min: 60, max: 180, integer: true }),
|
|
556
|
+
seconds: command === "music" ? numberOption("--seconds", { min: 10, max: 360, integer: true }) : numberOption("--seconds", { min: 0.5, max: 30 }),
|
|
557
|
+
lyrics: get("--lyrics"),
|
|
558
|
+
autoLyrics: rest.includes("--auto-lyrics"),
|
|
559
|
+
about: get("--about"),
|
|
560
|
+
voice: get("--voice"),
|
|
561
|
+
styleWeight: numberOption("--style-weight", { min: 0, max: 1 }),
|
|
562
|
+
loop: rest.includes("--loop"),
|
|
563
|
+
loopOf: get("--loop-of"),
|
|
564
|
+
restyle: get("--restyle"),
|
|
565
|
+
improve: rest.includes("--improve")
|
|
486
566
|
};
|
|
487
567
|
}
|
|
488
568
|
|
|
@@ -568,6 +648,23 @@ Commands
|
|
|
568
648
|
words instead (lite 1-5, pro 6-28 generations); asks first.
|
|
569
649
|
font PixelLab: generate a pixel font (--description, --out); writes a
|
|
570
650
|
.ttf and a glyph atlas PNG. 15 generations; asks first.
|
|
651
|
+
music PixelLab: a song from a style (--description, --out); writes two
|
|
652
|
+
takes as MP3 and a .music.json record. 10 generations; --loop adds
|
|
653
|
+
seamless loops (4 more); --loop-of loops an existing song.
|
|
654
|
+
music style / music lyrics draft a style or lyrics. Asks first.
|
|
655
|
+
ui PixelLab: work on a generated UI panel by --id. ui show lists its
|
|
656
|
+
elements and states; ui split cuts a template into elements (free);
|
|
657
|
+
ui states draws hover/pressed/... for them (10-25 generations; asks
|
|
658
|
+
first); ui nine-slice sets stretch insets (free); ui pull downloads
|
|
659
|
+
every image with a ui.json record.
|
|
660
|
+
asset PixelLab: upkeep for an object or character by --id. asset import
|
|
661
|
+
stores your own PNG as an object; asset expand draws a 1-direction
|
|
662
|
+
object's other 7 (10-25 generations; asks first), asset review
|
|
663
|
+
downloads them, then --keep or --discard; asset canvas resizes
|
|
664
|
+
the canvas; asset mirror flips a loop's direction; asset export
|
|
665
|
+
writes a zip, spritesheet, .aseprite or gif. All but expand free.
|
|
666
|
+
sfx PixelLab: a sound effect (--description, --seconds, --out); writes
|
|
667
|
+
a WAV and a .sfx.json record. From 1 generation, by length.
|
|
571
668
|
|
|
572
669
|
Options
|
|
573
670
|
--columns <n> pack/export: sprites or tiles per row (default: near-square)
|
|
@@ -596,6 +693,30 @@ Options
|
|
|
596
693
|
what to change)
|
|
597
694
|
--artist <a> vfx --description: lite (default) or pro
|
|
598
695
|
--weight <w> font: Bold or Regular (default)
|
|
696
|
+
--id <id> ui/asset: the PixelLab asset to work on
|
|
697
|
+
--kind <kind> asset: object (default) or character
|
|
698
|
+
--size <WxH> asset canvas: the new canvas, in multiples of 4
|
|
699
|
+
--animation <id> asset mirror/export: an animation group id
|
|
700
|
+
--direction <dir> asset mirror: the direction to flip; asset expand: the
|
|
701
|
+
way the object faces now; asset export gif: the direction
|
|
702
|
+
--keep, --discard asset expand: keep or discard the reviewed directions
|
|
703
|
+
--pro pixelate: the Pro converter (20 generations)
|
|
704
|
+
--state <n=desc> ui states: one state as "name=description" (repeatable)
|
|
705
|
+
--element <ids> ui states: only these elements of a template
|
|
706
|
+
--insets <n|l,r,t,b> ui nine-slice: border insets in pixels
|
|
707
|
+
--clear ui nine-slice: remove the insets
|
|
708
|
+
--box <l:x,y,w,h> ui split: a custom crop box in template pixels (repeatable)
|
|
709
|
+
--seconds <n> music: length to aim for, 10-360; sfx: clip length, 0.5-30 (default 2)
|
|
710
|
+
--bpm <n> music: tempo, 60-180
|
|
711
|
+
--loop music: also make seamless loops of take 1 (instrumental only)
|
|
712
|
+
--loop-of <id> music: loop this finished song instead of making one
|
|
713
|
+
--restyle <id> music: make this song again in the new style
|
|
714
|
+
--improve music: expand a short idea into a full style first
|
|
715
|
+
--lyrics <file> music: lyrics to sing (makes it a song with vocals)
|
|
716
|
+
--auto-lyrics music: have the lyrics written for the song
|
|
717
|
+
--about <text> music: what an --auto-lyrics song is about; music lyrics: the topic
|
|
718
|
+
--voice <text> music: the singing voice, e.g. "warm female voice"
|
|
719
|
+
--style-weight <n> music: how closely to follow the style, 0-1
|
|
599
720
|
--frames <n> estimate-skeleton: poses to scaffold, 3-15;
|
|
600
721
|
normal-map: equal frames in the --from strip, 1-32
|
|
601
722
|
--convention <c> normal-map: opengl (green up, default) or directx (green down)
|
|
@@ -670,6 +791,11 @@ Examples
|
|
|
670
791
|
pixelkiln vfx --preset explosion --part scorch_mark --out fx/explosion --game-pack
|
|
671
792
|
pixelkiln vfx --description "a blue lightning strike that leaves sparks" --out fx/zap
|
|
672
793
|
pixelkiln font --description "warm orange arcade font" --weight Bold --out fonts/arcade
|
|
794
|
+
pixelkiln music --description "calm chiptune town theme" --improve --seconds 60 --loop --out audio/town
|
|
795
|
+
pixelkiln ui states --id <template id> --state "hover=brighter, a soft glow" --state "pressed=darker, 1 px lower"
|
|
796
|
+
pixelkiln asset import --from art/knight.png --name knight
|
|
797
|
+
pixelkiln asset expand --id <object id> --direction south
|
|
798
|
+
pixelkiln sfx --description "a heavy sword slash hitting metal armor" --seconds 1 --out audio/slash
|
|
673
799
|
pixelkiln workspace add ../other-game/pixelkiln.manifest.json
|
|
674
800
|
pixelkiln workspace status --json
|
|
675
801
|
pixelkiln salvage --workspace pixelkiln.workspace.json
|
|
@@ -1149,10 +1275,10 @@ function normalizeHex(value) {
|
|
|
1149
1275
|
function sha256(data) {
|
|
1150
1276
|
return createHash("sha256").update(data).digest("hex");
|
|
1151
1277
|
}
|
|
1152
|
-
async function sha256File(
|
|
1278
|
+
async function sha256File(path63) {
|
|
1153
1279
|
return new Promise((resolve, reject) => {
|
|
1154
1280
|
const hash = createHash("sha256");
|
|
1155
|
-
const stream = createReadStream(
|
|
1281
|
+
const stream = createReadStream(path63);
|
|
1156
1282
|
stream.on("data", (chunk2) => hash.update(chunk2));
|
|
1157
1283
|
stream.on("error", reject);
|
|
1158
1284
|
stream.on("end", () => resolve(hash.digest("hex")));
|
|
@@ -1204,6 +1330,21 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
|
|
|
1204
1330
|
terrainBoundarySeed: spec.terrainBoundarySeed,
|
|
1205
1331
|
terrainStepSlope: spec.terrainStepSlope,
|
|
1206
1332
|
terrainConnectDiagonals: spec.terrainConnectDiagonals,
|
|
1333
|
+
// Added after the fields above, each only when set, so no terrain entry
|
|
1334
|
+
// written before them changes hash. The walkable flags change no pixel
|
|
1335
|
+
// and are deliberately not here.
|
|
1336
|
+
terrainShapeSeed: spec.terrainShapeSeed,
|
|
1337
|
+
terrainSideWallThickness: spec.terrainSideWallThickness,
|
|
1338
|
+
terrainSideWallPlacement: spec.terrainSideWallPlacement,
|
|
1339
|
+
terrainEnhance: spec.terrainEnhance,
|
|
1340
|
+
terrainPlatformThickness: spec.terrainPlatformThickness,
|
|
1341
|
+
// Reference images enter as their bytes' hashes, never their paths.
|
|
1342
|
+
terrainReferences: spec.terrainReferences && Object.keys(spec.terrainReferences).length ? Object.fromEntries(
|
|
1343
|
+
["lower", "upper", "transition"].flatMap((side) => {
|
|
1344
|
+
const reference = spec.terrainReferences[side];
|
|
1345
|
+
return reference ? [[side, reference.sha256]] : [];
|
|
1346
|
+
})
|
|
1347
|
+
) : void 0,
|
|
1207
1348
|
// "top-down" is the default and draws the same set as leaving it out.
|
|
1208
1349
|
terrainOrientation: spec.terrainOrientation === "sidescroller" ? spec.terrainOrientation : void 0,
|
|
1209
1350
|
// Which set and which of its terrains, not that terrain's id: the id
|
|
@@ -1470,7 +1611,7 @@ function terrainTileCount(transitionSize, mode2, orientation) {
|
|
|
1470
1611
|
return transitionSize === 1 ? 25 : 16;
|
|
1471
1612
|
}
|
|
1472
1613
|
function terrainCost(mode2, tileSize, orientation) {
|
|
1473
|
-
if (orientation === "sidescroller") return
|
|
1614
|
+
if (orientation === "sidescroller") return mode2 === "pro" ? 15 : 1;
|
|
1474
1615
|
if (mode2 === "pro") return tileSize <= 32 ? 15 : 25;
|
|
1475
1616
|
return 4;
|
|
1476
1617
|
}
|
|
@@ -2258,6 +2399,48 @@ var StyleObjectSchema = z.object({
|
|
|
2258
2399
|
* lower terrain between them.
|
|
2259
2400
|
*/
|
|
2260
2401
|
terrainConnectDiagonals: z.boolean().optional(),
|
|
2402
|
+
/**
|
|
2403
|
+
* `terrain` generator only, standard mode, top-down. Which ragged border
|
|
2404
|
+
* `terrainRaggedness` draws, 0 to 99 (the website's Reshuffle): another
|
|
2405
|
+
* number gives a different boundary at the same raggedness. API default 0.
|
|
2406
|
+
*/
|
|
2407
|
+
terrainShapeSeed: z.number().int().min(0).max(99).optional(),
|
|
2408
|
+
/**
|
|
2409
|
+
* `terrain` generator only, standard mode, top-down, with
|
|
2410
|
+
* `terrainTransitionSize` above 0. How thick the wall reads on the top
|
|
2411
|
+
* rim and down both sides of the front face, 0 to 1. The website starts
|
|
2412
|
+
* at 0.1.
|
|
2413
|
+
*/
|
|
2414
|
+
terrainSideWallThickness: z.number().min(0).max(1).optional(),
|
|
2415
|
+
/**
|
|
2416
|
+
* `terrain` generator only, standard mode, top-down, with
|
|
2417
|
+
* `terrainTransitionSize` above 0. Which side of the border the wall sits
|
|
2418
|
+
* on: 0 sticks out past the terrain (the API default), 1 is carved into
|
|
2419
|
+
* it so the shape stays put. The website starts at 0.5.
|
|
2420
|
+
*/
|
|
2421
|
+
terrainSideWallPlacement: z.number().min(0).max(1).optional(),
|
|
2422
|
+
/**
|
|
2423
|
+
* `terrain` generator only, standard mode. PixelLab rewrites the terrain
|
|
2424
|
+
* descriptions and picks base colors before drawing unless this is
|
|
2425
|
+
* false. On by default upstream; set false to have your wording used as
|
|
2426
|
+
* written.
|
|
2427
|
+
*/
|
|
2428
|
+
terrainEnhance: z.boolean().optional(),
|
|
2429
|
+
/**
|
|
2430
|
+
* `terrain` generator only, a standard sidescroller set. How thick the
|
|
2431
|
+
* platform body is, 0 thin to 1 thick. Left out, PixelLab fits it to
|
|
2432
|
+
* `terrainTransitionSize`.
|
|
2433
|
+
*/
|
|
2434
|
+
terrainPlatformThickness: z.number().min(0).max(1).optional(),
|
|
2435
|
+
/**
|
|
2436
|
+
* `terrain` generator only, top-down. Whether each terrain can be walked
|
|
2437
|
+
* on, stored with the set for PixelLab's maps and engine exports (left
|
|
2438
|
+
* out, those guess from the terrain's name). They change no pixel, so
|
|
2439
|
+
* they are sent when the set is generated and are not part of its
|
|
2440
|
+
* identity: changing one later does not make the set stale.
|
|
2441
|
+
*/
|
|
2442
|
+
terrainLowerWalkable: z.boolean().optional(),
|
|
2443
|
+
terrainUpperWalkable: z.boolean().optional(),
|
|
2261
2444
|
/**
|
|
2262
2445
|
* `terrain` generator only. Visual height of the step between lower and
|
|
2263
2446
|
* upper terrain. Without `terrainShapeStyle`, only 0, 0.25, 0.5, or 1 are
|
|
@@ -2495,7 +2678,7 @@ var AssetDeriveSchema = z.object({
|
|
|
2495
2678
|
/** scale: `nearest` (default) keeps hard edges; `box` averages the covered pixels. */
|
|
2496
2679
|
mode: z.enum(["nearest", "box"]).optional()
|
|
2497
2680
|
}).strict().superRefine((derive, context) => {
|
|
2498
|
-
const issue = (message6,
|
|
2681
|
+
const issue = (message6, path63) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path63] });
|
|
2499
2682
|
if (Boolean(derive.from) === Boolean(derive.file)) {
|
|
2500
2683
|
issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
|
|
2501
2684
|
}
|
|
@@ -2650,6 +2833,18 @@ var AssetSchema = z.object({
|
|
|
2650
2833
|
* (a sword hand, a parted fringe) comes out the other way round.
|
|
2651
2834
|
*/
|
|
2652
2835
|
mirror: z.string().min(1).optional(),
|
|
2836
|
+
/**
|
|
2837
|
+
* `terrain` styles only: a PNG per terrain for PixelLab to take that
|
|
2838
|
+
* terrain's look from, paths relative to the manifest. Top-down sets
|
|
2839
|
+
* take `lower`, `upper` and `transition`. A sidescroller set takes
|
|
2840
|
+
* `lower` (the platform body, pro mode) or `transition` (the surface
|
|
2841
|
+
* layer, standard mode), each a square PNG of the tile size.
|
|
2842
|
+
*/
|
|
2843
|
+
terrainReferences: z.object({
|
|
2844
|
+
lower: z.string().min(1).optional(),
|
|
2845
|
+
upper: z.string().min(1).optional(),
|
|
2846
|
+
transition: z.string().min(1).optional()
|
|
2847
|
+
}).strict().optional(),
|
|
2653
2848
|
/** Made from existing pixels by a local transform; see AssetDeriveSchema. Free; the provider is never called. */
|
|
2654
2849
|
derive: AssetDeriveSchema.optional(),
|
|
2655
2850
|
/** Built by a tool outside pixelkiln; see AssetExternalSchema. Never generated. */
|
|
@@ -6938,6 +7133,69 @@ var UiAssetGetSchema = z3.object({
|
|
|
6938
7133
|
progress_percent: z3.number().nullable().optional(),
|
|
6939
7134
|
eta_seconds: z3.number().nullable().optional()
|
|
6940
7135
|
}).passthrough();
|
|
7136
|
+
var CanvasChangeSchema = z3.object({
|
|
7137
|
+
id: z3.string(),
|
|
7138
|
+
previous: z3.object({ width: z3.number(), height: z3.number() }).passthrough(),
|
|
7139
|
+
canvas: z3.object({ width: z3.number(), height: z3.number() }).passthrough(),
|
|
7140
|
+
rotations_moved: z3.number().int().default(0),
|
|
7141
|
+
placements_moved: z3.number().int().nullable().optional()
|
|
7142
|
+
}).passthrough();
|
|
7143
|
+
var MirrorAnimationSchema = z3.object({
|
|
7144
|
+
animation_group_id: z3.string(),
|
|
7145
|
+
source_direction: z3.string(),
|
|
7146
|
+
target_direction: z3.string(),
|
|
7147
|
+
frames_created: z3.number().int()
|
|
7148
|
+
}).passthrough();
|
|
7149
|
+
var ImportObjectSchema = z3.object({
|
|
7150
|
+
object_id: z3.string().min(1),
|
|
7151
|
+
name: z3.string().nullable().optional(),
|
|
7152
|
+
size: z3.object({ width: z3.number(), height: z3.number() }).passthrough(),
|
|
7153
|
+
image_url: z3.string()
|
|
7154
|
+
}).passthrough();
|
|
7155
|
+
var ExpandRotationsSchema = z3.object({
|
|
7156
|
+
object_id: z3.string().min(1),
|
|
7157
|
+
background_job_id: z3.string().min(1),
|
|
7158
|
+
status: z3.string().default("expanding"),
|
|
7159
|
+
min_generations: z3.number(),
|
|
7160
|
+
max_generations: z3.number()
|
|
7161
|
+
}).passthrough();
|
|
7162
|
+
var UiNineSliceSchema = z3.object({ left: z3.number().int(), right: z3.number().int(), top: z3.number().int(), bottom: z3.number().int() }).passthrough();
|
|
7163
|
+
var UiSplitBoxSchema = z3.object({ label: z3.string().default(""), x: z3.number().int(), y: z3.number().int(), width: z3.number().int(), height: z3.number().int() }).passthrough();
|
|
7164
|
+
var UiSizeSchema = z3.object({ width: z3.number().int(), height: z3.number().int() }).passthrough();
|
|
7165
|
+
var UiStatePartSchema = z3.object({
|
|
7166
|
+
id: z3.string().min(1),
|
|
7167
|
+
name: z3.string().nullable().optional(),
|
|
7168
|
+
kind: z3.string().default("state"),
|
|
7169
|
+
size: UiSizeSchema,
|
|
7170
|
+
image_url: z3.string(),
|
|
7171
|
+
nine_slice: UiNineSliceSchema.nullable().optional()
|
|
7172
|
+
}).passthrough();
|
|
7173
|
+
var UiElementPartSchema = UiStatePartSchema.extend({
|
|
7174
|
+
template_box: UiSplitBoxSchema.nullable().optional(),
|
|
7175
|
+
states: z3.array(UiStatePartSchema).default([])
|
|
7176
|
+
}).passthrough();
|
|
7177
|
+
var UiAssetDetailSchema = z3.object({
|
|
7178
|
+
id: z3.string().min(1),
|
|
7179
|
+
name: z3.string().nullable().optional(),
|
|
7180
|
+
prompt: z3.string().default(""),
|
|
7181
|
+
size: UiSizeSchema,
|
|
7182
|
+
image_url: z3.string().nullable().optional(),
|
|
7183
|
+
status: z3.string().nullable().optional(),
|
|
7184
|
+
kind: z3.string().nullable().optional(),
|
|
7185
|
+
template_id: z3.string().nullable().optional(),
|
|
7186
|
+
parent_id: z3.string().nullable().optional(),
|
|
7187
|
+
nine_slice: UiNineSliceSchema.nullable().optional(),
|
|
7188
|
+
elements: z3.array(UiElementPartSchema).default([]),
|
|
7189
|
+
states: z3.array(UiStatePartSchema).default([]),
|
|
7190
|
+
split_preview: z3.array(UiSplitBoxSchema).default([])
|
|
7191
|
+
}).passthrough();
|
|
7192
|
+
var UiSplitResponseSchema = z3.object({ elements: z3.array(UiElementPartSchema) }).passthrough();
|
|
7193
|
+
var UiStatesSubmitSchema = z3.object({
|
|
7194
|
+
background_job_id: z3.string().min(1),
|
|
7195
|
+
status: z3.string().default("processing"),
|
|
7196
|
+
generations: z3.number(),
|
|
7197
|
+
count: z3.number().int()
|
|
7198
|
+
}).passthrough();
|
|
6941
7199
|
var RevisionJobSubmitSchema = z3.object({
|
|
6942
7200
|
background_job_id: z3.string().min(1),
|
|
6943
7201
|
status: z3.string().default("processing")
|
|
@@ -7024,6 +7282,48 @@ var FontJobSchema = z3.object({
|
|
|
7024
7282
|
download_ttf_url: z3.string().nullable().optional(),
|
|
7025
7283
|
usage: z3.unknown().optional()
|
|
7026
7284
|
}).passthrough();
|
|
7285
|
+
var SongSchema = z3.object({
|
|
7286
|
+
id: z3.string().min(1),
|
|
7287
|
+
status: z3.string(),
|
|
7288
|
+
error: z3.string().nullable().optional(),
|
|
7289
|
+
name: z3.string().default(""),
|
|
7290
|
+
audio_url: z3.string().nullable().optional(),
|
|
7291
|
+
duration_ms: z3.number().nullable().optional(),
|
|
7292
|
+
style: z3.string().default(""),
|
|
7293
|
+
instrumental: z3.boolean().default(true),
|
|
7294
|
+
lyrics: z3.string().default(""),
|
|
7295
|
+
take: z3.number().int().default(1),
|
|
7296
|
+
request_id: z3.string().optional(),
|
|
7297
|
+
loop_of: z3.string().nullable().optional(),
|
|
7298
|
+
loop_start_s: z3.number().nullable().optional(),
|
|
7299
|
+
loop_end_s: z3.number().nullable().optional()
|
|
7300
|
+
}).passthrough();
|
|
7301
|
+
var MusicSubmitSchema = z3.object({
|
|
7302
|
+
background_job_id: z3.string().min(1),
|
|
7303
|
+
status: z3.string().default("processing"),
|
|
7304
|
+
songs: z3.array(SongSchema).min(1),
|
|
7305
|
+
quoted_generations: z3.number().nullable().optional(),
|
|
7306
|
+
usage: z3.unknown().optional()
|
|
7307
|
+
}).passthrough();
|
|
7308
|
+
var SoundEffectSchema = z3.object({
|
|
7309
|
+
id: z3.string().min(1),
|
|
7310
|
+
status: z3.string(),
|
|
7311
|
+
error: z3.string().nullable().optional(),
|
|
7312
|
+
name: z3.string().default(""),
|
|
7313
|
+
audio_url: z3.string().nullable().optional(),
|
|
7314
|
+
duration_ms: z3.number().nullable().optional(),
|
|
7315
|
+
prompt: z3.string().default(""),
|
|
7316
|
+
seconds: z3.number().optional()
|
|
7317
|
+
}).passthrough();
|
|
7318
|
+
var SoundEffectSubmitSchema = z3.object({
|
|
7319
|
+
background_job_id: z3.string().min(1),
|
|
7320
|
+
status: z3.string().default("processing"),
|
|
7321
|
+
sound_effect: SoundEffectSchema,
|
|
7322
|
+
quoted_generations: z3.number().nullable().optional(),
|
|
7323
|
+
usage: z3.unknown().optional()
|
|
7324
|
+
}).passthrough();
|
|
7325
|
+
var ImproveStyleSchema = z3.object({ style: z3.string().min(1), usage: z3.unknown().optional() }).passthrough();
|
|
7326
|
+
var WriteLyricsSchema = z3.object({ lyrics: z3.array(z3.string()).min(1), usage: z3.unknown().optional() }).passthrough();
|
|
7027
7327
|
var SelectFramesSchema = z3.object({ created_object_ids: z3.array(z3.string()) }).passthrough();
|
|
7028
7328
|
var EstimateSkeletonResponseSchema = z3.object({
|
|
7029
7329
|
keypoints: z3.array(SkeletonKeypointSchema).length(18),
|
|
@@ -7166,6 +7466,20 @@ function parseProFlashQuote(raw) {
|
|
|
7166
7466
|
if (image !== null || rotations !== null) return { image, rotations, total: (image ?? 0) + (rotations ?? 0) };
|
|
7167
7467
|
throw new Error(`GET /pro-flash/cost returned no price: ${JSON.stringify(raw).slice(0, 200)}`);
|
|
7168
7468
|
}
|
|
7469
|
+
function refusalReason(status, body) {
|
|
7470
|
+
if (status < 400 || status >= 500 || !body.startsWith("{")) return "";
|
|
7471
|
+
try {
|
|
7472
|
+
const detail = JSON.parse(body).detail;
|
|
7473
|
+
if (typeof detail === "string" && detail) return `: ${detail.slice(0, 400)}`;
|
|
7474
|
+
if (Array.isArray(detail)) {
|
|
7475
|
+
const messages = detail.map((item) => item && typeof item === "object" && typeof item.msg === "string" ? item.msg : "").filter(Boolean).map((msg) => msg.replace(/^Value error, /, ""));
|
|
7476
|
+
if (messages.length) return `: ${messages.join("; ").slice(0, 400)}`;
|
|
7477
|
+
}
|
|
7478
|
+
return "";
|
|
7479
|
+
} catch {
|
|
7480
|
+
return "";
|
|
7481
|
+
}
|
|
7482
|
+
}
|
|
7169
7483
|
var PixelLabError = class extends ProviderError {
|
|
7170
7484
|
constructor(message6, status, body) {
|
|
7171
7485
|
super("pixellab", message6, { status });
|
|
@@ -7204,9 +7518,9 @@ var PixelLabClient = class {
|
|
|
7204
7518
|
apiKey;
|
|
7205
7519
|
http;
|
|
7206
7520
|
/** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
|
|
7207
|
-
async request(
|
|
7521
|
+
async request(path63, init) {
|
|
7208
7522
|
const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
|
|
7209
|
-
const res = await this.http(`${BASE}${
|
|
7523
|
+
const res = await this.http(`${BASE}${path63}`, {
|
|
7210
7524
|
...init,
|
|
7211
7525
|
headers: {
|
|
7212
7526
|
Authorization: auth,
|
|
@@ -7217,13 +7531,13 @@ var PixelLabClient = class {
|
|
|
7217
7531
|
const text = await res.text();
|
|
7218
7532
|
if (!res.ok) {
|
|
7219
7533
|
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' : "";
|
|
7220
|
-
throw new PixelLabError(`${init?.method ?? "GET"} ${
|
|
7534
|
+
throw new PixelLabError(`${init?.method ?? "GET"} ${path63} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
|
|
7221
7535
|
}
|
|
7222
7536
|
if (!text) return {};
|
|
7223
7537
|
try {
|
|
7224
7538
|
return JSON.parse(text);
|
|
7225
7539
|
} catch {
|
|
7226
|
-
throw new Error(`${init?.method ?? "GET"} ${
|
|
7540
|
+
throw new Error(`${init?.method ?? "GET"} ${path63} returned invalid JSON`);
|
|
7227
7541
|
}
|
|
7228
7542
|
}
|
|
7229
7543
|
async balance() {
|
|
@@ -7363,6 +7677,16 @@ var PixelLabClient = class {
|
|
|
7363
7677
|
lower_description: args.lowerDescription,
|
|
7364
7678
|
upper_description: args.upperDescription
|
|
7365
7679
|
};
|
|
7680
|
+
const image = (value) => ({ type: "base64", base64: value.base64, format: value.format });
|
|
7681
|
+
if (args.shapeSeed != null) body.shape_seed = args.shapeSeed;
|
|
7682
|
+
if (args.sideWallThickness != null) body.side_wall_thickness = args.sideWallThickness;
|
|
7683
|
+
if (args.sideWallPlacement != null) body.side_wall_placement = args.sideWallPlacement;
|
|
7684
|
+
if (args.enhance != null) body.enhance = args.enhance;
|
|
7685
|
+
if (args.lowerWalkable != null) body.lower_walkable = args.lowerWalkable;
|
|
7686
|
+
if (args.upperWalkable != null) body.upper_walkable = args.upperWalkable;
|
|
7687
|
+
if (args.lowerReferenceImage) body.lower_reference_image = image(args.lowerReferenceImage);
|
|
7688
|
+
if (args.upperReferenceImage) body.upper_reference_image = image(args.upperReferenceImage);
|
|
7689
|
+
if (args.transitionReferenceImage) body.transition_reference_image = image(args.transitionReferenceImage);
|
|
7366
7690
|
if (args.transitionDescription) body.transition_description = args.transitionDescription;
|
|
7367
7691
|
if (args.lowerBaseTileId) body.lower_base_tile_id = args.lowerBaseTileId;
|
|
7368
7692
|
if (args.upperBaseTileId) body.upper_base_tile_id = args.upperBaseTileId;
|
|
@@ -7400,6 +7724,12 @@ var PixelLabClient = class {
|
|
|
7400
7724
|
*/
|
|
7401
7725
|
async createTilesetSidescroller(args) {
|
|
7402
7726
|
const body = { lower_description: args.lowerDescription };
|
|
7727
|
+
const image = (value) => ({ type: "base64", base64: value.base64, format: value.format });
|
|
7728
|
+
if (args.mode) body.mode = args.mode;
|
|
7729
|
+
if (args.enhance != null) body.enhance = args.enhance;
|
|
7730
|
+
if (args.platformThickness != null) body.platform_thickness = args.platformThickness;
|
|
7731
|
+
if (args.transitionReferenceImage) body.transition_reference_image = image(args.transitionReferenceImage);
|
|
7732
|
+
if (args.lowerReferenceImage) body.lower_reference_image = image(args.lowerReferenceImage);
|
|
7403
7733
|
if (args.transitionDescription) body.transition_description = args.transitionDescription;
|
|
7404
7734
|
if (args.lowerBaseTileId) body.lower_base_tile_id = args.lowerBaseTileId;
|
|
7405
7735
|
if (args.tileSize != null) body.tile_size = { width: args.tileSize, height: args.tileSize };
|
|
@@ -7490,6 +7820,57 @@ var PixelLabClient = class {
|
|
|
7490
7820
|
);
|
|
7491
7821
|
return { ui_asset_id: res.ui_asset_id, background_job_id: res.background_job_id, usage: res.usage };
|
|
7492
7822
|
}
|
|
7823
|
+
/** `GET /ui-assets/{id}` with everything it reports: kind, elements and their states, 9-slice, and the default split boxes. */
|
|
7824
|
+
async getUiAssetDetail(uiAssetId) {
|
|
7825
|
+
return validateResponse(
|
|
7826
|
+
UiAssetDetailSchema,
|
|
7827
|
+
await this.request(`/ui-assets/${encodeURIComponent(uiAssetId)}`),
|
|
7828
|
+
"ui-assets/{id}"
|
|
7829
|
+
);
|
|
7830
|
+
}
|
|
7831
|
+
/**
|
|
7832
|
+
* `POST /ui-assets/{id}/split`: cut a template into one UI asset per shape.
|
|
7833
|
+
* Free; nothing is generated. A template splits once. Without `boxes` it
|
|
7834
|
+
* cuts along the shapes the template was generated from (`split_preview`).
|
|
7835
|
+
*/
|
|
7836
|
+
async splitUiAsset(uiAssetId, boxes) {
|
|
7837
|
+
const res = validateResponse(
|
|
7838
|
+
UiSplitResponseSchema,
|
|
7839
|
+
await this.request(`/ui-assets/${encodeURIComponent(uiAssetId)}/split`, {
|
|
7840
|
+
method: "POST",
|
|
7841
|
+
body: JSON.stringify(boxes?.length ? { boxes } : {})
|
|
7842
|
+
}),
|
|
7843
|
+
"ui-assets/{id}/split"
|
|
7844
|
+
);
|
|
7845
|
+
return res.elements;
|
|
7846
|
+
}
|
|
7847
|
+
/**
|
|
7848
|
+
* `POST /ui-assets/states`: draw every listed element in every listed state
|
|
7849
|
+
* in one generation, so the set matches. A background job; the 202 carries
|
|
7850
|
+
* the price (`generations`: 10, 15 or 25 by the size of the grid PixelLab
|
|
7851
|
+
* lays out) and is charged when the states are saved.
|
|
7852
|
+
*/
|
|
7853
|
+
async createUiStates(args) {
|
|
7854
|
+
const body = { element_ids: args.elementIds, states: args.states };
|
|
7855
|
+
Object.assign(body, targetPaletteBody(args.targetPalette));
|
|
7856
|
+
return validateResponse(
|
|
7857
|
+
UiStatesSubmitSchema,
|
|
7858
|
+
await this.request("/ui-assets/states", { method: "POST", body: JSON.stringify(body) }),
|
|
7859
|
+
"ui-assets/states"
|
|
7860
|
+
);
|
|
7861
|
+
}
|
|
7862
|
+
/** `PATCH /ui-assets/{id}`: rename, or set or clear the 9-slice insets. Free. */
|
|
7863
|
+
async updateUiAsset(uiAssetId, args) {
|
|
7864
|
+
const body = {};
|
|
7865
|
+
if (args.name) body.name = args.name;
|
|
7866
|
+
if (args.nineSlice) body.nine_slice = args.nineSlice;
|
|
7867
|
+
if (args.clearNineSlice) body.clear_nine_slice = true;
|
|
7868
|
+
return validateResponse(
|
|
7869
|
+
UiAssetDetailSchema,
|
|
7870
|
+
await this.request(`/ui-assets/${encodeURIComponent(uiAssetId)}`, { method: "PATCH", body: JSON.stringify(body) }),
|
|
7871
|
+
"ui-assets/{id}"
|
|
7872
|
+
);
|
|
7873
|
+
}
|
|
7493
7874
|
async getUiAsset(uiAssetId) {
|
|
7494
7875
|
const res = await validateResponse(
|
|
7495
7876
|
UiAssetGetSchema,
|
|
@@ -7676,10 +8057,10 @@ var PixelLabClient = class {
|
|
|
7676
8057
|
const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
|
|
7677
8058
|
const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
|
|
7678
8059
|
const south = args.reference?.south;
|
|
7679
|
-
let
|
|
8060
|
+
let path63;
|
|
7680
8061
|
let body;
|
|
7681
8062
|
if (args.mode === "v3") {
|
|
7682
|
-
|
|
8063
|
+
path63 = "/create-character-v3";
|
|
7683
8064
|
body = {
|
|
7684
8065
|
description: args.description,
|
|
7685
8066
|
image_size: imageSize,
|
|
@@ -7693,7 +8074,7 @@ var PixelLabClient = class {
|
|
|
7693
8074
|
...args.enhancePrompt ? { enhance_prompt: true } : {}
|
|
7694
8075
|
};
|
|
7695
8076
|
} else if (args.mode === "pro-flash") {
|
|
7696
|
-
|
|
8077
|
+
path63 = "/create-character-pro-flash";
|
|
7697
8078
|
const traits = args.styleTraits;
|
|
7698
8079
|
body = {
|
|
7699
8080
|
description: args.description,
|
|
@@ -7717,7 +8098,7 @@ var PixelLabClient = class {
|
|
|
7717
8098
|
} : {}
|
|
7718
8099
|
};
|
|
7719
8100
|
} else if (args.mode === "pro") {
|
|
7720
|
-
|
|
8101
|
+
path63 = "/create-character-pro";
|
|
7721
8102
|
body = {
|
|
7722
8103
|
description: args.description,
|
|
7723
8104
|
image_size: imageSize,
|
|
@@ -7731,7 +8112,7 @@ var PixelLabClient = class {
|
|
|
7731
8112
|
...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
|
|
7732
8113
|
};
|
|
7733
8114
|
} else {
|
|
7734
|
-
|
|
8115
|
+
path63 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
|
|
7735
8116
|
body = {
|
|
7736
8117
|
description: args.description,
|
|
7737
8118
|
image_size: imageSize,
|
|
@@ -7749,8 +8130,8 @@ var PixelLabClient = class {
|
|
|
7749
8130
|
};
|
|
7750
8131
|
}
|
|
7751
8132
|
if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
|
|
7752
|
-
const raw = await this.request(
|
|
7753
|
-
return validateResponse(CharacterSubmitSchema, raw,
|
|
8133
|
+
const raw = await this.request(path63, { method: "POST", body: JSON.stringify(body) });
|
|
8134
|
+
return validateResponse(CharacterSubmitSchema, raw, path63.slice(1));
|
|
7754
8135
|
}
|
|
7755
8136
|
/** A text edit of an existing character, applied to every direction and stored as a sibling. */
|
|
7756
8137
|
async createCharacterState(args) {
|
|
@@ -8328,6 +8709,184 @@ var PixelLabClient = class {
|
|
|
8328
8709
|
"vfx"
|
|
8329
8710
|
);
|
|
8330
8711
|
}
|
|
8712
|
+
/**
|
|
8713
|
+
* `POST /music`: two takes of a song from a style description, instrumental
|
|
8714
|
+
* unless lyrics are sent or `autoLyrics` is set. A background job whose 202
|
|
8715
|
+
* carries the pending takes and `quoted_generations` (10 for the pair);
|
|
8716
|
+
* PixelLab bills when the takes are made. Poll each take with `getMusic`.
|
|
8717
|
+
*/
|
|
8718
|
+
async createMusic(args) {
|
|
8719
|
+
const body = { style: args.style };
|
|
8720
|
+
if (args.instrumental !== void 0) body.instrumental = args.instrumental;
|
|
8721
|
+
if (args.lyrics) body.lyrics = args.lyrics;
|
|
8722
|
+
if (args.autoLyrics) body.auto_lyrics = true;
|
|
8723
|
+
if (args.about) body.about = args.about;
|
|
8724
|
+
if (args.lengthS != null) body.length_s = args.lengthS;
|
|
8725
|
+
if (args.bpm != null) body.bpm = args.bpm;
|
|
8726
|
+
if (args.voice) body.voice = args.voice;
|
|
8727
|
+
if (args.exclude) body.exclude = args.exclude;
|
|
8728
|
+
if (args.styleWeight != null) body.style_weight = args.styleWeight;
|
|
8729
|
+
if (args.name) body.name = args.name;
|
|
8730
|
+
if (args.restyleSongId) body.restyle_song_id = args.restyleSongId;
|
|
8731
|
+
return validateResponse(
|
|
8732
|
+
MusicSubmitSchema,
|
|
8733
|
+
await this.request("/music", { method: "POST", body: JSON.stringify(body) }),
|
|
8734
|
+
"music"
|
|
8735
|
+
);
|
|
8736
|
+
}
|
|
8737
|
+
/** `GET /music/{song_id}`: status, then a no-auth MP3 URL and, for a loop, its loop points. */
|
|
8738
|
+
async getMusic(songId) {
|
|
8739
|
+
return validateResponse(SongSchema, await this.request(`/music/${encodeURIComponent(songId)}`), "music/{song_id}");
|
|
8740
|
+
}
|
|
8741
|
+
/**
|
|
8742
|
+
* `POST /music/{song_id}/loop`: a finished instrumental song made again so
|
|
8743
|
+
* the part between its intro and ending repeats without a seam. Two new
|
|
8744
|
+
* takes, each a song with `loop_start_s` and `loop_end_s`; 4 generations.
|
|
8745
|
+
*/
|
|
8746
|
+
async loopMusic(songId) {
|
|
8747
|
+
return validateResponse(
|
|
8748
|
+
MusicSubmitSchema,
|
|
8749
|
+
await this.request(`/music/${encodeURIComponent(songId)}/loop`, { method: "POST", body: "{}" }),
|
|
8750
|
+
"music/{song_id}/loop"
|
|
8751
|
+
);
|
|
8752
|
+
}
|
|
8753
|
+
/** `POST /music/improve-style`: a short idea written out as a full style for `createMusic`. Synchronous. */
|
|
8754
|
+
async improveMusicStyle(args) {
|
|
8755
|
+
const body = { style: args.style };
|
|
8756
|
+
if (args.instrumental !== void 0) body.instrumental = args.instrumental;
|
|
8757
|
+
if (args.bpm != null) body.bpm = args.bpm;
|
|
8758
|
+
const res = validateResponse(
|
|
8759
|
+
ImproveStyleSchema,
|
|
8760
|
+
await this.request("/music/improve-style", { method: "POST", body: JSON.stringify(body) }),
|
|
8761
|
+
"music/improve-style"
|
|
8762
|
+
);
|
|
8763
|
+
return { style: res.style, usage: res.usage };
|
|
8764
|
+
}
|
|
8765
|
+
/** `POST /music/lyrics`: two lyric drafts with section tags, for `createMusic`'s `lyrics`. Synchronous. */
|
|
8766
|
+
async writeMusicLyrics(topic) {
|
|
8767
|
+
const res = validateResponse(
|
|
8768
|
+
WriteLyricsSchema,
|
|
8769
|
+
await this.request("/music/lyrics", { method: "POST", body: JSON.stringify({ topic }) }),
|
|
8770
|
+
"music/lyrics"
|
|
8771
|
+
);
|
|
8772
|
+
return { lyrics: res.lyrics, usage: res.usage };
|
|
8773
|
+
}
|
|
8774
|
+
/**
|
|
8775
|
+
* `POST /sound-effects`: one clip (WAV) from a description, 0.5 to 30
|
|
8776
|
+
* seconds. A background job whose 202 carries the pending clip and
|
|
8777
|
+
* `quoted_generations`, priced by length; billed when the clip is made.
|
|
8778
|
+
*/
|
|
8779
|
+
async createSoundEffect(args) {
|
|
8780
|
+
const body = { prompt: args.prompt };
|
|
8781
|
+
if (args.seconds != null) body.seconds = args.seconds;
|
|
8782
|
+
if (args.name) body.name = args.name;
|
|
8783
|
+
return validateResponse(
|
|
8784
|
+
SoundEffectSubmitSchema,
|
|
8785
|
+
await this.request("/sound-effects", { method: "POST", body: JSON.stringify(body) }),
|
|
8786
|
+
"sound-effects"
|
|
8787
|
+
);
|
|
8788
|
+
}
|
|
8789
|
+
/** `GET /sound-effects/{id}`: status, then a no-auth WAV URL once completed. */
|
|
8790
|
+
async getSoundEffect(id) {
|
|
8791
|
+
return validateResponse(
|
|
8792
|
+
SoundEffectSchema,
|
|
8793
|
+
await this.request(`/sound-effects/${encodeURIComponent(id)}`),
|
|
8794
|
+
"sound-effects/{id}"
|
|
8795
|
+
);
|
|
8796
|
+
}
|
|
8797
|
+
/**
|
|
8798
|
+
* `POST /image-to-pixelart-pro`: the strongest of the three converters. Like
|
|
8799
|
+
* Pro Flash the output size is picked from the picture; 20 generations at
|
|
8800
|
+
* any source size. A plain background job.
|
|
8801
|
+
*/
|
|
8802
|
+
async imageToPixelartPro(args) {
|
|
8803
|
+
const body = { image: args.image };
|
|
8804
|
+
if (args.description) body.description = args.description;
|
|
8805
|
+
if (args.seed != null) body.seed = args.seed;
|
|
8806
|
+
Object.assign(body, targetPaletteBody(args.targetPalette));
|
|
8807
|
+
return validateResponse(
|
|
8808
|
+
RevisionJobSubmitSchema,
|
|
8809
|
+
await this.request("/image-to-pixelart-pro", { method: "POST", body: JSON.stringify(body) }),
|
|
8810
|
+
"image-to-pixelart-pro"
|
|
8811
|
+
);
|
|
8812
|
+
}
|
|
8813
|
+
/**
|
|
8814
|
+
* `POST /{objects|characters}/{id}/canvas`: add or remove transparent margin
|
|
8815
|
+
* around every rotation. Never scales or crops; a size smaller than the art
|
|
8816
|
+
* is refused with the art's bounds. Free.
|
|
8817
|
+
*/
|
|
8818
|
+
async setCanvasSize(kind, id, size) {
|
|
8819
|
+
return validateResponse(
|
|
8820
|
+
CanvasChangeSchema,
|
|
8821
|
+
await this.request(`/${kind}s/${encodeURIComponent(id)}/canvas`, { method: "POST", body: JSON.stringify({ image_size: size }) }),
|
|
8822
|
+
`${kind}s/{id}/canvas`
|
|
8823
|
+
);
|
|
8824
|
+
}
|
|
8825
|
+
/** `POST /{objects|characters}/{id}/animations/{group}/mirror`: flip one direction of a loop into its missing opposite. Free. */
|
|
8826
|
+
async mirrorAnimation(kind, id, animationGroupId, sourceDirection) {
|
|
8827
|
+
return validateResponse(
|
|
8828
|
+
MirrorAnimationSchema,
|
|
8829
|
+
await this.request(
|
|
8830
|
+
`/${kind}s/${encodeURIComponent(id)}/animations/${encodeURIComponent(animationGroupId)}/mirror`,
|
|
8831
|
+
{ method: "POST", body: JSON.stringify({ source_direction: sourceDirection }) }
|
|
8832
|
+
),
|
|
8833
|
+
`${kind}s/{id}/animations/{group}/mirror`
|
|
8834
|
+
);
|
|
8835
|
+
}
|
|
8836
|
+
/** `POST /objects/import`: your own PNG (at most 256x256) as a completed 1-direction object. Stored exactly; free. */
|
|
8837
|
+
async importObject(args) {
|
|
8838
|
+
const body = { image: { type: "base64", base64: args.image.base64, format: args.image.format } };
|
|
8839
|
+
if (args.name) body.name = args.name;
|
|
8840
|
+
return validateResponse(
|
|
8841
|
+
ImportObjectSchema,
|
|
8842
|
+
await this.request("/objects/import", { method: "POST", body: JSON.stringify(body) }),
|
|
8843
|
+
"objects/import"
|
|
8844
|
+
);
|
|
8845
|
+
}
|
|
8846
|
+
/**
|
|
8847
|
+
* `POST /objects/{id}/expand-rotations`: draw the 7 missing directions of a
|
|
8848
|
+
* 1-direction object. The object then waits in `review-expansion` until
|
|
8849
|
+
* `acceptObjectExpansion` or `dismissObjectReview`. 10 to 25 generations.
|
|
8850
|
+
*/
|
|
8851
|
+
async expandObjectRotations(id, args) {
|
|
8852
|
+
const body = { existing_direction: args.existingDirection };
|
|
8853
|
+
if (args.description) body.description = args.description;
|
|
8854
|
+
return validateResponse(
|
|
8855
|
+
ExpandRotationsSchema,
|
|
8856
|
+
await this.request(`/objects/${encodeURIComponent(id)}/expand-rotations`, { method: "POST", body: JSON.stringify(body) }),
|
|
8857
|
+
"objects/{id}/expand-rotations"
|
|
8858
|
+
);
|
|
8859
|
+
}
|
|
8860
|
+
/** Keep a reviewed 8-direction expansion: `select-frames` with no indices. The object becomes 8-direction. */
|
|
8861
|
+
async acceptObjectExpansion(id) {
|
|
8862
|
+
return this.request(`/objects/${encodeURIComponent(id)}/select-frames`, { method: "POST", body: "{}" });
|
|
8863
|
+
}
|
|
8864
|
+
/** Discard a pending expansion (or a review pack); the object itself is kept as it was. */
|
|
8865
|
+
async dismissObjectReview(id) {
|
|
8866
|
+
return this.request(`/objects/${encodeURIComponent(id)}/dismiss-review`, { method: "POST", body: "{}" });
|
|
8867
|
+
}
|
|
8868
|
+
/**
|
|
8869
|
+
* `GET /{objects|characters}/{id}/{zip|spritesheet|aseprite|gif}`: the
|
|
8870
|
+
* website's exports as bytes. Answers 423 while the asset or one of its
|
|
8871
|
+
* animations is still generating.
|
|
8872
|
+
*/
|
|
8873
|
+
async exportAsset(kind, id, format, opts = {}) {
|
|
8874
|
+
const query = new URLSearchParams();
|
|
8875
|
+
if (opts.animationGroupId) query.set("animation_group_id", opts.animationGroupId);
|
|
8876
|
+
if (opts.direction) query.set("direction", opts.direction);
|
|
8877
|
+
const suffix = query.size ? `?${query}` : "";
|
|
8878
|
+
const pathname = `/${kind}s/${encodeURIComponent(id)}/${format}${suffix}`;
|
|
8879
|
+
const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
|
|
8880
|
+
const res = await this.http(`${BASE}${pathname}`, { headers: { Authorization: auth } });
|
|
8881
|
+
if (!res.ok) {
|
|
8882
|
+
const text = await res.text();
|
|
8883
|
+
const hint = res.status === 423 ? "; the asset or one of its animations is still generating, try again shortly" : "";
|
|
8884
|
+
throw new PixelLabError(`GET ${pathname} \u2192 ${res.status}${hint}`, res.status, text);
|
|
8885
|
+
}
|
|
8886
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
8887
|
+
if (bytes.length > MAX_DOWNLOAD_BYTES) throw new Error(`export ${pathname} exceeds the ${MAX_DOWNLOAD_BYTES}-byte safety limit`);
|
|
8888
|
+
return bytes;
|
|
8889
|
+
}
|
|
8331
8890
|
/** `GET /generate-font-pro/{job_id}`: status, then no-auth atlas and `.ttf` URLs once completed. */
|
|
8332
8891
|
async getFontJob(jobId) {
|
|
8333
8892
|
const raw = await this.request(`/generate-font-pro/${encodeURIComponent(jobId)}`);
|
|
@@ -8670,37 +9229,37 @@ async function runVfxWorkbench(client2, opts) {
|
|
|
8670
9229
|
if (starts === 0 && !opts.parts?.length) {
|
|
8671
9230
|
throw new Error("A VFX needs something to start from: a preset, a recipe, a saved effect, or at least one part");
|
|
8672
9231
|
}
|
|
8673
|
-
const
|
|
9232
|
+
const progress2 = opts.onProgress ?? (() => {
|
|
8674
9233
|
});
|
|
8675
9234
|
const call = async (argv) => (await client2.callTool(VFX_TOOL, { argv, ...opts.notes ? { notes: opts.notes } : {} })).text;
|
|
8676
9235
|
const startArgv = ["start"];
|
|
8677
9236
|
if (opts.sprite) startArgv.push("--sprite", opts.sprite);
|
|
8678
9237
|
if (opts.preset) startArgv.push("--preset", opts.preset);
|
|
8679
9238
|
if (opts.effect) startArgv.push("--effect", opts.effect);
|
|
8680
|
-
|
|
9239
|
+
progress2(opts.preset ? `starting from preset ${opts.preset}` : opts.effect ? `starting from saved effect ${opts.effect}` : "starting");
|
|
8681
9240
|
const started = await call(startArgv);
|
|
8682
9241
|
let step = parseVfxStep(started);
|
|
8683
9242
|
const savedName = opts.effect ? parseVfxRecipe(started)?.name : opts.recipe?.name;
|
|
8684
9243
|
const name = opts.name ?? (typeof savedName === "string" ? savedName : void 0) ?? opts.defaultName;
|
|
8685
9244
|
if (opts.recipe) {
|
|
8686
|
-
|
|
9245
|
+
progress2("rendering the recipe");
|
|
8687
9246
|
step = parseVfxStep(await call([step, "render", JSON.stringify({ recipe: opts.recipe })]));
|
|
8688
9247
|
}
|
|
8689
9248
|
if (opts.parts?.length) {
|
|
8690
|
-
|
|
9249
|
+
progress2(`adding ${opts.parts.map((part) => part.name).join(", ")}`);
|
|
8691
9250
|
step = parseVfxStep(await call([step, "add_part", JSON.stringify({ parts: opts.parts })]));
|
|
8692
9251
|
}
|
|
8693
9252
|
if (opts.fps !== void 0) {
|
|
8694
|
-
|
|
9253
|
+
progress2(`setting ${opts.fps} fps`);
|
|
8695
9254
|
step = parseVfxStep(await call([step, "render", JSON.stringify({ patch: [{ op: "set", path: "fps", value: opts.fps }] })]));
|
|
8696
9255
|
}
|
|
8697
9256
|
const exportArgv = [step, "export", "--name", name];
|
|
8698
9257
|
if (opts.replace) exportArgv.push("--replace", opts.replace);
|
|
8699
9258
|
if (opts.gamePack) exportArgv.push("--game-pack");
|
|
8700
|
-
|
|
9259
|
+
progress2(opts.gamePack ? "exporting with a game pack" : "exporting");
|
|
8701
9260
|
const exported = parseVfxExport(await call(exportArgv));
|
|
8702
9261
|
await opts.onExported?.(exported, name);
|
|
8703
|
-
|
|
9262
|
+
progress2("reading the saved recipe");
|
|
8704
9263
|
const recipe = parseVfxRecipe(await call(["start", "--effect", exported.effectId]));
|
|
8705
9264
|
return { exported, recipe, name };
|
|
8706
9265
|
}
|
|
@@ -8757,7 +9316,7 @@ async function makeVfx(client2, opts) {
|
|
|
8757
9316
|
if (existsSync9(file)) throw new Error(`${file} already exists; pass --force to replace it`);
|
|
8758
9317
|
}
|
|
8759
9318
|
}
|
|
8760
|
-
const
|
|
9319
|
+
const progress2 = opts.onProgress ?? (() => {
|
|
8761
9320
|
});
|
|
8762
9321
|
const { exported, recipe, name } = await runVfxWorkbench(client2, {
|
|
8763
9322
|
preset: opts.preset,
|
|
@@ -8771,7 +9330,7 @@ async function makeVfx(client2, opts) {
|
|
|
8771
9330
|
replace: opts.replace ?? opts.effect,
|
|
8772
9331
|
gamePack: opts.gamePack,
|
|
8773
9332
|
notes: "pixelkiln vfx",
|
|
8774
|
-
onProgress:
|
|
9333
|
+
onProgress: progress2
|
|
8775
9334
|
});
|
|
8776
9335
|
const download = opts.download ?? defaultDownload;
|
|
8777
9336
|
const written = { sheet: paths.sheet, gif: paths.gif, atlas: paths.atlas, provenance: paths.provenance };
|
|
@@ -8931,7 +9490,7 @@ async function makeVfxWithArtist(client2, opts) {
|
|
|
8931
9490
|
if (existsSync9(file)) throw new Error(`${file} already exists; pass --force to replace it`);
|
|
8932
9491
|
}
|
|
8933
9492
|
}
|
|
8934
|
-
const
|
|
9493
|
+
const progress2 = opts.onProgress ?? (() => {
|
|
8935
9494
|
});
|
|
8936
9495
|
const sprite = opts.sprite ? vfxArtistSprite(await readFile7(opts.sprite), opts.sprite).image : void 0;
|
|
8937
9496
|
const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
@@ -8947,7 +9506,7 @@ async function makeVfxWithArtist(client2, opts) {
|
|
|
8947
9506
|
gamePack: opts.gamePack
|
|
8948
9507
|
});
|
|
8949
9508
|
const jobId = submitted.background_job_id;
|
|
8950
|
-
|
|
9509
|
+
progress2(`submitted job ${jobId}, quoted ${submitted.quoted_generations ?? "?"} generations`);
|
|
8951
9510
|
const started = Date.now();
|
|
8952
9511
|
let job;
|
|
8953
9512
|
for (; ; ) {
|
|
@@ -8959,7 +9518,7 @@ async function makeVfxWithArtist(client2, opts) {
|
|
|
8959
9518
|
`PixelLab vfx job ${jobId} is still ${job.status} after ${Math.round(timeout / 1e3)} s; it keeps running upstream (and bills when delivered), but this command has stopped waiting`
|
|
8960
9519
|
);
|
|
8961
9520
|
}
|
|
8962
|
-
|
|
9521
|
+
progress2(job.status);
|
|
8963
9522
|
await sleep3(interval);
|
|
8964
9523
|
}
|
|
8965
9524
|
const result = parseVfxArtistResult(job.last_response ?? {}, jobId);
|
|
@@ -9166,6 +9725,7 @@ async function generateFont(client2, opts) {
|
|
|
9166
9725
|
await sleep3(interval);
|
|
9167
9726
|
}
|
|
9168
9727
|
}
|
|
9728
|
+
var PIXELATE_PRO_COST_GENERATIONS = 20;
|
|
9169
9729
|
var PIXELATE_COST_GENERATIONS = 6;
|
|
9170
9730
|
var PIXELATE_MAX_SIDE = 2048;
|
|
9171
9731
|
function defaultPixelateOut(input) {
|
|
@@ -9183,11 +9743,16 @@ async function pixelateFile(client2, input, opts = {}) {
|
|
|
9183
9743
|
const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
9184
9744
|
const interval = opts.intervalMs ?? 5e3;
|
|
9185
9745
|
const timeout = opts.timeoutMs ?? 10 * 6e4;
|
|
9186
|
-
const
|
|
9187
|
-
|
|
9746
|
+
const image = { base64: bytes.toString("base64"), format };
|
|
9747
|
+
if (!opts.pro && (opts.palette?.length || opts.maxColors != null)) {
|
|
9748
|
+
throw new Error("a palette or color cap needs the Pro converter; add --pro");
|
|
9749
|
+
}
|
|
9750
|
+
const submitted = opts.pro ? await client2.imageToPixelartPro({
|
|
9751
|
+
image,
|
|
9188
9752
|
description: opts.description,
|
|
9189
|
-
seed: opts.seed
|
|
9190
|
-
|
|
9753
|
+
seed: opts.seed,
|
|
9754
|
+
targetPalette: opts.palette?.length || opts.maxColors != null ? { ...opts.palette?.length ? { colors: opts.palette } : {}, ...opts.maxColors != null ? { maxColors: opts.maxColors } : {} } : void 0
|
|
9755
|
+
}) : await client2.imageToPixelartProFlash({ image, description: opts.description, seed: opts.seed });
|
|
9191
9756
|
const jobId = submitted.background_job_id;
|
|
9192
9757
|
const started = Date.now();
|
|
9193
9758
|
for (; ; ) {
|
|
@@ -9196,20 +9761,32 @@ async function pixelateFile(client2, input, opts = {}) {
|
|
|
9196
9761
|
if (job.status === "failed") throw new Error(`PixelLab pixelate job ${jobId} failed upstream`);
|
|
9197
9762
|
if (job.status === "completed") {
|
|
9198
9763
|
const images = job.last_response?.images;
|
|
9199
|
-
const first = Array.isArray(images) ? images[0] :
|
|
9764
|
+
const first = Array.isArray(images) ? images[0] : job.last_response?.image;
|
|
9200
9765
|
if (!first || typeof first.base64 !== "string" || !first.base64) {
|
|
9201
|
-
throw new Error(`PixelLab pixelate job ${jobId} completed without an image at last_response.images[0]`);
|
|
9766
|
+
throw new Error(`PixelLab pixelate job ${jobId} completed without an image at last_response.images[0] or last_response.image`);
|
|
9202
9767
|
}
|
|
9203
9768
|
const png = Buffer.from(first.base64, "base64");
|
|
9204
9769
|
const size = imageMetadata(png);
|
|
9205
9770
|
await mkdir6(path15.dirname(out), { recursive: true });
|
|
9206
9771
|
await writeFile6(out, png);
|
|
9772
|
+
const reduced = job.last_response?.quantized_image;
|
|
9773
|
+
const count = (value) => typeof value === "number" ? value : null;
|
|
9774
|
+
let quantized;
|
|
9775
|
+
if (reduced && typeof reduced.base64 === "string" && reduced.base64) {
|
|
9776
|
+
const quantizedOut = out.replace(/(\.png)?$/i, ".quantized.png");
|
|
9777
|
+
if (!existsSync10(quantizedOut) || opts.force) {
|
|
9778
|
+
await writeFile6(quantizedOut, Buffer.from(reduced.base64, "base64"));
|
|
9779
|
+
quantized = { out: quantizedOut, colors: count(job.last_response?.quantized_image_n_colors) };
|
|
9780
|
+
}
|
|
9781
|
+
}
|
|
9207
9782
|
return {
|
|
9208
9783
|
jobId,
|
|
9209
9784
|
out,
|
|
9210
9785
|
original: { width, height },
|
|
9211
9786
|
pixelated: { width: size?.width ?? Number(first.width), height: size?.height ?? Number(first.height) },
|
|
9212
|
-
imageId: submitted.image_id,
|
|
9787
|
+
...submitted.image_id ? { imageId: submitted.image_id } : {},
|
|
9788
|
+
...quantized ? { quantized } : {},
|
|
9789
|
+
...opts.pro ? { colors: count(job.last_response?.original_image_n_colors) } : {},
|
|
9213
9790
|
usage: job.usage ?? null
|
|
9214
9791
|
};
|
|
9215
9792
|
}
|
|
@@ -9957,6 +10534,23 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
9957
10534
|
if (spec.terrainTileSize === 64 && spec.terrainMode !== "pro") {
|
|
9958
10535
|
throw new Error('PixelLab terrain: a 64px tile needs terrainMode: "pro"');
|
|
9959
10536
|
}
|
|
10537
|
+
const standardOnly = {
|
|
10538
|
+
terrainShapeSeed: spec.terrainShapeSeed,
|
|
10539
|
+
terrainSideWallThickness: spec.terrainSideWallThickness,
|
|
10540
|
+
terrainSideWallPlacement: spec.terrainSideWallPlacement,
|
|
10541
|
+
terrainEnhance: spec.terrainEnhance
|
|
10542
|
+
};
|
|
10543
|
+
const proSet = Object.entries(standardOnly).filter(([, value]) => value != null).map(([field]) => field);
|
|
10544
|
+
if (pro && proSet.length) {
|
|
10545
|
+
throw new Error(`PixelLab terrain: ${proSet.join(", ")} shape a standard set; terrainMode: "pro" ignores them`);
|
|
10546
|
+
}
|
|
10547
|
+
if ((spec.terrainSideWallThickness != null || spec.terrainSideWallPlacement != null) && !(spec.terrainTransitionSize != null && spec.terrainTransitionSize > 0)) {
|
|
10548
|
+
throw new Error("PixelLab terrain: terrainSideWallThickness and terrainSideWallPlacement shape the wall, which needs a terrainTransitionSize above 0");
|
|
10549
|
+
}
|
|
10550
|
+
if (spec.terrainPlatformThickness != null) {
|
|
10551
|
+
throw new Error("PixelLab terrain: terrainPlatformThickness is a sidescroller control");
|
|
10552
|
+
}
|
|
10553
|
+
this.requireTerrainReferences(spec);
|
|
9960
10554
|
if (spec.terrainShapeStyle && spec.terrainTransitionSize != null && spec.terrainTransitionSize > 0.5) {
|
|
9961
10555
|
throw new Error(
|
|
9962
10556
|
"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"
|
|
@@ -9975,7 +10569,6 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
9975
10569
|
*/
|
|
9976
10570
|
validateSidescrollerTerrain(spec) {
|
|
9977
10571
|
const topDownOnly = {
|
|
9978
|
-
terrainMode: spec.terrainMode,
|
|
9979
10572
|
terrainShapeStyle: spec.terrainShapeStyle,
|
|
9980
10573
|
terrainView: spec.terrainView,
|
|
9981
10574
|
terrainSpreadX: spec.terrainSpreadX,
|
|
@@ -9985,7 +10578,12 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
9985
10578
|
terrainBoundaryAmplitude: spec.terrainBoundaryAmplitude,
|
|
9986
10579
|
terrainBoundarySeed: spec.terrainBoundarySeed,
|
|
9987
10580
|
terrainStepSlope: spec.terrainStepSlope,
|
|
9988
|
-
terrainConnectDiagonals: spec.terrainConnectDiagonals
|
|
10581
|
+
terrainConnectDiagonals: spec.terrainConnectDiagonals,
|
|
10582
|
+
terrainShapeSeed: spec.terrainShapeSeed,
|
|
10583
|
+
terrainSideWallThickness: spec.terrainSideWallThickness,
|
|
10584
|
+
terrainSideWallPlacement: spec.terrainSideWallPlacement,
|
|
10585
|
+
terrainLowerWalkable: spec.terrainLowerWalkable,
|
|
10586
|
+
terrainUpperWalkable: spec.terrainUpperWalkable
|
|
9989
10587
|
};
|
|
9990
10588
|
const set = Object.entries(topDownOnly).filter(([, value]) => value != null).map(([field]) => field);
|
|
9991
10589
|
if (set.length) {
|
|
@@ -9994,9 +10592,26 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
9994
10592
|
if (spec.terrainTileSize !== 16 && spec.terrainTileSize !== 32) {
|
|
9995
10593
|
throw new Error(`PixelLab terrain: a sidescroller set's tiles are 16 or 32px, got ${spec.terrainTileSize}`);
|
|
9996
10594
|
}
|
|
9997
|
-
if (spec.terrainTransitionSize != null && ![0, 0.25, 0.5
|
|
9998
|
-
throw new Error("PixelLab terrain: a sidescroller set's terrainTransitionSize must be 0, 0.25, 0.5
|
|
10595
|
+
if (spec.terrainTransitionSize != null && ![0, 0.25, 0.5].includes(spec.terrainTransitionSize)) {
|
|
10596
|
+
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)");
|
|
10597
|
+
}
|
|
10598
|
+
const pro = spec.terrainMode === "pro";
|
|
10599
|
+
if (pro && (spec.terrainEnhance != null || spec.terrainPlatformThickness != null)) {
|
|
10600
|
+
throw new Error('PixelLab terrain: terrainEnhance and terrainPlatformThickness shape a standard sidescroller set; terrainMode: "pro" ignores them');
|
|
10601
|
+
}
|
|
10602
|
+
if (spec.terrainConnect?.lower && !pro) {
|
|
10603
|
+
throw new Error(`PixelLab terrain: a sidescroller set connects to another set's platform only with terrainMode: "pro"`);
|
|
9999
10604
|
}
|
|
10605
|
+
if (spec.terrainReferences?.upper) {
|
|
10606
|
+
throw new Error("PixelLab terrain: a sidescroller set's upper terrain is empty air; it takes no upper reference");
|
|
10607
|
+
}
|
|
10608
|
+
if (spec.terrainReferences?.lower && !pro) {
|
|
10609
|
+
throw new Error('PixelLab terrain: a sidescroller set keeps a lower (platform body) reference only with terrainMode: "pro"');
|
|
10610
|
+
}
|
|
10611
|
+
if (spec.terrainReferences?.transition && pro) {
|
|
10612
|
+
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"');
|
|
10613
|
+
}
|
|
10614
|
+
this.requireTerrainReferences(spec, spec.terrainTileSize);
|
|
10000
10615
|
if (spec.terrainConnect?.upper) {
|
|
10001
10616
|
throw new Error(
|
|
10002
10617
|
"PixelLab terrain: a sidescroller set's upper terrain is empty air; only its lower (platform) terrain can connect"
|
|
@@ -10009,6 +10624,19 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
10009
10624
|
);
|
|
10010
10625
|
}
|
|
10011
10626
|
}
|
|
10627
|
+
/** Reference files must exist; a sidescroller's must be a square PNG of the tile size. */
|
|
10628
|
+
requireTerrainReferences(spec, tileSize) {
|
|
10629
|
+
for (const [side, reference] of Object.entries(spec.terrainReferences ?? {})) {
|
|
10630
|
+
if (!reference?.sha256) {
|
|
10631
|
+
throw new Error(`PixelLab terrain: the ${side} reference is missing or not a PNG: ${reference?.file}`);
|
|
10632
|
+
}
|
|
10633
|
+
if (tileSize != null && (reference.width !== tileSize || reference.height !== tileSize)) {
|
|
10634
|
+
throw new Error(
|
|
10635
|
+
`PixelLab terrain: a sidescroller set's ${side} reference must be a ${tileSize}x${tileSize} PNG; ${reference.file} is ${reference.width}x${reference.height}`
|
|
10636
|
+
);
|
|
10637
|
+
}
|
|
10638
|
+
}
|
|
10639
|
+
}
|
|
10012
10640
|
validateCharacter(spec, styleImages = []) {
|
|
10013
10641
|
const character = spec.character;
|
|
10014
10642
|
if (!character) throw new Error(`${spec.styleId}/${spec.assetId} has no character shape`);
|
|
@@ -10786,7 +11414,12 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
10786
11414
|
outline: spec.outline,
|
|
10787
11415
|
shading: spec.shading,
|
|
10788
11416
|
detail: spec.detail,
|
|
10789
|
-
seed: spec.seed
|
|
11417
|
+
seed: spec.seed,
|
|
11418
|
+
mode: spec.terrainMode,
|
|
11419
|
+
enhance: spec.terrainEnhance,
|
|
11420
|
+
platformThickness: spec.terrainPlatformThickness,
|
|
11421
|
+
lowerReferenceImage: await terrainReferenceImage(spec, "lower"),
|
|
11422
|
+
transitionReferenceImage: await terrainReferenceImage(spec, "transition")
|
|
10790
11423
|
});
|
|
10791
11424
|
return {
|
|
10792
11425
|
jobId: res2.tileset_id,
|
|
@@ -10821,7 +11454,16 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
10821
11454
|
shading: spec.shading,
|
|
10822
11455
|
detail: spec.detail,
|
|
10823
11456
|
seed: spec.seed,
|
|
10824
|
-
targetPalette: targetPaletteFor(spec)
|
|
11457
|
+
targetPalette: targetPaletteFor(spec),
|
|
11458
|
+
shapeSeed: spec.terrainShapeSeed,
|
|
11459
|
+
sideWallThickness: spec.terrainSideWallThickness,
|
|
11460
|
+
sideWallPlacement: spec.terrainSideWallPlacement,
|
|
11461
|
+
enhance: spec.terrainEnhance,
|
|
11462
|
+
lowerWalkable: spec.terrainLowerWalkable,
|
|
11463
|
+
upperWalkable: spec.terrainUpperWalkable,
|
|
11464
|
+
lowerReferenceImage: await terrainReferenceImage(spec, "lower"),
|
|
11465
|
+
upperReferenceImage: await terrainReferenceImage(spec, "upper"),
|
|
11466
|
+
transitionReferenceImage: await terrainReferenceImage(spec, "transition")
|
|
10825
11467
|
});
|
|
10826
11468
|
return {
|
|
10827
11469
|
jobId: res2.tileset_id,
|
|
@@ -11779,8 +12421,8 @@ var PixelLabProvider = class _PixelLabProvider {
|
|
|
11779
12421
|
const sources = [];
|
|
11780
12422
|
const terrainTiles = [];
|
|
11781
12423
|
for (const [index, tile] of tileset.tiles.entries()) {
|
|
11782
|
-
const
|
|
11783
|
-
const role = `tile-${String(index).padStart(2, "0")}-${
|
|
12424
|
+
const slug3 = tile.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "tile";
|
|
12425
|
+
const role = `tile-${String(index).padStart(2, "0")}-${slug3}`;
|
|
11784
12426
|
const file = path16.join(_PixelLabProvider.cacheDir(), `${tilesetId}-${index}.png`);
|
|
11785
12427
|
writeFileSync(file, Buffer.from(tile.image.base64, "base64"));
|
|
11786
12428
|
sources.push({ url: `file://${file}`, role });
|
|
@@ -12000,6 +12642,16 @@ function sendsTargetPalette(spec) {
|
|
|
12000
12642
|
return false;
|
|
12001
12643
|
}
|
|
12002
12644
|
}
|
|
12645
|
+
async function terrainReferenceImage(spec, side) {
|
|
12646
|
+
const reference = spec.terrainReferences?.[side];
|
|
12647
|
+
if (!reference) return void 0;
|
|
12648
|
+
if (!existsSync11(reference.file)) throw new Error(`terrain ${side} reference is missing: ${reference.file}`);
|
|
12649
|
+
const bytes = readFileSync2(reference.file);
|
|
12650
|
+
if (sha256(bytes) !== reference.sha256) {
|
|
12651
|
+
throw new Error(`terrain ${side} reference changed after the manifest was resolved: ${reference.file}; run the command again`);
|
|
12652
|
+
}
|
|
12653
|
+
return { base64: bytes.toString("base64"), format: "png" };
|
|
12654
|
+
}
|
|
12003
12655
|
function targetPaletteFor(spec) {
|
|
12004
12656
|
if (!sendsTargetPalette(spec)) return void 0;
|
|
12005
12657
|
if (!spec.palette.length && spec.maxColors == null) return void 0;
|
|
@@ -12173,9 +12825,9 @@ var RetroDiffusionClient = class {
|
|
|
12173
12825
|
if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
|
|
12174
12826
|
return Buffer.from(await response.arrayBuffer());
|
|
12175
12827
|
}
|
|
12176
|
-
async call(
|
|
12828
|
+
async call(path63, init = {}) {
|
|
12177
12829
|
if (!this.token) throw new Error("RD_API_KEY is not set");
|
|
12178
|
-
const response = await this.request(`${this.baseUrl}${
|
|
12830
|
+
const response = await this.request(`${this.baseUrl}${path63}`, {
|
|
12179
12831
|
...init,
|
|
12180
12832
|
headers: {
|
|
12181
12833
|
"Content-Type": "application/json",
|
|
@@ -13047,11 +13699,11 @@ function scenarioJobError(job) {
|
|
|
13047
13699
|
const detail = typeof raw === "string" ? raw : raw && typeof raw === "object" && typeof raw.message === "string" ? String(raw.message) : "job did not complete";
|
|
13048
13700
|
return `Scenario job ${job.status}: ${detail.slice(0, 500)}`;
|
|
13049
13701
|
}
|
|
13050
|
-
function validProgress(
|
|
13051
|
-
if (typeof
|
|
13702
|
+
function validProgress(progress2) {
|
|
13703
|
+
if (typeof progress2 !== "number" || !Number.isFinite(progress2) || progress2 < 0 || progress2 > 1) {
|
|
13052
13704
|
return null;
|
|
13053
13705
|
}
|
|
13054
|
-
return Math.round(
|
|
13706
|
+
return Math.round(progress2 * 100);
|
|
13055
13707
|
}
|
|
13056
13708
|
function finiteNonnegative(value, message6) {
|
|
13057
13709
|
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error(message6);
|
|
@@ -13864,6 +14516,13 @@ async function resolveSpecs(loaded, filter) {
|
|
|
13864
14516
|
terrainBoundarySeed: generator === "terrain" ? style.terrainBoundarySeed : void 0,
|
|
13865
14517
|
terrainStepSlope: generator === "terrain" ? style.terrainStepSlope : void 0,
|
|
13866
14518
|
terrainConnectDiagonals: generator === "terrain" ? style.terrainConnectDiagonals : void 0,
|
|
14519
|
+
terrainShapeSeed: generator === "terrain" ? style.terrainShapeSeed : void 0,
|
|
14520
|
+
terrainSideWallThickness: generator === "terrain" ? style.terrainSideWallThickness : void 0,
|
|
14521
|
+
terrainSideWallPlacement: generator === "terrain" ? style.terrainSideWallPlacement : void 0,
|
|
14522
|
+
terrainEnhance: generator === "terrain" ? style.terrainEnhance : void 0,
|
|
14523
|
+
terrainPlatformThickness: generator === "terrain" ? style.terrainPlatformThickness : void 0,
|
|
14524
|
+
terrainLowerWalkable: generator === "terrain" ? style.terrainLowerWalkable : void 0,
|
|
14525
|
+
terrainUpperWalkable: generator === "terrain" ? style.terrainUpperWalkable : void 0,
|
|
13867
14526
|
terrainTransitionSize: generator === "terrain" ? style.terrainTransitionSize : void 0,
|
|
13868
14527
|
terrainView: generator === "terrain" ? style.terrainView : void 0,
|
|
13869
14528
|
terrainOrientation: generator === "terrain" ? style.terrainOrientation : void 0,
|
|
@@ -14296,6 +14955,20 @@ async function resolveSpecs(loaded, filter) {
|
|
|
14296
14955
|
}
|
|
14297
14956
|
resolved.terrainConnect = links;
|
|
14298
14957
|
}
|
|
14958
|
+
if (asset.terrainReferences) {
|
|
14959
|
+
if (resolved.generator !== "terrain") {
|
|
14960
|
+
throw new Error(`assets.${assetId}.terrainReferences: only a terrain set takes terrain references; style "${styleId}" uses "${resolved.generator}"`);
|
|
14961
|
+
}
|
|
14962
|
+
const references = {};
|
|
14963
|
+
for (const side of ["lower", "upper", "transition"]) {
|
|
14964
|
+
const relative = asset.terrainReferences[side];
|
|
14965
|
+
if (!relative) continue;
|
|
14966
|
+
const file = path18.resolve(root, relative);
|
|
14967
|
+
const image = await optionalRevisionImage(file, `terrain ${side} reference`, "png");
|
|
14968
|
+
references[side] = { file, sha256: image?.hash ?? null, width: image?.width ?? null, height: image?.height ?? null };
|
|
14969
|
+
}
|
|
14970
|
+
if (Object.keys(references).length) resolved.terrainReferences = references;
|
|
14971
|
+
}
|
|
14299
14972
|
if (asset.scene) resolved.scene = await resolveMapScene(root, styleId, assetId, resolved.generator, asset.scene, activeProvider);
|
|
14300
14973
|
resolved.specHash = specHash(
|
|
14301
14974
|
resolved,
|
|
@@ -15273,10 +15946,10 @@ function isSha256Hash(value) {
|
|
|
15273
15946
|
function parseCache(value) {
|
|
15274
15947
|
return HashCacheSchema.parse(value);
|
|
15275
15948
|
}
|
|
15276
|
-
async function loadCache(
|
|
15277
|
-
if (!existsSync17(
|
|
15949
|
+
async function loadCache(path63) {
|
|
15950
|
+
if (!existsSync17(path63)) return { version: 1, hashes: {} };
|
|
15278
15951
|
try {
|
|
15279
|
-
const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile12(
|
|
15952
|
+
const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile12(path63, "utf8")));
|
|
15280
15953
|
if (!parsed.success) return { version: 1, hashes: {} };
|
|
15281
15954
|
return {
|
|
15282
15955
|
version: 1,
|
|
@@ -15288,18 +15961,18 @@ async function loadCache(path57) {
|
|
|
15288
15961
|
return { version: 1, hashes: {} };
|
|
15289
15962
|
}
|
|
15290
15963
|
}
|
|
15291
|
-
async function saveCache(
|
|
15964
|
+
async function saveCache(path63, cache) {
|
|
15292
15965
|
const sorted = {};
|
|
15293
15966
|
for (const key2 of Object.keys(cache.hashes).sort()) {
|
|
15294
15967
|
const hash = cache.hashes[key2];
|
|
15295
15968
|
if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
|
|
15296
15969
|
sorted[key2] = hash;
|
|
15297
15970
|
}
|
|
15298
|
-
await mkdir8(pathModule.dirname(pathModule.resolve(
|
|
15299
|
-
const tmp = `${
|
|
15971
|
+
await mkdir8(pathModule.dirname(pathModule.resolve(path63)), { recursive: true });
|
|
15972
|
+
const tmp = `${path63}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
15300
15973
|
try {
|
|
15301
15974
|
await writeFile8(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
|
|
15302
|
-
await rename6(tmp,
|
|
15975
|
+
await rename6(tmp, path63);
|
|
15303
15976
|
} finally {
|
|
15304
15977
|
await rm5(tmp, { force: true });
|
|
15305
15978
|
}
|
|
@@ -21495,8 +22168,8 @@ function createGalleryEditorHandlers(opts = {}) {
|
|
|
21495
22168
|
dir,
|
|
21496
22169
|
baseUrl: opts.baseUrl ?? editorBaseUrl(pin) ?? void 0,
|
|
21497
22170
|
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
21498
|
-
onProgress: (
|
|
21499
|
-
installing =
|
|
22171
|
+
onProgress: (progress2) => {
|
|
22172
|
+
installing = progress2;
|
|
21500
22173
|
}
|
|
21501
22174
|
}).then((result) => {
|
|
21502
22175
|
verified = result;
|
|
@@ -23860,20 +24533,27 @@ async function runPixelate(args) {
|
|
|
23860
24533
|
if (!args.from) throw new UsageError("pixelate needs --from <image>: the photo, painting, or render to convert");
|
|
23861
24534
|
const out = args.out ?? defaultPixelateOut(args.from);
|
|
23862
24535
|
log(` pixelate ${args.from} \u2192 ${out}${args.description ? ` ("${args.description}")` : ""}; PixelLab picks the output size`);
|
|
23863
|
-
|
|
23864
|
-
if (args.
|
|
23865
|
-
throw new
|
|
24536
|
+
const cost = args.pro ? PIXELATE_PRO_COST_GENERATIONS : PIXELATE_COST_GENERATIONS;
|
|
24537
|
+
if (!args.pro && (args.palette.length || args.maxColors !== void 0)) {
|
|
24538
|
+
throw new UsageError("--palette and --max-colors need the Pro converter; add --pro");
|
|
24539
|
+
}
|
|
24540
|
+
log(` cost: ${cost} generations (Image to Pixel Art ${args.pro ? "Pro" : "Pro Flash"}, flat)`);
|
|
24541
|
+
if (args.budget !== void 0 && args.budget < cost) {
|
|
24542
|
+
throw new Error(`--budget ${args.budget} is below this conversion's ${cost}-generation cost`);
|
|
23866
24543
|
}
|
|
23867
24544
|
if (args.dryRun) {
|
|
23868
24545
|
log(" dry run: nothing sent");
|
|
23869
24546
|
return;
|
|
23870
24547
|
}
|
|
23871
|
-
if (!await confirm(` Spend ${
|
|
24548
|
+
if (!await confirm(` Spend ${cost} generations on this conversion?`, args.yes)) return;
|
|
23872
24549
|
loadKeys(args);
|
|
23873
24550
|
let last = "";
|
|
23874
24551
|
const res = await pixelateFile(clientFromEnv(), args.from, {
|
|
23875
24552
|
out,
|
|
23876
24553
|
description: args.description,
|
|
24554
|
+
pro: args.pro,
|
|
24555
|
+
palette: args.palette,
|
|
24556
|
+
maxColors: args.maxColors,
|
|
23877
24557
|
force: args.force,
|
|
23878
24558
|
onProgress: (status) => {
|
|
23879
24559
|
if (status !== last) log(` ${status}\u2026`);
|
|
@@ -23888,6 +24568,9 @@ async function runPixelate(args) {
|
|
|
23888
24568
|
log(
|
|
23889
24569
|
` ${res.original.width}x${res.original.height}${scaled} \u2192 ${res.pixelated.width}x${res.pixelated.height}; wrote ${res.out}`
|
|
23890
24570
|
);
|
|
24571
|
+
if (res.quantized) {
|
|
24572
|
+
log(` wrote ${res.quantized.out}: the same image on ${res.quantized.colors ?? "fewer"} colors${res.colors ? ` (the main result has ${res.colors})` : ""}`);
|
|
24573
|
+
}
|
|
23891
24574
|
}
|
|
23892
24575
|
async function runNormalMap(args) {
|
|
23893
24576
|
if (!args.from) throw new UsageError("normal-map needs --from <png>: the sprite, or a horizontal strip of --frames equal frames");
|
|
@@ -24063,20 +24746,957 @@ async function runVfxArtist(args, out) {
|
|
|
24063
24746
|
log(` render it again for free with the workbench: pixelkiln vfx --effect ${res.effectId} --out <base>`);
|
|
24064
24747
|
}
|
|
24065
24748
|
|
|
24066
|
-
// src/cli/commands/
|
|
24749
|
+
// src/cli/commands/audio.ts
|
|
24750
|
+
import { readFile as readFile34 } from "fs/promises";
|
|
24067
24751
|
import path51 from "path";
|
|
24068
|
-
import { readFile as readFile35 } from "fs/promises";
|
|
24069
24752
|
|
|
24070
|
-
// src/
|
|
24071
|
-
import path50 from "path";
|
|
24753
|
+
// src/pixellab-audio.ts
|
|
24072
24754
|
import { existsSync as existsSync40 } from "fs";
|
|
24073
|
-
import {
|
|
24755
|
+
import { mkdir as mkdir16, writeFile as writeFile21 } from "fs/promises";
|
|
24756
|
+
import path50 from "path";
|
|
24757
|
+
var MUSIC_COST_GENERATIONS = 10;
|
|
24758
|
+
var MUSIC_LOOP_COST_GENERATIONS = 4;
|
|
24759
|
+
var MUSIC_LOOP_MIN_BODY_SECONDS = 36;
|
|
24760
|
+
function soundEffectCost(seconds) {
|
|
24761
|
+
return Math.max(1, Math.ceil(0.614 * seconds - 1e-9));
|
|
24762
|
+
}
|
|
24763
|
+
function detectAudioFormat(bytes) {
|
|
24764
|
+
if (bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WAVE") {
|
|
24765
|
+
return "wav";
|
|
24766
|
+
}
|
|
24767
|
+
if (bytes.length >= 3 && bytes.subarray(0, 3).toString("ascii") === "ID3") return "mp3";
|
|
24768
|
+
if (bytes.length >= 2 && bytes[0] === 255 && (bytes[1] & 224) === 224) return "mp3";
|
|
24769
|
+
return null;
|
|
24770
|
+
}
|
|
24771
|
+
function validateAudio(bytes, expected) {
|
|
24772
|
+
const actual = detectAudioFormat(bytes);
|
|
24773
|
+
if (actual !== expected) {
|
|
24774
|
+
throw new Error(`PixelLab returned ${actual ?? `${bytes.length} bytes that are not audio`}, expected ${expected}`);
|
|
24775
|
+
}
|
|
24776
|
+
}
|
|
24777
|
+
async function waitFor(what, read, opts, defaults) {
|
|
24778
|
+
const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
24779
|
+
const interval = opts.intervalMs ?? defaults.intervalMs;
|
|
24780
|
+
const timeout = opts.timeoutMs ?? defaults.timeoutMs;
|
|
24781
|
+
const started = Date.now();
|
|
24782
|
+
for (; ; ) {
|
|
24783
|
+
const item = await read();
|
|
24784
|
+
opts.onProgress?.(item.status);
|
|
24785
|
+
if (item.status === "failed") throw new Error(`PixelLab ${what} failed upstream${item.error ? `: ${item.error}` : ""}`);
|
|
24786
|
+
if (item.status === "completed") return item;
|
|
24787
|
+
if (Date.now() - started > timeout) {
|
|
24788
|
+
throw new Error(
|
|
24789
|
+
`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`
|
|
24790
|
+
);
|
|
24791
|
+
}
|
|
24792
|
+
await sleep3(interval);
|
|
24793
|
+
}
|
|
24794
|
+
}
|
|
24795
|
+
function refusalDetail(error) {
|
|
24796
|
+
const body = error?.body;
|
|
24797
|
+
if (typeof body !== "string" || !body) return null;
|
|
24798
|
+
try {
|
|
24799
|
+
const detail = JSON.parse(body).detail;
|
|
24800
|
+
return typeof detail === "string" ? detail : null;
|
|
24801
|
+
} catch {
|
|
24802
|
+
return null;
|
|
24803
|
+
}
|
|
24804
|
+
}
|
|
24805
|
+
async function billedUsage(client2, jobId) {
|
|
24806
|
+
try {
|
|
24807
|
+
return (await client2.getBackgroundJob(jobId)).usage ?? null;
|
|
24808
|
+
} catch {
|
|
24809
|
+
return null;
|
|
24810
|
+
}
|
|
24811
|
+
}
|
|
24812
|
+
function musicOutputPaths(out) {
|
|
24813
|
+
const base = path50.resolve(out.replace(/\.(music\.json|mp3)$/i, ""));
|
|
24814
|
+
return {
|
|
24815
|
+
takes: [`${base}.mp3`, `${base}.take2.mp3`],
|
|
24816
|
+
loops: [`${base}.loop.mp3`, `${base}.loop.take2.mp3`],
|
|
24817
|
+
record: `${base}.music.json`
|
|
24818
|
+
};
|
|
24819
|
+
}
|
|
24820
|
+
function musicCost(opts) {
|
|
24821
|
+
if (opts.loopOf) return MUSIC_LOOP_COST_GENERATIONS;
|
|
24822
|
+
return MUSIC_COST_GENERATIONS + (opts.loop ? MUSIC_LOOP_COST_GENERATIONS : 0);
|
|
24823
|
+
}
|
|
24824
|
+
async function collectTakes(client2, songs, files, what, opts) {
|
|
24825
|
+
const takes = [];
|
|
24826
|
+
const finished = [];
|
|
24827
|
+
const ordered = [...songs].sort((a, b) => a.take - b.take);
|
|
24828
|
+
for (const [index, pending] of ordered.entries()) {
|
|
24829
|
+
const file = files[index];
|
|
24830
|
+
if (!file) break;
|
|
24831
|
+
const song = await waitFor(`${what} ${pending.id}`, () => client2.getMusic(pending.id), opts, { intervalMs: 1e4, timeoutMs: 6 * 6e4 });
|
|
24832
|
+
if (!song.audio_url) throw new Error(`PixelLab ${what} ${song.id} completed without an audio URL`);
|
|
24833
|
+
const bytes = await client2.download(song.audio_url);
|
|
24834
|
+
validateAudio(bytes, "mp3");
|
|
24835
|
+
await mkdir16(path50.dirname(file), { recursive: true });
|
|
24836
|
+
await writeFile21(file, bytes);
|
|
24837
|
+
finished.push(song);
|
|
24838
|
+
takes.push({
|
|
24839
|
+
songId: song.id,
|
|
24840
|
+
take: song.take,
|
|
24841
|
+
file,
|
|
24842
|
+
sha256: sha256(bytes),
|
|
24843
|
+
durationMs: song.duration_ms ?? null,
|
|
24844
|
+
...song.loop_start_s != null ? { loopStartS: song.loop_start_s } : {},
|
|
24845
|
+
...song.loop_end_s != null ? { loopEndS: song.loop_end_s } : {}
|
|
24846
|
+
});
|
|
24847
|
+
}
|
|
24848
|
+
return { takes, finished };
|
|
24849
|
+
}
|
|
24850
|
+
async function generateMusic(client2, opts) {
|
|
24851
|
+
const paths = musicOutputPaths(opts.out);
|
|
24852
|
+
const instrumental = !(opts.lyrics || opts.autoLyrics);
|
|
24853
|
+
const wantsLoop = Boolean(opts.loop || opts.loopOf);
|
|
24854
|
+
if (!opts.loopOf && !opts.style) throw new Error("music needs a style description");
|
|
24855
|
+
if (wantsLoop && !opts.loopOf && !instrumental) throw new Error("PixelLab loops instrumental songs only; drop the lyrics or the loop");
|
|
24856
|
+
if (opts.loop && opts.lengthS != null && opts.lengthS <= MUSIC_LOOP_MIN_BODY_SECONDS) {
|
|
24857
|
+
throw new Error(
|
|
24858
|
+
`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`
|
|
24859
|
+
);
|
|
24860
|
+
}
|
|
24861
|
+
const writes = [paths.record, ...opts.loopOf ? [] : paths.takes, ...wantsLoop ? paths.loops : []];
|
|
24862
|
+
if (!opts.force) {
|
|
24863
|
+
for (const file of writes) if (existsSync40(file)) throw new Error(`${file} already exists; pass --force to replace it`);
|
|
24864
|
+
}
|
|
24865
|
+
const usage = [];
|
|
24866
|
+
let quoted = null;
|
|
24867
|
+
let takes = [];
|
|
24868
|
+
let source;
|
|
24869
|
+
if (!opts.loopOf) {
|
|
24870
|
+
const submitted = await client2.createMusic({
|
|
24871
|
+
style: opts.style,
|
|
24872
|
+
instrumental,
|
|
24873
|
+
lyrics: opts.lyrics,
|
|
24874
|
+
autoLyrics: opts.autoLyrics,
|
|
24875
|
+
about: opts.about,
|
|
24876
|
+
lengthS: opts.lengthS,
|
|
24877
|
+
bpm: opts.bpm,
|
|
24878
|
+
voice: opts.voice,
|
|
24879
|
+
exclude: opts.exclude,
|
|
24880
|
+
styleWeight: opts.styleWeight,
|
|
24881
|
+
name: opts.name,
|
|
24882
|
+
restyleSongId: opts.restyleSongId
|
|
24883
|
+
});
|
|
24884
|
+
quoted = submitted.quoted_generations ?? null;
|
|
24885
|
+
const made = await collectTakes(client2, submitted.songs, paths.takes, "song", opts);
|
|
24886
|
+
takes = made.takes;
|
|
24887
|
+
source = made.finished[0];
|
|
24888
|
+
usage.push(await billedUsage(client2, submitted.background_job_id));
|
|
24889
|
+
}
|
|
24890
|
+
let loops = [];
|
|
24891
|
+
const snapshot = () => ({
|
|
24892
|
+
record: paths.record,
|
|
24893
|
+
takes,
|
|
24894
|
+
loops,
|
|
24895
|
+
style: source?.style ?? opts.style ?? "",
|
|
24896
|
+
instrumental: source?.instrumental ?? instrumental,
|
|
24897
|
+
lyrics: source?.lyrics ?? opts.lyrics ?? "",
|
|
24898
|
+
quotedGenerations: quoted,
|
|
24899
|
+
usage
|
|
24900
|
+
});
|
|
24901
|
+
const relative = (take) => ({ ...take, file: path50.basename(take.file) });
|
|
24902
|
+
const writeRecord = async (result2) => {
|
|
24903
|
+
await mkdir16(path50.dirname(paths.record), { recursive: true });
|
|
24904
|
+
await writeFile21(
|
|
24905
|
+
paths.record,
|
|
24906
|
+
JSON.stringify(
|
|
24907
|
+
{
|
|
24908
|
+
schema: "pixelkiln-music",
|
|
24909
|
+
version: 1,
|
|
24910
|
+
provider: "pixellab",
|
|
24911
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
24912
|
+
request: {
|
|
24913
|
+
...opts.style ? { style: opts.style } : {},
|
|
24914
|
+
...opts.bpm != null ? { bpm: opts.bpm } : {},
|
|
24915
|
+
...opts.lengthS != null ? { lengthS: opts.lengthS } : {},
|
|
24916
|
+
...opts.exclude ? { exclude: opts.exclude } : {},
|
|
24917
|
+
...opts.styleWeight != null ? { styleWeight: opts.styleWeight } : {},
|
|
24918
|
+
...opts.voice ? { voice: opts.voice } : {},
|
|
24919
|
+
...opts.autoLyrics ? { autoLyrics: true, ...opts.about ? { about: opts.about } : {} } : {},
|
|
24920
|
+
...opts.restyleSongId ? { restyleSongId: opts.restyleSongId } : {},
|
|
24921
|
+
...opts.loopOf ? { loopOf: opts.loopOf } : {}
|
|
24922
|
+
},
|
|
24923
|
+
style: result2.style,
|
|
24924
|
+
instrumental: result2.instrumental,
|
|
24925
|
+
...result2.lyrics ? { lyrics: result2.lyrics } : {},
|
|
24926
|
+
takes: result2.takes.map(relative),
|
|
24927
|
+
loops: result2.loops.map(relative),
|
|
24928
|
+
quotedGenerations: result2.quotedGenerations,
|
|
24929
|
+
usage: result2.usage
|
|
24930
|
+
},
|
|
24931
|
+
null,
|
|
24932
|
+
2
|
|
24933
|
+
) + "\n"
|
|
24934
|
+
);
|
|
24935
|
+
};
|
|
24936
|
+
if (takes.length) await writeRecord(snapshot());
|
|
24937
|
+
if (wantsLoop) {
|
|
24938
|
+
const loopSource = opts.loopOf ?? source.id;
|
|
24939
|
+
let submitted;
|
|
24940
|
+
try {
|
|
24941
|
+
submitted = await client2.loopMusic(loopSource);
|
|
24942
|
+
} catch (error) {
|
|
24943
|
+
const detail = refusalDetail(error);
|
|
24944
|
+
const kept = takes.length ? ` The song's takes are saved (${path50.basename(paths.record)}); nothing was charged for the loop.` : "";
|
|
24945
|
+
throw new Error(`PixelLab refused to loop ${loopSource}: ${detail ?? (error instanceof Error ? error.message : String(error))}${kept}`, { cause: error });
|
|
24946
|
+
}
|
|
24947
|
+
quoted = (quoted ?? 0) + (submitted.quoted_generations ?? 0);
|
|
24948
|
+
const made = await collectTakes(client2, submitted.songs, paths.loops, "loop", opts);
|
|
24949
|
+
loops = made.takes;
|
|
24950
|
+
source ??= made.finished[0];
|
|
24951
|
+
usage.push(await billedUsage(client2, submitted.background_job_id));
|
|
24952
|
+
}
|
|
24953
|
+
const result = snapshot();
|
|
24954
|
+
await writeRecord(result);
|
|
24955
|
+
return result;
|
|
24956
|
+
}
|
|
24957
|
+
function soundEffectOutputPaths(out) {
|
|
24958
|
+
const base = path50.resolve(out.replace(/\.(sfx\.json|wav)$/i, ""));
|
|
24959
|
+
return { wav: `${base}.wav`, record: `${base}.sfx.json` };
|
|
24960
|
+
}
|
|
24961
|
+
async function generateSoundEffect(client2, opts) {
|
|
24962
|
+
const { wav, record } = soundEffectOutputPaths(opts.out);
|
|
24963
|
+
if (!opts.force) {
|
|
24964
|
+
for (const file of [wav, record]) if (existsSync40(file)) throw new Error(`${file} already exists; pass --force to replace it`);
|
|
24965
|
+
}
|
|
24966
|
+
const seconds = opts.seconds ?? 2;
|
|
24967
|
+
const submitted = await client2.createSoundEffect({ prompt: opts.prompt, seconds, name: opts.name });
|
|
24968
|
+
const id = submitted.sound_effect.id;
|
|
24969
|
+
const clip = await waitFor(`sound effect ${id}`, () => client2.getSoundEffect(id), opts, { intervalMs: 4e3, timeoutMs: 4 * 6e4 });
|
|
24970
|
+
if (!clip.audio_url) throw new Error(`PixelLab sound effect ${id} completed without an audio URL`);
|
|
24971
|
+
const bytes = await client2.download(clip.audio_url);
|
|
24972
|
+
validateAudio(bytes, "wav");
|
|
24973
|
+
await mkdir16(path50.dirname(wav), { recursive: true });
|
|
24974
|
+
await writeFile21(wav, bytes);
|
|
24975
|
+
const result = {
|
|
24976
|
+
soundEffectId: id,
|
|
24977
|
+
file: wav,
|
|
24978
|
+
record,
|
|
24979
|
+
sha256: sha256(bytes),
|
|
24980
|
+
durationMs: clip.duration_ms ?? null,
|
|
24981
|
+
seconds,
|
|
24982
|
+
quotedGenerations: submitted.quoted_generations ?? null,
|
|
24983
|
+
usage: await billedUsage(client2, submitted.background_job_id)
|
|
24984
|
+
};
|
|
24985
|
+
await writeFile21(
|
|
24986
|
+
record,
|
|
24987
|
+
JSON.stringify(
|
|
24988
|
+
{
|
|
24989
|
+
schema: "pixelkiln-sfx",
|
|
24990
|
+
version: 1,
|
|
24991
|
+
provider: "pixellab",
|
|
24992
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
24993
|
+
prompt: opts.prompt,
|
|
24994
|
+
seconds,
|
|
24995
|
+
soundEffectId: id,
|
|
24996
|
+
file: path50.basename(wav),
|
|
24997
|
+
sha256: result.sha256,
|
|
24998
|
+
durationMs: result.durationMs,
|
|
24999
|
+
quotedGenerations: result.quotedGenerations,
|
|
25000
|
+
usage: result.usage
|
|
25001
|
+
},
|
|
25002
|
+
null,
|
|
25003
|
+
2
|
|
25004
|
+
) + "\n"
|
|
25005
|
+
);
|
|
25006
|
+
return result;
|
|
25007
|
+
}
|
|
25008
|
+
|
|
25009
|
+
// src/cli/commands/audio.ts
|
|
25010
|
+
function loadKeys2(args) {
|
|
25011
|
+
loadEnvFiles(path51.dirname(path51.resolve(args.manifest)));
|
|
25012
|
+
loadEnvFiles(process.cwd());
|
|
25013
|
+
}
|
|
25014
|
+
function progress() {
|
|
25015
|
+
let last = "";
|
|
25016
|
+
return (status) => {
|
|
25017
|
+
if (status !== last) log(` ${status}\u2026`);
|
|
25018
|
+
last = status;
|
|
25019
|
+
};
|
|
25020
|
+
}
|
|
25021
|
+
async function runMusicStyle(args) {
|
|
25022
|
+
if (!args.description) throw new UsageError('music style needs --description "<idea>", e.g. "spooky swamp level"');
|
|
25023
|
+
if (args.dryRun) {
|
|
25024
|
+
log(" dry run: nothing sent (about 0.05 generations)");
|
|
25025
|
+
return;
|
|
25026
|
+
}
|
|
25027
|
+
loadKeys2(args);
|
|
25028
|
+
const res = await clientFromEnv().improveMusicStyle({ style: args.description, instrumental: !(args.lyrics || args.autoLyrics), bpm: args.bpm });
|
|
25029
|
+
log(args.json ? JSON.stringify({ version: 1, ...res }, null, 2) : res.style);
|
|
25030
|
+
}
|
|
25031
|
+
async function runMusicLyrics(args) {
|
|
25032
|
+
if (!args.about) throw new UsageError(`music lyrics needs --about "<topic>", e.g. "a knight's last stand at the castle gate"`);
|
|
25033
|
+
if (args.dryRun) {
|
|
25034
|
+
log(" dry run: nothing sent (about 0.05 generations)");
|
|
25035
|
+
return;
|
|
25036
|
+
}
|
|
25037
|
+
loadKeys2(args);
|
|
25038
|
+
const res = await clientFromEnv().writeMusicLyrics(args.about);
|
|
25039
|
+
if (args.json) {
|
|
25040
|
+
log(JSON.stringify({ version: 1, ...res }, null, 2));
|
|
25041
|
+
return;
|
|
25042
|
+
}
|
|
25043
|
+
for (const [i, draft] of res.lyrics.entries()) log(`--- version ${i + 1} ---
|
|
25044
|
+
${draft}
|
|
25045
|
+
`);
|
|
25046
|
+
}
|
|
25047
|
+
async function runMusic(args) {
|
|
25048
|
+
if (args.subcommand === "style") return runMusicStyle(args);
|
|
25049
|
+
if (args.subcommand === "lyrics") return runMusicLyrics(args);
|
|
25050
|
+
if (!args.out) throw new UsageError("music needs --out <base>: <base>.mp3, <base>.take2.mp3 and <base>.music.json are written");
|
|
25051
|
+
if (!args.loopOf && !args.description) {
|
|
25052
|
+
throw new UsageError('music needs --description "<style>", e.g. "calm chiptune town theme: a soft square-wave melody over a bouncy bass"');
|
|
25053
|
+
}
|
|
25054
|
+
if (args.loopOf && (args.description || args.lyrics || args.autoLyrics || args.restyle || args.loop)) {
|
|
25055
|
+
throw new UsageError("--loop-of loops an existing song as it is; it takes no style, lyrics, --restyle or --loop");
|
|
25056
|
+
}
|
|
25057
|
+
if (args.lyrics && args.autoLyrics) throw new UsageError("pass --lyrics <file> or --auto-lyrics, not both");
|
|
25058
|
+
const vocals = Boolean(args.lyrics || args.autoLyrics);
|
|
25059
|
+
if (vocals && args.loop) throw new UsageError("PixelLab loops instrumental songs only; drop --loop or the lyrics");
|
|
25060
|
+
if (args.about && !args.autoLyrics) throw new UsageError("--about describes the song for --auto-lyrics");
|
|
25061
|
+
if (args.voice && !vocals) throw new UsageError("--voice applies to a song with vocals; add --lyrics <file> or --auto-lyrics");
|
|
25062
|
+
if (args.autoLyrics && (args.seconds !== void 0 || args.styleWeight !== void 0)) {
|
|
25063
|
+
throw new UsageError("PixelLab fits length and style weight itself with --auto-lyrics; drop --seconds and --style-weight");
|
|
25064
|
+
}
|
|
25065
|
+
const cost = musicCost({ loop: args.loop, loopOf: args.loopOf });
|
|
25066
|
+
const paths = musicOutputPaths(args.out);
|
|
25067
|
+
const what = args.loopOf ? `loop of ${args.loopOf} (two loop takes)` : `"${args.description}"${vocals ? ", with vocals" : ", instrumental"}, two takes${args.loop ? " plus loops of take 1" : ""}`;
|
|
25068
|
+
log(` music: ${what} \u2192 ${path51.relative(process.cwd(), args.loopOf ? paths.loops[0] : paths.takes[0])} \u2026`);
|
|
25069
|
+
log(` cost: ${cost} generations (PixelLab's published price)${args.improve ? ", plus about 0.05 for --improve" : ""}`);
|
|
25070
|
+
if (args.budget !== void 0 && args.budget < cost) {
|
|
25071
|
+
throw new Error(`--budget ${args.budget} is below this run's ${cost}-generation cost`);
|
|
25072
|
+
}
|
|
25073
|
+
if (args.dryRun) {
|
|
25074
|
+
log(" dry run: nothing sent");
|
|
25075
|
+
return;
|
|
25076
|
+
}
|
|
25077
|
+
if (!await confirm(` Spend ${cost} generations on this music?`, args.yes)) return;
|
|
25078
|
+
loadKeys2(args);
|
|
25079
|
+
const client2 = clientFromEnv();
|
|
25080
|
+
let style = args.description;
|
|
25081
|
+
if (args.improve && style) {
|
|
25082
|
+
style = (await client2.improveMusicStyle({ style, instrumental: !vocals, bpm: args.bpm })).style;
|
|
25083
|
+
log(` style: ${style}`);
|
|
25084
|
+
}
|
|
25085
|
+
const lyrics = args.lyrics ? await readFile34(path51.resolve(args.lyrics), "utf8") : void 0;
|
|
25086
|
+
const res = await generateMusic(client2, {
|
|
25087
|
+
style,
|
|
25088
|
+
lyrics,
|
|
25089
|
+
autoLyrics: args.autoLyrics,
|
|
25090
|
+
about: args.about,
|
|
25091
|
+
voice: args.voice,
|
|
25092
|
+
lengthS: args.seconds,
|
|
25093
|
+
bpm: args.bpm,
|
|
25094
|
+
exclude: args.exclude.length ? args.exclude.join(", ") : void 0,
|
|
25095
|
+
styleWeight: args.styleWeight,
|
|
25096
|
+
name: args.name,
|
|
25097
|
+
restyleSongId: args.restyle,
|
|
25098
|
+
loop: args.loop,
|
|
25099
|
+
loopOf: args.loopOf,
|
|
25100
|
+
out: args.out,
|
|
25101
|
+
force: args.force,
|
|
25102
|
+
onProgress: progress()
|
|
25103
|
+
});
|
|
25104
|
+
if (args.json) {
|
|
25105
|
+
log(JSON.stringify({ version: 1, ...res }, null, 2));
|
|
25106
|
+
return;
|
|
25107
|
+
}
|
|
25108
|
+
for (const take of res.takes) log(` wrote ${take.file} (${take.durationMs == null ? "?" : (take.durationMs / 1e3).toFixed(1)} s, ${take.songId})`);
|
|
25109
|
+
for (const take of res.loops) {
|
|
25110
|
+
log(` wrote ${take.file} (loop ${take.loopStartS?.toFixed(2) ?? "?"} s to ${take.loopEndS?.toFixed(2) ?? "?"} s, ${take.songId})`);
|
|
25111
|
+
}
|
|
25112
|
+
log(` wrote ${res.record}`);
|
|
25113
|
+
if (res.loops.length) log(" to loop: play to the loop end, then jump back to the loop start; the intro plays once");
|
|
25114
|
+
}
|
|
25115
|
+
async function runSfx(args) {
|
|
25116
|
+
if (!args.description) throw new UsageError('sfx needs --description "<sound>", e.g. "a heavy sword slash hitting metal armor"');
|
|
25117
|
+
if (!args.out) throw new UsageError("sfx needs --out <base>: <base>.wav and <base>.sfx.json are written");
|
|
25118
|
+
const seconds = args.seconds ?? 2;
|
|
25119
|
+
const cost = soundEffectCost(seconds);
|
|
25120
|
+
const { wav } = soundEffectOutputPaths(args.out);
|
|
25121
|
+
log(` sfx: "${args.description}", ${seconds} s \u2192 ${path51.relative(process.cwd(), wav)}`);
|
|
25122
|
+
log(` cost: ${cost} generation${cost === 1 ? "" : "s"} (PixelLab's published price, by length)`);
|
|
25123
|
+
if (args.budget !== void 0 && args.budget < cost) {
|
|
25124
|
+
throw new Error(`--budget ${args.budget} is below this clip's ${cost}-generation cost`);
|
|
25125
|
+
}
|
|
25126
|
+
if (args.dryRun) {
|
|
25127
|
+
log(" dry run: nothing sent");
|
|
25128
|
+
return;
|
|
25129
|
+
}
|
|
25130
|
+
if (!await confirm(` Spend ${cost} generation${cost === 1 ? "" : "s"} on this sound effect?`, args.yes)) return;
|
|
25131
|
+
loadKeys2(args);
|
|
25132
|
+
const res = await generateSoundEffect(clientFromEnv(), {
|
|
25133
|
+
prompt: args.description,
|
|
25134
|
+
seconds,
|
|
25135
|
+
name: args.name,
|
|
25136
|
+
out: args.out,
|
|
25137
|
+
force: args.force,
|
|
25138
|
+
onProgress: progress()
|
|
25139
|
+
});
|
|
25140
|
+
if (args.json) {
|
|
25141
|
+
log(JSON.stringify({ version: 1, ...res }, null, 2));
|
|
25142
|
+
return;
|
|
25143
|
+
}
|
|
25144
|
+
log(` wrote ${res.file} (${res.durationMs == null ? "?" : (res.durationMs / 1e3).toFixed(1)} s, ${res.soundEffectId})`);
|
|
25145
|
+
log(` wrote ${res.record}`);
|
|
25146
|
+
}
|
|
25147
|
+
|
|
25148
|
+
// src/cli/commands/ui.ts
|
|
25149
|
+
import path53 from "path";
|
|
25150
|
+
|
|
25151
|
+
// src/pixellab-ui.ts
|
|
25152
|
+
import { existsSync as existsSync41 } from "fs";
|
|
25153
|
+
import { mkdir as mkdir17, writeFile as writeFile22 } from "fs/promises";
|
|
25154
|
+
import path52 from "path";
|
|
25155
|
+
var UI_STATES_COSTS = [10, 15, 25];
|
|
25156
|
+
var UI_STATES_MAX_COST = 25;
|
|
25157
|
+
var UI_STATES_MAX_ELEMENTS = 64;
|
|
25158
|
+
var UI_STATES_MAX_STATES = 16;
|
|
25159
|
+
function parseUiState(text) {
|
|
25160
|
+
const at = text.indexOf("=");
|
|
25161
|
+
const name = at < 0 ? "" : text.slice(0, at).trim();
|
|
25162
|
+
const description = at < 0 ? "" : text.slice(at + 1).trim();
|
|
25163
|
+
if (!name || !description) {
|
|
25164
|
+
throw new Error(`a state is written "name=description", e.g. "pressed=pushed in: darker, face 1 px lower"; got "${text}"`);
|
|
25165
|
+
}
|
|
25166
|
+
return { name, description };
|
|
25167
|
+
}
|
|
25168
|
+
function parseUiBox(text) {
|
|
25169
|
+
const colon = text.lastIndexOf(":");
|
|
25170
|
+
const label = colon < 0 ? "" : text.slice(0, colon).trim();
|
|
25171
|
+
const numbers = (colon < 0 ? text : text.slice(colon + 1)).split(",").map((part) => Number(part.trim()));
|
|
25172
|
+
if (numbers.length !== 4 || numbers.some((n) => !Number.isInteger(n) || n < 0) || numbers[2] < 1 || numbers[3] < 1) {
|
|
25173
|
+
throw new Error(`a box is written "label:x,y,width,height" in template pixels, e.g. "Play:40,30,120,40"; got "${text}"`);
|
|
25174
|
+
}
|
|
25175
|
+
const [x, y, width, height] = numbers;
|
|
25176
|
+
return { ...label ? { label } : {}, x, y, width, height };
|
|
25177
|
+
}
|
|
25178
|
+
function parseUiInsets(text) {
|
|
25179
|
+
const numbers = text.split(",").map((part) => Number(part.trim()));
|
|
25180
|
+
if (numbers.length !== 1 && numbers.length !== 4 || numbers.some((n) => !Number.isInteger(n) || n < 0)) {
|
|
25181
|
+
throw new Error(`insets are one whole number for every side, or "left,right,top,bottom"; got "${text}"`);
|
|
25182
|
+
}
|
|
25183
|
+
const [left, right = left, top = left, bottom = left] = numbers;
|
|
25184
|
+
return { left, right, top, bottom };
|
|
25185
|
+
}
|
|
25186
|
+
function checkUiInsets(insets, size) {
|
|
25187
|
+
if (insets.left + insets.right >= size.width || insets.top + insets.bottom >= size.height) {
|
|
25188
|
+
throw new Error(
|
|
25189
|
+
`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`
|
|
25190
|
+
);
|
|
25191
|
+
}
|
|
25192
|
+
}
|
|
25193
|
+
function uiStateElements(asset, only) {
|
|
25194
|
+
if (asset.kind === "state") throw new Error(`${asset.id} is a state; states are made for an element or a split template`);
|
|
25195
|
+
if (asset.kind === "element") return [asset.id];
|
|
25196
|
+
if (!asset.elements.length) {
|
|
25197
|
+
throw new Error(`template ${asset.id} has not been split; run pixelkiln ui split --id ${asset.id} first (free)`);
|
|
25198
|
+
}
|
|
25199
|
+
const ids = asset.elements.map((element) => element.id);
|
|
25200
|
+
if (!only?.length) return ids;
|
|
25201
|
+
const unknown = only.filter((id) => !ids.includes(id));
|
|
25202
|
+
if (unknown.length) throw new Error(`not elements of template ${asset.id}: ${unknown.join(", ")}`);
|
|
25203
|
+
return only;
|
|
25204
|
+
}
|
|
25205
|
+
async function createUiStates(client2, opts) {
|
|
25206
|
+
if (!opts.states.length) throw new Error("ui states needs at least one state");
|
|
25207
|
+
if (opts.states.length > UI_STATES_MAX_STATES) throw new Error(`PixelLab takes at most ${UI_STATES_MAX_STATES} states per call`);
|
|
25208
|
+
const before = await client2.getUiAssetDetail(opts.uiAssetId);
|
|
25209
|
+
const elementIds = uiStateElements(before, opts.elementIds);
|
|
25210
|
+
if (elementIds.length > UI_STATES_MAX_ELEMENTS) throw new Error(`PixelLab takes at most ${UI_STATES_MAX_ELEMENTS} elements per call`);
|
|
25211
|
+
const submitted = await client2.createUiStates({ elementIds, states: opts.states, targetPalette: opts.targetPalette });
|
|
25212
|
+
opts.onQuote?.(submitted.generations, submitted.count);
|
|
25213
|
+
const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
25214
|
+
const interval = opts.intervalMs ?? 8e3;
|
|
25215
|
+
const timeout = opts.timeoutMs ?? 8 * 6e4;
|
|
25216
|
+
const started = Date.now();
|
|
25217
|
+
for (; ; ) {
|
|
25218
|
+
const job = await client2.getBackgroundJob(submitted.background_job_id);
|
|
25219
|
+
opts.onProgress?.(job.status);
|
|
25220
|
+
if (job.status === "failed") throw new Error(`PixelLab UI states job ${submitted.background_job_id} failed upstream`);
|
|
25221
|
+
if (job.status === "completed") {
|
|
25222
|
+
return {
|
|
25223
|
+
jobId: submitted.background_job_id,
|
|
25224
|
+
elementIds,
|
|
25225
|
+
quotedGenerations: submitted.generations,
|
|
25226
|
+
count: submitted.count,
|
|
25227
|
+
usage: job.usage ?? null,
|
|
25228
|
+
asset: await client2.getUiAssetDetail(opts.uiAssetId)
|
|
25229
|
+
};
|
|
25230
|
+
}
|
|
25231
|
+
if (Date.now() - started > timeout) {
|
|
25232
|
+
throw new Error(
|
|
25233
|
+
`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`
|
|
25234
|
+
);
|
|
25235
|
+
}
|
|
25236
|
+
await sleep3(interval);
|
|
25237
|
+
}
|
|
25238
|
+
}
|
|
25239
|
+
function slug2(text, fallback) {
|
|
25240
|
+
const cleaned = (text ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
25241
|
+
return cleaned || fallback;
|
|
25242
|
+
}
|
|
25243
|
+
async function pullUiAsset(client2, uiAssetId, opts) {
|
|
25244
|
+
const asset = await client2.getUiAssetDetail(uiAssetId);
|
|
25245
|
+
if (asset.status && asset.status !== "completed") throw new Error(`UI asset ${uiAssetId} is ${asset.status}; pull it once it is completed`);
|
|
25246
|
+
if (!asset.image_url) throw new Error(`UI asset ${uiAssetId} has no image yet`);
|
|
25247
|
+
const dir = path52.resolve(opts.out);
|
|
25248
|
+
const record = path52.join(dir, "ui.json");
|
|
25249
|
+
const plan = [];
|
|
25250
|
+
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 } } : {};
|
|
25251
|
+
const taken = /* @__PURE__ */ new Set();
|
|
25252
|
+
const unique = (base) => {
|
|
25253
|
+
let name = base;
|
|
25254
|
+
for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
|
|
25255
|
+
taken.add(name);
|
|
25256
|
+
return name;
|
|
25257
|
+
};
|
|
25258
|
+
const kind = asset.kind ?? "template";
|
|
25259
|
+
const rootName = slug2(asset.name, kind);
|
|
25260
|
+
plan.push({ id: asset.id, kind, name: rootName, file: `${rootName}.png`, size: asset.size, url: asset.image_url, ...insets(asset) });
|
|
25261
|
+
const addStates = (owner, ownerName, states) => {
|
|
25262
|
+
const stateNames = /* @__PURE__ */ new Set();
|
|
25263
|
+
for (const [i, state] of states.entries()) {
|
|
25264
|
+
let stateName = slug2(state.name, `state-${i + 1}`);
|
|
25265
|
+
for (let n = 2; stateNames.has(stateName); n++) stateName = `${slug2(state.name, `state-${i + 1}`)}-${n}`;
|
|
25266
|
+
stateNames.add(stateName);
|
|
25267
|
+
plan.push({
|
|
25268
|
+
id: state.id,
|
|
25269
|
+
kind: "state",
|
|
25270
|
+
name: `${ownerName}.${stateName}`,
|
|
25271
|
+
file: `elements/${ownerName}.${stateName}.png`,
|
|
25272
|
+
size: state.size,
|
|
25273
|
+
url: state.image_url,
|
|
25274
|
+
elementId: owner.id,
|
|
25275
|
+
...insets(state)
|
|
25276
|
+
});
|
|
25277
|
+
}
|
|
25278
|
+
};
|
|
25279
|
+
for (const [i, element] of asset.elements.entries()) {
|
|
25280
|
+
const name = unique(slug2(element.name || element.template_box?.label, `element-${i + 1}`));
|
|
25281
|
+
const box = element.template_box;
|
|
25282
|
+
plan.push({
|
|
25283
|
+
id: element.id,
|
|
25284
|
+
kind: "element",
|
|
25285
|
+
name,
|
|
25286
|
+
file: `elements/${name}.png`,
|
|
25287
|
+
size: element.size,
|
|
25288
|
+
url: element.image_url,
|
|
25289
|
+
...box ? { box: { ...box.label ? { label: box.label } : {}, x: box.x, y: box.y, width: box.width, height: box.height } } : {},
|
|
25290
|
+
...insets(element)
|
|
25291
|
+
});
|
|
25292
|
+
addStates(element, name, element.states);
|
|
25293
|
+
}
|
|
25294
|
+
if (kind === "element") addStates(asset, rootName, asset.states);
|
|
25295
|
+
if (!opts.force) {
|
|
25296
|
+
for (const file of [record, ...plan.map((item) => path52.join(dir, item.file))]) {
|
|
25297
|
+
if (existsSync41(file)) throw new Error(`${file} already exists; pass --force to replace it`);
|
|
25298
|
+
}
|
|
25299
|
+
}
|
|
25300
|
+
const files = [];
|
|
25301
|
+
for (const { url, ...item } of plan) {
|
|
25302
|
+
const bytes = await client2.download(url);
|
|
25303
|
+
validateMedia(bytes, MediaType.PNG);
|
|
25304
|
+
const target = path52.join(dir, item.file);
|
|
25305
|
+
await mkdir17(path52.dirname(target), { recursive: true });
|
|
25306
|
+
await writeFile22(target, bytes);
|
|
25307
|
+
files.push({ ...item, sha256: sha256(bytes) });
|
|
25308
|
+
}
|
|
25309
|
+
await writeFile22(
|
|
25310
|
+
record,
|
|
25311
|
+
JSON.stringify(
|
|
25312
|
+
{
|
|
25313
|
+
schema: "pixelkiln-ui",
|
|
25314
|
+
version: 1,
|
|
25315
|
+
provider: "pixellab",
|
|
25316
|
+
pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
25317
|
+
uiAssetId: asset.id,
|
|
25318
|
+
kind,
|
|
25319
|
+
prompt: asset.prompt,
|
|
25320
|
+
files
|
|
25321
|
+
},
|
|
25322
|
+
null,
|
|
25323
|
+
2
|
|
25324
|
+
) + "\n"
|
|
25325
|
+
);
|
|
25326
|
+
return { dir, record, files };
|
|
25327
|
+
}
|
|
25328
|
+
|
|
25329
|
+
// src/cli/commands/ui.ts
|
|
25330
|
+
function loadKeys3(args) {
|
|
25331
|
+
loadEnvFiles(path53.dirname(path53.resolve(args.manifest)));
|
|
25332
|
+
loadEnvFiles(process.cwd());
|
|
25333
|
+
}
|
|
25334
|
+
function requireId(args) {
|
|
25335
|
+
if (!args.id) throw new UsageError(`ui ${args.subcommand} needs --id <ui asset id>: a template from the uiAsset generator, or one of its elements`);
|
|
25336
|
+
return args.id;
|
|
25337
|
+
}
|
|
25338
|
+
var insetsText = (slice) => slice ? ` 9-slice ${slice.left},${slice.right},${slice.top},${slice.bottom}` : "";
|
|
25339
|
+
function printAsset(asset) {
|
|
25340
|
+
log(` ${asset.kind ?? "template"} ${asset.id} ${asset.size.width}x${asset.size.height} ${asset.status ?? ""}${insetsText(asset.nine_slice)}`);
|
|
25341
|
+
if (asset.prompt) log(` "${asset.prompt}"`);
|
|
25342
|
+
for (const element of asset.elements) {
|
|
25343
|
+
const box = element.template_box;
|
|
25344
|
+
log(` element ${element.id} ${element.name || box?.label || "(unnamed)"} ${element.size.width}x${element.size.height}${box ? ` at ${box.x},${box.y}` : ""}${insetsText(element.nine_slice)}`);
|
|
25345
|
+
for (const state of element.states) log(` state ${state.id} ${state.name ?? "(unnamed)"}`);
|
|
25346
|
+
}
|
|
25347
|
+
for (const state of asset.states) log(` state ${state.id} ${state.name ?? "(unnamed)"}`);
|
|
25348
|
+
if (!asset.elements.length && asset.split_preview.length) {
|
|
25349
|
+
log(` not split yet; ui split would cut ${asset.split_preview.length} element(s):`);
|
|
25350
|
+
for (const box of asset.split_preview) log(` ${box.label || "(unnamed)"} ${box.width}x${box.height} at ${box.x},${box.y}`);
|
|
25351
|
+
}
|
|
25352
|
+
}
|
|
25353
|
+
async function runUi(args) {
|
|
25354
|
+
const id = requireId(args);
|
|
25355
|
+
if (args.subcommand === "show") {
|
|
25356
|
+
loadKeys3(args);
|
|
25357
|
+
const asset = await clientFromEnv().getUiAssetDetail(id);
|
|
25358
|
+
if (args.json) log(JSON.stringify({ version: 1, asset }, null, 2));
|
|
25359
|
+
else printAsset(asset);
|
|
25360
|
+
return;
|
|
25361
|
+
}
|
|
25362
|
+
if (args.subcommand === "split") {
|
|
25363
|
+
const boxes = args.boxes.map(parseUiBox);
|
|
25364
|
+
if (args.dryRun) {
|
|
25365
|
+
log(` would split ${id} ${boxes.length ? `into ${boxes.length} box(es)` : "along its generated shapes"}; nothing sent`);
|
|
25366
|
+
return;
|
|
25367
|
+
}
|
|
25368
|
+
loadKeys3(args);
|
|
25369
|
+
const client2 = clientFromEnv();
|
|
25370
|
+
const before = await client2.getUiAssetDetail(id);
|
|
25371
|
+
if (before.elements.length) {
|
|
25372
|
+
throw new Error(`template ${id} is already split into ${before.elements.length} element(s); a template splits once (delete its elements on PixelLab to split it again)`);
|
|
25373
|
+
}
|
|
25374
|
+
const elements = await client2.splitUiAsset(id, boxes.length ? boxes : void 0);
|
|
25375
|
+
if (args.json) {
|
|
25376
|
+
log(JSON.stringify({ version: 1, elements }, null, 2));
|
|
25377
|
+
return;
|
|
25378
|
+
}
|
|
25379
|
+
log(` split ${id} into ${elements.length} element(s) (free):`);
|
|
25380
|
+
for (const element of elements) log(` ${element.id} ${element.name || element.template_box?.label || "(unnamed)"} ${element.size.width}x${element.size.height}`);
|
|
25381
|
+
return;
|
|
25382
|
+
}
|
|
25383
|
+
if (args.subcommand === "states") {
|
|
25384
|
+
if (!args.uiStates.length) {
|
|
25385
|
+
throw new UsageError('ui states needs at least one --state "name=description", e.g. --state "hover=brighter, a soft glow on the rim"');
|
|
25386
|
+
}
|
|
25387
|
+
const states = args.uiStates.map(parseUiState);
|
|
25388
|
+
log(` ui states: ${states.map((state) => state.name).join(", ")} for ${args.elements.length ? `${args.elements.length} element(s) of ${id}` : id}`);
|
|
25389
|
+
log(` cost: ${UI_STATES_COSTS.join(", ")} generations by the size of the grid PixelLab lays out; the exact price is quoted on submit`);
|
|
25390
|
+
if (args.budget !== void 0 && args.budget < UI_STATES_MAX_COST) {
|
|
25391
|
+
throw new Error(`--budget ${args.budget} is below the ${UI_STATES_MAX_COST} generations this call can cost`);
|
|
25392
|
+
}
|
|
25393
|
+
if (args.dryRun) {
|
|
25394
|
+
log(" dry run: nothing sent");
|
|
25395
|
+
return;
|
|
25396
|
+
}
|
|
25397
|
+
if (!await confirm(` Spend up to ${UI_STATES_MAX_COST} generations on these states?`, args.yes)) return;
|
|
25398
|
+
loadKeys3(args);
|
|
25399
|
+
let last = "";
|
|
25400
|
+
const res2 = await createUiStates(clientFromEnv(), {
|
|
25401
|
+
uiAssetId: id,
|
|
25402
|
+
elementIds: args.elements,
|
|
25403
|
+
states,
|
|
25404
|
+
targetPalette: args.palette.length || args.maxColors !== void 0 ? { ...args.palette.length ? { colors: args.palette } : {}, ...args.maxColors !== void 0 ? { maxColors: args.maxColors } : {} } : void 0,
|
|
25405
|
+
onQuote: (generations, count) => log(` quoted ${generations} generations for ${count} state image(s)`),
|
|
25406
|
+
onProgress: (status) => {
|
|
25407
|
+
if (status !== last) log(` ${status}\u2026`);
|
|
25408
|
+
last = status;
|
|
25409
|
+
}
|
|
25410
|
+
});
|
|
25411
|
+
if (args.json) {
|
|
25412
|
+
log(JSON.stringify({ version: 1, ...res2 }, null, 2));
|
|
25413
|
+
return;
|
|
25414
|
+
}
|
|
25415
|
+
printAsset(res2.asset);
|
|
25416
|
+
log(` pull the images with: pixelkiln ui pull --id ${id} --out <dir>`);
|
|
25417
|
+
return;
|
|
25418
|
+
}
|
|
25419
|
+
if (args.subcommand === "nine-slice") {
|
|
25420
|
+
if (args.clear === Boolean(args.insets)) throw new UsageError("ui nine-slice needs --insets <n | left,right,top,bottom> or --clear");
|
|
25421
|
+
const insets = args.insets ? parseUiInsets(args.insets) : void 0;
|
|
25422
|
+
if (args.dryRun) {
|
|
25423
|
+
log(` would ${insets ? `set 9-slice ${args.insets}` : "clear the 9-slice"} on ${id}; nothing sent`);
|
|
25424
|
+
return;
|
|
25425
|
+
}
|
|
25426
|
+
loadKeys3(args);
|
|
25427
|
+
const client2 = clientFromEnv();
|
|
25428
|
+
if (insets) checkUiInsets(insets, (await client2.getUiAssetDetail(id)).size);
|
|
25429
|
+
const asset = await client2.updateUiAsset(id, insets ? { nineSlice: insets } : { clearNineSlice: true });
|
|
25430
|
+
if (args.json) log(JSON.stringify({ version: 1, asset }, null, 2));
|
|
25431
|
+
else log(` ${id}: ${asset.nine_slice ? `9-slice ${asset.nine_slice.left},${asset.nine_slice.right},${asset.nine_slice.top},${asset.nine_slice.bottom}` : "no 9-slice (plain scaling)"} (free)`);
|
|
25432
|
+
return;
|
|
25433
|
+
}
|
|
25434
|
+
if (!args.out) throw new UsageError("ui pull needs --out <dir>: the images and a ui.json record are written there");
|
|
25435
|
+
if (args.dryRun) {
|
|
25436
|
+
log(` would download ${id} into ${args.out}; nothing sent`);
|
|
25437
|
+
return;
|
|
25438
|
+
}
|
|
25439
|
+
loadKeys3(args);
|
|
25440
|
+
const res = await pullUiAsset(clientFromEnv(), id, { out: args.out, force: args.force });
|
|
25441
|
+
if (args.json) {
|
|
25442
|
+
log(JSON.stringify({ version: 1, ...res }, null, 2));
|
|
25443
|
+
return;
|
|
25444
|
+
}
|
|
25445
|
+
for (const file of res.files) log(` wrote ${path53.join(args.out, file.file)} (${file.kind}, ${file.size.width}x${file.size.height})`);
|
|
25446
|
+
log(` wrote ${path53.join(args.out, "ui.json")}`);
|
|
25447
|
+
}
|
|
25448
|
+
|
|
25449
|
+
// src/cli/commands/asset.ts
|
|
25450
|
+
import path55 from "path";
|
|
25451
|
+
|
|
25452
|
+
// src/pixellab-assets.ts
|
|
25453
|
+
import { existsSync as existsSync42 } from "fs";
|
|
25454
|
+
import { mkdir as mkdir18, readFile as readFile35, writeFile as writeFile23 } from "fs/promises";
|
|
25455
|
+
import path54 from "path";
|
|
25456
|
+
var ASSET_KINDS = ["object", "character"];
|
|
25457
|
+
var EXPORT_FORMATS = ["zip", "spritesheet", "aseprite", "gif"];
|
|
25458
|
+
var MIRROR_DIRECTIONS = ["east", "west", "south-east", "south-west", "north-east", "north-west"];
|
|
25459
|
+
var EXPAND_DIRECTIONS = ["south", "south-east", "east", "north-east", "north", "north-west", "west", "south-west"];
|
|
25460
|
+
var EXPAND_MIN_COST = 10;
|
|
25461
|
+
var EXPAND_MAX_COST = 25;
|
|
25462
|
+
var IMPORT_MAX_SIDE = 256;
|
|
25463
|
+
function parseCanvasSize(text, kind) {
|
|
25464
|
+
const match = /^(\d+)\s*x\s*(\d+)$/i.exec(text.trim());
|
|
25465
|
+
const max = kind === "object" ? 400 : 256;
|
|
25466
|
+
const width = Number(match?.[1]);
|
|
25467
|
+
const height = Number(match?.[2]);
|
|
25468
|
+
if (!match || [width, height].some((side) => side < 8 || side > max || side % 4 !== 0)) {
|
|
25469
|
+
throw new Error(`--size is <width>x<height> in multiples of 4, from 8 to ${max} for a ${kind}, e.g. 64x64; got "${text}"`);
|
|
25470
|
+
}
|
|
25471
|
+
return { width, height };
|
|
25472
|
+
}
|
|
25473
|
+
function exportOutPath(out, format) {
|
|
25474
|
+
const extension = format === "aseprite" ? ".aseprite" : format === "gif" ? ".gif" : ".zip";
|
|
25475
|
+
return path54.extname(out) ? path54.resolve(out) : path54.resolve(`${out}${extension}`);
|
|
25476
|
+
}
|
|
25477
|
+
function checkExportBytes(bytes, format) {
|
|
25478
|
+
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";
|
|
25479
|
+
if (!ok) throw new Error(`PixelLab's ${format} export was not a ${format === "spritesheet" ? "ZIP" : format} file (${bytes.length} bytes)`);
|
|
25480
|
+
}
|
|
25481
|
+
async function exportAssetFile(client2, kind, id, format, opts) {
|
|
25482
|
+
const out = exportOutPath(opts.out, format);
|
|
25483
|
+
if (existsSync42(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
|
|
25484
|
+
const bytes = await client2.exportAsset(kind, id, format, { animationGroupId: opts.animationGroupId, direction: opts.direction });
|
|
25485
|
+
checkExportBytes(bytes, format);
|
|
25486
|
+
await mkdir18(path54.dirname(out), { recursive: true });
|
|
25487
|
+
await writeFile23(out, bytes);
|
|
25488
|
+
return { out, bytes: bytes.length };
|
|
25489
|
+
}
|
|
25490
|
+
async function importObjectFile(client2, file, opts = {}) {
|
|
25491
|
+
const bytes = await readFile35(file);
|
|
25492
|
+
const metadata = imageMetadata(bytes);
|
|
25493
|
+
if (!metadata || metadata.format !== "png") throw new Error(`${file} is not a PNG; PixelLab imports PNG only (JPEG compression would be stored as pixels)`);
|
|
25494
|
+
if (metadata.width > IMPORT_MAX_SIDE || metadata.height > IMPORT_MAX_SIDE) {
|
|
25495
|
+
throw new Error(`${file} is ${metadata.width}x${metadata.height}; PixelLab imports at most ${IMPORT_MAX_SIDE}x${IMPORT_MAX_SIDE}`);
|
|
25496
|
+
}
|
|
25497
|
+
const res = await client2.importObject({ image: { base64: bytes.toString("base64"), format: "png" }, name: opts.name });
|
|
25498
|
+
return { objectId: res.object_id, name: res.name ?? null, size: { width: res.size.width, height: res.size.height }, imageUrl: res.image_url };
|
|
25499
|
+
}
|
|
25500
|
+
async function expandObject(client2, id, opts) {
|
|
25501
|
+
const submitted = await client2.expandObjectRotations(id, { existingDirection: opts.existingDirection, description: opts.description });
|
|
25502
|
+
opts.onQuote?.(submitted.min_generations, submitted.max_generations);
|
|
25503
|
+
const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
25504
|
+
const interval = opts.intervalMs ?? 1e4;
|
|
25505
|
+
const timeout = opts.timeoutMs ?? 10 * 6e4;
|
|
25506
|
+
const started = Date.now();
|
|
25507
|
+
for (; ; ) {
|
|
25508
|
+
const object = await client2.getObject(id);
|
|
25509
|
+
const status = object.status ?? "unknown";
|
|
25510
|
+
opts.onProgress?.(status);
|
|
25511
|
+
if (status === "failed") throw new Error(`PixelLab could not expand object ${id}`);
|
|
25512
|
+
if (status !== "expanding") {
|
|
25513
|
+
let usage = null;
|
|
25514
|
+
try {
|
|
25515
|
+
usage = (await client2.getBackgroundJob(submitted.background_job_id)).usage ?? null;
|
|
25516
|
+
} catch {
|
|
25517
|
+
usage = null;
|
|
25518
|
+
}
|
|
25519
|
+
return { objectId: id, jobId: submitted.background_job_id, minGenerations: submitted.min_generations, maxGenerations: submitted.max_generations, status, usage };
|
|
25520
|
+
}
|
|
25521
|
+
if (Date.now() - started > timeout) {
|
|
25522
|
+
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`);
|
|
25523
|
+
}
|
|
25524
|
+
await sleep3(interval);
|
|
25525
|
+
}
|
|
25526
|
+
}
|
|
25527
|
+
async function pullExpansionReview(client2, id, opts) {
|
|
25528
|
+
const object = await client2.getObject(id);
|
|
25529
|
+
const review = object.expansion_review;
|
|
25530
|
+
if (object.status !== "review-expansion" || !review?.rotation_urls) {
|
|
25531
|
+
throw new Error(`object ${id} is ${object.status ?? "unknown"}; there is no expansion waiting for review`);
|
|
25532
|
+
}
|
|
25533
|
+
const dir = path54.resolve(opts.out);
|
|
25534
|
+
const entries = Object.entries(review.rotation_urls).filter((entry) => typeof entry[1] === "string");
|
|
25535
|
+
const files = entries.map(([direction]) => ({ direction, file: path54.join(dir, `${direction}.png`) }));
|
|
25536
|
+
if (!opts.force) {
|
|
25537
|
+
for (const { file } of files) if (existsSync42(file)) throw new Error(`${file} already exists; pass --force to replace it`);
|
|
25538
|
+
}
|
|
25539
|
+
await mkdir18(dir, { recursive: true });
|
|
25540
|
+
for (const [index, [, url]] of entries.entries()) {
|
|
25541
|
+
const bytes = await client2.download(url);
|
|
25542
|
+
validateMedia(bytes, MediaType.PNG);
|
|
25543
|
+
await writeFile23(files[index].file, bytes);
|
|
25544
|
+
}
|
|
25545
|
+
return { dir, existingDirection: review.existing_direction ?? null, files };
|
|
25546
|
+
}
|
|
25547
|
+
|
|
25548
|
+
// src/cli/commands/asset.ts
|
|
25549
|
+
function loadKeys4(args) {
|
|
25550
|
+
loadEnvFiles(path55.dirname(path55.resolve(args.manifest)));
|
|
25551
|
+
loadEnvFiles(process.cwd());
|
|
25552
|
+
}
|
|
25553
|
+
function kindOf(args) {
|
|
25554
|
+
const kind = args.kind ?? "object";
|
|
25555
|
+
if (!ASSET_KINDS.includes(kind)) throw new UsageError(`--kind must be ${ASSET_KINDS.join(" or ")}, got "${args.kind}"`);
|
|
25556
|
+
return kind;
|
|
25557
|
+
}
|
|
25558
|
+
function requireId2(args) {
|
|
25559
|
+
if (!args.id) throw new UsageError(`asset ${args.subcommand} needs --id <PixelLab object or character id> (a lock entry's objectId)`);
|
|
25560
|
+
return args.id;
|
|
25561
|
+
}
|
|
25562
|
+
async function runAsset(args) {
|
|
25563
|
+
const emit = (value) => log(JSON.stringify({ version: 1, ...value }, null, 2));
|
|
25564
|
+
if (args.subcommand === "import") {
|
|
25565
|
+
if (!args.from) throw new UsageError("asset import needs --from <png>: your own sprite, at most 256x256");
|
|
25566
|
+
if (args.dryRun) {
|
|
25567
|
+
log(` would import ${args.from} as a 1-direction object; nothing sent`);
|
|
25568
|
+
return;
|
|
25569
|
+
}
|
|
25570
|
+
loadKeys4(args);
|
|
25571
|
+
const res2 = await importObjectFile(clientFromEnv(), args.from, { name: args.name });
|
|
25572
|
+
if (args.json) emit(res2);
|
|
25573
|
+
else log(` imported ${args.from} as object ${res2.objectId} (${res2.size.width}x${res2.size.height}, free)`);
|
|
25574
|
+
return;
|
|
25575
|
+
}
|
|
25576
|
+
const id = requireId2(args);
|
|
25577
|
+
const kind = kindOf(args);
|
|
25578
|
+
if (args.subcommand === "canvas") {
|
|
25579
|
+
if (!args.size) throw new UsageError("asset canvas needs --size <width>x<height>, e.g. --size 64x64");
|
|
25580
|
+
const size = parseCanvasSize(args.size, kind);
|
|
25581
|
+
if (args.dryRun) {
|
|
25582
|
+
log(` would set ${kind} ${id}'s canvas to ${size.width}x${size.height}; nothing sent`);
|
|
25583
|
+
return;
|
|
25584
|
+
}
|
|
25585
|
+
loadKeys4(args);
|
|
25586
|
+
const res2 = await clientFromEnv().setCanvasSize(kind, id, size);
|
|
25587
|
+
if (args.json) emit(res2);
|
|
25588
|
+
else {
|
|
25589
|
+
log(` ${kind} ${id}: canvas ${res2.previous.width}x${res2.previous.height} \u2192 ${res2.canvas.width}x${res2.canvas.height}, ${res2.rotations_moved} rotation(s) re-centred (free)${res2.placements_moved ? `, ${res2.placements_moved} map placement(s) moved` : ""}`);
|
|
25590
|
+
log(" the art is not scaled or cropped; existing animations keep the canvas they were made on");
|
|
25591
|
+
}
|
|
25592
|
+
return;
|
|
25593
|
+
}
|
|
25594
|
+
if (args.subcommand === "mirror") {
|
|
25595
|
+
if (!args.animation) throw new UsageError("asset mirror needs --animation <animation group id>");
|
|
25596
|
+
if (!args.direction || !MIRROR_DIRECTIONS.includes(args.direction)) {
|
|
25597
|
+
throw new UsageError(`asset mirror needs --direction, one of ${MIRROR_DIRECTIONS.join(", ")} (south and north have no mirror)`);
|
|
25598
|
+
}
|
|
25599
|
+
if (args.dryRun) {
|
|
25600
|
+
log(` would flip ${kind} ${id}'s ${args.direction} frames of ${args.animation} into the opposite direction; nothing sent`);
|
|
25601
|
+
return;
|
|
25602
|
+
}
|
|
25603
|
+
loadKeys4(args);
|
|
25604
|
+
const res2 = await clientFromEnv().mirrorAnimation(kind, id, args.animation, args.direction);
|
|
25605
|
+
if (args.json) emit(res2);
|
|
25606
|
+
else log(` ${kind} ${id}: ${res2.source_direction} flipped into ${res2.target_direction}, ${res2.frames_created} frame(s) (free)`);
|
|
25607
|
+
return;
|
|
25608
|
+
}
|
|
25609
|
+
if (args.subcommand === "expand") {
|
|
25610
|
+
if (kind !== "object") throw new UsageError("asset expand works on objects; a character is created with its directions");
|
|
25611
|
+
if (args.keep && args.discard) throw new UsageError("pass --keep or --discard, not both");
|
|
25612
|
+
if (args.keep || args.discard) {
|
|
25613
|
+
if (args.dryRun) {
|
|
25614
|
+
log(` would ${args.keep ? "keep" : "discard"} object ${id}'s reviewed directions; nothing sent`);
|
|
25615
|
+
return;
|
|
25616
|
+
}
|
|
25617
|
+
loadKeys4(args);
|
|
25618
|
+
const client2 = clientFromEnv();
|
|
25619
|
+
if (args.keep) await client2.acceptObjectExpansion(id);
|
|
25620
|
+
else await client2.dismissObjectReview(id);
|
|
25621
|
+
log(args.keep ? ` object ${id} is now 8-direction` : ` object ${id}'s new directions were discarded; it is unchanged`);
|
|
25622
|
+
return;
|
|
25623
|
+
}
|
|
25624
|
+
if (!args.direction || !EXPAND_DIRECTIONS.includes(args.direction)) {
|
|
25625
|
+
throw new UsageError(`asset expand needs --direction: the way the object's image faces now, one of ${EXPAND_DIRECTIONS.join(", ")}`);
|
|
25626
|
+
}
|
|
25627
|
+
log(` expand object ${id} to 8 directions; its image is kept as ${args.direction}`);
|
|
25628
|
+
log(` cost: ${EXPAND_MIN_COST} to ${EXPAND_MAX_COST} generations, by the padded canvas (PixelLab's published range)`);
|
|
25629
|
+
if (args.budget !== void 0 && args.budget < EXPAND_MAX_COST) {
|
|
25630
|
+
throw new Error(`--budget ${args.budget} is below the ${EXPAND_MAX_COST} generations this expansion can cost`);
|
|
25631
|
+
}
|
|
25632
|
+
if (args.dryRun) {
|
|
25633
|
+
log(" dry run: nothing sent");
|
|
25634
|
+
return;
|
|
25635
|
+
}
|
|
25636
|
+
if (!await confirm(` Spend up to ${EXPAND_MAX_COST} generations on this expansion?`, args.yes)) return;
|
|
25637
|
+
loadKeys4(args);
|
|
25638
|
+
let last = "";
|
|
25639
|
+
const res2 = await expandObject(clientFromEnv(), id, {
|
|
25640
|
+
existingDirection: args.direction,
|
|
25641
|
+
description: args.description,
|
|
25642
|
+
onQuote: (min, max) => log(` quoted ${min === max ? min : `${min} to ${max}`} generations`),
|
|
25643
|
+
onProgress: (status) => {
|
|
25644
|
+
if (status !== last) log(` ${status}\u2026`);
|
|
25645
|
+
last = status;
|
|
25646
|
+
}
|
|
25647
|
+
});
|
|
25648
|
+
if (args.json) emit({ ...res2 });
|
|
25649
|
+
else if (res2.status === "review-expansion") {
|
|
25650
|
+
log(` the 7 new directions are ready for review on PixelLab; the object is still 1-direction`);
|
|
25651
|
+
log(` look first: pixelkiln asset review --id ${id} --out <dir>`);
|
|
25652
|
+
log(` keep them: pixelkiln asset expand --id ${id} --keep discard: pixelkiln asset expand --id ${id} --discard`);
|
|
25653
|
+
} else log(` object ${id} is ${res2.status}`);
|
|
25654
|
+
return;
|
|
25655
|
+
}
|
|
25656
|
+
if (args.subcommand === "review") {
|
|
25657
|
+
if (!args.out) throw new UsageError("asset review needs --out <dir>: one PNG per direction is written there");
|
|
25658
|
+
loadKeys4(args);
|
|
25659
|
+
const res2 = await pullExpansionReview(clientFromEnv(), id, { out: args.out, force: args.force });
|
|
25660
|
+
if (args.json) emit(res2);
|
|
25661
|
+
else {
|
|
25662
|
+
for (const file of res2.files) log(` wrote ${path55.join(args.out, `${file.direction}.png`)}${file.direction === res2.existingDirection ? " (your image, unchanged)" : ""}`);
|
|
25663
|
+
log(` keep them: pixelkiln asset expand --id ${id} --keep discard: pixelkiln asset expand --id ${id} --discard`);
|
|
25664
|
+
}
|
|
25665
|
+
return;
|
|
25666
|
+
}
|
|
25667
|
+
const format = args.format ?? "zip";
|
|
25668
|
+
if (!EXPORT_FORMATS.includes(format)) throw new UsageError(`--format must be one of ${EXPORT_FORMATS.join(", ")}`);
|
|
25669
|
+
if (!args.out) throw new UsageError("asset export needs --out <file>");
|
|
25670
|
+
if ((args.animation || args.direction) && format !== "gif") throw new UsageError("--animation and --direction choose a loop for --format gif");
|
|
25671
|
+
if (args.dryRun) {
|
|
25672
|
+
log(` would export ${kind} ${id} as ${format} \u2192 ${exportOutPath(args.out, format)}; nothing sent`);
|
|
25673
|
+
return;
|
|
25674
|
+
}
|
|
25675
|
+
loadKeys4(args);
|
|
25676
|
+
const res = await exportAssetFile(clientFromEnv(), kind, id, format, {
|
|
25677
|
+
out: args.out,
|
|
25678
|
+
animationGroupId: args.animation,
|
|
25679
|
+
direction: args.direction,
|
|
25680
|
+
force: args.force
|
|
25681
|
+
});
|
|
25682
|
+
if (args.json) emit({ ...res, format });
|
|
25683
|
+
else log(` wrote ${res.out} (${format}, ${res.bytes} bytes, free)`);
|
|
25684
|
+
}
|
|
25685
|
+
|
|
25686
|
+
// src/cli/commands/quality.ts
|
|
25687
|
+
import path57 from "path";
|
|
25688
|
+
import { readFile as readFile37 } from "fs/promises";
|
|
25689
|
+
|
|
25690
|
+
// src/pipeline/quality-regression.ts
|
|
25691
|
+
import path56 from "path";
|
|
25692
|
+
import { existsSync as existsSync43 } from "fs";
|
|
25693
|
+
import { readFile as readFile36 } from "fs/promises";
|
|
24074
25694
|
import { z as z13 } from "zod";
|
|
24075
25695
|
var SHA256_RE = /^[0-9a-f]{64}$/;
|
|
24076
25696
|
var HEX_RE = /^#[0-9a-f]{6}$/;
|
|
24077
25697
|
var MAX_REDMEAN_DISTANCE = 765;
|
|
24078
25698
|
var QualityPathSchema = z13.string().min(1).refine(
|
|
24079
|
-
(value) => !
|
|
25699
|
+
(value) => !path56.posix.isAbsolute(value) && !value.includes("\\"),
|
|
24080
25700
|
"expected a portable relative path"
|
|
24081
25701
|
);
|
|
24082
25702
|
var DEFAULT_QUALITY_TOLERANCES = {
|
|
@@ -24223,10 +25843,10 @@ function measureDecodedImageQuality(png, digest2) {
|
|
|
24223
25843
|
};
|
|
24224
25844
|
}
|
|
24225
25845
|
async function measureImageQuality(file) {
|
|
24226
|
-
const absolute =
|
|
25846
|
+
const absolute = path56.resolve(file);
|
|
24227
25847
|
let bytes;
|
|
24228
25848
|
try {
|
|
24229
|
-
bytes = await
|
|
25849
|
+
bytes = await readFile36(absolute);
|
|
24230
25850
|
} catch (error) {
|
|
24231
25851
|
throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
|
|
24232
25852
|
}
|
|
@@ -24245,11 +25865,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
|
|
|
24245
25865
|
}
|
|
24246
25866
|
const ids = parsed.data.map((entry) => entry.id);
|
|
24247
25867
|
if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
|
|
24248
|
-
const root =
|
|
25868
|
+
const root = path56.dirname(path56.resolve(inputsFilePath));
|
|
24249
25869
|
return parsed.data.map((entry) => ({
|
|
24250
25870
|
id: entry.id,
|
|
24251
|
-
file:
|
|
24252
|
-
...entry.record ? { record:
|
|
25871
|
+
file: path56.resolve(root, entry.path),
|
|
25872
|
+
...entry.record ? { record: path56.resolve(root, entry.record) } : {},
|
|
24253
25873
|
tolerances: QualityToleranceSchema.parse({
|
|
24254
25874
|
...DEFAULT_QUALITY_TOLERANCES,
|
|
24255
25875
|
...entry.tolerances
|
|
@@ -24257,7 +25877,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
|
|
|
24257
25877
|
}));
|
|
24258
25878
|
}
|
|
24259
25879
|
function portableRelative2(from, to) {
|
|
24260
|
-
return
|
|
25880
|
+
return path56.relative(from, path56.resolve(to)).split(path56.sep).join("/") || ".";
|
|
24261
25881
|
}
|
|
24262
25882
|
async function verifyRecordForImage(recordPath, imagePath) {
|
|
24263
25883
|
const verification = await verifyArtifactBundle(recordPath);
|
|
@@ -24272,20 +25892,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
|
|
|
24272
25892
|
if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
|
|
24273
25893
|
throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
|
|
24274
25894
|
}
|
|
24275
|
-
const outputs = record.outputs.map((output) =>
|
|
24276
|
-
if (!outputs.includes(
|
|
25895
|
+
const outputs = record.outputs.map((output) => path56.resolve(path56.dirname(recordPath), output.path));
|
|
25896
|
+
if (!outputs.includes(path56.resolve(imagePath))) {
|
|
24277
25897
|
throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
|
|
24278
25898
|
}
|
|
24279
25899
|
}
|
|
24280
25900
|
async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
|
|
24281
25901
|
if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
|
|
24282
|
-
const absolute =
|
|
25902
|
+
const absolute = path56.resolve(baselinePath);
|
|
24283
25903
|
for (const input of inputs) {
|
|
24284
|
-
if (
|
|
25904
|
+
if (path56.resolve(input.file) === absolute || input.record && path56.resolve(input.record) === absolute) {
|
|
24285
25905
|
throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
|
|
24286
25906
|
}
|
|
24287
25907
|
}
|
|
24288
|
-
const root =
|
|
25908
|
+
const root = path56.dirname(absolute);
|
|
24289
25909
|
const cases = [];
|
|
24290
25910
|
for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
24291
25911
|
const expected = await measureImageQuality(input.file);
|
|
@@ -24312,8 +25932,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
|
|
|
24312
25932
|
cases
|
|
24313
25933
|
});
|
|
24314
25934
|
const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
|
|
24315
|
-
if (
|
|
24316
|
-
const current = await
|
|
25935
|
+
if (existsSync43(absolute) && !options.force) {
|
|
25936
|
+
const current = await readFile36(absolute);
|
|
24317
25937
|
if (!current.equals(data)) {
|
|
24318
25938
|
throw new OverwriteRefusedError(
|
|
24319
25939
|
`Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
|
|
@@ -24325,13 +25945,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
|
|
|
24325
25945
|
return { baseline, path: absolute, changed: result.changed.length > 0 };
|
|
24326
25946
|
}
|
|
24327
25947
|
async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
|
|
24328
|
-
const absolute =
|
|
24329
|
-
if (!
|
|
25948
|
+
const absolute = path56.resolve(baselinePath);
|
|
25949
|
+
if (!existsSync43(absolute)) {
|
|
24330
25950
|
throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
|
|
24331
25951
|
}
|
|
24332
25952
|
let raw;
|
|
24333
25953
|
try {
|
|
24334
|
-
raw = JSON.parse(await
|
|
25954
|
+
raw = JSON.parse(await readFile36(absolute, "utf8"));
|
|
24335
25955
|
} catch (error) {
|
|
24336
25956
|
throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
|
|
24337
25957
|
}
|
|
@@ -24341,12 +25961,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
|
|
|
24341
25961
|
if (unknown.length) {
|
|
24342
25962
|
throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
|
|
24343
25963
|
}
|
|
24344
|
-
const root =
|
|
25964
|
+
const root = path56.dirname(absolute);
|
|
24345
25965
|
const cases = [...raw.cases];
|
|
24346
25966
|
const report = [];
|
|
24347
25967
|
for (const id of only) {
|
|
24348
25968
|
const input = byId.get(id);
|
|
24349
|
-
if (
|
|
25969
|
+
if (path56.resolve(input.file) === absolute || input.record && path56.resolve(input.record) === absolute) {
|
|
24350
25970
|
throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
|
|
24351
25971
|
}
|
|
24352
25972
|
const expected = await measureImageQuality(input.file);
|
|
@@ -24376,16 +25996,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
|
|
|
24376
25996
|
}
|
|
24377
25997
|
const baseline = QualityBaselineSchema.parse({ ...raw, cases });
|
|
24378
25998
|
const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
|
|
24379
|
-
const current = await
|
|
25999
|
+
const current = await readFile36(absolute);
|
|
24380
26000
|
const changed = !current.equals(data);
|
|
24381
26001
|
if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
|
|
24382
26002
|
return { baseline, path: absolute, changed, cases: report };
|
|
24383
26003
|
}
|
|
24384
26004
|
async function readQualityBaseline(baselinePath) {
|
|
24385
|
-
const absolute =
|
|
26005
|
+
const absolute = path56.resolve(baselinePath);
|
|
24386
26006
|
let raw;
|
|
24387
26007
|
try {
|
|
24388
|
-
raw = JSON.parse(await
|
|
26008
|
+
raw = JSON.parse(await readFile36(absolute, "utf8"));
|
|
24389
26009
|
} catch (error) {
|
|
24390
26010
|
throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
|
|
24391
26011
|
}
|
|
@@ -24407,7 +26027,7 @@ async function readQualityBaseline(baselinePath) {
|
|
|
24407
26027
|
throw new Error(
|
|
24408
26028
|
`Invalid quality baseline ${absolute}:
|
|
24409
26029
|
` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
|
|
24410
|
-
Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${
|
|
26030
|
+
Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path56.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
|
|
24411
26031
|
);
|
|
24412
26032
|
}
|
|
24413
26033
|
return parsed.data;
|
|
@@ -24469,12 +26089,12 @@ function regressionViolations(expected, actual, tolerances) {
|
|
|
24469
26089
|
return { violations, warnings };
|
|
24470
26090
|
}
|
|
24471
26091
|
async function checkQualityBaseline(baselinePath) {
|
|
24472
|
-
const absolute =
|
|
26092
|
+
const absolute = path56.resolve(baselinePath);
|
|
24473
26093
|
const baseline = await readQualityBaseline(absolute);
|
|
24474
|
-
const root =
|
|
26094
|
+
const root = path56.dirname(absolute);
|
|
24475
26095
|
const cases = [];
|
|
24476
26096
|
for (const entry of baseline.cases) {
|
|
24477
|
-
const file =
|
|
26097
|
+
const file = path56.resolve(root, entry.file);
|
|
24478
26098
|
let actual = null;
|
|
24479
26099
|
const violations = [];
|
|
24480
26100
|
const warnings = [];
|
|
@@ -24487,7 +26107,7 @@ async function checkQualityBaseline(baselinePath) {
|
|
|
24487
26107
|
violations.push(message4(error));
|
|
24488
26108
|
}
|
|
24489
26109
|
if (entry.record) {
|
|
24490
|
-
const recordPath =
|
|
26110
|
+
const recordPath = path56.resolve(root, entry.record.path);
|
|
24491
26111
|
try {
|
|
24492
26112
|
const recordHash = await sha256File(recordPath);
|
|
24493
26113
|
if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
|
|
@@ -24529,15 +26149,15 @@ async function runQuality(args) {
|
|
|
24529
26149
|
if (!args.out) throw new Error("quality snapshot needs --out <pixelkiln.quality.json>.");
|
|
24530
26150
|
let raw;
|
|
24531
26151
|
try {
|
|
24532
|
-
raw = JSON.parse(await
|
|
26152
|
+
raw = JSON.parse(await readFile37(path57.resolve(args.inputs), "utf8"));
|
|
24533
26153
|
} catch (error) {
|
|
24534
26154
|
throw new Error(
|
|
24535
|
-
`Could not read quality inputs ${
|
|
26155
|
+
`Could not read quality inputs ${path57.resolve(args.inputs)}: ${error instanceof Error ? error.message : String(error)}`,
|
|
24536
26156
|
{ cause: error }
|
|
24537
26157
|
);
|
|
24538
26158
|
}
|
|
24539
26159
|
const inputs = resolveQualityInputs(raw, args.inputs);
|
|
24540
|
-
if (
|
|
26160
|
+
if (path57.resolve(args.inputs) === path57.resolve(args.out)) {
|
|
24541
26161
|
throw new Error("quality snapshot --out must not overwrite its --inputs file.");
|
|
24542
26162
|
}
|
|
24543
26163
|
if (args.assets.length) {
|
|
@@ -24552,7 +26172,7 @@ async function runQuality(args) {
|
|
|
24552
26172
|
}
|
|
24553
26173
|
log(
|
|
24554
26174
|
`
|
|
24555
|
-
${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${
|
|
26175
|
+
${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${path57.relative(process.cwd(), result2.path)}; other cases left as they were.`
|
|
24556
26176
|
);
|
|
24557
26177
|
return;
|
|
24558
26178
|
}
|
|
@@ -24567,7 +26187,7 @@ async function runQuality(args) {
|
|
|
24567
26187
|
}, null, 2));
|
|
24568
26188
|
} else {
|
|
24569
26189
|
log(
|
|
24570
|
-
` ${result.changed ? "wrote" : "unchanged"} ${
|
|
26190
|
+
` ${result.changed ? "wrote" : "unchanged"} ${path57.relative(process.cwd(), result.path)} (${result.baseline.cases.length} case(s))`
|
|
24571
26191
|
);
|
|
24572
26192
|
log(` Review the tolerances, commit the baseline, then run quality check in CI.`);
|
|
24573
26193
|
}
|
|
@@ -24593,12 +26213,12 @@ async function runQuality(args) {
|
|
|
24593
26213
|
}
|
|
24594
26214
|
|
|
24595
26215
|
// src/cli/commands/recipe.ts
|
|
24596
|
-
import
|
|
26216
|
+
import path59 from "path";
|
|
24597
26217
|
|
|
24598
26218
|
// src/recipes.ts
|
|
24599
|
-
import
|
|
24600
|
-
import { existsSync as
|
|
24601
|
-
import { readdir as readdir3, readFile as
|
|
26219
|
+
import path58 from "path";
|
|
26220
|
+
import { existsSync as existsSync44 } from "fs";
|
|
26221
|
+
import { readdir as readdir3, readFile as readFile38 } from "fs/promises";
|
|
24602
26222
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
24603
26223
|
import { z as z14 } from "zod";
|
|
24604
26224
|
var SHA256_RE2 = /^[0-9a-f]{64}$/;
|
|
@@ -24607,7 +26227,7 @@ var VERSION_RE = /^\d+\.\d+\.\d+$/;
|
|
|
24607
26227
|
var RECIPE_FILE = "pixelkiln.recipe.json";
|
|
24608
26228
|
var RECIPE_DIR_TOKEN = "{{recipeDir}}";
|
|
24609
26229
|
var PortablePathSchema = z14.string().min(1).refine((value) => {
|
|
24610
|
-
if (value.includes("\\") ||
|
|
26230
|
+
if (value.includes("\\") || path58.posix.isAbsolute(value)) return false;
|
|
24611
26231
|
const parts = value.split("/");
|
|
24612
26232
|
return !parts.includes("") && !parts.includes(".") && !parts.includes("..");
|
|
24613
26233
|
}, "expected a portable relative path without '.', '..', or backslashes");
|
|
@@ -24783,10 +26403,10 @@ function message5(error) {
|
|
|
24783
26403
|
return error instanceof Error ? error.message : String(error);
|
|
24784
26404
|
}
|
|
24785
26405
|
async function readRecipeFile(recipePath, bundled) {
|
|
24786
|
-
const absolute =
|
|
26406
|
+
const absolute = path58.resolve(recipePath);
|
|
24787
26407
|
let raw;
|
|
24788
26408
|
try {
|
|
24789
|
-
raw = JSON.parse(await
|
|
26409
|
+
raw = JSON.parse(await readFile38(absolute, "utf8"));
|
|
24790
26410
|
} catch (error) {
|
|
24791
26411
|
throw new Error(`Could not read recipe ${absolute}: ${message5(error)}`, { cause: error });
|
|
24792
26412
|
}
|
|
@@ -24797,13 +26417,13 @@ async function readRecipeFile(recipePath, bundled) {
|
|
|
24797
26417
|
` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
|
|
24798
26418
|
);
|
|
24799
26419
|
}
|
|
24800
|
-
return { recipe: parsed.data, authored: raw, path: absolute, dir:
|
|
26420
|
+
return { recipe: parsed.data, authored: raw, path: absolute, dir: path58.dirname(absolute), bundled };
|
|
24801
26421
|
}
|
|
24802
26422
|
async function walkRecipeFiles(root) {
|
|
24803
|
-
if (!
|
|
26423
|
+
if (!existsSync44(root)) return [];
|
|
24804
26424
|
const out = [];
|
|
24805
26425
|
for (const entry of await readdir3(root, { withFileTypes: true })) {
|
|
24806
|
-
const resolved =
|
|
26426
|
+
const resolved = path58.join(root, entry.name);
|
|
24807
26427
|
if (entry.isDirectory()) out.push(...await walkRecipeFiles(resolved));
|
|
24808
26428
|
else if (entry.isFile() && entry.name === RECIPE_FILE) out.push(resolved);
|
|
24809
26429
|
}
|
|
@@ -24814,7 +26434,7 @@ function bundledRecipeRoot() {
|
|
|
24814
26434
|
}
|
|
24815
26435
|
async function listBundledRecipes(root = bundledRecipeRoot()) {
|
|
24816
26436
|
const recipes = await Promise.all(
|
|
24817
|
-
(await walkRecipeFiles(
|
|
26437
|
+
(await walkRecipeFiles(path58.resolve(root))).map((file) => readRecipeFile(file, true))
|
|
24818
26438
|
);
|
|
24819
26439
|
return recipes.sort(
|
|
24820
26440
|
(a, b) => a.recipe.id.localeCompare(b.recipe.id) || compareVersions(b.recipe.version, a.recipe.version)
|
|
@@ -24837,9 +26457,9 @@ function parseSelector(selector) {
|
|
|
24837
26457
|
return { id: match[1], version: match[2] };
|
|
24838
26458
|
}
|
|
24839
26459
|
async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
|
|
24840
|
-
const local =
|
|
24841
|
-
if (
|
|
24842
|
-
const recipePath =
|
|
26460
|
+
const local = path58.resolve(target);
|
|
26461
|
+
if (existsSync44(local)) {
|
|
26462
|
+
const recipePath = path58.basename(local) === RECIPE_FILE ? local : path58.join(local, RECIPE_FILE);
|
|
24843
26463
|
return readRecipeFile(recipePath, false);
|
|
24844
26464
|
}
|
|
24845
26465
|
if (target.startsWith(".") || target.startsWith("/") || target.includes("\\")) {
|
|
@@ -24853,8 +26473,8 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
|
|
|
24853
26473
|
return matches[0];
|
|
24854
26474
|
}
|
|
24855
26475
|
async function verifyFile(root, file) {
|
|
24856
|
-
const absolute =
|
|
24857
|
-
if (!
|
|
26476
|
+
const absolute = path58.resolve(root, ...file.path.split("/"));
|
|
26477
|
+
if (!existsSync44(absolute)) {
|
|
24858
26478
|
return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
|
|
24859
26479
|
}
|
|
24860
26480
|
const actualSha256 = await sha256File(absolute);
|
|
@@ -24869,7 +26489,7 @@ async function verifyRecipe(target, options = {}) {
|
|
|
24869
26489
|
const loaded = await resolveRecipe(target, options.bundledRoot);
|
|
24870
26490
|
const actualIntegrity = recipeDigest(loaded.authored);
|
|
24871
26491
|
const files = await Promise.all(loaded.recipe.files.map((file) => verifyFile(loaded.dir, file)));
|
|
24872
|
-
const modelRoot = options.modelRoot ?
|
|
26492
|
+
const modelRoot = options.modelRoot ? path58.resolve(options.modelRoot) : null;
|
|
24873
26493
|
const models = modelRoot ? await Promise.all(loaded.recipe.models.map(async (model) => ({
|
|
24874
26494
|
...await verifyFile(modelRoot, model),
|
|
24875
26495
|
source: model.source,
|
|
@@ -24903,7 +26523,7 @@ async function verifyRecipe(target, options = {}) {
|
|
|
24903
26523
|
};
|
|
24904
26524
|
}
|
|
24905
26525
|
function renderStyle(style, destination, cwd) {
|
|
24906
|
-
const portableDir =
|
|
26526
|
+
const portableDir = path58.relative(cwd, destination).split(path58.sep).join("/") || ".";
|
|
24907
26527
|
const replace = (value) => {
|
|
24908
26528
|
if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
|
|
24909
26529
|
if (Array.isArray(value)) return value.map(replace);
|
|
@@ -24915,25 +26535,25 @@ function renderStyle(style, destination, cwd) {
|
|
|
24915
26535
|
return replace(style);
|
|
24916
26536
|
}
|
|
24917
26537
|
async function installRecipe(target, options = {}) {
|
|
24918
|
-
const cwd =
|
|
26538
|
+
const cwd = path58.resolve(options.cwd ?? process.cwd());
|
|
24919
26539
|
const loaded = await resolveRecipe(target, options.bundledRoot);
|
|
24920
26540
|
const verification = await verifyRecipe(loaded.path);
|
|
24921
26541
|
if (!verification.ok) {
|
|
24922
26542
|
throw new Error(`Recipe ${loaded.recipe.id}@${loaded.recipe.version} failed integrity verification.`);
|
|
24923
26543
|
}
|
|
24924
|
-
const destination = options.out ?
|
|
26544
|
+
const destination = options.out ? path58.resolve(cwd, options.out) : path58.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
|
|
24925
26545
|
const sources = [
|
|
24926
26546
|
{ path: RECIPE_FILE, source: loaded.path },
|
|
24927
|
-
...loaded.recipe.files.map((file) => ({ path: file.path, source:
|
|
26547
|
+
...loaded.recipe.files.map((file) => ({ path: file.path, source: path58.join(loaded.dir, ...file.path.split("/")) }))
|
|
24928
26548
|
];
|
|
24929
26549
|
const files = await Promise.all(sources.map(async (file) => ({
|
|
24930
|
-
path:
|
|
24931
|
-
data: await
|
|
26550
|
+
path: path58.join(destination, ...file.path.split("/")),
|
|
26551
|
+
data: await readFile38(file.source)
|
|
24932
26552
|
})));
|
|
24933
26553
|
if (!options.force) {
|
|
24934
26554
|
for (const file of files) {
|
|
24935
|
-
if (!
|
|
24936
|
-
const current = await
|
|
26555
|
+
if (!existsSync44(file.path)) continue;
|
|
26556
|
+
const current = await readFile38(file.path);
|
|
24937
26557
|
if (!current.equals(file.data)) {
|
|
24938
26558
|
throw new OverwriteRefusedError(
|
|
24939
26559
|
`Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
|
|
@@ -25027,14 +26647,14 @@ async function runRecipe(args) {
|
|
|
25027
26647
|
}, null, 2));
|
|
25028
26648
|
} else {
|
|
25029
26649
|
log(` installed ${result.recipe.id}@${result.recipe.version}`);
|
|
25030
|
-
log(` ${
|
|
26650
|
+
log(` ${path59.relative(process.cwd(), result.destination) || "."}`);
|
|
25031
26651
|
log(`
|
|
25032
26652
|
Add this entry under your manifest's styles object:`);
|
|
25033
26653
|
log(JSON.stringify({ [result.styleId]: result.style }, null, 2));
|
|
25034
26654
|
if (result.recipe.models.length) {
|
|
25035
26655
|
log(`
|
|
25036
26656
|
Models are not downloaded automatically. Verify them with:`);
|
|
25037
|
-
log(` pixelkiln recipe verify ${
|
|
26657
|
+
log(` pixelkiln recipe verify ${path59.relative(process.cwd(), result.destination)} --model-root <ComfyUI/models>`);
|
|
25038
26658
|
}
|
|
25039
26659
|
}
|
|
25040
26660
|
return;
|
|
@@ -25042,7 +26662,7 @@ async function runRecipe(args) {
|
|
|
25042
26662
|
}
|
|
25043
26663
|
|
|
25044
26664
|
// src/cli/commands/refine.ts
|
|
25045
|
-
import
|
|
26665
|
+
import path60 from "path";
|
|
25046
26666
|
async function runRefine(args) {
|
|
25047
26667
|
if (args.from || args.subcommand === "approve") {
|
|
25048
26668
|
if (!args.from) {
|
|
@@ -25072,12 +26692,12 @@ async function runRefine(args) {
|
|
|
25072
26692
|
` recovered ${result3.detection.columns}x${result3.detection.rows} native grid (${result3.detection.confidence}: ${result3.detection.consensus})`
|
|
25073
26693
|
);
|
|
25074
26694
|
log(` enforced ${result3.palette.length}-color palette without dithering`);
|
|
25075
|
-
log(` wrote ${
|
|
25076
|
-
log(` quality record: ${
|
|
26695
|
+
log(` wrote ${path60.relative(process.cwd(), result3.output)}`);
|
|
26696
|
+
log(` quality record: ${path60.relative(process.cwd(), result3.record)}`);
|
|
25077
26697
|
log(`
|
|
25078
26698
|
Automated checks passed. Human 1\xD7 review is still required:`);
|
|
25079
26699
|
log(
|
|
25080
|
-
` pixelkiln refine approve --from ${
|
|
26700
|
+
` pixelkiln refine approve --from ${path60.relative(process.cwd(), result3.record)} --reviewer "Your Name"`
|
|
25081
26701
|
);
|
|
25082
26702
|
}
|
|
25083
26703
|
return;
|
|
@@ -25105,7 +26725,7 @@ async function runRefine(args) {
|
|
|
25105
26725
|
if (args.json) log(JSON.stringify(result3, null, 2));
|
|
25106
26726
|
else {
|
|
25107
26727
|
log(
|
|
25108
|
-
result3.options.frameSet ? ` approved ${result3.outputs.length} frames in ${
|
|
26728
|
+
result3.options.frameSet ? ` approved ${result3.outputs.length} frames in ${path60.relative(process.cwd(), result3.record)} by ${args.reviewer.trim()}` : ` approved ${path60.relative(process.cwd(), result3.output)} by ${args.reviewer.trim()}`
|
|
25109
26729
|
);
|
|
25110
26730
|
}
|
|
25111
26731
|
return;
|
|
@@ -25114,7 +26734,7 @@ async function runRefine(args) {
|
|
|
25114
26734
|
if (args.json) {
|
|
25115
26735
|
log(JSON.stringify(result2, null, 2));
|
|
25116
26736
|
} else {
|
|
25117
|
-
log(` ${result2.safe ? "release-ready" : "not release-ready"}: ${
|
|
26737
|
+
log(` ${result2.safe ? "release-ready" : "not release-ready"}: ${path60.relative(process.cwd(), result2.output || result2.record)}`);
|
|
25118
26738
|
for (const reason of result2.reasons) log(` ${reason}`);
|
|
25119
26739
|
}
|
|
25120
26740
|
if (!result2.safe) process.exitCode = 1;
|
|
@@ -25160,7 +26780,7 @@ async function runRefine(args) {
|
|
|
25160
26780
|
log(` ${item.state.padEnd(16)} ${item.key} ${item.reason}`);
|
|
25161
26781
|
if (item.state === "needs-approval") {
|
|
25162
26782
|
log(
|
|
25163
|
-
` pixelkiln refine approve --from ${
|
|
26783
|
+
` pixelkiln refine approve --from ${path60.relative(process.cwd(), item.record)} --reviewer "Your Name"`
|
|
25164
26784
|
);
|
|
25165
26785
|
}
|
|
25166
26786
|
}
|
|
@@ -25171,9 +26791,9 @@ async function runRefine(args) {
|
|
|
25171
26791
|
}
|
|
25172
26792
|
|
|
25173
26793
|
// src/cli/commands/skeleton.ts
|
|
25174
|
-
import
|
|
25175
|
-
import { existsSync as
|
|
25176
|
-
import { readFile as
|
|
26794
|
+
import path61 from "path";
|
|
26795
|
+
import { existsSync as existsSync45 } from "fs";
|
|
26796
|
+
import { readFile as readFile39, writeFile as writeFile24 } from "fs/promises";
|
|
25177
26797
|
|
|
25178
26798
|
// src/skeleton-preview.ts
|
|
25179
26799
|
var RIGHT = [255, 140, 40, 255];
|
|
@@ -25284,12 +26904,12 @@ var Canvas = class {
|
|
|
25284
26904
|
async function runEstimateSkeleton(args) {
|
|
25285
26905
|
const image = args.target;
|
|
25286
26906
|
if (!image) throw new UsageError("estimate-skeleton needs an image path: pixelkiln estimate-skeleton <image> [--out keypoints.json]");
|
|
25287
|
-
if (args.out &&
|
|
26907
|
+
if (args.out && existsSync45(path61.resolve(args.out)) && !args.force) {
|
|
25288
26908
|
throw new UsageError(`${args.out} already exists; pass --force to replace it`);
|
|
25289
26909
|
}
|
|
25290
|
-
loadEnvFiles(
|
|
26910
|
+
loadEnvFiles(path61.dirname(path61.resolve(args.manifest)));
|
|
25291
26911
|
loadEnvFiles(process.cwd());
|
|
25292
|
-
const bytes = await
|
|
26912
|
+
const bytes = await readFile39(path61.resolve(image));
|
|
25293
26913
|
const metadata = imageMetadata(bytes);
|
|
25294
26914
|
if (!metadata) throw new UsageError(`${image} is not a readable PNG or JPEG`);
|
|
25295
26915
|
const sizeProblem = estimateSkeletonSizeProblem(metadata.width, metadata.height);
|
|
@@ -25301,7 +26921,7 @@ async function runEstimateSkeleton(args) {
|
|
|
25301
26921
|
const frames = args.frames ?? DEFAULT_SCAFFOLD_FRAMES;
|
|
25302
26922
|
const json = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames), null, 2);
|
|
25303
26923
|
if (args.out) {
|
|
25304
|
-
await
|
|
26924
|
+
await writeFile24(path61.resolve(args.out), json + "\n");
|
|
25305
26925
|
log(` wrote ${args.out}: the estimated pose and ${frames} frames to edit`);
|
|
25306
26926
|
log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
|
|
25307
26927
|
} else {
|
|
@@ -25314,8 +26934,8 @@ async function runSkeletonPreview(args) {
|
|
|
25314
26934
|
let sourceFile2;
|
|
25315
26935
|
let label;
|
|
25316
26936
|
if (target.endsWith(".json")) {
|
|
25317
|
-
keypointsFile =
|
|
25318
|
-
sourceFile2 = args.from ?
|
|
26937
|
+
keypointsFile = path61.resolve(target);
|
|
26938
|
+
sourceFile2 = args.from ? path61.resolve(args.from) : void 0;
|
|
25319
26939
|
label = target;
|
|
25320
26940
|
} else {
|
|
25321
26941
|
const loaded = await loadManifest(args.manifest);
|
|
@@ -25327,31 +26947,31 @@ async function runSkeletonPreview(args) {
|
|
|
25327
26947
|
);
|
|
25328
26948
|
}
|
|
25329
26949
|
keypointsFile = spec.revision.keypointsFile;
|
|
25330
|
-
sourceFile2 = args.from ?
|
|
26950
|
+
sourceFile2 = args.from ? path61.resolve(args.from) : spec.revision.sourceFile;
|
|
25331
26951
|
label = `${spec.styleId}/${spec.assetId}`;
|
|
25332
26952
|
}
|
|
25333
|
-
if (!
|
|
26953
|
+
if (!existsSync45(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
|
|
25334
26954
|
let json;
|
|
25335
26955
|
try {
|
|
25336
|
-
json = JSON.parse(await
|
|
26956
|
+
json = JSON.parse(await readFile39(keypointsFile, "utf8"));
|
|
25337
26957
|
} catch (error) {
|
|
25338
26958
|
throw new UsageError(`${keypointsFile} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
25339
26959
|
}
|
|
25340
26960
|
const set = parseSkeletonSet(json, keypointsFile);
|
|
25341
26961
|
let source;
|
|
25342
26962
|
if (sourceFile2) {
|
|
25343
|
-
if (!
|
|
26963
|
+
if (!existsSync45(sourceFile2)) {
|
|
25344
26964
|
log(` source image does not exist yet, drawing on a plain ground: ${sourceFile2}`);
|
|
25345
26965
|
} else {
|
|
25346
|
-
const bytes = await
|
|
26966
|
+
const bytes = await readFile39(sourceFile2);
|
|
25347
26967
|
if (imageMetadata(bytes)?.format !== "png") throw new UsageError(`${sourceFile2} must be a PNG to preview over`);
|
|
25348
26968
|
source = decodePng(bytes);
|
|
25349
26969
|
}
|
|
25350
26970
|
}
|
|
25351
|
-
const out =
|
|
25352
|
-
await
|
|
26971
|
+
const out = path61.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
|
|
26972
|
+
await writeFile24(out, renderSkeletonSheet(set, { source }));
|
|
25353
26973
|
log(` ${label}: ${set.frames.length} frames after the starting pose`);
|
|
25354
|
-
const shown =
|
|
26974
|
+
const shown = path61.relative(process.cwd(), out);
|
|
25355
26975
|
log(` wrote ${shown.startsWith("..") ? out : shown}`);
|
|
25356
26976
|
}
|
|
25357
26977
|
|
|
@@ -25397,15 +27017,15 @@ async function runTools(args) {
|
|
|
25397
27017
|
}
|
|
25398
27018
|
|
|
25399
27019
|
// src/cli/commands/workspace.ts
|
|
25400
|
-
import
|
|
25401
|
-
import { existsSync as
|
|
27020
|
+
import path62 from "path";
|
|
27021
|
+
import { existsSync as existsSync46 } from "fs";
|
|
25402
27022
|
async function runWorkspace(args) {
|
|
25403
|
-
const workspacePath =
|
|
25404
|
-
const dir =
|
|
27023
|
+
const workspacePath = path62.resolve(args.workspace ?? "pixelkiln.workspace.json");
|
|
27024
|
+
const dir = path62.dirname(workspacePath);
|
|
25405
27025
|
if (args.subcommand === "add") {
|
|
25406
|
-
const manifestPath =
|
|
27026
|
+
const manifestPath = path62.resolve(args.target);
|
|
25407
27027
|
const loadedTarget = await loadManifest(manifestPath);
|
|
25408
|
-
const lockPath = args.explicitLock ?
|
|
27028
|
+
const lockPath = args.explicitLock ? path62.resolve(args.explicitLock) : path62.join(path62.dirname(manifestPath), "pixelkiln.lock.json");
|
|
25409
27029
|
const ws = await loadWorkspace(workspacePath);
|
|
25410
27030
|
const id = args.name ?? loadedTarget.manifest.name;
|
|
25411
27031
|
if (ws.projects.some((p) => p.id === id)) {
|
|
@@ -25425,10 +27045,10 @@ async function runWorkspace(args) {
|
|
|
25425
27045
|
...args.account ? { account: args.account } : {}
|
|
25426
27046
|
};
|
|
25427
27047
|
await saveWorkspace(workspacePath, { version: 1, projects: [...ws.projects, project] });
|
|
25428
|
-
log(` registered "${id}" in ${
|
|
27048
|
+
log(` registered "${id}" in ${path62.relative(process.cwd(), workspacePath)}`);
|
|
25429
27049
|
log(` manifest: ${project.manifest}`);
|
|
25430
27050
|
log(` lock: ${project.lock}`);
|
|
25431
|
-
if (!
|
|
27051
|
+
if (!existsSync46(lockPath)) {
|
|
25432
27052
|
log(
|
|
25433
27053
|
` warning: no lockfile there yet; this project contributes no claims until one is generated`
|
|
25434
27054
|
);
|
|
@@ -25437,7 +27057,7 @@ async function runWorkspace(args) {
|
|
|
25437
27057
|
}
|
|
25438
27058
|
if (args.subcommand === "remove") {
|
|
25439
27059
|
const ws = await loadWorkspace(workspacePath);
|
|
25440
|
-
const resolvedTarget =
|
|
27060
|
+
const resolvedTarget = path62.resolve(args.target);
|
|
25441
27061
|
const match = ws.projects.find(
|
|
25442
27062
|
(p) => p.id === args.target || resolveProject(dir, p).manifestPath === resolvedTarget
|
|
25443
27063
|
);
|
|
@@ -25448,11 +27068,11 @@ async function runWorkspace(args) {
|
|
|
25448
27068
|
version: 1,
|
|
25449
27069
|
projects: ws.projects.filter((p) => p !== match)
|
|
25450
27070
|
});
|
|
25451
|
-
log(` removed "${match.id}" from ${
|
|
27071
|
+
log(` removed "${match.id}" from ${path62.relative(process.cwd(), workspacePath)}`);
|
|
25452
27072
|
return;
|
|
25453
27073
|
}
|
|
25454
27074
|
if (args.subcommand === "list") {
|
|
25455
|
-
if (!
|
|
27075
|
+
if (!existsSync46(workspacePath)) {
|
|
25456
27076
|
throw new Error(`Workspace catalog not found: ${workspacePath}`);
|
|
25457
27077
|
}
|
|
25458
27078
|
const ws = await loadWorkspace(workspacePath);
|
|
@@ -25460,9 +27080,9 @@ async function runWorkspace(args) {
|
|
|
25460
27080
|
if (args.json) {
|
|
25461
27081
|
log(JSON.stringify({ version: 1, workspace: workspacePath, projects: ws.projects, diagnostics }, null, 2));
|
|
25462
27082
|
} else if (!ws.projects.length) {
|
|
25463
|
-
log(` no projects registered in ${
|
|
27083
|
+
log(` no projects registered in ${path62.relative(process.cwd(), workspacePath)}`);
|
|
25464
27084
|
} else {
|
|
25465
|
-
log(` ${ws.projects.length} project(s) in ${
|
|
27085
|
+
log(` ${ws.projects.length} project(s) in ${path62.relative(process.cwd(), workspacePath)}:`);
|
|
25466
27086
|
for (const p of ws.projects) {
|
|
25467
27087
|
log(` ${p.id.padEnd(24)} ${p.manifest.padEnd(40)} (${p.provider}${p.account ? `, ${p.account}` : ""})`);
|
|
25468
27088
|
}
|
|
@@ -25472,7 +27092,7 @@ async function runWorkspace(args) {
|
|
|
25472
27092
|
return;
|
|
25473
27093
|
}
|
|
25474
27094
|
if (args.subcommand === "status") {
|
|
25475
|
-
if (!
|
|
27095
|
+
if (!existsSync46(workspacePath)) {
|
|
25476
27096
|
throw new Error(`Workspace catalog not found: ${workspacePath}`);
|
|
25477
27097
|
}
|
|
25478
27098
|
const ws = await loadWorkspace(workspacePath);
|
|
@@ -25480,7 +27100,7 @@ async function runWorkspace(args) {
|
|
|
25480
27100
|
if (args.json) {
|
|
25481
27101
|
log(JSON.stringify({ ...report, workspace: workspacePath }, null, 2));
|
|
25482
27102
|
} else {
|
|
25483
|
-
log(` workspace: ${
|
|
27103
|
+
log(` workspace: ${path62.relative(process.cwd(), workspacePath)}`);
|
|
25484
27104
|
for (const p of report.projects) {
|
|
25485
27105
|
if (p.error) {
|
|
25486
27106
|
log(`
|
|
@@ -25534,8 +27154,8 @@ async function runHelp() {
|
|
|
25534
27154
|
async function runVersion() {
|
|
25535
27155
|
for (const up of ["../package.json", "../../package.json"]) {
|
|
25536
27156
|
const url = new URL(up, import.meta.url);
|
|
25537
|
-
if (!
|
|
25538
|
-
const pkg = JSON.parse(await
|
|
27157
|
+
if (!existsSync47(url)) continue;
|
|
27158
|
+
const pkg = JSON.parse(await readFile40(url, "utf8"));
|
|
25539
27159
|
if (pkg.name === "pixelkiln") {
|
|
25540
27160
|
log(`${pkg.name} ${pkg.version}`);
|
|
25541
27161
|
return;
|
|
@@ -25586,7 +27206,11 @@ var RUNNERS = {
|
|
|
25586
27206
|
pixelate: runPixelate,
|
|
25587
27207
|
"normal-map": runNormalMap,
|
|
25588
27208
|
vfx: runVfx,
|
|
25589
|
-
font: runFont
|
|
27209
|
+
font: runFont,
|
|
27210
|
+
music: runMusic,
|
|
27211
|
+
sfx: runSfx,
|
|
27212
|
+
ui: runUi,
|
|
27213
|
+
asset: runAsset
|
|
25590
27214
|
};
|
|
25591
27215
|
async function main(argv = process.argv.slice(2)) {
|
|
25592
27216
|
const args = parseArgs(argv);
|