vibedgames 0.4.1 → 0.5.1

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 (60) hide show
  1. package/README.md +1 -1
  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 +45 -47
  6. package/dist/commands/deploy.d.ts +10 -10
  7. package/dist/commands/deploy.js +157 -137
  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 +53 -45
  12. package/dist/commands/generate.js +343 -286
  13. package/dist/commands/init.d.ts +8 -8
  14. package/dist/commands/init.js +31 -24
  15. package/dist/commands/login.js +14 -14
  16. package/dist/commands/logout.js +2 -2
  17. package/dist/commands/new.d.ts +16 -16
  18. package/dist/commands/new.js +191 -165
  19. package/dist/commands/playtest.d.ts +5 -5
  20. package/dist/commands/playtest.js +103 -97
  21. package/dist/commands/update.d.ts +7 -7
  22. package/dist/commands/update.js +22 -17
  23. package/dist/commands/whoami.d.ts +5 -5
  24. package/dist/commands/whoami.js +11 -10
  25. package/dist/index.js +12 -10
  26. package/dist/lib/api.d.ts +16 -4
  27. package/dist/lib/api.js +20 -32
  28. package/dist/lib/archive.d.ts +4 -4
  29. package/dist/lib/archive.js +123 -102
  30. package/dist/lib/codex.d.ts +46 -15
  31. package/dist/lib/codex.js +178 -108
  32. package/dist/lib/config-file.d.ts +6 -6
  33. package/dist/lib/config-file.js +33 -30
  34. package/dist/lib/config.d.ts +8 -8
  35. package/dist/lib/config.js +38 -30
  36. package/dist/lib/manifest.d.ts +3 -3
  37. package/dist/lib/manifest.js +44 -40
  38. package/dist/lib/media-args.d.ts +8 -6
  39. package/dist/lib/media-args.js +113 -94
  40. package/dist/lib/media-download.d.ts +9 -8
  41. package/dist/lib/media-download.js +158 -144
  42. package/dist/lib/media-poll.d.ts +8 -7
  43. package/dist/lib/media-poll.js +38 -32
  44. package/dist/lib/media-upload.d.ts +1 -1
  45. package/dist/lib/media-upload.js +30 -29
  46. package/dist/lib/output.d.ts +34 -11
  47. package/dist/lib/output.js +28 -20
  48. package/dist/lib/package-manager.d.ts +3 -3
  49. package/dist/lib/package-manager.js +27 -22
  50. package/dist/lib/run.d.ts +4 -4
  51. package/dist/lib/run.js +7 -4
  52. package/dist/lib/strict-args.d.ts +4 -4
  53. package/dist/lib/strict-args.js +29 -19
  54. package/dist/lib/types.d.ts +16 -2
  55. package/dist/lib/types.js +10 -4
  56. package/dist/lib/update.d.ts +4 -4
  57. package/dist/lib/update.js +47 -35
  58. package/dist/lib/upload.d.ts +4 -4
  59. package/dist/lib/upload.js +14 -9
  60. package/package.json +7 -8
@@ -1,106 +1,170 @@
1
1
  import { existsSync, readFileSync, rmSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
- import { join, resolve } from "node:path";
3
+ import path from "node:path";
4
4
  import { defineCommand } from "citty";
5
- import consola from "consola";
5
+ import { consola } from "consola";
6
6
  import { createClient } from "../lib/api.js";
7
7
  import { packSource } from "../lib/archive.js";
8
8
  import { findProjectRoot, projectConfigPath, readProjectConfig, writeProjectConfig, SLUG_RE, } from "../lib/config-file.js";
9
9
  import { buildManifest } from "../lib/manifest.js";
10
10
  import { isJsonOutput, outputArgs, writeStructured } from "../lib/output.js";
11
11
  import { assertKnownFlags } from "../lib/strict-args.js";
12
+ import { isJsonString } from "../lib/types.js";
12
13
  import { uploadAll } from "../lib/upload.js";
13
14
  const deployArgs = {
14
15
  dir: {
15
- type: "positional",
16
+ default: ".",
16
17
  description: "Directory to deploy",
17
18
  required: false,
18
- default: ".",
19
+ type: "positional",
19
20
  },
20
21
  slug: {
21
- type: "string",
22
22
  description: "Override the slug (bypasses vibedgames.json)",
23
23
  required: false,
24
+ type: "string",
24
25
  },
25
26
  source: {
26
- type: "boolean",
27
- description: "Also upload a forkable source archive, letting anyone logged in fork the project.",
28
27
  default: false,
28
+ description: "Also upload a forkable source archive, letting anyone logged in fork the project.",
29
+ type: "boolean",
29
30
  },
30
31
  ...outputArgs,
31
32
  };
33
+ const formatBytes = (n) => {
34
+ if (n < 1024) {
35
+ return `${n} B`;
36
+ }
37
+ if (n < 1024 * 1024) {
38
+ return `${(n / 1024).toFixed(1)} KB`;
39
+ }
40
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
41
+ };
42
+ /** Build-tool projects (package.json present): the root index.html is the
43
+ * source template, the playable game lives in the build output. Deploying the
44
+ * root uploads the whole source tree — wrong content and usually over the file
45
+ * caps — so prefer a build directory when one exists. Checked in popularity
46
+ * order: Vite/Rollup/Parcel → CRA/Preact → Next export/esbuild. */
47
+ const resolveDeployDir = (dir, say) => {
48
+ if (!existsSync(path.join(dir, "package.json"))) {
49
+ return dir;
50
+ }
51
+ for (const name of ["dist", "build", "out"]) {
52
+ if (existsSync(path.join(dir, name, "index.html"))) {
53
+ say(`Project root detected — deploying its build output ${name}/ instead.`);
54
+ return path.join(dir, name);
55
+ }
56
+ }
57
+ consola.warn("This looks like an unbuilt project (package.json, no dist/build/out) — " +
58
+ "run the build first, or the deployed index.html will reference missing source files.");
59
+ return dir;
60
+ };
61
+ const promptForConfig = async (dir, say) => {
62
+ if (!process.stdin.isTTY) {
63
+ consola.error("No slug specified and no vibedgames.json found.\n" +
64
+ " Pass --slug <name> when running without a TTY (e.g. in CI or from a coding agent).\n" +
65
+ " Example: vg deploy ./dist --slug my-game");
66
+ process.exit(1);
67
+ }
68
+ // isJsonString: consola.prompt is typed to resolve a string but can resolve a
69
+ // cancel sentinel at runtime, and a symbol would throw inside RegExp.test.
70
+ const slug = await consola.prompt("Slug (e.g. pong):", { type: "text" });
71
+ if (!isJsonString(slug) || !SLUG_RE.test(slug)) {
72
+ consola.error("Invalid slug. Use lowercase letters, digits, hyphens.");
73
+ process.exit(1);
74
+ }
75
+ const name = await consola.prompt("Name (optional):", { type: "text" });
76
+ const config = {
77
+ name: isJsonString(name) && name.length > 0 ? name : undefined,
78
+ slug,
79
+ };
80
+ writeProjectConfig(dir, config);
81
+ say(`Wrote ${projectConfigPath(dir)}`);
82
+ return config;
83
+ };
84
+ const resolveDeployConfig = async (dir, slugOverride, say) => {
85
+ let config = null;
86
+ try {
87
+ config = readProjectConfig(dir);
88
+ }
89
+ catch (error) {
90
+ consola.error(error instanceof Error ? error.message : String(error));
91
+ process.exit(1);
92
+ }
93
+ if (slugOverride) {
94
+ config = { name: config?.name, slug: slugOverride };
95
+ }
96
+ config ??= await promptForConfig(dir, say);
97
+ if (!SLUG_RE.test(config.slug)) {
98
+ consola.error(`Invalid slug in vibedgames.json: ${config.slug}`);
99
+ process.exit(1);
100
+ }
101
+ return config;
102
+ };
103
+ const packForkableSource = async (dir, slug, say) => {
104
+ const root = findProjectRoot(dir);
105
+ if (!root) {
106
+ consola.warn("No vibedgames.json found above the deploy dir — skipping source upload.");
107
+ return null;
108
+ }
109
+ try {
110
+ const archive = await packSource(root, path.join(tmpdir(), "vibedgames"));
111
+ say(`Source: ${archive.files.length} files, ${formatBytes(archive.bytes)} — forkable via \`vg fork ${slug}\``);
112
+ return archive;
113
+ }
114
+ catch (error) {
115
+ consola.error(`Source archive failed: ${error instanceof Error ? error.message : String(error)}`);
116
+ process.exit(1);
117
+ }
118
+ };
119
+ const uploadSourceArchive = async (archive, upload) => {
120
+ try {
121
+ const res = await fetch(upload.url, {
122
+ body: readFileSync(archive.path),
123
+ headers: upload.headers,
124
+ method: "PUT",
125
+ });
126
+ if (!res.ok) {
127
+ throw new Error(`source upload failed: ${res.status} ${res.statusText}`);
128
+ }
129
+ }
130
+ catch (error) {
131
+ rmSync(archive.path, { force: true });
132
+ consola.error(error instanceof Error ? error.message : String(error));
133
+ process.exit(1);
134
+ }
135
+ };
136
+ const finalizeDeployment = async (client, deploymentId) => {
137
+ try {
138
+ return await client.deploy.finalize({ deploymentId });
139
+ }
140
+ catch (error) {
141
+ consola.error(error instanceof Error ? error.message : String(error));
142
+ process.exit(1);
143
+ }
144
+ };
32
145
  export const deployCommand = defineCommand({
146
+ args: deployArgs,
33
147
  meta: {
34
- name: "deploy",
35
148
  description: "Deploy a game to vibedgames",
149
+ name: "deploy",
36
150
  },
37
- args: deployArgs,
38
151
  run: async ({ args, rawArgs }) => {
39
152
  assertKnownFlags(rawArgs, deployArgs);
40
153
  // Progress narration shares stdout with the payload, so it has to go quiet
41
154
  // whenever stdout is the result rather than a story about it.
42
155
  const structured = isJsonOutput(args) || Boolean(args.field);
43
- const say = structured ? () => { } : (message) => consola.info(message);
44
- const dir = resolve(args.dir);
156
+ const say = structured
157
+ ? () => {
158
+ /* empty */
159
+ }
160
+ : (message) => consola.info(message);
161
+ const dir = path.resolve(args.dir);
45
162
  if (!existsSync(dir)) {
46
163
  consola.error(`Directory does not exist: ${dir}`);
47
164
  process.exit(1);
48
165
  }
49
- // Build-tool projects (package.json present): the root index.html is the
50
- // source template, the playable game lives in the build output. Deploying
51
- // the root uploads the whole source tree — wrong content and usually over
52
- // the file caps — so prefer a build directory when one exists. Checked in
53
- // popularity order: Vite/Rollup/Parcel → CRA/Preact → Next export/esbuild.
54
- let deployDir = dir;
55
- if (existsSync(join(dir, "package.json"))) {
56
- for (const name of ["dist", "build", "out"]) {
57
- if (existsSync(join(dir, name, "index.html"))) {
58
- deployDir = join(dir, name);
59
- say(`Project root detected — deploying its build output ${name}/ instead.`);
60
- break;
61
- }
62
- }
63
- if (deployDir === dir) {
64
- consola.warn("This looks like an unbuilt project (package.json, no dist/build/out) — " +
65
- "run the build first, or the deployed index.html will reference missing source files.");
66
- }
67
- }
68
- // ---- Resolve project config ---------------------------------------------
69
- let config = null;
70
- try {
71
- config = readProjectConfig(dir);
72
- }
73
- catch (err) {
74
- consola.error(err instanceof Error ? err.message : String(err));
75
- process.exit(1);
76
- }
77
- if (args.slug) {
78
- config = { slug: args.slug, name: config?.name };
79
- }
80
- if (!config) {
81
- if (!process.stdin.isTTY) {
82
- consola.error("No slug specified and no vibedgames.json found.\n" +
83
- " Pass --slug <name> when running without a TTY (e.g. in CI or from a coding agent).\n" +
84
- " Example: vg deploy ./dist --slug my-game");
85
- process.exit(1);
86
- }
87
- const slug = await consola.prompt("Slug (e.g. pong):", { type: "text" });
88
- if (typeof slug !== "string" || !SLUG_RE.test(slug)) {
89
- consola.error("Invalid slug. Use lowercase letters, digits, hyphens.");
90
- process.exit(1);
91
- }
92
- const name = await consola.prompt("Name (optional):", { type: "text" });
93
- config = {
94
- slug,
95
- name: typeof name === "string" && name.length > 0 ? name : undefined,
96
- };
97
- writeProjectConfig(dir, config);
98
- say(`Wrote ${projectConfigPath(dir)}`);
99
- }
100
- if (!SLUG_RE.test(config.slug)) {
101
- consola.error(`Invalid slug in vibedgames.json: ${config.slug}`);
102
- process.exit(1);
103
- }
166
+ const deployDir = resolveDeployDir(dir, say);
167
+ const config = await resolveDeployConfig(dir, args.slug, say);
104
168
  // ---- Walk files ---------------------------------------------------------
105
169
  const manifest = buildManifest(deployDir);
106
170
  if (manifest.length === 0) {
@@ -115,112 +179,75 @@ export const deployCommand = defineCommand({
115
179
  const totalBytes = manifest.reduce((acc, f) => acc + f.size, 0);
116
180
  say(`Deploying ${config.slug}: ${manifest.length} files, ${formatBytes(totalBytes)}`);
117
181
  // ---- Pack forkable source (opt-in: source is a publish, --source) -------
118
- let sourceArchive = null;
119
- if (args.source) {
120
- const root = findProjectRoot(dir);
121
- if (!root) {
122
- consola.warn("No vibedgames.json found above the deploy dir — skipping source upload.");
123
- }
124
- else {
125
- try {
126
- sourceArchive = await packSource(root, join(tmpdir(), "vibedgames"));
127
- say(`Source: ${sourceArchive.files.length} files, ${formatBytes(sourceArchive.bytes)} — forkable via \`vg fork ${config.slug}\``);
128
- }
129
- catch (err) {
130
- consola.error(`Source archive failed: ${err instanceof Error ? err.message : String(err)}`);
131
- process.exit(1);
132
- }
133
- }
134
- }
182
+ const sourceArchive = args.source ? await packForkableSource(dir, config.slug, say) : null;
135
183
  // ---- Create deployment --------------------------------------------------
136
184
  const client = createClient();
137
185
  const started = Date.now();
138
186
  let created;
139
187
  try {
140
- created = await client.deploy.create.mutate({
141
- slug: config.slug,
142
- name: config.name,
188
+ created = await client.deploy.create({
143
189
  files: manifest.map((f) => ({
190
+ contentType: f.contentType,
144
191
  path: f.path,
145
- size: f.size,
146
192
  sha256: f.sha256,
147
- contentType: f.contentType,
193
+ size: f.size,
148
194
  })),
195
+ name: config.name,
196
+ slug: config.slug,
149
197
  source: sourceArchive
150
- ? { sha256: sourceArchive.sha256, bytes: sourceArchive.bytes }
198
+ ? { bytes: sourceArchive.bytes, sha256: sourceArchive.sha256 }
151
199
  : undefined,
152
200
  });
153
201
  }
154
- catch (err) {
155
- if (sourceArchive)
202
+ catch (error) {
203
+ if (sourceArchive) {
156
204
  rmSync(sourceArchive.path, { force: true });
157
- consola.error(err instanceof Error ? err.message : String(err));
205
+ }
206
+ consola.error(error instanceof Error ? error.message : String(error));
158
207
  process.exit(1);
159
208
  }
160
209
  // ---- Upload to R2 -------------------------------------------------------
161
- if (!structured)
210
+ if (!structured) {
162
211
  consola.start(`Uploading ${created.uploads.length} files`);
212
+ }
163
213
  try {
164
214
  await uploadAll({
165
215
  files: manifest,
166
- uploads: created.uploads,
167
216
  onProgress: (done, total) => {
168
217
  if (done === total || done % 10 === 0) {
169
218
  say(`Uploaded ${done}/${total}`);
170
219
  }
171
220
  },
221
+ uploads: created.uploads,
172
222
  });
173
223
  }
174
- catch (err) {
175
- if (sourceArchive)
224
+ catch (error) {
225
+ if (sourceArchive) {
176
226
  rmSync(sourceArchive.path, { force: true });
177
- consola.error(err instanceof Error ? err.message : String(err));
227
+ }
228
+ consola.error(error instanceof Error ? error.message : String(error));
178
229
  process.exit(1);
179
230
  }
180
231
  // ---- Upload source archive (best-effort companion to the bundle) -------
181
- if (sourceArchive && created.sourceUpload) {
182
- try {
183
- const res = await fetch(created.sourceUpload.url, {
184
- method: "PUT",
185
- headers: created.sourceUpload.headers,
186
- body: readFileSync(sourceArchive.path),
187
- });
188
- if (!res.ok) {
189
- throw new Error(`source upload failed: ${res.status} ${res.statusText}`);
190
- }
191
- }
192
- catch (err) {
193
- rmSync(sourceArchive.path, { force: true });
194
- consola.error(err instanceof Error ? err.message : String(err));
195
- process.exit(1);
232
+ if (sourceArchive) {
233
+ if (created.sourceUpload) {
234
+ await uploadSourceArchive(sourceArchive, created.sourceUpload);
196
235
  }
197
236
  rmSync(sourceArchive.path, { force: true });
198
237
  }
199
- else if (sourceArchive) {
200
- rmSync(sourceArchive.path, { force: true });
201
- }
202
238
  // ---- Finalize -----------------------------------------------------------
203
- let finalized;
204
- try {
205
- finalized = await client.deploy.finalize.mutate({
206
- deploymentId: created.deploymentId,
207
- });
208
- }
209
- catch (err) {
210
- consola.error(err instanceof Error ? err.message : String(err));
211
- process.exit(1);
212
- }
239
+ const finalized = await finalizeDeployment(client, created.deploymentId);
213
240
  const elapsedMs = Date.now() - started;
214
241
  if (writeStructured({
215
- slug: config.slug,
216
- url: finalized.url,
242
+ bytes: totalBytes,
217
243
  deployment_id: created.deploymentId,
244
+ elapsed_ms: elapsedMs,
218
245
  files: manifest.length,
219
- bytes: totalBytes,
246
+ slug: config.slug,
220
247
  source: sourceArchive
221
- ? { files: sourceArchive.files.length, bytes: sourceArchive.bytes }
248
+ ? { bytes: sourceArchive.bytes, files: sourceArchive.files.length }
222
249
  : null,
223
- elapsed_ms: elapsedMs,
250
+ url: finalized.url,
224
251
  }, args)) {
225
252
  return;
226
253
  }
@@ -228,10 +255,3 @@ export const deployCommand = defineCommand({
228
255
  consola.log(` ${finalized.url}`);
229
256
  },
230
257
  });
231
- function formatBytes(n) {
232
- if (n < 1024)
233
- return `${n} B`;
234
- if (n < 1024 * 1024)
235
- return `${(n / 1024).toFixed(1)} KB`;
236
- return `${(n / (1024 * 1024)).toFixed(1)} MB`;
237
- }
@@ -1,3 +1,3 @@
1
1
  /** Resolve (installing on first use) and exec the factory. Never returns. */
2
- export declare function runFactory(args: string[]): never;
2
+ export declare const runFactory: (args: string[]) => never;
3
3
  export declare const factoryCommand: import("citty").CommandDef<import("citty").ArgsDef>;
@@ -1,8 +1,8 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
- import { join } from "node:path";
3
+ import path from "node:path";
4
4
  import { defineCommand } from "citty";
5
- import consola from "consola";
5
+ import { consola } from "consola";
6
6
  /**
7
7
  * `vg factory` — the autonomous game factory, shipped as an optional plugin.
8
8
  * The vg CLI carries none of it: the factory lives in a per-platform npm
@@ -14,31 +14,34 @@ import consola from "consola";
14
14
  */
15
15
  const PKG = `@vibedgames/factory-${process.platform}-${process.arch}`;
16
16
  const BIN = process.platform === "win32" ? "vg-factory.exe" : "vg-factory";
17
- function npmGlobalRoot() {
17
+ const npmGlobalRoot = () => {
18
18
  try {
19
- const res = spawnSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 30_000 });
20
- if (res.status !== 0 || res.error !== undefined)
19
+ const res = spawnSync("npm", ["root", "-g"], { encoding: "utf-8", timeout: 30_000 });
20
+ if (res.status !== 0 || res.error !== undefined) {
21
21
  return null;
22
+ }
22
23
  const root = res.stdout.trim();
23
24
  return root || null;
24
25
  }
25
26
  catch {
26
27
  return null;
27
28
  }
28
- }
29
+ };
29
30
  /** The installed factory binary, or null. VG_FACTORY_BIN overrides (dev). */
30
- function findBinary() {
31
+ const findBinary = () => {
31
32
  const override = process.env.VG_FACTORY_BIN;
32
- if (override)
33
+ if (override) {
33
34
  return existsSync(override) ? override : null;
35
+ }
34
36
  const root = npmGlobalRoot();
35
- if (!root)
37
+ if (!root) {
36
38
  return null;
37
- const path = join(root, PKG, "bin", BIN);
38
- return existsSync(path) ? path : null;
39
- }
39
+ }
40
+ const bin = path.join(root, PKG, "bin", BIN);
41
+ return existsSync(bin) ? bin : null;
42
+ };
40
43
  /** Resolve (installing on first use) and exec the factory. Never returns. */
41
- export function runFactory(args) {
44
+ export const runFactory = (args) => {
42
45
  let bin = findBinary();
43
46
  if (!bin) {
44
47
  consola.start(`Installing the factory (${PKG})…`);
@@ -56,11 +59,11 @@ export function runFactory(args) {
56
59
  }
57
60
  const result = spawnSync(bin, args, { stdio: "inherit" });
58
61
  process.exit(result.status ?? 1);
59
- }
62
+ };
60
63
  export const factoryCommand = defineCommand({
61
64
  meta: {
62
- name: "factory",
63
65
  description: "Run the vibedgames factory — an autonomous agent that builds a browser game and evolves it like a studio (optional plugin; installs on first use). All arguments are passed through: `vg factory` opens the dashboard, `vg factory start <slug>` resumes a game.",
66
+ name: "factory",
64
67
  },
65
68
  run: ({ rawArgs }) => {
66
69
  // Normally unreachable (index.ts routes `vg factory` before citty), but
@@ -1,29 +1,29 @@
1
1
  export declare const forkCommand: import("citty").CommandDef<{
2
+ readonly field: {
3
+ readonly description: "Print a single value from the JSON result, e.g. --field request_id or --field images[0].url. Prints scalars bare for shell capture.";
4
+ readonly type: "string";
5
+ };
2
6
  readonly json: {
3
- readonly type: "boolean";
4
7
  readonly description: "Print structured JSON to stdout.";
8
+ readonly type: "boolean";
5
9
  };
6
- readonly field: {
10
+ readonly force: {
11
+ readonly default: false;
12
+ readonly description: "Overwrite the target directory if it exists.";
13
+ readonly type: "boolean";
14
+ };
15
+ readonly name: {
16
+ readonly description: "Display name for the fork (defaults to the target slug).";
7
17
  readonly type: "string";
8
- readonly description: "Print a single value from the JSON result, e.g. --field request_id or --field images[0].url. Prints scalars bare for shell capture.";
9
18
  };
10
19
  readonly slug: {
11
- readonly type: "positional";
12
20
  readonly description: "Slug of the project to fork (e.g. bomberman).";
13
21
  readonly required: true;
22
+ readonly type: "positional";
14
23
  };
15
24
  readonly target: {
16
- readonly type: "positional";
17
25
  readonly description: "New slug + directory for the fork. Defaults to <slug>-fork.";
18
26
  readonly required: false;
19
- };
20
- readonly name: {
21
- readonly type: "string";
22
- readonly description: "Display name for the fork (defaults to the target slug).";
23
- };
24
- readonly force: {
25
- readonly type: "boolean";
26
- readonly description: "Overwrite the target directory if it exists.";
27
- readonly default: false;
27
+ readonly type: "positional";
28
28
  };
29
29
  }>;
@@ -1,41 +1,62 @@
1
1
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
- import { join, resolve } from "node:path";
3
+ import path from "node:path";
4
4
  import { defineCommand } from "citty";
5
- import consola from "consola";
5
+ import { consola } from "consola";
6
6
  import { createClient } from "../lib/api.js";
7
7
  import { extractSource } from "../lib/archive.js";
8
8
  import { SLUG_RE } from "../lib/config-file.js";
9
9
  import { isJsonOutput, outputArgs, writeStructured } from "../lib/output.js";
10
10
  import { assertKnownFlags } from "../lib/strict-args.js";
11
+ import { isJsonObject } from "../lib/types.js";
11
12
  const forkArgs = {
13
+ force: {
14
+ default: false,
15
+ description: "Overwrite the target directory if it exists.",
16
+ type: "boolean",
17
+ },
18
+ name: {
19
+ description: "Display name for the fork (defaults to the target slug).",
20
+ type: "string",
21
+ },
12
22
  slug: {
13
- type: "positional",
14
23
  description: "Slug of the project to fork (e.g. bomberman).",
15
24
  required: true,
25
+ type: "positional",
16
26
  },
17
27
  target: {
18
- type: "positional",
19
28
  description: "New slug + directory for the fork. Defaults to <slug>-fork.",
20
29
  required: false,
21
- },
22
- name: {
23
- type: "string",
24
- description: "Display name for the fork (defaults to the target slug).",
25
- },
26
- force: {
27
- type: "boolean",
28
- description: "Overwrite the target directory if it exists.",
29
- default: false,
30
+ type: "positional",
30
31
  },
31
32
  ...outputArgs,
32
33
  };
34
+ const rewritePackageName = (dir, slug) => {
35
+ const pkgPath = path.resolve(dir, "package.json");
36
+ if (!existsSync(pkgPath)) {
37
+ return;
38
+ }
39
+ try {
40
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
41
+ if (!isJsonObject(pkg)) {
42
+ throw new Error("package.json is not a JSON object");
43
+ }
44
+ pkg.name = slug;
45
+ delete pkg.repository;
46
+ delete pkg.bugs;
47
+ delete pkg.homepage;
48
+ writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
49
+ }
50
+ catch (error) {
51
+ consola.warn(`Could not rewrite package.json name: ${error instanceof Error ? error.message : String(error)}`);
52
+ }
53
+ };
33
54
  export const forkCommand = defineCommand({
55
+ args: forkArgs,
34
56
  meta: {
35
- name: "fork",
36
57
  description: "Fork another project's source so you can build on it. Downloads the source a project shipped with `vg deploy`, extracts it locally, and rewrites it to a new slug.",
58
+ name: "fork",
37
59
  },
38
- args: forkArgs,
39
60
  run: async ({ args, rawArgs }) => {
40
61
  assertKnownFlags(rawArgs, forkArgs);
41
62
  const source = args.slug.trim().toLowerCase();
@@ -44,7 +65,7 @@ export const forkCommand = defineCommand({
44
65
  consola.error(`Invalid target slug "${target}". Use lowercase letters, digits, and hyphens.`);
45
66
  process.exit(1);
46
67
  }
47
- const dir = resolve(process.cwd(), target);
68
+ const dir = path.resolve(process.cwd(), target);
48
69
  if (existsSync(dir)) {
49
70
  if (!args.force) {
50
71
  consola.error(`Directory ${dir} already exists. Pass --force to overwrite, or pick another target.`);
@@ -52,42 +73,45 @@ export const forkCommand = defineCommand({
52
73
  }
53
74
  // --force means replace, not merge — clear stale files first so the fork
54
75
  // isn't a dirty mix of the archive and whatever was already there.
55
- rmSync(dir, { recursive: true, force: true });
76
+ rmSync(dir, { force: true, recursive: true });
56
77
  }
57
78
  const client = createClient();
58
79
  // ---- Resolve + download source -----------------------------------------
59
- if (!isJsonOutput(args) && !args.field)
80
+ if (!isJsonOutput(args) && !args.field) {
60
81
  consola.start(`Forking ${source}`);
82
+ }
61
83
  let src;
62
84
  try {
63
- src = await client.deploy.getSource.query({ slug: source });
85
+ src = await client.deploy.getSource({ slug: source });
64
86
  }
65
- catch (err) {
66
- consola.error(err instanceof Error ? err.message : String(err));
87
+ catch (error) {
88
+ consola.error(error instanceof Error ? error.message : String(error));
67
89
  process.exit(1);
68
90
  }
69
- const tmp = join(tmpdir(), "vibedgames", `fork-${process.pid}.tgz`);
70
- mkdirSync(join(tmpdir(), "vibedgames"), { recursive: true });
91
+ const tmp = path.join(tmpdir(), "vibedgames", `fork-${process.pid}.tgz`);
92
+ mkdirSync(path.join(tmpdir(), "vibedgames"), { recursive: true });
71
93
  try {
72
94
  const res = await fetch(src.url);
73
- if (!res.ok)
95
+ if (!res.ok) {
74
96
  throw new Error(`download failed: ${res.status} ${res.statusText}`);
97
+ }
75
98
  writeFileSync(tmp, Buffer.from(await res.arrayBuffer()));
76
99
  await extractSource(tmp, dir);
77
100
  }
78
- catch (err) {
79
- consola.error(err instanceof Error ? err.message : String(err));
101
+ catch (error) {
102
+ consola.error(error instanceof Error ? error.message : String(error));
80
103
  process.exit(1);
81
104
  }
82
105
  finally {
83
106
  rmSync(tmp, { force: true });
84
107
  }
85
108
  // ---- Re-slug the fork (clean slate — no provenance recorded) ------------
86
- const name = args.name ?? target.replace(/-/g, " ");
87
- writeFileSync(resolve(dir, "vibedgames.json"), `${JSON.stringify({ slug: target, name }, null, 2)}\n`);
109
+ const name = args.name ?? target.replaceAll("-", " ");
110
+ writeFileSync(path.resolve(dir, "vibedgames.json"), `${JSON.stringify({ name, slug: target }, null, 2)}\n`);
88
111
  rewritePackageName(dir, target);
89
- if (writeStructured({ slug: target, dir, forkedFrom: source }, args))
112
+ if (writeStructured({ dir, forkedFrom: source, slug: target }, args)) {
90
113
  return;
114
+ }
91
115
  consola.success(`Forked ${source} → ${target}`);
92
116
  consola.log(` ${dir}`);
93
117
  consola.log("");
@@ -98,19 +122,3 @@ export const forkCommand = defineCommand({
98
122
  consola.log(` # then: npm run build && vg deploy ./dist → ${target}.vibedgames.com`);
99
123
  },
100
124
  });
101
- function rewritePackageName(dir, slug) {
102
- const pkgPath = resolve(dir, "package.json");
103
- if (!existsSync(pkgPath))
104
- return;
105
- try {
106
- const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
107
- pkg.name = slug;
108
- delete pkg.repository;
109
- delete pkg.bugs;
110
- delete pkg.homepage;
111
- writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
112
- }
113
- catch (err) {
114
- consola.warn(`Could not rewrite package.json name: ${err instanceof Error ? err.message : String(err)}`);
115
- }
116
- }