vibedgames 0.8.1 → 0.10.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.
Files changed (96) hide show
  1. package/README.md +17 -8
  2. package/assets/align-framing.py +242 -0
  3. package/assets/render-model.py +406 -0
  4. package/assets/tilemap-editor.html +630 -0
  5. package/dist/THIRD_PARTY_NOTICES.txt +59 -7
  6. package/dist/chunk-2KVQJKIZ.js +6495 -0
  7. package/dist/chunk-2SBBKY5C.js +16993 -0
  8. package/dist/chunk-2ZKS7V72.js +170 -0
  9. package/dist/{chunk-RAUJA3OY.js → chunk-3HGBIUM5.js} +21 -18
  10. package/dist/chunk-3UGGMFJJ.js +22 -0
  11. package/dist/{chunk-I6O4HIDY.js → chunk-42K3BJJH.js} +163 -131
  12. package/dist/chunk-43P4U7CB.js +104 -0
  13. package/dist/chunk-4FJXCS3K.js +741 -0
  14. package/dist/{chunk-NC5XCGYU.js → chunk-4UU622RK.js} +6 -5
  15. package/dist/{chunk-2QBYTIMH.js → chunk-5535KDYI.js} +1 -1
  16. package/dist/chunk-5YPLKGY3.js +87 -0
  17. package/dist/chunk-6KXXZXSO.js +475 -0
  18. package/dist/chunk-7RPLQWR2.js +91 -0
  19. package/dist/{chunk-C2IRIRAA.js → chunk-A556KALN.js} +15 -14
  20. package/dist/{chunk-N3XAUFKH.js → chunk-ABTUEIRC.js} +576 -301
  21. package/dist/{chunk-PEUP4MZR.js → chunk-AWJNAGPE.js} +6 -3
  22. package/dist/{chunk-QGEITHUP.js → chunk-BN3Q7UEC.js} +22 -19
  23. package/dist/chunk-BZOMEG3X.js +412 -0
  24. package/dist/{chunk-ZYCSYJWX.js → chunk-COSLGSVO.js} +14 -24
  25. package/dist/{chunk-PQDBCZRT.js → chunk-CTY2WZQK.js} +204 -158
  26. package/dist/{chunk-CU7UY5YJ.js → chunk-D2RF35HJ.js} +1 -1
  27. package/dist/chunk-DB7WVFS7.js +80 -0
  28. package/dist/chunk-DOOQUFPG.js +73 -0
  29. package/dist/chunk-E3FJUPLT.js +177 -0
  30. package/dist/chunk-E7NDOZ27.js +428 -0
  31. package/dist/chunk-F42QKWBB.js +39 -0
  32. package/dist/chunk-FXXVXDTW.js +168 -0
  33. package/dist/{chunk-VFFOT7KD.js → chunk-G66HRVDW.js} +1 -1
  34. package/dist/{chunk-CAKBGDCY.js → chunk-GKDUYJ7R.js} +5 -0
  35. package/dist/chunk-GLEW7VJQ.js +45 -0
  36. package/dist/{chunk-MGIASPED.js → chunk-H2C4QUTG.js} +9 -8
  37. package/dist/{chunk-HCMTSR7E.js → chunk-HRKVAXNN.js} +21 -17
  38. package/dist/{chunk-TLRL6FHW.js → chunk-HSMG6U7J.js} +10 -9
  39. package/dist/chunk-HX5Q63UA.js +48 -0
  40. package/dist/chunk-HYOXGNWS.js +53 -0
  41. package/dist/chunk-I5LELJSK.js +22 -0
  42. package/dist/{chunk-6FZPPUQH.js → chunk-JN4WZCR7.js} +5 -4
  43. package/dist/{chunk-QJZ72MSY.js → chunk-K36EOII3.js} +7 -6
  44. package/dist/chunk-KAGVI3CE.js +62 -0
  45. package/dist/chunk-KJK5CB6E.js +58 -0
  46. package/dist/chunk-KLFBAFXD.js +25 -0
  47. package/dist/{chunk-7MKUR7Y3.js → chunk-LONQWRTR.js} +112 -81
  48. package/dist/chunk-LORGE2NB.js +2484 -0
  49. package/dist/{chunk-HKA5LBYW.js → chunk-MEAO33XW.js} +22 -19
  50. package/dist/{chunk-PM5UOIKR.js → chunk-MR5KIFI7.js} +22 -21
  51. package/dist/{chunk-GCX5KQ6A.js → chunk-N2UHAQXC.js} +18 -11
  52. package/dist/chunk-NCX6LYNJ.js +117 -0
  53. package/dist/chunk-OGX4DKIS.js +215 -0
  54. package/dist/chunk-OPUCUUID.js +41 -0
  55. package/dist/chunk-Q2QC6KAZ.js +132 -0
  56. package/dist/{chunk-2GL2WJZX.js → chunk-Q3XQPNF6.js} +14 -14
  57. package/dist/{chunk-RYFO3ZPO.js → chunk-Q5NZNXJE.js} +15 -12
  58. package/dist/{chunk-JT2AU24K.js → chunk-QARXJGI5.js} +1 -1
  59. package/dist/chunk-QLCVLCPM.js +126 -0
  60. package/dist/chunk-R2WVORGD.js +91 -0
  61. package/dist/chunk-RKS7SI5L.js +64 -0
  62. package/dist/{chunk-4BGCA3W7.js → chunk-RPJR3S5S.js} +32 -18
  63. package/dist/chunk-RPSUFZAG.js +3307 -0
  64. package/dist/chunk-RRI23NK2.js +40 -0
  65. package/dist/chunk-S7HYWITX.js +57 -0
  66. package/dist/chunk-SBXCK2I2.js +48 -0
  67. package/dist/chunk-SUSX3QIA.js +62 -0
  68. package/dist/{chunk-PHEDW6C7.js → chunk-SXYQL4GK.js} +16 -7
  69. package/dist/{chunk-ZI6PKVXG.js → chunk-TMPBGXT4.js} +6 -5
  70. package/dist/chunk-TXOE5UY5.js +72 -0
  71. package/dist/chunk-U6DTE5IX.js +124 -0
  72. package/dist/chunk-UPHB5HWO.js +115 -0
  73. package/dist/chunk-UQ7VO6B3.js +91 -0
  74. package/dist/chunk-VB4WLJR2.js +47 -0
  75. package/dist/{chunk-FNYBZNW2.js → chunk-VIEKOGKG.js} +21 -3
  76. package/dist/{chunk-QIVCBUYD.js → chunk-VZEJ2ZHE.js} +18 -18
  77. package/dist/chunk-X75Y7LUW.js +126 -0
  78. package/dist/{chunk-Z4Z24FWO.js → chunk-YNCYMWER.js} +8 -5
  79. package/dist/chunk-ZHLPE6LI.js +71 -0
  80. package/dist/index.js +48 -34
  81. package/package.json +32 -16
  82. package/templates/none/src/main.ts +4 -0
  83. package/templates/none/vite.config.ts +0 -2
  84. package/templates/phaser/src/main.ts +0 -1
  85. package/templates/phaser/src/scenes/game-scene.ts +10 -8
  86. package/templates/phaser/vite.config.ts +0 -2
  87. package/templates/react-r3f/src/app.tsx +3 -1
  88. package/templates/react-r3f/src/main.tsx +1 -0
  89. package/templates/react-r3f/vite.config.ts +0 -2
  90. package/templates/threejs/src/main.ts +10 -1
  91. package/templates/threejs/vite.config.ts +0 -2
  92. package/LICENSE +0 -21
  93. package/dist/chunk-AYJQVZXY.js +0 -39
  94. package/dist/chunk-J6PKNPI2.js +0 -26
  95. package/dist/chunk-MJQSHP3Y.js +0 -415
  96. package/dist/chunk-MYFLYNPO.js +0 -68
@@ -6,40 +6,215 @@ var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
7
  import {
8
8
  resolveSetting
9
- } from "./chunk-6FZPPUQH.js";
9
+ } from "./chunk-JN4WZCR7.js";
10
10
  import {
11
- require_cross_spawn
12
- } from "./chunk-2QBYTIMH.js";
13
- import {
14
- createClient,
15
- forwardJson
16
- } from "./chunk-PQDBCZRT.js";
17
- import "./chunk-Z4Z24FWO.js";
18
- import "./chunk-PEUP4MZR.js";
11
+ createClient
12
+ } from "./chunk-CTY2WZQK.js";
13
+ import "./chunk-E3FJUPLT.js";
14
+ import "./chunk-Q5NZNXJE.js";
19
15
  import {
20
16
  isJsonOutput,
21
17
  outputArgs,
22
18
  writeJson,
23
19
  writeStructured
24
- } from "./chunk-ZYCSYJWX.js";
25
- import "./chunk-RYFO3ZPO.js";
20
+ } from "./chunk-COSLGSVO.js";
21
+ import {
22
+ defineCommand
23
+ } from "./chunk-MBXCVCC4.js";
24
+ import {
25
+ require_cross_spawn
26
+ } from "./chunk-5535KDYI.js";
26
27
  import {
27
28
  consola
28
- } from "./chunk-CU7UY5YJ.js";
29
+ } from "./chunk-D2RF35HJ.js";
30
+ import "./chunk-YNCYMWER.js";
31
+ import "./chunk-AWJNAGPE.js";
29
32
  import {
33
+ external_exports,
30
34
  isJsonNumber,
31
35
  isJsonObject,
32
- isJsonString
33
- } from "./chunk-J6PKNPI2.js";
34
- import {
35
- defineCommand
36
- } from "./chunk-MBXCVCC4.js";
36
+ isJsonString,
37
+ parseJson
38
+ } from "./chunk-RPSUFZAG.js";
39
+ import "./chunk-2SBBKY5C.js";
37
40
  import {
38
41
  __toESM
39
- } from "./chunk-CAKBGDCY.js";
42
+ } from "./chunk-GKDUYJ7R.js";
40
43
 
41
- // src/commands/generate.ts
42
- import { setTimeout as sleep2 } from "node:timers/promises";
44
+ // ../../packages/contract/src/generate/generate-schema.ts
45
+ var uploadInput = external_exports.object({
46
+ contentType: external_exports.string().min(1).max(127).describe("The file's MIME type, e.g. `image/png`; PUT the bytes with this Content-Type"),
47
+ fileName: external_exports.string().min(1).max(255).describe("The file's name with its extension, e.g. `hero.png`, up to 255 characters")
48
+ });
49
+ var MAX_WAIT_SECONDS = 25;
50
+ var endpointId = external_exports.string().min(1).max(256).describe("A model's endpoint id, as generate models lists it, e.g. `fal-ai/flux/dev`");
51
+ var requestId = external_exports.string().min(1).max(128).describe("The job's `request_id`, as generate returned it, with the endpoint_id it ran on");
52
+ var runInput = external_exports.object({
53
+ endpoint_id: endpointId,
54
+ input: external_exports.record(external_exports.string(), external_exports.json()).describe("The model's input, per generate schema"),
55
+ wait_seconds: external_exports.number().int().min(0).max(MAX_WAIT_SECONDS).default(20).describe("How long to wait for the result before returning the request id")
56
+ });
57
+ var statusInput = external_exports.object({
58
+ action: external_exports.enum(["status", "result", "cancel"]).default("status").describe(
59
+ "`status` (the default) reports where the job is; `result` fetches its output once COMPLETED, which settles the bill; `cancel` stops a job that is still queued or running"
60
+ ),
61
+ endpoint_id: endpointId,
62
+ logs: external_exports.boolean().default(false).describe("Include the job's logs with its status"),
63
+ request_id: requestId
64
+ });
65
+ var modelsInput = external_exports.object({
66
+ category: external_exports.string().max(128).optional().describe("Only models in this category, e.g. `text-to-image`, `image-to-video`"),
67
+ cursor: external_exports.string().max(512).optional().describe(
68
+ "The `next_cursor` of a previous result, for the page after it; omit for the first page"
69
+ ),
70
+ endpoint_id: external_exports.array(external_exports.string().min(1).max(256)).max(50).optional().describe("Endpoint ids to look up directly instead of searching, e.g. `fal-ai/flux/dev`"),
71
+ expand: external_exports.array(external_exports.enum(["openapi-3.0", "enterprise_status"])).optional().describe("Extra fields to include per model: `openapi-3.0`, `enterprise_status`"),
72
+ limit: external_exports.number().int().min(1).max(100).default(20).describe("How many models to return per page, 1 to 100; default 20"),
73
+ query: external_exports.string().max(500).optional().describe("Free text, e.g. `pixel art sprite`"),
74
+ status: external_exports.enum(["active", "deprecated", "all"]).optional().describe("`deprecated` or `all` to include models past their prime; omit for active models")
75
+ });
76
+ var schemaInput = external_exports.object({
77
+ endpoint_id: endpointId,
78
+ format: external_exports.enum(["compact", "openapi"]).default("compact").describe(
79
+ "`compact` (the default) returns the model's catalog entry; `openapi` adds its full OpenAPI 3.0 document, with every input and output field"
80
+ )
81
+ });
82
+ var pricingInput = external_exports.object({ endpoint_id: endpointId });
83
+ var docsInput = external_exports.object({
84
+ query: external_exports.string().min(1).max(500).describe(
85
+ "What to look up, in plain words and up to 500 characters, e.g. `how to prompt seedance camera moves`"
86
+ )
87
+ });
88
+
89
+ // ../../packages/contract/src/generate/media-schema.ts
90
+ var options = external_exports.record(external_exports.string(), external_exports.json()).default({}).describe(
91
+ "Any other input the model takes, per generate schema of its endpoint; the fields above win"
92
+ );
93
+ var prompt = external_exports.string().min(1).max(5e3);
94
+ var imageUrl = external_exports.url().describe("An image's URL, e.g. from generate upload");
95
+ var waitSeconds = runInput.shape.wait_seconds;
96
+ var animate3dInput = external_exports.object({
97
+ animation_action_ids: external_exports.array(external_exports.number().int().min(0).max(696)).min(1).max(10).describe("Up to 10 clips from Meshy's animation library, one GLB each, e.g. 0 for Idle"),
98
+ height_meters: external_exports.number().positive().max(100).optional().describe("The character's height, 1.7 by default"),
99
+ model_url: external_exports.url().describe("The character's GLB, e.g. generate 3d's model_glb"),
100
+ options,
101
+ wait_seconds: waitSeconds
102
+ });
103
+ var imageInput = external_exports.object({
104
+ background: external_exports.enum(["auto", "transparent", "opaque"]).optional().describe(
105
+ "`transparent` leaves no background, for sprites and props; `opaque` always fills one; `auto` lets the model choose. Omit for the model's default"
106
+ ),
107
+ image_size: external_exports.enum([
108
+ "auto",
109
+ "square_hd",
110
+ "square",
111
+ "portrait_4_3",
112
+ "portrait_16_9",
113
+ "landscape_4_3",
114
+ "landscape_16_9"
115
+ ]).optional().describe("A preset; pass `{width, height}` through options for an exact size"),
116
+ image_urls: external_exports.array(imageUrl).min(1).max(16).optional().describe("Images to edit or combine"),
117
+ num_images: external_exports.number().int().min(1).max(4).optional().describe("How many images to make from the one prompt, 1 to 4; omit for the model's default"),
118
+ options,
119
+ prompt: prompt.describe(
120
+ "What to draw, or with image_urls how to edit or combine them, up to 5,000 characters, e.g. `pixel-art knight sprite, side view`"
121
+ ),
122
+ quality: external_exports.enum(["auto", "low", "medium", "high", "xhigh", "max"]).optional().describe(
123
+ "Rendering quality from `low` (quick drafts) to `max`; higher takes longer and may cost more (see generate pricing). `auto` lets the model choose; omit for the model's default"
124
+ ),
125
+ wait_seconds: waitSeconds
126
+ });
127
+ var model3dInput = external_exports.object({
128
+ image_url: imageUrl.optional(),
129
+ options,
130
+ pose_mode: external_exports.enum(["a-pose", "t-pose"]).optional().describe("Model a character in this pose, which rigs cleanly in animate-3d"),
131
+ prompt: prompt.max(600).optional().describe("What to model; needed without image_url"),
132
+ target_polycount: external_exports.number().int().min(100).max(3e5).optional().describe(
133
+ "The mesh's polygon budget, 100 to 300,000; the model's default is 30,000. Games suit 5,000 to 15,000 for a prop, 15,000 to 40,000 for a hero character"
134
+ ),
135
+ topology: external_exports.enum(["quad", "triangle"]).optional().describe(
136
+ "The mesh's faces: `triangle` (the model's default) keeps detail, `quad` gives smoother surfaces"
137
+ ),
138
+ wait_seconds: waitSeconds
139
+ });
140
+ var musicInput = external_exports.object({
141
+ force_instrumental: external_exports.boolean().optional().describe("true makes a track with no vocals; omit to let the prompt decide"),
142
+ music_length_ms: external_exports.number().int().min(3e3).max(6e5).optional().describe(
143
+ "The track's length in milliseconds, 3,000 to 600,000 (3 seconds to 10 minutes), e.g. 60000 for a minute; omit for the model's default"
144
+ ),
145
+ options,
146
+ prompt: prompt.describe(
147
+ "The music to compose, up to 5,000 characters: genre, mood, instruments, tempo, structure, e.g. `upbeat chiptune boss battle loop, 140 bpm`"
148
+ ),
149
+ wait_seconds: waitSeconds
150
+ });
151
+ var removeBackgroundInput = external_exports.object({
152
+ image_url: imageUrl,
153
+ options,
154
+ prompt: external_exports.string().min(1).max(500).optional().describe("What to keep, e.g. the knight"),
155
+ wait_seconds: waitSeconds
156
+ });
157
+ var soundInput = external_exports.object({
158
+ duration_seconds: external_exports.number().min(0.5).max(30).optional().describe(
159
+ "The sound's length in seconds, 0.5 to 30; omit to let the model fit the length to the sound"
160
+ ),
161
+ loop: external_exports.boolean().optional().describe("Make it loop seamlessly"),
162
+ options,
163
+ text: prompt.describe("The sound to make"),
164
+ wait_seconds: waitSeconds
165
+ });
166
+ var speechInput = external_exports.object({
167
+ options,
168
+ text: prompt.describe("What to say"),
169
+ voice: external_exports.string().min(1).optional().describe("A voice name, e.g. Rachel, Aria, Roger"),
170
+ wait_seconds: waitSeconds
171
+ });
172
+ var videoInput = external_exports.object({
173
+ aspect_ratio: external_exports.enum(["auto", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"]).optional().describe(
174
+ "The frame's width to height, e.g. `16:9` landscape, `9:16` portrait, `1:1` square; `auto` lets the model choose, e.g. from image_url. Omit for the model's default"
175
+ ),
176
+ duration: external_exports.enum([
177
+ "auto",
178
+ "4",
179
+ "5",
180
+ "6",
181
+ "7",
182
+ "8",
183
+ "9",
184
+ "10",
185
+ "11",
186
+ "12",
187
+ "13",
188
+ "14",
189
+ "15",
190
+ "16",
191
+ "17",
192
+ "18",
193
+ "19",
194
+ "20",
195
+ "21",
196
+ "22",
197
+ "23",
198
+ "24",
199
+ "25",
200
+ "26",
201
+ "27",
202
+ "28",
203
+ "29",
204
+ "30"
205
+ ]).optional().describe("Seconds, 4 to 30"),
206
+ end_image_url: imageUrl.optional().describe("The last frame, with image_url"),
207
+ generate_audio: external_exports.boolean().optional().describe(
208
+ "false makes a silent clip; omit for the model's default, which generates sound with the video"
209
+ ),
210
+ image_url: imageUrl.optional().describe("The first frame"),
211
+ options,
212
+ prompt: prompt.optional().describe("What happens; needed without image_url"),
213
+ resolution: external_exports.enum(["480p", "720p", "1080p"]).optional().describe(
214
+ "The clip's resolution; higher takes longer and may cost more (see generate pricing). Omit for the model's default"
215
+ ),
216
+ wait_seconds: waitSeconds
217
+ });
43
218
 
44
219
  // src/lib/codex.ts
45
220
  var import_cross_spawn = __toESM(require_cross_spawn(), 1);
@@ -82,9 +257,9 @@ var parseValue = (raw) => {
82
257
  if (raw === "null") {
83
258
  return null;
84
259
  }
85
- if (raw.length > 0 && (raw[0] === "{" || raw[0] === "[")) {
260
+ if (raw.length > 0 && (raw.startsWith("{") || raw.startsWith("["))) {
86
261
  try {
87
- return JSON.parse(raw);
262
+ return parseJson(raw);
88
263
  } catch {
89
264
  return raw;
90
265
  }
@@ -101,7 +276,7 @@ var parseRunInput = (argv) => {
101
276
  const out = {};
102
277
  for (let i = 0; i < argv.length; i += 1) {
103
278
  const arg = argv[i];
104
- if (!arg || !arg.startsWith("--")) {
279
+ if (arg === void 0 || arg === "" || !arg.startsWith("--")) {
105
280
  continue;
106
281
  }
107
282
  if (arg === "--") {
@@ -113,7 +288,7 @@ var parseRunInput = (argv) => {
113
288
  if (RUN_RESERVED_FLAGS.has(name)) {
114
289
  if (name === "--download" && inlineValue === void 0) {
115
290
  const next2 = argv[i + 1];
116
- if (next2 && !next2.startsWith("--")) {
291
+ if (next2 !== void 0 && next2 !== "" && !next2.startsWith("--")) {
117
292
  i += 1;
118
293
  }
119
294
  }
@@ -202,7 +377,7 @@ var parseDownloadFlag = (argv) => {
202
377
  let inlineValue;
203
378
  for (let i = 0; i < argv.length; i += 1) {
204
379
  const arg = argv[i];
205
- if (!arg) {
380
+ if (arg === void 0 || arg === "") {
206
381
  continue;
207
382
  }
208
383
  if (arg === "--") {
@@ -232,6 +407,20 @@ var parseDownloadFlag = (argv) => {
232
407
  // src/lib/media-download.ts
233
408
  import { mkdirSync, writeFileSync } from "node:fs";
234
409
  import path2 from "node:path";
410
+
411
+ // ../../packages/contract/src/generate/media-hosts.ts
412
+ var HOSTS = /* @__PURE__ */ new Set(["fal.media", "fal.run", "fal.ai"]);
413
+ var SUFFIXES = [".fal.media", ".fal.run", ".fal.ai"];
414
+ var HTTPS = /^https:\/\/(?<host>[a-z0-9.-]+)(?::\d{1,5})?(?:[/?#]|$)/iu;
415
+ var isMediaUrl = (url) => {
416
+ const host = HTTPS.exec(url)?.groups?.host?.toLowerCase();
417
+ if (host === void 0 || host === "") {
418
+ return false;
419
+ }
420
+ return HOSTS.has(host) || SUFFIXES.some((suffix) => host.endsWith(suffix));
421
+ };
422
+
423
+ // src/lib/media-download.ts
235
424
  var MEDIA_EXT = /* @__PURE__ */ new Set([
236
425
  "png",
237
426
  "jpg",
@@ -251,24 +440,6 @@ var MEDIA_EXT = /* @__PURE__ */ new Set([
251
440
  "flac",
252
441
  "m4a"
253
442
  ]);
254
- var TRUSTED_HOST_SUFFIXES = [".fal.media", ".fal.run", ".fal.ai"];
255
- var TRUSTED_HOSTS = /* @__PURE__ */ new Set(["fal.media", "fal.run", "fal.ai"]);
256
- var isTrustedFalContentHost = (url) => {
257
- let parsed;
258
- try {
259
- parsed = new URL(url);
260
- } catch {
261
- return false;
262
- }
263
- if (parsed.protocol !== "https:") {
264
- return false;
265
- }
266
- const host = parsed.hostname.toLowerCase();
267
- if (TRUSTED_HOSTS.has(host)) {
268
- return true;
269
- }
270
- return TRUSTED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));
271
- };
272
443
  var extFromUrl = (url) => {
273
444
  try {
274
445
  const { pathname } = new URL(url);
@@ -296,10 +467,10 @@ var visit = (value, refs, seen) => {
296
467
  return;
297
468
  }
298
469
  const { url } = value;
299
- if (isJsonString(url) && isTrustedFalContentHost(url) && !seen.has(url)) {
470
+ if (isJsonString(url) && isMediaUrl(url) && !seen.has(url)) {
300
471
  const contentType = isJsonString(value.content_type) ? value.content_type.toLowerCase() : null;
301
472
  const filenameField = isJsonString(value.file_name) ? sanitizeFilename(value.file_name) : null;
302
- const ext = filenameField ? path2.extname(filenameField).slice(1).toLowerCase() : extFromUrl(url);
473
+ const ext = filenameField !== null && filenameField !== "" ? path2.extname(filenameField).slice(1).toLowerCase() : extFromUrl(url);
303
474
  const looksMedia = contentType === null ? MEDIA_EXT.has(ext) : /^(?:image|video|audio)\//u.test(contentType);
304
475
  if (looksMedia) {
305
476
  seen.add(url);
@@ -348,8 +519,8 @@ var mislabelOf = (target, ref) => {
348
519
  if (!asked) {
349
520
  return null;
350
521
  }
351
- const actual = ref.contentType ? EXT_FOR_CONTENT_TYPE.get(ref.contentType) : void 0;
352
- if (!actual || canonicalExt(actual) === asked) {
522
+ const actual = ref.contentType !== null && ref.contentType !== "" ? EXT_FOR_CONTENT_TYPE.get(ref.contentType) : void 0;
523
+ if (actual === void 0 || actual === "" || canonicalExt(actual) === asked) {
353
524
  return null;
354
525
  }
355
526
  return { actual, path: target };
@@ -373,7 +544,7 @@ var disambiguateTargets = (paths) => {
373
544
  return `${p.slice(0, p.length - ext.length)}_${n}${ext}`;
374
545
  });
375
546
  };
376
- var renderTemplate = (ref, template, index, requestId) => {
547
+ var renderTemplate = (ref, template, index, requestId2) => {
377
548
  const ext = (() => {
378
549
  const fromName = path2.extname(ref.filename).slice(1);
379
550
  if (fromName) {
@@ -384,14 +555,14 @@ var renderTemplate = (ref, template, index, requestId) => {
384
555
  const lowerName = ref.filename.toLowerCase();
385
556
  const dotExt = `.${ext.toLowerCase()}`;
386
557
  const stem = lowerName.endsWith(dotExt) ? ref.filename.slice(0, -dotExt.length) || "output" : ref.filename || "output";
387
- if (!template || !template.includes("{")) {
388
- if (template && path2.extname(template)) {
558
+ if (template === void 0 || template === "" || !template.includes("{")) {
559
+ if (template !== void 0 && template !== "" && path2.extname(template)) {
389
560
  return path2.resolve(template);
390
561
  }
391
562
  const dir = template ?? process.cwd();
392
563
  return path2.resolve(dir, ref.filename || `output-${index}.${ext}`);
393
564
  }
394
- const rendered = template.replaceAll("{index}", String(index)).replaceAll("{name}", stem).replaceAll("{ext}", ext).replaceAll("{request_id}", requestId);
565
+ const rendered = template.replaceAll("{index}", String(index)).replaceAll("{name}", stem).replaceAll("{ext}", ext).replaceAll("{request_id}", requestId2);
395
566
  return path2.resolve(rendered);
396
567
  };
397
568
  var downloadMedia = async (opts) => {
@@ -410,7 +581,11 @@ var downloadMedia = async (opts) => {
410
581
  try {
411
582
  const res = await fetch(ref.url);
412
583
  if (!res.ok) {
413
- return { error: `${res.status} ${res.statusText}`, ok: false, url: ref.url };
584
+ return {
585
+ error: `${res.status} ${res.statusText}`,
586
+ ok: false,
587
+ url: ref.url
588
+ };
414
589
  }
415
590
  const bytes = new Uint8Array(await res.arrayBuffer());
416
591
  writeFileSync(target, bytes);
@@ -462,7 +637,7 @@ var parseProvider = (raw, from = "--provider") => {
462
637
  throw new Error(`Unknown provider "${name}" (${from}). Supported: vibedgames, codex.`);
463
638
  };
464
639
  var CODEX_ENDPOINT = "codex";
465
- var isOpenAiImageEndpoint = (endpointId) => /^openai\/gpt-image/iu.test(endpointId);
640
+ var isOpenAiImageEndpoint = (endpointId2) => /^openai\/gpt-image/iu.test(endpointId2);
466
641
  var isLocalReference = (ref) => !/^(?:https?:|data:)/iu.test(ref);
467
642
  var chooseProvider = (flag, run) => {
468
643
  if (flag !== void 0 && flag.trim() !== "") {
@@ -521,11 +696,11 @@ var buildSizeHint = (input) => {
521
696
  return parts.length > 0 ? parts.join(", ") : void 0;
522
697
  };
523
698
  var parseCodexInput = (input) => {
524
- let prompt = "";
699
+ let prompt2 = "";
525
700
  for (const key of PROMPT_KEYS) {
526
701
  const v = input[key];
527
702
  if (isJsonString(v) && v.trim().length > 0) {
528
- prompt = v.trim();
703
+ prompt2 = v.trim();
529
704
  break;
530
705
  }
531
706
  }
@@ -550,7 +725,7 @@ var parseCodexInput = (input) => {
550
725
  }
551
726
  }
552
727
  }
553
- return { count, prompt, referenceCandidates, sizeHint: buildSizeHint(input) };
728
+ return { count, prompt: prompt2, referenceCandidates, sizeHint: buildSizeHint(input) };
554
729
  };
555
730
  var buildCodexPrompt = (input, filenames, hasReferences) => {
556
731
  const n = filenames.length;
@@ -559,7 +734,7 @@ var buildCodexPrompt = (input, filenames, hasReferences) => {
559
734
  hasReferences ? `Edit the attached reference image to produce ${noun} using your built-in image generation.` : `Generate ${noun} using your built-in image generation.`,
560
735
  `Prompt: ${input.prompt}`
561
736
  ];
562
- if (input.sizeHint) {
737
+ if (input.sizeHint !== void 0 && input.sizeHint !== "") {
563
738
  lines.push(
564
739
  `Size: aim for ${input.sizeHint}. Use the closest size the generator offers and save that as-is \u2014 never resize, crop or ask about it.`
565
740
  );
@@ -570,12 +745,12 @@ var buildCodexPrompt = (input, filenames, hasReferences) => {
570
745
  );
571
746
  return lines.join("\n");
572
747
  };
573
- var renderLocalTarget = (template, index, ext, requestId, count) => {
574
- if (!template) {
575
- return path3.resolve(process.cwd(), `codex-image-${requestId}-${index}.${ext}`);
748
+ var renderLocalTarget = (template, index, ext, requestId2, count) => {
749
+ if (template === void 0 || template === "") {
750
+ return path3.resolve(process.cwd(), `codex-image-${requestId2}-${index}.${ext}`);
576
751
  }
577
752
  if (template.includes("{")) {
578
- const rendered = template.replaceAll("{index}", String(index)).replaceAll("{ext}", ext).replaceAll("{request_id}", requestId).replaceAll("{name}", "output");
753
+ const rendered = template.replaceAll("{index}", String(index)).replaceAll("{ext}", ext).replaceAll("{request_id}", requestId2).replaceAll("{name}", "output");
579
754
  return path3.resolve(rendered);
580
755
  }
581
756
  if (path3.extname(template)) {
@@ -618,37 +793,37 @@ var pickNewest = (paths, limit) => {
618
793
  try {
619
794
  ({ mtimeMs } = statSync2(p));
620
795
  } catch {
796
+ mtimeMs = 0;
621
797
  }
622
798
  return { mtimeMs, p };
623
799
  });
624
800
  return withTime.toSorted((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit).map((x) => x.p).toSorted();
625
801
  };
626
- var spawnCodex = (bin, args, cwd) => (
627
- // oxlint-disable-next-line promise/avoid-new -- child_process.spawn is event-based
628
- new Promise((resolve) => {
629
- const child = (0, import_cross_spawn.default)(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
630
- let output = "";
631
- child.stdout?.on("data", (c) => {
632
- output += c.toString("utf-8");
633
- process.stderr.write(c);
634
- });
635
- child.stderr?.on("data", (c) => {
636
- output += c.toString("utf-8");
637
- process.stderr.write(c);
638
- });
639
- child.on("error", (err) => {
640
- resolve({
641
- code: 1,
642
- notFound: err.code === "ENOENT",
643
- output: output + err.message
644
- });
645
- });
646
- child.on("close", (code) => {
647
- resolve({ code: code ?? 1, notFound: false, output });
802
+ var spawnCodex = async (bin, args, cwd) => {
803
+ const { promise, resolve } = Promise.withResolvers();
804
+ const child = (0, import_cross_spawn.default)(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
805
+ let output = "";
806
+ child.stdout?.on("data", (c) => {
807
+ output += c.toString("utf-8");
808
+ process.stderr.write(c);
809
+ });
810
+ child.stderr?.on("data", (c) => {
811
+ output += c.toString("utf-8");
812
+ process.stderr.write(c);
813
+ });
814
+ child.on("error", (err) => {
815
+ resolve({
816
+ code: 1,
817
+ notFound: err.code === "ENOENT",
818
+ output: output + err.message
648
819
  });
649
- })
650
- );
651
- var codexExecArgs = (workDir, references, prompt) => [
820
+ });
821
+ child.on("close", (code) => {
822
+ resolve({ code: code ?? 1, notFound: false, output });
823
+ });
824
+ return await promise;
825
+ };
826
+ var codexExecArgs = (workDir, references, prompt2) => [
652
827
  "exec",
653
828
  "--skip-git-repo-check",
654
829
  "-s",
@@ -656,10 +831,8 @@ var codexExecArgs = (workDir, references, prompt) => [
656
831
  "-C",
657
832
  workDir,
658
833
  ...references.flatMap((r) => ["-i", r]),
659
- // `-i` is variadic (`--image <FILE>...`): without the separator it
660
- // swallows the prompt as one more image and codex waits on stdin for one.
661
834
  "--",
662
- prompt
835
+ prompt2
663
836
  ];
664
837
  var generateImagesWithCodex = async (opts) => {
665
838
  const parsed = parseCodexInput(opts.input);
@@ -676,12 +849,12 @@ var generateImagesWithCodex = async (opts) => {
676
849
  ignoredReferences.push(candidate);
677
850
  }
678
851
  }
679
- const requestId = randomBytes(4).toString("hex");
852
+ const requestId2 = randomBytes(4).toString("hex");
680
853
  const workDir = mkdtempSync(path3.join(tmpdir(), "vg-codex-"));
681
854
  const filenames = Array.from({ length: parsed.count }, (_, i) => `output-${i}.png`);
682
- const prompt = buildCodexPrompt(parsed, filenames, references.length > 0);
855
+ const prompt2 = buildCodexPrompt(parsed, filenames, references.length > 0);
683
856
  const bin = resolveSetting("generate.codex-bin").value;
684
- const args = codexExecArgs(workDir, references, prompt);
857
+ const args = codexExecArgs(workDir, references, prompt2);
685
858
  const storeDir = path3.join(codexHome(), "generated_images");
686
859
  const before = new Set(listImages(storeDir));
687
860
  const outcome = await spawnCodex(bin, args, workDir);
@@ -715,14 +888,14 @@ var generateImagesWithCodex = async (opts) => {
715
888
  { output: outcome.output }
716
889
  );
717
890
  }
718
- return { ignoredReferences, prompt, rawFiles, requestId };
891
+ return { ignoredReferences, prompt: prompt2, rawFiles, requestId: requestId2 };
719
892
  };
720
- var placeCodexOutputs = (rawFiles, template, requestId) => {
893
+ var placeCodexOutputs = (rawFiles, template, requestId2) => {
721
894
  const downloaded = [];
722
895
  const failed = [];
723
896
  const rendered = rawFiles.map((source, index) => {
724
897
  const ext = path3.extname(source).slice(1).toLowerCase() || "png";
725
- return renderLocalTarget(template, index, ext, requestId, rawFiles.length);
898
+ return renderLocalTarget(template, index, ext, requestId2, rawFiles.length);
726
899
  });
727
900
  const targets = disambiguateTargets(rendered);
728
901
  for (const [index, source] of rawFiles.entries()) {
@@ -743,15 +916,116 @@ var placeCodexOutputs = (rawFiles, template, requestId) => {
743
916
  return { downloaded, failed };
744
917
  };
745
918
 
919
+ // ../../packages/contract/src/run-in-order.ts
920
+ var runInOrder = async (items, step) => {
921
+ const iterator = items[Symbol.iterator]();
922
+ const results = [];
923
+ const advance = async () => {
924
+ const current = iterator.next();
925
+ if (current.done === true) {
926
+ return results;
927
+ }
928
+ results.push(await step(current.value, results.length));
929
+ return await advance();
930
+ };
931
+ return await advance();
932
+ };
933
+
934
+ // src/lib/media-flags.ts
935
+ var RESERVED = /* @__PURE__ */ new Set(["options", "wait_seconds"]);
936
+ var REMOTE = /^(?:https?:|data:)/iu;
937
+ var unwrap = (schema) => schema instanceof external_exports.ZodOptional || schema instanceof external_exports.ZodDefault ? unwrap(schema.def.innerType) : schema;
938
+ var kindOf = (schema) => {
939
+ const inner = unwrap(schema);
940
+ if (inner instanceof external_exports.ZodArray) {
941
+ return "array";
942
+ }
943
+ if (inner instanceof external_exports.ZodBoolean) {
944
+ return "boolean";
945
+ }
946
+ if (inner instanceof external_exports.ZodNumber) {
947
+ return "number";
948
+ }
949
+ if (inner instanceof external_exports.ZodRecord) {
950
+ return "record";
951
+ }
952
+ return "string";
953
+ };
954
+ var elementOf = (schema) => {
955
+ const inner = unwrap(schema);
956
+ return inner instanceof external_exports.ZodArray ? kindOf(inner.element) : "string";
957
+ };
958
+ var describe = (schema) => external_exports.globalRegistry.get(schema)?.description ?? external_exports.globalRegistry.get(unwrap(schema))?.description ?? "";
959
+ var isLocalFileField = (key) => key.endsWith("_url") || key.endsWith("_urls");
960
+ var mediaFlagArgs = (fields) => Object.fromEntries(
961
+ Object.entries(fields).filter(([key]) => !RESERVED.has(key)).map(([key, schema]) => {
962
+ const kind = kindOf(schema);
963
+ const local = isLocalFileField(key) ? " A local path is uploaded first." : "";
964
+ const many = kind === "array" ? " Repeat or comma-separate." : "";
965
+ return [
966
+ key,
967
+ {
968
+ description: `${describe(schema)}.${many}${local}`.replaceAll("..", "."),
969
+ type: kind === "boolean" ? "boolean" : "string"
970
+ }
971
+ ];
972
+ })
973
+ );
974
+ var coerce = (kind, value) => {
975
+ if (kind === "number") {
976
+ return isJsonString(value) ? Number(value) : value;
977
+ }
978
+ if (kind === "string") {
979
+ return isJsonNumber(value) || value === true || value === false ? String(value) : value;
980
+ }
981
+ return value;
982
+ };
983
+ var listOf = (value) => {
984
+ if (Array.isArray(value)) {
985
+ return value;
986
+ }
987
+ if (isJsonString(value)) {
988
+ return value.split(",").map((part) => part.trim()).filter(Boolean);
989
+ }
990
+ return [value];
991
+ };
992
+ var readMediaInput = async (fields, argv, upload) => {
993
+ const raw = parseRunInput(argv);
994
+ const input = {};
995
+ const resolve = async (key, value) => {
996
+ if (!isJsonString(value) || !isLocalFileField(key)) {
997
+ return value;
998
+ }
999
+ if (REMOTE.test(value)) {
1000
+ return value;
1001
+ }
1002
+ const file = readExplicitLocalFile(value);
1003
+ if (!file) {
1004
+ throw new Error(`--${key}: no file at ${value}, and it is not an http(s) or data: URL.`);
1005
+ }
1006
+ return await upload(file);
1007
+ };
1008
+ await runInOrder(Object.entries(fields), async ([key, schema]) => {
1009
+ const kind = kindOf(schema);
1010
+ const value = kind === "boolean" && raw[`no-${key}`] === true ? false : raw[key];
1011
+ if (value === void 0 || key === "wait_seconds") {
1012
+ return;
1013
+ }
1014
+ if (kind === "array") {
1015
+ const element = elementOf(schema);
1016
+ input[key] = await runInOrder(
1017
+ listOf(value),
1018
+ async (item) => coerce(element, await resolve(key, item))
1019
+ );
1020
+ } else {
1021
+ input[key] = coerce(kind, await resolve(key, value));
1022
+ }
1023
+ });
1024
+ return input;
1025
+ };
1026
+
746
1027
  // src/lib/media-poll.ts
747
1028
  import { setTimeout as sleep } from "node:timers/promises";
748
- var endpointPath = (endpointId) => endpointId.replaceAll(/^\/+|\/+$/gu, "");
749
- var QUEUE_APP_NAMESPACES = /* @__PURE__ */ new Set(["workflows", "comfy"]);
750
- var queueAppId = (endpointId) => {
751
- const parts = endpointPath(endpointId).split("/").filter(Boolean);
752
- const take = QUEUE_APP_NAMESPACES.has(parts[0] ?? "") ? 3 : 2;
753
- return parts.slice(0, take).join("/");
754
- };
755
1029
  var POLL_INTERVAL_MS = 2e3;
756
1030
  var POLL_TIMEOUT_MS = 30 * 60 * 1e3;
757
1031
  var pickErrorReason = (value) => {
@@ -773,85 +1047,53 @@ var pickErrorReason = (value) => {
773
1047
  return null;
774
1048
  };
775
1049
  var waitForCompletion = async (client, endpoint_id, request_id, opts) => {
776
- const ep = queueAppId(endpoint_id);
1050
+ const job = { endpoint_id, request_id };
777
1051
  const deadline = Date.now() + POLL_TIMEOUT_MS;
778
- let lastStatus;
779
- while (true) {
1052
+ const poll = async (lastStatus) => {
780
1053
  if (Date.now() > deadline) {
781
1054
  throw new Error(
782
1055
  `Job did not complete within ${POLL_TIMEOUT_MS}ms (endpoint=${endpoint_id} request_id=${request_id}). Use \`vg generate status ${endpoint_id} ${request_id} --result\` to check later.`
783
1056
  );
784
1057
  }
785
- const raw = await forwardJson(client, {
786
- method: "GET",
787
- path: `/${ep}/requests/${request_id}/status`,
788
- target: "queue"
789
- });
1058
+ const raw = await client.generate.status({ ...job, action: "status" });
790
1059
  const status = isJsonObject(raw) && isJsonString(raw.status) ? raw.status : "UNKNOWN";
791
1060
  const upper = status.toUpperCase();
792
1061
  if (!opts.quiet && upper !== lastStatus) {
793
- lastStatus = upper;
794
1062
  const queuePos = isJsonObject(raw) && isJsonNumber(raw.queue_position) ? raw.queue_position : null;
795
1063
  const tag = queuePos === null ? upper.toLowerCase() : `${upper.toLowerCase()} (queue ${queuePos})`;
796
1064
  consola.log(` ${tag}`);
797
1065
  }
798
1066
  if (upper === "COMPLETED") {
799
- break;
1067
+ return;
800
1068
  }
801
1069
  if (upper === "FAILED" || upper === "CANCELLED") {
802
1070
  const reason = pickErrorReason(raw);
803
1071
  throw new Error(
804
- reason ? `Job ${upper.toLowerCase()}: ${reason}` : `Job ${upper.toLowerCase()}`
1072
+ reason !== null && reason !== "" ? `Job ${upper.toLowerCase()}: ${reason}` : `Job ${upper.toLowerCase()}`
805
1073
  );
806
1074
  }
807
1075
  await sleep(POLL_INTERVAL_MS);
808
- }
809
- const result = await forwardJson(client, {
810
- method: "GET",
811
- path: `/${ep}/requests/${request_id}`,
812
- target: "queue"
813
- });
1076
+ await poll(upper);
1077
+ };
1078
+ await poll(void 0);
1079
+ const result = await client.generate.status({ ...job, action: "result" });
814
1080
  return { request_id, result };
815
1081
  };
816
1082
 
817
1083
  // src/lib/media-upload.ts
818
1084
  import { openAsBlob } from "node:fs";
819
- var pickUrl = (slot, key) => {
820
- const value = isJsonObject(slot) ? slot[key] : void 0;
821
- if (!isJsonString(value) || value.length === 0) {
822
- throw new Error(`fal storage initiate response missing ${key}.`);
823
- }
824
- let parsed;
825
- try {
826
- parsed = new URL(value);
827
- } catch {
828
- throw new Error(`fal storage initiate response ${key} is not a valid URL.`);
829
- }
830
- if (parsed.protocol !== "https:") {
831
- throw new Error(`fal storage initiate response ${key} must be HTTPS, got ${parsed.protocol}.`);
832
- }
833
- return value;
834
- };
835
1085
  var uploadFile = async (client, file) => {
836
- const slot = await forwardJson(client, {
837
- body: { content_type: file.contentType, file_name: file.filename },
838
- method: "POST",
839
- path: "/storage/upload/initiate",
840
- target: "storage"
1086
+ const slot = await client.generate.upload({
1087
+ contentType: file.contentType,
1088
+ fileName: file.filename
841
1089
  });
842
- const uploadUrl = pickUrl(slot, "upload_url");
843
- const fileUrl = pickUrl(slot, "file_url");
844
1090
  const body = await openAsBlob(file.path, { type: file.contentType });
845
- const res = await fetch(uploadUrl, {
846
- body,
847
- headers: { "Content-Type": file.contentType },
848
- method: "PUT"
849
- });
1091
+ const res = await fetch(slot.uploadUrl, { body, headers: slot.headers, method: "PUT" });
850
1092
  if (!res.ok) {
851
1093
  const text = await res.text().catch(() => "");
852
1094
  throw new Error(`Upload failed for ${file.filename}: ${res.status} ${res.statusText} ${text}`);
853
1095
  }
854
- return fileUrl;
1096
+ return slot.fileUrl;
855
1097
  };
856
1098
 
857
1099
  // src/commands/generate.ts
@@ -883,7 +1125,7 @@ var warnMislabeled = (mislabeled) => {
883
1125
  };
884
1126
  var runViaCodex = async (opts) => {
885
1127
  const { args, finalInput, downloadFlag, endpoint_id } = opts;
886
- if (args.async) {
1128
+ if (args.async === true) {
887
1129
  consola.error("--async is not supported with --provider codex (Codex runs synchronously).");
888
1130
  process.exit(1);
889
1131
  }
@@ -897,18 +1139,18 @@ var runViaCodex = async (opts) => {
897
1139
  }
898
1140
  throw error;
899
1141
  }
900
- const { requestId, rawFiles, prompt, ignoredReferences } = result;
1142
+ const { requestId: requestId2, rawFiles, prompt: prompt2, ignoredReferences } = result;
901
1143
  for (const ref of ignoredReferences) {
902
1144
  consola.warn(`Ignored non-local reference (codex needs a local file path): ${ref}`);
903
1145
  }
904
1146
  const template = downloadFlag.mode === "on" ? downloadFlag.template : void 0;
905
- const { downloaded, failed } = placeCodexOutputs(rawFiles, template, requestId);
1147
+ const { downloaded, failed } = placeCodexOutputs(rawFiles, template, requestId2);
906
1148
  const payload = {
907
1149
  downloaded_files: downloaded,
908
1150
  endpoint_id,
909
1151
  provider: "codex",
910
- request_id: requestId,
911
- result: { images: downloaded.map((path4) => ({ path: path4 })), prompt, provider: "codex" },
1152
+ request_id: requestId2,
1153
+ result: { images: downloaded.map((path4) => ({ path: path4 })), prompt: prompt2, provider: "codex" },
912
1154
  status: "completed"
913
1155
  };
914
1156
  if (failed.length > 0) {
@@ -918,7 +1160,7 @@ var runViaCodex = async (opts) => {
918
1160
  payload.ignored_references = ignoredReferences;
919
1161
  }
920
1162
  if (!writeStructured(payload, args)) {
921
- consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
1163
+ consola.success(`Codex generated ${downloaded.length} image(s) (${requestId2})`);
922
1164
  for (const path4 of downloaded) {
923
1165
  consola.log(` ${path4}`);
924
1166
  }
@@ -930,9 +1172,9 @@ var runViaCodex = async (opts) => {
930
1172
  process.exit(1);
931
1173
  }
932
1174
  };
933
- var buildRunPayload = (endpointId, completed, downloaded) => {
1175
+ var buildRunPayload = (endpointId2, completed, downloaded) => {
934
1176
  const payload = {
935
- endpoint_id: endpointId,
1177
+ endpoint_id: endpointId2,
936
1178
  request_id: completed.request_id,
937
1179
  result: completed.result,
938
1180
  status: "completed"
@@ -960,12 +1202,49 @@ var reportRun = (completed, downloaded) => {
960
1202
  }
961
1203
  warnMislabeled(downloaded.mislabeled);
962
1204
  }
963
- if (!downloaded?.downloaded.length) {
1205
+ if (downloaded === void 0 || downloaded.downloaded.length === void 0 || downloaded.downloaded.length === 0) {
964
1206
  for (const url of extractMediaUrls(completed.result)) {
965
1207
  consola.log(` ${url}`);
966
1208
  }
967
1209
  }
968
1210
  };
1211
+ var finishRun = async (client, opts) => {
1212
+ const { args, downloadFlag, submission } = opts;
1213
+ const { endpoint_id } = submission;
1214
+ const requestId2 = submission.request_id;
1215
+ if (args.async === true) {
1216
+ const payload2 = {
1217
+ endpoint_id,
1218
+ hint: `Check status: vg generate status ${endpoint_id} ${requestId2}`,
1219
+ request_id: requestId2,
1220
+ status: "submitted"
1221
+ };
1222
+ if (!writeStructured(payload2, args)) {
1223
+ consola.success(`Submitted ${endpoint_id}`);
1224
+ consola.log(` request_id: ${requestId2}`);
1225
+ }
1226
+ return;
1227
+ }
1228
+ const completed = submission.status.toUpperCase() === "COMPLETED" ? { request_id: requestId2, result: submission.result } : await waitForCompletion(client, endpoint_id, requestId2, {
1229
+ quiet: Boolean(args.quiet) || isStructuredOutput(args)
1230
+ });
1231
+ let downloaded;
1232
+ if (downloadFlag.mode === "on") {
1233
+ const refs = extractMediaRefs(completed.result);
1234
+ downloaded = await downloadMedia({
1235
+ refs,
1236
+ requestId: completed.request_id,
1237
+ template: downloadFlag.template
1238
+ });
1239
+ }
1240
+ const payload = buildRunPayload(endpoint_id, completed, downloaded);
1241
+ if (!writeStructured(payload, args)) {
1242
+ reportRun(completed, downloaded);
1243
+ }
1244
+ if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
1245
+ process.exit(1);
1246
+ }
1247
+ };
969
1248
  var runCommand = defineCommand({
970
1249
  args: {
971
1250
  async: {
@@ -998,7 +1277,7 @@ var runCommand = defineCommand({
998
1277
  endpointId: endpoint_id,
999
1278
  input: finalInput
1000
1279
  });
1001
- if (choice.note) {
1280
+ if (choice.note !== void 0 && choice.note !== "") {
1002
1281
  process.stderr.write(`${choice.note}
1003
1282
  `);
1004
1283
  }
@@ -1007,66 +1286,15 @@ var runCommand = defineCommand({
1007
1286
  return;
1008
1287
  }
1009
1288
  const client = createClient();
1010
- const submission = await forwardJson(client, {
1011
- body: finalInput,
1012
- method: "POST",
1013
- path: `/${endpointPath(endpoint_id)}`,
1014
- target: "queue"
1289
+ const submission = await client.generate.run({
1290
+ endpoint_id,
1291
+ input: finalInput,
1292
+ wait_seconds: 0
1015
1293
  });
1016
- const requestId = isJsonObject(submission) && isJsonString(submission.request_id) ? submission.request_id : null;
1017
- if (!requestId) {
1018
- throw new Error("queue submit did not return a request_id.");
1019
- }
1020
- if (args.async) {
1021
- const payload2 = {
1022
- endpoint_id,
1023
- hint: `Check status: vg generate status ${endpoint_id} ${requestId}`,
1024
- request_id: requestId,
1025
- status: "submitted"
1026
- };
1027
- if (!writeStructured(payload2, args)) {
1028
- consola.success(`Submitted ${endpoint_id}`);
1029
- consola.log(` request_id: ${requestId}`);
1030
- }
1031
- return;
1032
- }
1033
- const completed = await waitForCompletion(client, endpoint_id, requestId, {
1034
- quiet: Boolean(args.quiet) || isStructuredOutput(args)
1035
- });
1036
- let downloaded;
1037
- if (downloadFlag.mode === "on") {
1038
- const refs = extractMediaRefs(completed.result);
1039
- downloaded = await downloadMedia({
1040
- refs,
1041
- requestId: completed.request_id,
1042
- template: downloadFlag.template
1043
- });
1044
- }
1045
- const payload = buildRunPayload(endpoint_id, completed, downloaded);
1046
- if (!writeStructured(payload, args)) {
1047
- reportRun(completed, downloaded);
1048
- }
1049
- if (downloaded && downloaded.failed.length > 0 && downloaded.downloaded.length === 0) {
1050
- process.exit(1);
1051
- }
1294
+ await finishRun(client, { args, downloadFlag, submission });
1052
1295
  }
1053
1296
  });
1054
- var confirmCancelled = async (client, ep, requestId) => {
1055
- const statusPath = `/${ep}/requests/${requestId}/status`;
1056
- for (let attempt = 0; attempt < 3; attempt += 1) {
1057
- await sleep2(1e3);
1058
- try {
1059
- const poll = await forwardJson(client, { method: "GET", path: statusPath, target: "queue" });
1060
- const status = isJsonObject(poll) && isJsonString(poll.status) ? poll.status.toUpperCase() : "";
1061
- if (["CANCELLED", "FAILED", "COMPLETED"].includes(status)) {
1062
- break;
1063
- }
1064
- } catch {
1065
- break;
1066
- }
1067
- }
1068
- };
1069
- var reportStatus = (action, endpointId, requestId, data, downloaded) => {
1297
+ var reportStatus = (action, endpointId2, requestId2, data, downloaded) => {
1070
1298
  if (action === "status") {
1071
1299
  const status = isJsonObject(data) && isJsonString(data.status) ? data.status : "?";
1072
1300
  consola.log(`status: ${status}`);
@@ -1075,7 +1303,7 @@ var reportStatus = (action, endpointId, requestId, data, downloaded) => {
1075
1303
  }
1076
1304
  return;
1077
1305
  }
1078
- consola.success(`${action} ${endpointId} ${requestId}`);
1306
+ consola.success(`${action} ${endpointId2} ${requestId2}`);
1079
1307
  if (downloaded) {
1080
1308
  for (const p of downloaded.downloaded) {
1081
1309
  consola.log(` ${p}`);
@@ -1085,7 +1313,7 @@ var reportStatus = (action, endpointId, requestId, data, downloaded) => {
1085
1313
  }
1086
1314
  warnMislabeled(downloaded.mislabeled);
1087
1315
  }
1088
- if (action === "result" && !downloaded?.downloaded.length) {
1316
+ if (action === "result" && (downloaded === void 0 || downloaded.downloaded.length === void 0 || downloaded.downloaded.length === 0)) {
1089
1317
  for (const url of extractMediaUrls(data)) {
1090
1318
  consola.log(` ${url}`);
1091
1319
  }
@@ -1109,31 +1337,25 @@ var statusCommand = defineCommand({
1109
1337
  name: "status"
1110
1338
  },
1111
1339
  run: async ({ args, rawArgs }) => {
1112
- if (args.result && args.cancel) {
1340
+ if (args.result === true && args.cancel === true) {
1113
1341
  consola.error("Pick one of --result or --cancel.");
1114
1342
  process.exit(1);
1115
1343
  }
1116
1344
  const downloadFlag = parseDownloadFlag(rawArgs);
1117
- const wantResult = args.result || downloadFlag.mode === "on";
1345
+ const wantResult = args.result === true || downloadFlag.mode === "on";
1118
1346
  let action = "status";
1119
- if (args.cancel) {
1347
+ if (args.cancel === true) {
1120
1348
  action = "cancel";
1121
1349
  } else if (wantResult) {
1122
1350
  action = "result";
1123
1351
  }
1124
- const ep = queueAppId(args.endpoint_id);
1125
1352
  const client = createClient();
1126
- const suffixes = { cancel: "/cancel", result: "", status: "/status" };
1127
- const path4 = `/${ep}/requests/${args.request_id}${suffixes[action]}`;
1128
- const data = await forwardJson(client, {
1129
- method: action === "cancel" ? "PUT" : "GET",
1130
- path: path4,
1131
- query: action === "status" && args.logs ? { logs: "1" } : void 0,
1132
- target: "queue"
1353
+ const data = await client.generate.status({
1354
+ action,
1355
+ endpoint_id: args.endpoint_id,
1356
+ logs: Boolean(args.logs),
1357
+ request_id: args.request_id
1133
1358
  });
1134
- if (action === "cancel") {
1135
- await confirmCancelled(client, ep, args.request_id);
1136
- }
1137
1359
  let downloaded;
1138
1360
  if (action === "result" && downloadFlag.mode === "on") {
1139
1361
  const refs = extractMediaRefs(data);
@@ -1167,7 +1389,7 @@ var statusCommand = defineCommand({
1167
1389
  }
1168
1390
  });
1169
1391
  var splitList = (value) => {
1170
- if (!value) {
1392
+ if (value === void 0 || value === "") {
1171
1393
  return [];
1172
1394
  }
1173
1395
  return value.split(",").map((s) => s.trim()).filter(Boolean);
@@ -1178,21 +1400,27 @@ var printModels = (data) => {
1178
1400
  if (!isJsonObject(m)) {
1179
1401
  continue;
1180
1402
  }
1181
- const id = String(m.endpoint_id ?? "?");
1403
+ const id = isJsonString(m.endpoint_id) ? m.endpoint_id : "?";
1182
1404
  const meta = isJsonObject(m.metadata) ? m.metadata : {};
1183
- const tags = [];
1184
- if (meta.category) {
1185
- tags.push(String(meta.category));
1186
- }
1187
- if (meta.status) {
1188
- tags.push(String(meta.status));
1189
- }
1405
+ const tags = [meta.category, meta.status].filter(
1406
+ (tag) => isJsonString(tag) && tag !== ""
1407
+ );
1190
1408
  consola.log(`${id}${tags.length > 0 ? ` [${tags.join(", ")}]` : ""}`);
1191
1409
  }
1192
- if (isJsonObject(data) && data.next_cursor) {
1410
+ if (isJsonObject(data) && isJsonString(data.next_cursor) && data.next_cursor !== "") {
1193
1411
  consola.log(`
1194
- next_cursor: ${String(data.next_cursor)}`);
1412
+ next_cursor: ${data.next_cursor}`);
1413
+ }
1414
+ };
1415
+ var MODEL_STATUSES = ["active", "deprecated", "all"];
1416
+ var MODEL_EXPANSIONS = ["openapi-3.0", "enterprise_status"];
1417
+ var pickOne = (allowed, value, flag) => {
1418
+ const found = allowed.find((option) => option === value);
1419
+ if (found === void 0 || found === "") {
1420
+ consola.error(`--${flag} takes ${allowed.join(" | ")}, not "${value}".`);
1421
+ process.exit(1);
1195
1422
  }
1423
+ return found;
1196
1424
  };
1197
1425
  var modelsCommand = defineCommand({
1198
1426
  args: {
@@ -1213,34 +1441,16 @@ var modelsCommand = defineCommand({
1213
1441
  },
1214
1442
  meta: { description: "Search/list available models.", name: "models" },
1215
1443
  run: async ({ args }) => {
1216
- const query = {};
1217
- if (args.query) {
1218
- query.q = args.query;
1219
- }
1220
- if (args.category) {
1221
- query.category = args.category;
1222
- }
1223
- if (args.status && args.status !== "all") {
1224
- query.status = args.status;
1225
- }
1226
- query.limit = args.limit ?? "20";
1227
- if (args.cursor) {
1228
- query.cursor = args.cursor;
1229
- }
1230
1444
  const endpointIds = splitList(args.endpoint_id);
1231
- if (endpointIds.length > 0) {
1232
- query.endpoint_id = endpointIds;
1233
- }
1234
- const expand = splitList(args.expand);
1235
- if (expand.length > 0) {
1236
- query.expand = expand;
1237
- }
1238
- const client = createClient();
1239
- const data = await forwardJson(client, {
1240
- method: "GET",
1241
- path: "/v1/models",
1242
- query,
1243
- target: "platform"
1445
+ const expand = splitList(args.expand).map((e) => pickOne(MODEL_EXPANSIONS, e, "expand"));
1446
+ const data = await createClient().generate.models({
1447
+ category: args.category === void 0 || args.category === "" ? void 0 : args.category,
1448
+ cursor: args.cursor === void 0 || args.cursor === "" ? void 0 : args.cursor,
1449
+ endpoint_id: endpointIds.length > 0 ? endpointIds : void 0,
1450
+ expand: expand.length > 0 ? expand : void 0,
1451
+ limit: args.limit !== void 0 && args.limit !== "" ? Number(args.limit) : 20,
1452
+ query: args.query === void 0 || args.query === "" ? void 0 : args.query,
1453
+ status: args.status !== void 0 && args.status !== "" ? pickOne(MODEL_STATUSES, args.status, "status") : void 0
1244
1454
  });
1245
1455
  if (!writeStructured(data, args)) {
1246
1456
  printModels(data);
@@ -1255,19 +1465,9 @@ var schemaCommand = defineCommand({
1255
1465
  },
1256
1466
  meta: { description: "Fetch a model's input/output schema.", name: "schema" },
1257
1467
  run: async ({ args }) => {
1258
- const expand = args.format === "openapi" ? ["openapi-3.0"] : [];
1259
- const client = createClient();
1260
- const query = {};
1261
- query.endpoint_id = args.endpoint_id;
1262
- query.limit = "1";
1263
- if (expand.length > 0) {
1264
- query.expand = expand;
1265
- }
1266
- const data = await forwardJson(client, {
1267
- method: "GET",
1268
- path: "/v1/models",
1269
- query,
1270
- target: "platform"
1468
+ const data = await createClient().generate.schema({
1469
+ endpoint_id: args.endpoint_id,
1470
+ format: args.format === "openapi" ? "openapi" : "compact"
1271
1471
  });
1272
1472
  if (!writeStructured(data, args)) {
1273
1473
  writeJson(data);
@@ -1281,13 +1481,7 @@ var pricingCommand = defineCommand({
1281
1481
  },
1282
1482
  meta: { description: "Fetch pricing for a model.", name: "pricing" },
1283
1483
  run: async ({ args }) => {
1284
- const client = createClient();
1285
- const data = await forwardJson(client, {
1286
- method: "GET",
1287
- path: "/v1/models/pricing",
1288
- query: { endpoint_id: args.endpoint_id },
1289
- target: "platform"
1290
- });
1484
+ const data = await createClient().generate.pricing({ endpoint_id: args.endpoint_id });
1291
1485
  if (!writeStructured(data, args)) {
1292
1486
  writeJson(data);
1293
1487
  }
@@ -1300,18 +1494,7 @@ var docsCommand = defineCommand({
1300
1494
  },
1301
1495
  meta: { description: "Search generative-model documentation.", name: "docs" },
1302
1496
  run: async ({ args }) => {
1303
- const client = createClient();
1304
- const data = await forwardJson(client, {
1305
- body: {
1306
- id: 1,
1307
- jsonrpc: "2.0",
1308
- method: "tools/call",
1309
- params: { arguments: { query: args.query }, name: "search_fal" }
1310
- },
1311
- method: "POST",
1312
- path: "/docs/mcp",
1313
- target: "docs"
1314
- });
1497
+ const data = await createClient().generate.docs({ query: args.query });
1315
1498
  if (!writeStructured(data, args)) {
1316
1499
  writeJson(data);
1317
1500
  }
@@ -1340,12 +1523,104 @@ var uploadCommand = defineCommand({
1340
1523
  }
1341
1524
  }
1342
1525
  });
1526
+ var mediaCommand = (name, description, schema, submit) => defineCommand({
1527
+ args: {
1528
+ ...mediaFlagArgs(schema.shape),
1529
+ async: {
1530
+ description: "Submit to queue and return request_id without waiting.",
1531
+ type: "boolean"
1532
+ },
1533
+ download: {
1534
+ description: "Download media from result. Optional value is a path or template with {index},{name},{ext},{request_id}.",
1535
+ type: "string"
1536
+ },
1537
+ options: {
1538
+ description: "Any other model input as a JSON object; the flags above win.",
1539
+ type: "string"
1540
+ },
1541
+ ...outputArgs,
1542
+ quiet: { description: "Suppress progress output while waiting.", type: "boolean" }
1543
+ },
1544
+ meta: { description, name },
1545
+ run: async ({ args, rawArgs }) => {
1546
+ const client = createClient();
1547
+ const downloadFlag = parseDownloadFlag(rawArgs);
1548
+ const input = await readMediaInput(
1549
+ schema.shape,
1550
+ rawArgs,
1551
+ async (file) => await uploadFile(client, file)
1552
+ );
1553
+ const parsed = schema.safeParse({ ...input, wait_seconds: 0 });
1554
+ if (!parsed.success) {
1555
+ for (const issue of parsed.error.issues) {
1556
+ consola.error(`--${issue.path.join(".") || "input"}: ${issue.message}`);
1557
+ }
1558
+ process.exit(1);
1559
+ }
1560
+ await finishRun(client, {
1561
+ args,
1562
+ downloadFlag,
1563
+ submission: await submit(client, parsed.data)
1564
+ });
1565
+ }
1566
+ });
1567
+ var mediaCommands = {
1568
+ "3d": mediaCommand(
1569
+ "3d",
1570
+ "Generate a textured 3D model (GLB) from a prompt or an image.",
1571
+ model3dInput,
1572
+ async (client, body) => await client.generate.model3d(body)
1573
+ ),
1574
+ "animate-3d": mediaCommand(
1575
+ "animate-3d",
1576
+ "Rig a humanoid GLB and bake animation clips onto it.",
1577
+ animate3dInput,
1578
+ async (client, body) => await client.generate.animate3d(body)
1579
+ ),
1580
+ image: mediaCommand(
1581
+ "image",
1582
+ "Generate images from a prompt, or edit and combine reference images.",
1583
+ imageInput,
1584
+ async (client, body) => await client.generate.image(body)
1585
+ ),
1586
+ music: mediaCommand(
1587
+ "music",
1588
+ "Compose music from a prompt.",
1589
+ musicInput,
1590
+ async (client, body) => await client.generate.music(body)
1591
+ ),
1592
+ "remove-background": mediaCommand(
1593
+ "remove-background",
1594
+ "Cut an image's subject out onto a transparent background.",
1595
+ removeBackgroundInput,
1596
+ async (client, body) => await client.generate.removeBackground(body)
1597
+ ),
1598
+ sound: mediaCommand(
1599
+ "sound",
1600
+ "Generate a sound effect from a description.",
1601
+ soundInput,
1602
+ async (client, body) => await client.generate.sound(body)
1603
+ ),
1604
+ speech: mediaCommand(
1605
+ "speech",
1606
+ "Speak a line of text.",
1607
+ speechInput,
1608
+ async (client, body) => await client.generate.speech(body)
1609
+ ),
1610
+ video: mediaCommand(
1611
+ "video",
1612
+ "Generate a video clip from a prompt, or animate an image.",
1613
+ videoInput,
1614
+ async (client, body) => await client.generate.video(body)
1615
+ )
1616
+ };
1343
1617
  var generateCommand = defineCommand({
1344
1618
  meta: {
1345
1619
  description: "Generate, edit, and inspect images, video, and audio.",
1346
1620
  name: "generate"
1347
1621
  },
1348
1622
  subCommands: {
1623
+ ...mediaCommands,
1349
1624
  docs: docsCommand,
1350
1625
  models: modelsCommand,
1351
1626
  pricing: pricingCommand,