vibedgames 0.5.0 → 0.6.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/dist/commands/completions.d.ts +1 -1
  3. package/dist/commands/completions.js +21 -20
  4. package/dist/commands/credits.d.ts +5 -5
  5. package/dist/commands/credits.js +43 -33
  6. package/dist/commands/deploy.d.ts +10 -10
  7. package/dist/commands/deploy.js +155 -139
  8. package/dist/commands/factory.d.ts +1 -1
  9. package/dist/commands/factory.js +18 -15
  10. package/dist/commands/fork.d.ts +14 -14
  11. package/dist/commands/fork.js +51 -46
  12. package/dist/commands/generate.js +318 -264
  13. package/dist/commands/init.d.ts +8 -8
  14. package/dist/commands/init.js +31 -24
  15. package/dist/commands/login.js +12 -12
  16. package/dist/commands/logout.js +2 -2
  17. package/dist/commands/new.d.ts +16 -16
  18. package/dist/commands/new.js +153 -142
  19. package/dist/commands/playtest-run.d.ts +62 -0
  20. package/dist/commands/playtest-run.js +258 -0
  21. package/dist/commands/playtest.d.ts +41 -6
  22. package/dist/commands/playtest.js +114 -101
  23. package/dist/commands/update.d.ts +7 -7
  24. package/dist/commands/update.js +20 -17
  25. package/dist/commands/whoami.d.ts +5 -5
  26. package/dist/commands/whoami.js +8 -7
  27. package/dist/index.js +21 -11
  28. package/dist/lib/api.d.ts +4 -4
  29. package/dist/lib/api.js +6 -12
  30. package/dist/lib/archive.d.ts +4 -4
  31. package/dist/lib/archive.js +121 -104
  32. package/dist/lib/codex.d.ts +45 -15
  33. package/dist/lib/codex.js +175 -106
  34. package/dist/lib/config-file.d.ts +6 -6
  35. package/dist/lib/config-file.js +28 -26
  36. package/dist/lib/config.d.ts +8 -8
  37. package/dist/lib/config.js +31 -33
  38. package/dist/lib/manifest.d.ts +3 -3
  39. package/dist/lib/manifest.js +42 -38
  40. package/dist/lib/media-args.d.ts +7 -7
  41. package/dist/lib/media-args.js +113 -95
  42. package/dist/lib/media-download.d.ts +9 -9
  43. package/dist/lib/media-download.js +148 -134
  44. package/dist/lib/media-poll.d.ts +8 -8
  45. package/dist/lib/media-poll.js +32 -27
  46. package/dist/lib/media-upload.d.ts +2 -2
  47. package/dist/lib/media-upload.js +27 -27
  48. package/dist/lib/output.d.ts +27 -12
  49. package/dist/lib/output.js +26 -26
  50. package/dist/lib/package-manager.d.ts +3 -3
  51. package/dist/lib/package-manager.js +27 -22
  52. package/dist/lib/playtest/agent.d.ts +188 -0
  53. package/dist/lib/playtest/agent.js +610 -0
  54. package/dist/lib/playtest/browser.d.ts +109 -0
  55. package/dist/lib/playtest/browser.js +219 -0
  56. package/dist/lib/playtest/controls.d.ts +47 -0
  57. package/dist/lib/playtest/controls.js +218 -0
  58. package/dist/lib/playtest/errors.d.ts +9 -0
  59. package/dist/lib/playtest/errors.js +12 -0
  60. package/dist/lib/playtest/keys.d.ts +41 -0
  61. package/dist/lib/playtest/keys.js +157 -0
  62. package/dist/lib/playtest/run.d.ts +193 -0
  63. package/dist/lib/playtest/run.js +408 -0
  64. package/dist/lib/run.d.ts +4 -4
  65. package/dist/lib/run.js +7 -4
  66. package/dist/lib/strict-args.d.ts +4 -4
  67. package/dist/lib/strict-args.js +28 -18
  68. package/dist/lib/types.d.ts +5 -5
  69. package/dist/lib/types.js +9 -12
  70. package/dist/lib/update.d.ts +4 -4
  71. package/dist/lib/update.js +41 -32
  72. package/dist/lib/upload.d.ts +4 -4
  73. package/dist/lib/upload.js +14 -9
  74. package/package.json +16 -16
package/dist/lib/codex.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, statSync } from "node:fs";
2
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, statSync } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
- import { basename, dirname, extname, join, resolve } from "node:path";
4
+ import path from "node:path";
5
5
  import spawn from "cross-spawn";
6
6
  import { readExplicitLocalFile } from "./media-args.js";
7
7
  import { disambiguateTargets } from "./media-download.js";
@@ -23,20 +23,52 @@ export class CodexError extends Error {
23
23
  }
24
24
  }
25
25
  /**
26
- * Resolve the effective provider from the `--provider` flag, falling back
27
- * to the `VG_GENERATE_PROVIDER` env var and finally the vibedgames
26
+ * Resolve an explicitly named provider from the `--provider` flag, falling
27
+ * back to the `VG_GENERATE_PROVIDER` env var and finally the vibedgames
28
28
  * default. Unknown values throw so a typo (`--provider coddex`) fails
29
- * loudly instead of silently hitting the paid backend.
29
+ * loudly instead of silently hitting the paid backend. `chooseProvider`
30
+ * layers the automatic Codex routing on top of this.
30
31
  */
31
- export function resolveProvider(flag) {
32
+ export const resolveProvider = (flag) => {
32
33
  const raw = (flag ?? process.env.VG_GENERATE_PROVIDER ?? "").trim().toLowerCase();
33
- if (raw === "codex")
34
+ if (raw === "codex") {
34
35
  return "codex";
36
+ }
35
37
  if (raw === "" || raw === "vibedgames" || raw === "fal" || raw === "default") {
36
38
  return "vibedgames";
37
39
  }
38
40
  throw new Error(`Unknown --provider "${raw}". Supported: vibedgames (default), codex.`);
39
- }
41
+ };
42
+ /** The OpenAI image family — the models a signed-in Codex plan serves itself. */
43
+ export const isOpenAiImageEndpoint = (endpointId) => endpointId === "codex" || /^openai\/gpt-image/iu.test(endpointId);
44
+ /**
45
+ * The `codex` binary this machine would run: `VG_CODEX_BIN` when set (and
46
+ * present), else the first `codex` on PATH. Null when there is none — the
47
+ * signal that keeps automatic routing on the vibedgames runner.
48
+ */
49
+ export const findCodexBinary = (env = process.env) => {
50
+ const pinned = env.VG_CODEX_BIN;
51
+ if (pinned) {
52
+ return existsSync(pinned) ? pinned : null;
53
+ }
54
+ for (const dir of (env.PATH ?? "").split(path.delimiter)) {
55
+ if (!dir) {
56
+ continue;
57
+ }
58
+ for (const name of ["codex", "codex.cmd"]) {
59
+ const candidate = path.join(dir, name);
60
+ try {
61
+ if (statSync(candidate).isFile()) {
62
+ return candidate;
63
+ }
64
+ }
65
+ catch {
66
+ // not here; keep walking PATH
67
+ }
68
+ }
69
+ }
70
+ return null;
71
+ };
40
72
  // Input keys we map onto Codex's natural-language image request. Codex
41
73
  // only exposes a single built-in image model, so most fal-style params
42
74
  // don't apply — we fold the few that have a meaning (prompt, count,
@@ -55,12 +87,29 @@ const REF_KEYS = [
55
87
  ];
56
88
  const MAX_IMAGES = 8;
57
89
  const IMAGE_EXT = new Set(["png", "jpg", "jpeg", "webp", "gif"]);
90
+ const buildSizeHint = (input) => {
91
+ const parts = [];
92
+ const size = input.image_size ?? input.size;
93
+ if (isJsonString(size) && size.trim().length > 0) {
94
+ parts.push(size.trim());
95
+ }
96
+ const aspect = input.aspect_ratio;
97
+ if (isJsonString(aspect) && aspect.trim().length > 0) {
98
+ parts.push(`aspect ratio ${aspect.trim()}`);
99
+ }
100
+ const w = input.width;
101
+ const h = input.height;
102
+ if (isJsonNumber(w) && isJsonNumber(h)) {
103
+ parts.push(`${w}x${h}px`);
104
+ }
105
+ return parts.length > 0 ? parts.join(", ") : undefined;
106
+ };
58
107
  /**
59
108
  * Pull the fields Codex can act on out of the parsed `run` input. Pure:
60
109
  * no filesystem access, so the reference values are returned verbatim and
61
110
  * resolved to local files later.
62
111
  */
63
- export function parseCodexInput(input) {
112
+ export const parseCodexInput = (input) => {
64
113
  let prompt = "";
65
114
  for (const key of PROMPT_KEYS) {
66
115
  const v = input[key];
@@ -80,37 +129,47 @@ export function parseCodexInput(input) {
80
129
  const referenceCandidates = [];
81
130
  for (const key of REF_KEYS) {
82
131
  const v = input[key];
83
- if (isJsonString(v))
132
+ if (isJsonString(v)) {
84
133
  referenceCandidates.push(v);
134
+ }
85
135
  else if (Array.isArray(v)) {
86
- for (const item of v)
87
- if (isJsonString(item))
136
+ for (const item of v) {
137
+ if (isJsonString(item)) {
88
138
  referenceCandidates.push(item);
139
+ }
140
+ }
89
141
  }
90
142
  }
91
- return { prompt, count, sizeHint: buildSizeHint(input), referenceCandidates };
92
- }
93
- function buildSizeHint(input) {
94
- const parts = [];
95
- const size = input.image_size ?? input.size;
96
- if (isJsonString(size) && size.trim().length > 0)
97
- parts.push(size.trim());
98
- const aspect = input.aspect_ratio;
99
- if (isJsonString(aspect) && aspect.trim().length > 0) {
100
- parts.push(`aspect ratio ${aspect.trim()}`);
143
+ return { count, prompt, referenceCandidates, sizeHint: buildSizeHint(input) };
144
+ };
145
+ const isLocalReference = (ref) => !/^(?:https?:|data:)/iu.test(ref);
146
+ /**
147
+ * Pick the backend for one `run`. An explicit `--provider` or
148
+ * `VG_GENERATE_PROVIDER` always wins. Left unset, an OpenAI image endpoint
149
+ * goes to a locally installed Codex CLI — the same model family on the
150
+ * user's own plan, nothing billed to vibedgames — whenever Codex can honour
151
+ * the request (synchronous, local references only). Everything else stays
152
+ * on the vibedgames runner, so video/audio and non-OpenAI image models are
153
+ * unaffected by having Codex installed.
154
+ */
155
+ export const chooseProvider = (flag, ctx) => {
156
+ const named = (flag ?? process.env.VG_GENERATE_PROVIDER ?? "").trim();
157
+ if (named !== "") {
158
+ return { auto: false, provider: resolveProvider(named) };
101
159
  }
102
- const w = input.width;
103
- const h = input.height;
104
- if (isJsonNumber(w) && isJsonNumber(h))
105
- parts.push(`${w}x${h}px`);
106
- return parts.length > 0 ? parts.join(", ") : undefined;
107
- }
160
+ const refs = parseCodexInput(ctx.input).referenceCandidates;
161
+ const eligible = ctx.codexInstalled &&
162
+ !ctx.async &&
163
+ isOpenAiImageEndpoint(ctx.endpointId) &&
164
+ refs.every((ref) => isLocalReference(ref));
165
+ return { auto: eligible, provider: eligible ? "codex" : "vibedgames" };
166
+ };
108
167
  /**
109
168
  * Build the natural-language instruction handed to `codex exec`. We pin
110
169
  * exact output filenames and the working directory so the generated
111
170
  * files land somewhere we can deterministically collect them.
112
171
  */
113
- export function buildCodexPrompt(input, filenames, hasReferences) {
172
+ export const buildCodexPrompt = (input, filenames, hasReferences) => {
114
173
  const n = filenames.length;
115
174
  const noun = n === 1 ? "image" : `${n} images`;
116
175
  const lines = [
@@ -119,21 +178,22 @@ export function buildCodexPrompt(input, filenames, hasReferences) {
119
178
  : `Generate ${noun} using your built-in image generation.`,
120
179
  `Prompt: ${input.prompt}`,
121
180
  ];
122
- if (input.sizeHint)
181
+ if (input.sizeHint) {
123
182
  lines.push(`Size: ${input.sizeHint}.`);
183
+ }
124
184
  lines.push(`Save the output as PNG into the current working directory using exactly ` +
125
185
  `these filenames: ${filenames.join(", ")}.`, `Do not read, create, or modify any other files, and do not write or run code. $imagegen`);
126
186
  return lines.join("\n");
127
- }
187
+ };
128
188
  /**
129
189
  * Choose the on-disk destination for a collected Codex output, mirroring
130
190
  * the `--download` template semantics used for the vibedgames path
131
191
  * ({index}, {ext}, {request_id} placeholders; bare path treated as a
132
192
  * directory or a literal file by extension).
133
193
  */
134
- export function renderLocalTarget(template, index, ext, requestId, count) {
194
+ export const renderLocalTarget = (template, index, ext, requestId, count) => {
135
195
  if (!template) {
136
- return resolve(process.cwd(), `codex-image-${requestId}-${index}.${ext}`);
196
+ return path.resolve(process.cwd(), `codex-image-${requestId}-${index}.${ext}`);
137
197
  }
138
198
  if (template.includes("{")) {
139
199
  const rendered = template
@@ -141,21 +201,20 @@ export function renderLocalTarget(template, index, ext, requestId, count) {
141
201
  .replaceAll("{ext}", ext)
142
202
  .replaceAll("{request_id}", requestId)
143
203
  .replaceAll("{name}", "output");
144
- return resolve(rendered);
204
+ return path.resolve(rendered);
145
205
  }
146
- if (extname(template)) {
147
- if (count <= 1)
148
- return resolve(template);
149
- const e = extname(template);
206
+ if (path.extname(template)) {
207
+ if (count <= 1) {
208
+ return path.resolve(template);
209
+ }
210
+ const e = path.extname(template);
150
211
  const stem = template.slice(0, template.length - e.length);
151
- return resolve(index === 0 ? template : `${stem}_${index}${e}`);
212
+ return path.resolve(index === 0 ? template : `${stem}_${index}${e}`);
152
213
  }
153
- return resolve(template, `codex-image-${index}.${ext}`);
154
- }
155
- function codexHome() {
156
- return process.env.CODEX_HOME ?? join(homedir(), ".codex");
157
- }
158
- function listImages(dir) {
214
+ return path.resolve(template, `codex-image-${index}.${ext}`);
215
+ };
216
+ const codexHome = () => process.env.CODEX_HOME ?? path.join(homedir(), ".codex");
217
+ const listImages = (dir) => {
159
218
  let names;
160
219
  try {
161
220
  names = readdirSync(dir);
@@ -165,41 +224,73 @@ function listImages(dir) {
165
224
  }
166
225
  const out = [];
167
226
  for (const name of names) {
168
- const ext = extname(name).slice(1).toLowerCase();
169
- if (!IMAGE_EXT.has(ext))
227
+ const ext = path.extname(name).slice(1).toLowerCase();
228
+ if (!IMAGE_EXT.has(ext)) {
170
229
  continue;
171
- const full = join(dir, name);
230
+ }
231
+ const full = path.join(dir, name);
172
232
  try {
173
- if (statSync(full).isFile())
233
+ if (statSync(full).isFile()) {
174
234
  out.push(full);
235
+ }
175
236
  }
176
237
  catch {
177
238
  // Raced away between readdir and stat; skip.
178
239
  }
179
240
  }
180
241
  return out.toSorted();
181
- }
242
+ };
182
243
  // Keep the `limit` most-recently-modified paths (by mtime), returned in
183
244
  // stable name order. Used to bound the shared-store fallback.
184
- function pickNewest(paths, limit) {
185
- if (paths.length <= limit)
245
+ const pickNewest = (paths, limit) => {
246
+ if (paths.length <= limit) {
186
247
  return paths;
248
+ }
187
249
  const withTime = paths.map((p) => {
188
250
  let mtimeMs = 0;
189
251
  try {
190
- mtimeMs = statSync(p).mtimeMs;
252
+ ({ mtimeMs } = statSync(p));
191
253
  }
192
254
  catch {
193
255
  // Gone between listing and stat; sort it oldest.
194
256
  }
195
- return { p, mtimeMs };
257
+ return { mtimeMs, p };
196
258
  });
197
259
  return withTime
198
260
  .toSorted((a, b) => b.mtimeMs - a.mtimeMs)
199
261
  .slice(0, limit)
200
262
  .map((x) => x.p)
201
263
  .toSorted();
202
- }
264
+ };
265
+ const spawnCodex = (bin, args, cwd) =>
266
+ // oxlint-disable-next-line promise/avoid-new -- child_process.spawn is event-based
267
+ new Promise((resolve) => {
268
+ const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
269
+ let output = "";
270
+ // Forward Codex's own stdout/stderr straight to our stderr so the user
271
+ // sees its progress and messages directly. It goes to stderr (never
272
+ // stdout) so it can't corrupt our `--json` payload. We also buffer it
273
+ // so a failure can surface the tail even for a caller that isn't
274
+ // watching the live stream.
275
+ child.stdout?.on("data", (c) => {
276
+ output += c.toString("utf-8");
277
+ process.stderr.write(c);
278
+ });
279
+ child.stderr?.on("data", (c) => {
280
+ output += c.toString("utf-8");
281
+ process.stderr.write(c);
282
+ });
283
+ child.on("error", (err) => {
284
+ resolve({
285
+ code: 1,
286
+ notFound: err.code === "ENOENT",
287
+ output: output + err.message,
288
+ });
289
+ });
290
+ child.on("close", (code) => {
291
+ resolve({ code: code ?? 1, notFound: false, output });
292
+ });
293
+ });
203
294
  /**
204
295
  * Delegate image generation to the local `codex` CLI. Runs
205
296
  * `codex exec` in an isolated temp workspace, then collects the produced
@@ -207,7 +298,7 @@ function pickNewest(paths, limit) {
207
298
  * `generated_images` store). Throws with actionable guidance when Codex
208
299
  * is missing, fails, or produces nothing.
209
300
  */
210
- export async function generateImagesWithCodex(opts) {
301
+ export const generateImagesWithCodex = async (opts) => {
211
302
  const parsed = parseCodexInput(opts.input);
212
303
  if (!parsed.prompt) {
213
304
  throw new CodexError("codex image generation requires a prompt (--prompt).");
@@ -219,13 +310,15 @@ export async function generateImagesWithCodex(opts) {
219
310
  const ignoredReferences = [];
220
311
  for (const candidate of parsed.referenceCandidates) {
221
312
  const local = readExplicitLocalFile(candidate);
222
- if (local)
313
+ if (local) {
223
314
  references.push(local.path);
224
- else
315
+ }
316
+ else {
225
317
  ignoredReferences.push(candidate);
318
+ }
226
319
  }
227
320
  const requestId = randomBytes(4).toString("hex");
228
- const workDir = mkdtempSync(join(tmpdir(), "vg-codex-"));
321
+ const workDir = mkdtempSync(path.join(tmpdir(), "vg-codex-"));
229
322
  const filenames = Array.from({ length: parsed.count }, (_, i) => `output-${i}.png`);
230
323
  const prompt = buildCodexPrompt(parsed, filenames, references.length > 0);
231
324
  const bin = process.env.VG_CODEX_BIN ?? "codex";
@@ -241,7 +334,7 @@ export async function generateImagesWithCodex(opts) {
241
334
  ];
242
335
  // Snapshot Codex's default image store so we can tell which files this
243
336
  // run produced if the model saves there instead of the workspace.
244
- const storeDir = join(codexHome(), "generated_images");
337
+ const storeDir = path.join(codexHome(), "generated_images");
245
338
  const before = new Set(listImages(storeDir));
246
339
  const outcome = await spawnCodex(bin, args, workDir);
247
340
  if (outcome.notFound) {
@@ -259,7 +352,7 @@ export async function generateImagesWithCodex(opts) {
259
352
  // workspace must NOT count as output nor suppress the store fallback.
260
353
  const pinned = new Set(filenames);
261
354
  const fromWork = listImages(workDir);
262
- const pinnedWork = fromWork.filter((p) => pinned.has(basename(p)));
355
+ const pinnedWork = fromWork.filter((p) => pinned.has(path.basename(p)));
263
356
  // Fallback for when Codex ignored the workspace and wrote to its shared
264
357
  // store instead. That store is not scoped to this invocation, so cap to
265
358
  // the newest `count` new files to limit picking up a concurrent run's
@@ -270,23 +363,25 @@ export async function generateImagesWithCodex(opts) {
270
363
  // any workspace PNG (Codex saved images but chose different names) —
271
364
  // capped to `count` like the store branch so an unexpected extra file
272
365
  // can't inflate the output set.
273
- const rawFiles = pinnedWork.length > 0
274
- ? pinnedWork
275
- : fromStore.length > 0
276
- ? fromStore
277
- : pickNewest(fromWork, parsed.count);
366
+ let rawFiles = pickNewest(fromWork, parsed.count);
367
+ if (pinnedWork.length > 0) {
368
+ rawFiles = pinnedWork;
369
+ }
370
+ else if (fromStore.length > 0) {
371
+ rawFiles = fromStore;
372
+ }
278
373
  if (rawFiles.length === 0) {
279
374
  throw new CodexError(`codex produced no image files. It may have declined the request or lack ` +
280
375
  `image-generation access on the signed-in plan.`, { output: outcome.output });
281
376
  }
282
- return { requestId, prompt, rawFiles, ignoredReferences };
283
- }
377
+ return { ignoredReferences, prompt, rawFiles, requestId };
378
+ };
284
379
  /**
285
380
  * Copy Codex's raw outputs to their final destinations per the
286
381
  * `--download` template (or default cwd naming). Returns the written
287
382
  * paths and any per-file failures.
288
383
  */
289
- export function placeCodexOutputs(rawFiles, template, requestId) {
384
+ export const placeCodexOutputs = (rawFiles, template, requestId) => {
290
385
  const downloaded = [];
291
386
  // Keyed `url` (holding the source path) to match the shape the
292
387
  // vibedgames run/status paths use for `download_failures`, so agents
@@ -298,51 +393,25 @@ export function placeCodexOutputs(rawFiles, template, requestId) {
298
393
  // {index} (e.g. `{request_id}.{ext}` or a fixed filename) would
299
394
  // otherwise overwrite earlier outputs while still reporting each path.
300
395
  const rendered = rawFiles.map((source, index) => {
301
- const ext = extname(source).slice(1).toLowerCase() || "png";
396
+ const ext = path.extname(source).slice(1).toLowerCase() || "png";
302
397
  return renderLocalTarget(template, index, ext, requestId, rawFiles.length);
303
398
  });
304
399
  const targets = disambiguateTargets(rendered);
305
- rawFiles.forEach((source, index) => {
400
+ for (const [index, source] of rawFiles.entries()) {
306
401
  const target = targets[index];
402
+ if (target === undefined) {
403
+ continue;
404
+ }
307
405
  try {
308
- if (resolve(source) !== target) {
309
- mkdirSync(dirname(target), { recursive: true });
406
+ if (path.resolve(source) !== target) {
407
+ mkdirSync(path.dirname(target), { recursive: true });
310
408
  copyFileSync(source, target);
311
409
  }
312
410
  downloaded.push(target);
313
411
  }
314
- catch (err) {
315
- failed.push({ url: source, error: err instanceof Error ? err.message : String(err) });
412
+ catch (error) {
413
+ failed.push({ error: error instanceof Error ? error.message : String(error), url: source });
316
414
  }
317
- });
415
+ }
318
416
  return { downloaded, failed };
319
- }
320
- function spawnCodex(bin, args, cwd) {
321
- return new Promise((resolvePromise) => {
322
- const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
323
- let output = "";
324
- // Forward Codex's own stdout/stderr straight to our stderr so the user
325
- // sees its progress and messages directly. It goes to stderr (never
326
- // stdout) so it can't corrupt our `--json` payload. We also buffer it
327
- // so a failure can surface the tail even for a caller that isn't
328
- // watching the live stream.
329
- child.stdout?.on("data", (c) => {
330
- output += c.toString("utf8");
331
- process.stderr.write(c);
332
- });
333
- child.stderr?.on("data", (c) => {
334
- output += c.toString("utf8");
335
- process.stderr.write(c);
336
- });
337
- child.on("error", (err) => {
338
- resolvePromise({
339
- code: 1,
340
- output: output + err.message,
341
- notFound: err.code === "ENOENT",
342
- });
343
- });
344
- child.on("close", (code) => {
345
- resolvePromise({ code: code ?? 1, output, notFound: false });
346
- });
347
- });
348
- }
417
+ };
@@ -1,7 +1,7 @@
1
- export type ProjectConfig = {
1
+ export interface ProjectConfig {
2
2
  slug: string;
3
3
  name?: string;
4
- };
4
+ }
5
5
  /**
6
6
  * The slug grammar every surface must agree on — it is the deploy target, the
7
7
  * fork target, and the label in `{slug}.vibedgames.com`. Kept here rather than
@@ -10,7 +10,7 @@ export type ProjectConfig = {
10
10
  export declare const SLUG_RE: RegExp;
11
11
  /** The directory containing the nearest vibedgames.json at or above `dir`,
12
12
  * or null if none — i.e. the project root to archive as forkable source. */
13
- export declare function findProjectRoot(dir: string): string | null;
14
- export declare function readProjectConfig(dir: string): ProjectConfig | null;
15
- export declare function writeProjectConfig(dir: string, config: ProjectConfig): void;
16
- export declare function projectConfigPath(dir: string): string;
13
+ export declare const findProjectRoot: (dir: string) => string | null;
14
+ export declare const readProjectConfig: (dir: string) => ProjectConfig | null;
15
+ export declare const writeProjectConfig: (dir: string, config: ProjectConfig) => void;
16
+ export declare const projectConfigPath: (dir: string) => string;
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, join, resolve } from "node:path";
2
+ import path from "node:path";
3
3
  import { isJsonObject, isJsonString } from "./types.js";
4
4
  const FILENAME = "vibedgames.json";
5
5
  /**
@@ -7,46 +7,48 @@ const FILENAME = "vibedgames.json";
7
7
  * fork target, and the label in `{slug}.vibedgames.com`. Kept here rather than
8
8
  * per-command so a validator can't drift and reject a slug that deploy accepts.
9
9
  */
10
- export const SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
10
+ export const SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/u;
11
11
  // Walk from `dir` up toward the filesystem root, stopping at the first
12
12
  // vibedgames.json. Lets `vg deploy ./dist` pick up the config from the
13
13
  // project root even when the build step doesn't copy it into the output.
14
- function findConfigPath(dir) {
15
- let current = resolve(dir);
14
+ const findConfigPath = (dir) => {
15
+ let current = path.resolve(dir);
16
16
  while (true) {
17
- const candidate = join(current, FILENAME);
18
- if (existsSync(candidate))
17
+ const candidate = path.join(current, FILENAME);
18
+ if (existsSync(candidate)) {
19
19
  return candidate;
20
- const parent = dirname(current);
21
- if (parent === current)
20
+ }
21
+ const parent = path.dirname(current);
22
+ if (parent === current) {
22
23
  return null;
24
+ }
23
25
  current = parent;
24
26
  }
25
- }
27
+ };
26
28
  /** The directory containing the nearest vibedgames.json at or above `dir`,
27
29
  * or null if none — i.e. the project root to archive as forkable source. */
28
- export function findProjectRoot(dir) {
29
- const path = findConfigPath(dir);
30
- return path ? dirname(path) : null;
31
- }
32
- export function readProjectConfig(dir) {
33
- const path = findConfigPath(dir);
34
- if (!path)
30
+ export const findProjectRoot = (dir) => {
31
+ const found = findConfigPath(dir);
32
+ return found ? path.dirname(found) : null;
33
+ };
34
+ export const readProjectConfig = (dir) => {
35
+ const file = findConfigPath(dir);
36
+ if (!file) {
35
37
  return null;
36
- const raw = readFileSync(path, "utf-8");
38
+ }
39
+ const raw = readFileSync(file, "utf-8");
37
40
  const parsed = JSON.parse(raw);
38
41
  if (!isJsonObject(parsed) || !isJsonString(parsed.slug)) {
39
42
  throw new Error(`${FILENAME} is malformed — missing "slug".`);
40
43
  }
41
44
  const config = { slug: parsed.slug };
42
- if (isJsonString(parsed.name))
45
+ if (isJsonString(parsed.name)) {
43
46
  config.name = parsed.name;
47
+ }
44
48
  return config;
45
- }
46
- export function writeProjectConfig(dir, config) {
47
- const path = join(dir, FILENAME);
48
- writeFileSync(path, JSON.stringify(config, null, 2) + "\n");
49
- }
50
- export function projectConfigPath(dir) {
51
- return join(dir, FILENAME);
52
- }
49
+ };
50
+ export const writeProjectConfig = (dir, config) => {
51
+ const file = path.join(dir, FILENAME);
52
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
53
+ };
54
+ export const projectConfigPath = (dir) => path.join(dir, FILENAME);
@@ -1,11 +1,11 @@
1
- type Config = {
1
+ interface Config {
2
2
  token: string;
3
3
  baseUrl: string;
4
- };
5
- export declare function getConfigDir(): string;
6
- export declare function getConfig(): Config | null;
7
- export declare function saveConfig(config: Config): void;
8
- export declare function clearConfig(): void;
9
- export declare function getBaseUrl(): string;
10
- export declare function getToken(): string | null;
4
+ }
5
+ export declare const getConfigDir: () => string;
6
+ export declare const getConfig: () => Config | null;
7
+ export declare const saveConfig: (config: Config) => void;
8
+ export declare const clearConfig: () => void;
9
+ export declare const getBaseUrl: () => string;
10
+ export declare const getToken: () => string | null;
11
11
  export {};
@@ -1,56 +1,54 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { join } from "node:path";
3
+ import path from "node:path";
4
4
  import { isJsonObject, isJsonString } from "./types.js";
5
- export function getConfigDir() {
5
+ export const getConfigDir = () => {
6
6
  const xdg = process.env.XDG_CONFIG_HOME;
7
- const base = xdg ?? join(homedir(), ".config");
8
- return join(base, "vg");
9
- }
10
- function getConfigPath() {
11
- return join(getConfigDir(), "auth.json");
12
- }
13
- export function getConfig() {
14
- const path = getConfigPath();
15
- if (!existsSync(path))
7
+ const base = xdg ?? path.join(homedir(), ".config");
8
+ return path.join(base, "vg");
9
+ };
10
+ const getConfigPath = () => path.join(getConfigDir(), "auth.json");
11
+ export const getConfig = () => {
12
+ const file = getConfigPath();
13
+ if (!existsSync(file)) {
16
14
  return null;
15
+ }
17
16
  let raw;
18
17
  try {
19
- raw = JSON.parse(readFileSync(path, "utf-8"));
18
+ raw = JSON.parse(readFileSync(file, "utf-8"));
20
19
  }
21
20
  catch {
22
21
  return null;
23
22
  }
24
23
  // auth.json is only ever written by saveConfig, so both fields are present
25
24
  // in practice; a hand-corrupted file reads as "not logged in".
26
- if (!isJsonObject(raw))
25
+ if (!isJsonObject(raw)) {
27
26
  return null;
27
+ }
28
28
  const { token, baseUrl } = raw;
29
- if (!isJsonString(token) || !isJsonString(baseUrl))
29
+ if (!isJsonString(token) || !isJsonString(baseUrl)) {
30
30
  return null;
31
- return { token, baseUrl };
32
- }
33
- export function saveConfig(config) {
31
+ }
32
+ return { baseUrl, token };
33
+ };
34
+ export const saveConfig = (config) => {
34
35
  const dir = getConfigDir();
35
36
  if (!existsSync(dir)) {
36
- mkdirSync(dir, { recursive: true, mode: 0o700 });
37
+ mkdirSync(dir, { mode: 0o700, recursive: true });
37
38
  }
38
39
  writeFileSync(getConfigPath(), JSON.stringify(config, null, 2), {
39
40
  mode: 0o600,
40
41
  });
41
- }
42
- export function clearConfig() {
43
- const path = getConfigPath();
44
- if (existsSync(path)) {
45
- unlinkSync(path);
42
+ };
43
+ export const clearConfig = () => {
44
+ const file = getConfigPath();
45
+ if (existsSync(file)) {
46
+ unlinkSync(file);
46
47
  }
47
- }
48
- export function getBaseUrl() {
49
- return process.env.VG_API_URL ?? getConfig()?.baseUrl ?? "https://vibedgames.com";
50
- }
51
- export function getToken() {
52
- // VG_TOKEN lets local/CI runs authenticate without touching the saved
53
- // login (e.g. a seeded dev session), so headless testing never clobbers
54
- // the user's real `vg login` credentials.
55
- return process.env.VG_TOKEN ?? getConfig()?.token ?? null;
56
- }
48
+ };
49
+ export const getBaseUrl = () => process.env.VG_API_URL ?? getConfig()?.baseUrl ?? "https://vibedgames.com";
50
+ export const getToken = () =>
51
+ // VG_TOKEN lets local/CI runs authenticate without touching the saved
52
+ // login (e.g. a seeded dev session), so headless testing never clobbers
53
+ // the user's real `vg login` credentials.
54
+ process.env.VG_TOKEN ?? getConfig()?.token ?? null;