vibedgames 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -64,7 +64,7 @@ of failing with a bare exit code.
64
64
  installed as a platform-specific optional package on first use — the CLI itself
65
65
  carries none of it.
66
66
 
67
- `vg generate` calls the `generate.forward` tRPC proc — the server holds the
67
+ `vg generate` calls the `generate.forward` proc — the server holds the
68
68
  provider API key, so generation works for any logged-in user with no local keys.
69
69
 
70
70
  ## Using with a coding agent
@@ -1,6 +1,6 @@
1
1
  import { defineCommand } from "citty";
2
2
  import consola from "consola";
3
- import { createClient } from "../lib/api.js";
3
+ import { authErrorCode, createClient } from "../lib/api.js";
4
4
  import { getToken } from "../lib/config.js";
5
5
  import { outputArgs, writeStructured } from "../lib/output.js";
6
6
  import { assertKnownFlags } from "../lib/strict-args.js";
@@ -53,18 +53,6 @@ function formatWhen(date, now) {
53
53
  opts.year = "numeric";
54
54
  return date.toLocaleDateString("en-US", opts);
55
55
  }
56
- function authErrorCode(err) {
57
- if (typeof err === "object" && err !== null && "data" in err) {
58
- const data = err.data;
59
- if (typeof data === "object" &&
60
- data !== null &&
61
- "code" in data &&
62
- typeof data.code === "string") {
63
- return data.code;
64
- }
65
- }
66
- return null;
67
- }
68
56
  export const creditsCommand = defineCommand({
69
57
  meta: {
70
58
  name: "credits",
@@ -80,7 +68,7 @@ export const creditsCommand = defineCommand({
80
68
  }
81
69
  const client = createClient();
82
70
  try {
83
- const { balanceMicro, entries } = await client.credits.me.query();
71
+ const { balanceMicro, entries } = await client.credits.me();
84
72
  const payload = {
85
73
  balance_micro: balanceMicro,
86
74
  balance_usd: balanceMicro / MICRO_PER_USD,
@@ -9,6 +9,7 @@ import { findProjectRoot, projectConfigPath, readProjectConfig, writeProjectConf
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: {
@@ -84,15 +85,18 @@ export const deployCommand = defineCommand({
84
85
  " Example: vg deploy ./dist --slug my-game");
85
86
  process.exit(1);
86
87
  }
88
+ // isJsonString: consola.prompt is typed to resolve a string but can
89
+ // resolve a cancel sentinel at runtime, and a symbol would throw
90
+ // inside RegExp.test.
87
91
  const slug = await consola.prompt("Slug (e.g. pong):", { type: "text" });
88
- if (typeof slug !== "string" || !SLUG_RE.test(slug)) {
92
+ if (!isJsonString(slug) || !SLUG_RE.test(slug)) {
89
93
  consola.error("Invalid slug. Use lowercase letters, digits, hyphens.");
90
94
  process.exit(1);
91
95
  }
92
96
  const name = await consola.prompt("Name (optional):", { type: "text" });
93
97
  config = {
94
98
  slug,
95
- name: typeof name === "string" && name.length > 0 ? name : undefined,
99
+ name: isJsonString(name) && name.length > 0 ? name : undefined,
96
100
  };
97
101
  writeProjectConfig(dir, config);
98
102
  say(`Wrote ${projectConfigPath(dir)}`);
@@ -137,7 +141,7 @@ export const deployCommand = defineCommand({
137
141
  const started = Date.now();
138
142
  let created;
139
143
  try {
140
- created = await client.deploy.create.mutate({
144
+ created = await client.deploy.create({
141
145
  slug: config.slug,
142
146
  name: config.name,
143
147
  files: manifest.map((f) => ({
@@ -202,7 +206,7 @@ export const deployCommand = defineCommand({
202
206
  // ---- Finalize -----------------------------------------------------------
203
207
  let finalized;
204
208
  try {
205
- finalized = await client.deploy.finalize.mutate({
209
+ finalized = await client.deploy.finalize({
206
210
  deploymentId: created.deploymentId,
207
211
  });
208
212
  }
@@ -8,6 +8,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 = {
12
13
  slug: {
13
14
  type: "positional",
@@ -60,7 +61,7 @@ export const forkCommand = defineCommand({
60
61
  consola.start(`Forking ${source}`);
61
62
  let src;
62
63
  try {
63
- src = await client.deploy.getSource.query({ slug: source });
64
+ src = await client.deploy.getSource({ slug: source });
64
65
  }
65
66
  catch (err) {
66
67
  consola.error(err instanceof Error ? err.message : String(err));
@@ -104,6 +105,8 @@ function rewritePackageName(dir, slug) {
104
105
  return;
105
106
  try {
106
107
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
108
+ if (!isJsonObject(pkg))
109
+ throw new Error("package.json is not a JSON object");
107
110
  pkg.name = slug;
108
111
  delete pkg.repository;
109
112
  delete pkg.bugs;
@@ -1,26 +1,25 @@
1
1
  import { defineCommand } from "citty";
2
2
  import consola from "consola";
3
- import { createClient } from "../lib/api.js";
3
+ import { createClient, forwardJson } from "../lib/api.js";
4
4
  import { CodexError, generateImagesWithCodex, placeCodexOutputs, resolveProvider, } from "../lib/codex.js";
5
- import { parseDownloadFlag, parseRunInput, readExplicitLocalFile } from "../lib/media-args.js";
5
+ import { parseDownloadFlag, parseRunInput, readExplicitLocalFile, } from "../lib/media-args.js";
6
6
  import { downloadMedia, extractMediaRefs } from "../lib/media-download.js";
7
7
  import { endpointPath, queueAppId, waitForCompletion } from "../lib/media-poll.js";
8
8
  import { uploadFile } from "../lib/media-upload.js";
9
9
  import { isJsonOutput, outputArgs, writeJson, writeStructured } from "../lib/output.js";
10
- import { isRecord } from "../lib/types.js";
11
- // Action-specific fields for the status-command payload. `result` wraps
12
- // the raw fal payload under `result:` so fal's own keys can't clobber
13
- // our top-level (action / endpoint_id / request_id). `status` cherry-
14
- // picks known fields for the same reason.
10
+ import { isJsonNumber, isJsonObject, isJsonString, } from "../lib/types.js";
15
11
  function buildActionFields(action, data) {
16
12
  if (action === "result")
17
13
  return { result: data };
18
- if (action === "status" && isRecord(data)) {
19
- return {
20
- status: typeof data.status === "string" ? data.status : undefined,
21
- queue_position: typeof data.queue_position === "number" ? data.queue_position : undefined,
22
- logs: data.logs,
23
- };
14
+ if (action === "status" && isJsonObject(data)) {
15
+ const fields = {};
16
+ if (isJsonString(data.status))
17
+ fields.status = data.status;
18
+ if (isJsonNumber(data.queue_position))
19
+ fields.queue_position = data.queue_position;
20
+ if (data.logs !== undefined)
21
+ fields.logs = data.logs;
22
+ return fields;
24
23
  }
25
24
  return {};
26
25
  }
@@ -71,13 +70,13 @@ const runCommand = defineCommand({
71
70
  return;
72
71
  }
73
72
  const client = createClient();
74
- const submission = await client.generate.forward.mutate({
73
+ const submission = await forwardJson(client, {
75
74
  target: "queue",
76
75
  method: "POST",
77
76
  path: `/${endpointPath(endpoint_id)}`,
78
77
  body: finalInput,
79
78
  });
80
- const requestId = isRecord(submission) && typeof submission.request_id === "string"
79
+ const requestId = isJsonObject(submission) && isJsonString(submission.request_id)
81
80
  ? submission.request_id
82
81
  : null;
83
82
  if (!requestId) {
@@ -113,14 +112,15 @@ const runCommand = defineCommand({
113
112
  endpoint_id,
114
113
  request_id: completed.request_id,
115
114
  result: completed.result,
116
- ...(downloaded ? { downloaded_files: downloaded.downloaded } : {}),
117
- ...(downloaded && downloaded.failed.length > 0
118
- ? { download_failures: downloaded.failed }
119
- : {}),
120
- ...(downloaded && downloaded.mislabeled.length > 0
121
- ? { download_format_mismatches: downloaded.mislabeled }
122
- : {}),
123
115
  };
116
+ if (downloaded) {
117
+ payload.downloaded_files = downloaded.downloaded;
118
+ if (downloaded.failed.length > 0)
119
+ payload.download_failures = downloaded.failed;
120
+ if (downloaded.mislabeled.length > 0) {
121
+ payload.download_format_mismatches = downloaded.mislabeled;
122
+ }
123
+ }
124
124
  if (!writeStructured(payload, args)) {
125
125
  consola.success(`Run completed (${completed.request_id})`);
126
126
  if (downloaded) {
@@ -197,9 +197,11 @@ async function runViaCodex(opts) {
197
197
  request_id: requestId,
198
198
  result: { provider: "codex", prompt, images: downloaded.map((path) => ({ path })) },
199
199
  downloaded_files: downloaded,
200
- ...(failed.length > 0 ? { download_failures: failed } : {}),
201
- ...(ignoredReferences.length > 0 ? { ignored_references: ignoredReferences } : {}),
202
200
  };
201
+ if (failed.length > 0)
202
+ payload.download_failures = failed;
203
+ if (ignoredReferences.length > 0)
204
+ payload.ignored_references = ignoredReferences;
203
205
  if (!writeStructured(payload, args)) {
204
206
  consola.success(`Codex generated ${downloaded.length} image(s) (${requestId})`);
205
207
  for (const path of downloaded)
@@ -247,7 +249,7 @@ const statusCommand = defineCommand({
247
249
  : action === "result"
248
250
  ? `/${ep}/requests/${args.request_id}`
249
251
  : `/${ep}/requests/${args.request_id}/status`;
250
- const data = await client.generate.forward.mutate({
252
+ const data = await forwardJson(client, {
251
253
  target: "queue",
252
254
  method: action === "cancel" ? "PUT" : "GET",
253
255
  path,
@@ -262,12 +264,12 @@ const statusCommand = defineCommand({
262
264
  for (let attempt = 0; attempt < 3; attempt++) {
263
265
  await new Promise((resolve) => setTimeout(resolve, 1_000));
264
266
  try {
265
- const poll = await client.generate.forward.mutate({
267
+ const poll = await forwardJson(client, {
266
268
  target: "queue",
267
269
  method: "GET",
268
270
  path: statusPath,
269
271
  });
270
- const status = isRecord(poll) && typeof poll.status === "string" ? poll.status.toUpperCase() : "";
272
+ const status = isJsonObject(poll) && isJsonString(poll.status) ? poll.status.toUpperCase() : "";
271
273
  if (["CANCELLED", "FAILED", "COMPLETED"].includes(status))
272
274
  break;
273
275
  }
@@ -285,25 +287,25 @@ const statusCommand = defineCommand({
285
287
  requestId: args.request_id,
286
288
  });
287
289
  }
288
- const actionFields = buildActionFields(action, data);
289
290
  const payload = {
290
291
  action,
291
292
  endpoint_id: args.endpoint_id,
292
293
  request_id: args.request_id,
293
- ...actionFields,
294
- ...(downloaded ? { downloaded_files: downloaded.downloaded } : {}),
295
- ...(downloaded && downloaded.failed.length > 0
296
- ? { download_failures: downloaded.failed }
297
- : {}),
298
- ...(downloaded && downloaded.mislabeled.length > 0
299
- ? { download_format_mismatches: downloaded.mislabeled }
300
- : {}),
294
+ ...buildActionFields(action, data),
301
295
  };
296
+ if (downloaded) {
297
+ payload.downloaded_files = downloaded.downloaded;
298
+ if (downloaded.failed.length > 0)
299
+ payload.download_failures = downloaded.failed;
300
+ if (downloaded.mislabeled.length > 0) {
301
+ payload.download_format_mismatches = downloaded.mislabeled;
302
+ }
303
+ }
302
304
  if (!writeStructured(payload, args)) {
303
305
  if (action === "status") {
304
- const status = isRecord(data) && typeof data.status === "string" ? data.status : "?";
306
+ const status = isJsonObject(data) && isJsonString(data.status) ? data.status : "?";
305
307
  consola.log(`status: ${status}`);
306
- if (isRecord(data) && typeof data.queue_position === "number") {
308
+ if (isJsonObject(data) && isJsonNumber(data.queue_position)) {
307
309
  consola.log(`queue_position: ${data.queue_position}`);
308
310
  }
309
311
  }
@@ -364,7 +366,7 @@ const modelsCommand = defineCommand({
364
366
  if (expand.length > 0)
365
367
  query.expand = expand;
366
368
  const client = createClient();
367
- const data = await client.generate.forward.mutate({
369
+ const data = await forwardJson(client, {
368
370
  target: "platform",
369
371
  method: "GET",
370
372
  path: "/v1/models",
@@ -383,12 +385,12 @@ function splitList(value) {
383
385
  .filter(Boolean);
384
386
  }
385
387
  function printModels(data) {
386
- const models = isRecord(data) && Array.isArray(data.models) ? data.models : [];
388
+ const models = isJsonObject(data) && Array.isArray(data.models) ? data.models : [];
387
389
  for (const m of models) {
388
- if (!isRecord(m))
390
+ if (!isJsonObject(m))
389
391
  continue;
390
392
  const id = String(m.endpoint_id ?? "?");
391
- const meta = isRecord(m.metadata) ? m.metadata : {};
393
+ const meta = isJsonObject(m.metadata) ? m.metadata : {};
392
394
  const tags = [];
393
395
  if (meta.category)
394
396
  tags.push(String(meta.category));
@@ -396,7 +398,7 @@ function printModels(data) {
396
398
  tags.push(String(meta.status));
397
399
  consola.log(`${id}${tags.length > 0 ? ` [${tags.join(", ")}]` : ""}`);
398
400
  }
399
- if (isRecord(data) && data.next_cursor) {
401
+ if (isJsonObject(data) && data.next_cursor) {
400
402
  consola.log(`\nnext_cursor: ${String(data.next_cursor)}`);
401
403
  }
402
404
  }
@@ -411,15 +413,16 @@ const schemaCommand = defineCommand({
411
413
  run: async ({ args }) => {
412
414
  const expand = args.format === "openapi" ? ["openapi-3.0"] : [];
413
415
  const client = createClient();
414
- const data = await client.generate.forward.mutate({
416
+ const query = {};
417
+ query.endpoint_id = args.endpoint_id;
418
+ query.limit = "1";
419
+ if (expand.length > 0)
420
+ query.expand = expand;
421
+ const data = await forwardJson(client, {
415
422
  target: "platform",
416
423
  method: "GET",
417
424
  path: "/v1/models",
418
- query: {
419
- endpoint_id: args.endpoint_id,
420
- limit: "1",
421
- ...(expand.length > 0 ? { expand } : {}),
422
- },
425
+ query,
423
426
  });
424
427
  if (!writeStructured(data, args))
425
428
  writeJson(data);
@@ -434,7 +437,7 @@ const pricingCommand = defineCommand({
434
437
  },
435
438
  run: async ({ args }) => {
436
439
  const client = createClient();
437
- const data = await client.generate.forward.mutate({
440
+ const data = await forwardJson(client, {
438
441
  target: "platform",
439
442
  method: "GET",
440
443
  path: "/v1/models/pricing",
@@ -453,7 +456,7 @@ const docsCommand = defineCommand({
453
456
  },
454
457
  run: async ({ args }) => {
455
458
  const client = createClient();
456
- const data = await client.generate.forward.mutate({
459
+ const data = await forwardJson(client, {
457
460
  target: "docs",
458
461
  method: "POST",
459
462
  path: "/docs/mcp",
@@ -20,7 +20,7 @@ export const loginCommand = defineCommand({
20
20
  run: async () => {
21
21
  const baseUrl = getBaseUrl();
22
22
  const client = createPublicClient(baseUrl);
23
- const { code } = await client.auth.cliInit.mutate();
23
+ const { code } = await client.auth.cliInit();
24
24
  consola.box(`Code: ${code}`);
25
25
  consola.info("Opening browser to complete authentication...");
26
26
  const authUrl = `${baseUrl}/auth/cli?code=${code}`;
@@ -28,7 +28,7 @@ export const loginCommand = defineCommand({
28
28
  consola.start("Waiting for confirmation...");
29
29
  for (let i = 0; i < MAX_POLLS; i++) {
30
30
  await sleep(POLL_INTERVAL_MS);
31
- const result = await client.auth.cliPoll.query({ code });
31
+ const result = await client.auth.cliPoll({ code });
32
32
  if (result.status === "confirmed") {
33
33
  saveConfig({ token: result.token, baseUrl });
34
34
  consola.success("Logged in successfully");
@@ -5,48 +5,61 @@ import consola from "consola";
5
5
  import tiged from "tiged";
6
6
  import { SLUG_RE } from "../lib/config-file.js";
7
7
  import { assertKnownFlags } from "../lib/strict-args.js";
8
- const ENGINES = {
8
+ import { isJsonObject, isJsonString } from "../lib/types.js";
9
+ const ENGINES = new Map([
9
10
  // phaserjs/template-vite-ts is the official Phaser 4 + Vite + TypeScript
10
11
  // starter (despite the description still saying "Phaser 3" — package.json
11
12
  // pins phaser@^4). Pulled fresh on each `vg new`.
12
- phaser: {
13
- repo: "phaserjs/template-vite-ts",
14
- label: "Phaser 4 + Vite + TypeScript (official)",
15
- skill: "phaser",
16
- postNotes: [
17
- "The phaser template ships a `log.js` telemetry shim and uses `vite/config.*.mjs` for build configs — both are upstream, not vibedgames.",
18
- ],
19
- },
13
+ [
14
+ "phaser",
15
+ {
16
+ repo: "phaserjs/template-vite-ts",
17
+ label: "Phaser 4 + Vite + TypeScript (official)",
18
+ skill: "phaser",
19
+ postNotes: [
20
+ "The phaser template ships a `log.js` telemetry shim and uses `vite/config.*.mjs` for build configs — both are upstream, not vibedgames.",
21
+ ],
22
+ },
23
+ ],
20
24
  // No officially-blessed Three.js starter exists. Using the most-starred
21
25
  // community Vite+TS starter that's been kept current.
22
- threejs: {
23
- repo: "pachoclo/vite-threejs-ts-template",
24
- label: "Three.js + Vite + TypeScript (community)",
25
- skill: "threejs",
26
- postNotes: [
27
- "The demo scene (src/scene.ts) wires lil-gui, stats.js and Drag/OrbitControls as a showcase — replace it with your game and drop the debug deps for production.",
28
- ],
29
- },
26
+ [
27
+ "threejs",
28
+ {
29
+ repo: "pachoclo/vite-threejs-ts-template",
30
+ label: "Three.js + Vite + TypeScript (community)",
31
+ skill: "threejs",
32
+ postNotes: [
33
+ "The demo scene (src/scene.ts) wires lil-gui, stats.js and Drag/OrbitControls as a showcase — replace it with your game and drop the debug deps for production.",
34
+ ],
35
+ },
36
+ ],
30
37
  // React Three Fiber. Same author as the threejs preset — Vite + TS +
31
38
  // React 18 + R3F 8 + drei, with leva and r3f-perf wired up for debug.
32
39
  // The pmndrs org doesn't ship an official R3F starter (its templates
33
40
  // are all Next.js-based), and the highest-starred R3F template on
34
41
  // GitHub is still on CRA + React 17, so this is the cleanest current
35
42
  // option for an agent.
36
- "react-r3f": {
37
- repo: "pachoclo/vite-r3f-ts-template",
38
- label: "React + React Three Fiber + Vite + TypeScript (community)",
39
- skill: "threejs",
40
- },
43
+ [
44
+ "react-r3f",
45
+ {
46
+ repo: "pachoclo/vite-r3f-ts-template",
47
+ label: "React + React Three Fiber + Vite + TypeScript (community)",
48
+ skill: "threejs",
49
+ },
50
+ ],
41
51
  // Engine-agnostic fallback for "I'll wire it up myself" / non-canvas
42
52
  // games. Stays inline so we don't get blocked on a network fetch when
43
53
  // the user explicitly asked for a minimal start.
44
- none: {
45
- inline: true,
46
- label: "minimal Vite + TypeScript canvas",
47
- skill: "deploy",
48
- },
49
- };
54
+ [
55
+ "none",
56
+ {
57
+ inline: true,
58
+ label: "minimal Vite + TypeScript canvas",
59
+ skill: "deploy",
60
+ },
61
+ ],
62
+ ]);
50
63
  const NONE_FILES = [
51
64
  {
52
65
  path: "package.json",
@@ -97,7 +110,7 @@ const NONE_FILES = [
97
110
  { path: ".gitignore", content: () => `node_modules\ndist\n.DS_Store\n` },
98
111
  ];
99
112
  // Derived so `--help` and the error message can't drift from the presets again.
100
- const ENGINE_IDS = Object.keys(ENGINES);
113
+ const ENGINE_IDS = [...ENGINES.keys()];
101
114
  const newArgs = {
102
115
  slug: {
103
116
  type: "positional",
@@ -143,7 +156,7 @@ export const newCommand = defineCommand({
143
156
  label: `custom: ${args.template}`,
144
157
  skill: "deploy",
145
158
  }
146
- : ENGINES[args.engine];
159
+ : ENGINES.get(args.engine);
147
160
  if (!preset) {
148
161
  consola.error(`Unknown engine: ${args.engine}. Use one of: ${ENGINE_IDS.join(", ")}.`);
149
162
  process.exit(1);
@@ -231,10 +244,10 @@ function ensureTypecheckScript(target) {
231
244
  return;
232
245
  try {
233
246
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
234
- const scripts = typeof pkg.scripts === "object" && pkg.scripts !== null
235
- ? pkg.scripts
236
- : {};
237
- if (typeof scripts.typecheck === "string")
247
+ if (!isJsonObject(pkg))
248
+ return;
249
+ const scripts = isJsonObject(pkg.scripts) ? pkg.scripts : {};
250
+ if (isJsonString(scripts.typecheck))
238
251
  return;
239
252
  scripts.typecheck = "tsc --noEmit";
240
253
  pkg.scripts = scripts;
@@ -260,6 +273,8 @@ function rewritePackageName(target, slug) {
260
273
  try {
261
274
  const raw = readFileSync(pkgPath, "utf8");
262
275
  const pkg = JSON.parse(raw);
276
+ if (!isJsonObject(pkg))
277
+ throw new Error("package.json is not a JSON object");
263
278
  pkg.name = slug;
264
279
  delete pkg.repository;
265
280
  delete pkg.bugs;
@@ -6,6 +6,8 @@ import { detectPackageManager, globalInstallArgs, globalInstallCommand, } from "
6
6
  import { isMissingCommand, run } from "../lib/run.js";
7
7
  import { assertKnownFlags } from "../lib/strict-args.js";
8
8
  import { fetchLatestVersion, isNewerVersion } from "../lib/update.js";
9
+ // SAFETY: this is the CLI's own package.json, shipped alongside dist — npm
10
+ // refuses to publish a package without a string `version`.
9
11
  const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
10
12
  const skillsUpdateArgs = (global) => {
11
13
  const args = ["-y", "skills", "update", "-y"];
@@ -1,6 +1,6 @@
1
1
  import { defineCommand } from "citty";
2
2
  import consola from "consola";
3
- import { createClient } from "../lib/api.js";
3
+ import { authErrorCode, createClient } from "../lib/api.js";
4
4
  import { getToken } from "../lib/config.js";
5
5
  import { outputArgs, writeStructured } from "../lib/output.js";
6
6
  import { assertKnownFlags } from "../lib/strict-args.js";
@@ -18,11 +18,11 @@ export const whoamiCommand = defineCommand({
18
18
  consola.warn("Not logged in. Run `vg login` to authenticate.");
19
19
  process.exit(1);
20
20
  }
21
- // Goes through tRPC (not the raw better-auth endpoint) so it resolves
21
+ // Goes through the API (not the raw better-auth endpoint) so it resolves
22
22
  // both session tokens and `vg_…` API keys.
23
23
  const client = createClient();
24
24
  try {
25
- const user = await client.auth.me.query();
25
+ const user = await client.auth.me();
26
26
  if (writeStructured({ id: user.id, name: user.name, email: user.email }, args))
27
27
  return;
28
28
  consola.log(`${user.name} (${user.email})`);
@@ -30,7 +30,7 @@ export const whoamiCommand = defineCommand({
30
30
  catch (err) {
31
31
  // Only an auth error means "log in"; surface network/server failures as
32
32
  // themselves so they aren't mistaken for a bad credential.
33
- const code = err?.data?.code;
33
+ const code = authErrorCode(err);
34
34
  if (code === "UNAUTHORIZED" || code === "FORBIDDEN") {
35
35
  consola.warn("Not authenticated. Run `vg login`, or check your VG_TOKEN / API key.");
36
36
  }
package/dist/index.js CHANGED
@@ -15,6 +15,8 @@ import { playtestCommand, runPlaytest } from "./commands/playtest.js";
15
15
  import { updateCommand } from "./commands/update.js";
16
16
  import { whoamiCommand } from "./commands/whoami.js";
17
17
  import { maybeScheduleAutoUpdate } from "./lib/update.js";
18
+ // SAFETY: this is the CLI's own package.json, shipped alongside dist — npm
19
+ // refuses to publish a package without a string `version`.
18
20
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
19
21
  const main = defineCommand({
20
22
  meta: {
package/dist/lib/api.d.ts CHANGED
@@ -1,6 +1,18 @@
1
- import type { AppRouter } from "@repo/api";
2
- import type { TRPCClient } from "@trpc/client";
1
+ import type { AppRouter, RouterInputs } from "@repo/api";
2
+ import type { RouterClient } from "@orpc/server";
3
+ import type { JsonValue } from "./types.js";
3
4
  /** Authenticated client — requires a saved session token. */
4
- export declare function createClient(): TRPCClient<AppRouter>;
5
+ export declare function createClient(): RouterClient<AppRouter>;
6
+ /** The oRPC error code on a failed call, or null for non-oRPC failures. */
7
+ export declare function authErrorCode(cause: unknown): string | null;
8
+ type ForwardInput = RouterInputs["generate"]["forward"];
9
+ /**
10
+ * The single boundary where fal payloads enter the CLI. `generate.forward` is
11
+ * deliberately untyped per endpoint — it resolves to bare `JsonValue` — so
12
+ * everything downstream narrows with the guards in `types.ts` rather than
13
+ * asserting a shape at the call site.
14
+ */
15
+ export declare function forwardJson(client: RouterClient<AppRouter>, input: ForwardInput): Promise<JsonValue>;
5
16
  /** Unauthenticated client — for login flow. */
6
- export declare function createPublicClient(baseUrl: string): TRPCClient<AppRouter>;
17
+ export declare function createPublicClient(baseUrl: string): RouterClient<AppRouter>;
18
+ export {};
package/dist/lib/api.js CHANGED
@@ -1,39 +1,33 @@
1
- import { createTRPCClient, httpBatchLink, httpLink, splitLink } from "@trpc/client";
2
- import superjson from "superjson";
1
+ import { createORPCClient, ORPCError } from "@orpc/client";
2
+ import { RPCLink } from "@orpc/client/fetch";
3
3
  import { getBaseUrl, getToken } from "./config.js";
4
+ const makeClient = (baseUrl, token) => createORPCClient(new RPCLink({
5
+ origin: baseUrl,
6
+ url: "/api/orpc",
7
+ headers: () => (token ? { Authorization: `Bearer ${token}` } : {}),
8
+ }));
4
9
  /** Authenticated client — requires a saved session token. */
5
10
  export function createClient() {
6
11
  const token = getToken();
7
12
  if (!token) {
8
13
  throw new Error("Not logged in. Run `vg login` to authenticate.");
9
14
  }
10
- const url = `${getBaseUrl()}/api/trpc`;
11
- const headers = () => ({ Authorization: `Bearer ${token}` });
12
- return createTRPCClient({
13
- links: [
14
- // Media input bytes use presigned uploads, but mutations can still
15
- // carry model params. Keep writes off httpBatchLink so one batch
16
- // body cannot grow with concurrent calls.
17
- splitLink({
18
- condition: (op) => op.type === "mutation",
19
- true: httpLink({ url, transformer: superjson, headers }),
20
- false: httpBatchLink({ url, transformer: superjson, headers }),
21
- }),
22
- ],
23
- });
15
+ return makeClient(getBaseUrl(), token);
16
+ }
17
+ /** The oRPC error code on a failed call, or null for non-oRPC failures. */
18
+ export function authErrorCode(cause) {
19
+ return cause instanceof ORPCError ? cause.code : null;
20
+ }
21
+ /**
22
+ * The single boundary where fal payloads enter the CLI. `generate.forward` is
23
+ * deliberately untyped per endpoint — it resolves to bare `JsonValue` — so
24
+ * everything downstream narrows with the guards in `types.ts` rather than
25
+ * asserting a shape at the call site.
26
+ */
27
+ export async function forwardJson(client, input) {
28
+ return await client.generate.forward(input);
24
29
  }
25
30
  /** Unauthenticated client — for login flow. */
26
31
  export function createPublicClient(baseUrl) {
27
- // The login-flow procedures carry no large payloads, so the plain
28
- // batch link is fine here — no need for the splitLink dance the
29
- // authenticated client uses to keep `media.run` mutations off the
30
- // batched path.
31
- return createTRPCClient({
32
- links: [
33
- httpBatchLink({
34
- url: `${baseUrl}/api/trpc`,
35
- transformer: superjson,
36
- }),
37
- ],
38
- });
32
+ return makeClient(baseUrl);
39
33
  }