vibedgames 0.0.3 → 0.0.5

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.
@@ -0,0 +1,17 @@
1
+ import type { createClient } from "./api.js";
2
+ type Client = ReturnType<typeof createClient>;
3
+ export declare function endpointPath(endpointId: string): string;
4
+ export declare function queueAppId(endpointId: string): string;
5
+ type CompletedResult = {
6
+ request_id: string;
7
+ result: unknown;
8
+ };
9
+ /**
10
+ * Poll fal's queue from the client side until the job reaches a
11
+ * terminal status, then fetch the result. The Worker isn't in the
12
+ * loop — it's only along for each individual `media.forward` hop.
13
+ */
14
+ export declare function waitForCompletion(client: Client, endpoint_id: string, request_id: string, opts: {
15
+ quiet: boolean;
16
+ }): Promise<CompletedResult>;
17
+ export {};
@@ -0,0 +1,80 @@
1
+ import consola from "consola";
2
+ import { isRecord } from "./types.js";
3
+ // Strip leading/trailing slashes from a fal endpoint id so it can be
4
+ // spliced into a URL path without doubling separators.
5
+ export function endpointPath(endpointId) {
6
+ return endpointId.replace(/^\/+|\/+$/g, "");
7
+ }
8
+ // fal's queue accepts the full endpoint id (including any model subpath,
9
+ // e.g. `fal-ai/flux/schnell`) on submit, but the status/result/cancel
10
+ // routes are keyed by the owning *application* id only (`fal-ai/flux`).
11
+ // Passing the subpath to those routes returns 405. `workflows`/`comfy`
12
+ // ids carry the namespace as a leading segment, so their app id is three
13
+ // segments deep.
14
+ const QUEUE_APP_NAMESPACES = new Set(["workflows", "comfy"]);
15
+ export function queueAppId(endpointId) {
16
+ const parts = endpointPath(endpointId).split("/").filter(Boolean);
17
+ const take = QUEUE_APP_NAMESPACES.has(parts[0] ?? "") ? 3 : 2;
18
+ return parts.slice(0, take).join("/");
19
+ }
20
+ const POLL_INTERVAL_MS = 2_000;
21
+ // 30-minute ceiling on a sync run. Generous (this is the user's local
22
+ // CLI process, not a billed Worker) but bounded so a stuck IN_QUEUE
23
+ // job can't hang the CLI indefinitely. Long jobs should use --async.
24
+ const POLL_TIMEOUT_MS = 30 * 60 * 1000;
25
+ /**
26
+ * Poll fal's queue from the client side until the job reaches a
27
+ * terminal status, then fetch the result. The Worker isn't in the
28
+ * loop — it's only along for each individual `media.forward` hop.
29
+ */
30
+ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
31
+ const ep = queueAppId(endpoint_id);
32
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
33
+ let lastStatus;
34
+ while (true) {
35
+ if (Date.now() > deadline) {
36
+ throw new Error(`fal job did not complete within ${POLL_TIMEOUT_MS}ms ` +
37
+ `(endpoint=${endpoint_id} request_id=${request_id}). ` +
38
+ `Use \`vg media status ${endpoint_id} ${request_id} --result\` to check later.`);
39
+ }
40
+ const raw = await client.media.forward.mutate({
41
+ target: "queue",
42
+ method: "GET",
43
+ path: `/${ep}/requests/${request_id}/status`,
44
+ });
45
+ const status = isRecord(raw) && typeof raw.status === "string" ? raw.status : "UNKNOWN";
46
+ const upper = status.toUpperCase();
47
+ if (!opts.quiet && upper !== lastStatus) {
48
+ lastStatus = upper;
49
+ const queuePos = isRecord(raw) && typeof raw.queue_position === "number" ? raw.queue_position : null;
50
+ const tag = queuePos !== null ? `${upper.toLowerCase()} (queue ${queuePos})` : upper.toLowerCase();
51
+ consola.log(` ${tag}`);
52
+ }
53
+ if (upper === "COMPLETED")
54
+ break;
55
+ if (upper === "FAILED" || upper === "CANCELLED") {
56
+ const reason = pickErrorReason(raw);
57
+ throw new Error(reason ? `fal job ${upper.toLowerCase()}: ${reason}` : `fal job ${upper.toLowerCase()}`);
58
+ }
59
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
60
+ }
61
+ const result = await client.media.forward.mutate({
62
+ target: "queue",
63
+ method: "GET",
64
+ path: `/${ep}/requests/${request_id}`,
65
+ });
66
+ return { request_id, result };
67
+ }
68
+ function pickErrorReason(value) {
69
+ if (!isRecord(value))
70
+ return null;
71
+ if (typeof value.error === "string" && value.error.length > 0)
72
+ return value.error;
73
+ if (typeof value.detail === "string" && value.detail.length > 0)
74
+ return value.detail;
75
+ if (isRecord(value.error) && typeof value.error.message === "string")
76
+ return value.error.message;
77
+ if (isRecord(value.response))
78
+ return pickErrorReason(value.response);
79
+ return null;
80
+ }
@@ -0,0 +1,12 @@
1
+ import type { createClient } from "./api.js";
2
+ import type { LocalFile } from "./media-args.js";
3
+ type Client = ReturnType<typeof createClient>;
4
+ /**
5
+ * Upload one local file directly to fal's CDN. The proxy hands us a
6
+ * presigned upload slot (upload_url + file_url) via the `media.forward`
7
+ * storage target; bytes go straight from the client to fal, never
8
+ * through the worker. The returned file_url is a stable fal CDN URL
9
+ * that can be reused across runs without re-uploading.
10
+ */
11
+ export declare function uploadFile(client: Client, file: LocalFile): Promise<string>;
12
+ export {};
@@ -0,0 +1,51 @@
1
+ import { openAsBlob } from "node:fs";
2
+ import { isRecord } from "./types.js";
3
+ /**
4
+ * Upload one local file directly to fal's CDN. The proxy hands us a
5
+ * presigned upload slot (upload_url + file_url) via the `media.forward`
6
+ * storage target; bytes go straight from the client to fal, never
7
+ * through the worker. The returned file_url is a stable fal CDN URL
8
+ * that can be reused across runs without re-uploading.
9
+ */
10
+ export async function uploadFile(client, file) {
11
+ const slot = await client.media.forward.mutate({
12
+ target: "storage",
13
+ method: "POST",
14
+ path: "/storage/upload/initiate",
15
+ body: { content_type: file.contentType, file_name: file.filename },
16
+ });
17
+ const uploadUrl = pickUrl(slot, "upload_url");
18
+ const fileUrl = pickUrl(slot, "file_url");
19
+ const body = await openAsBlob(file.path, { type: file.contentType });
20
+ const res = await fetch(uploadUrl, {
21
+ method: "PUT",
22
+ headers: { "Content-Type": file.contentType },
23
+ body,
24
+ });
25
+ if (!res.ok) {
26
+ const text = await res.text().catch(() => "");
27
+ throw new Error(`Upload failed for ${file.filename}: ${res.status} ${res.statusText} ${text}`);
28
+ }
29
+ return fileUrl;
30
+ }
31
+ function pickUrl(slot, key) {
32
+ if (!isRecord(slot) || typeof slot[key] !== "string" || slot[key].length === 0) {
33
+ throw new Error(`fal storage initiate response missing ${key}.`);
34
+ }
35
+ const value = slot[key];
36
+ // Refuse any non-HTTPS URL even if it comes from a trusted server
37
+ // response — a misconfigured response (or a downgrade attack on the
38
+ // proxy hop) must not silently send user bytes over plain HTTP, and
39
+ // file_url gets passed into later runs where it should stay HTTPS.
40
+ let parsed;
41
+ try {
42
+ parsed = new URL(value);
43
+ }
44
+ catch {
45
+ throw new Error(`fal storage initiate response ${key} is not a valid URL.`);
46
+ }
47
+ if (parsed.protocol !== "https:") {
48
+ throw new Error(`fal storage initiate response ${key} must be HTTPS, got ${parsed.protocol}.`);
49
+ }
50
+ return value;
51
+ }
@@ -0,0 +1,2 @@
1
+ /** Type-guard helpers shared across CLI modules. */
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,4 @@
1
+ /** Type-guard helpers shared across CLI modules. */
2
+ export function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
package/package.json CHANGED
@@ -1,34 +1,38 @@
1
1
  {
2
2
  "name": "vibedgames",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "private": false,
5
- "type": "module",
6
5
  "bin": {
7
6
  "vg": "./dist/index.js"
8
7
  },
9
8
  "files": [
10
9
  "dist"
11
10
  ],
11
+ "type": "module",
12
12
  "dependencies": {
13
- "@trpc/client": "^11.16.0",
14
- "citty": "^0.1.6",
13
+ "@trpc/client": "^11.17.0",
14
+ "citty": "^0.2.2",
15
15
  "consola": "^3.4.2",
16
16
  "cross-spawn": "^7.0.6",
17
- "superjson": "^2.2.6"
17
+ "ignore": "^7.0.5",
18
+ "superjson": "^2.2.6",
19
+ "tar": "^7.4.3",
20
+ "tiged": "^2.12.8"
18
21
  },
19
22
  "devDependencies": {
20
- "@cloudflare/workers-types": "^4.20260408.1",
23
+ "@cloudflare/workers-types": "^4.20260522.1",
21
24
  "@kyh/tsconfig": "^1.1.14",
22
- "@trpc/server": "^11.16.0",
25
+ "@trpc/server": "^11.17.0",
23
26
  "@types/cross-spawn": "^6.0.6",
24
- "@types/node": "^25.5.2",
25
- "typescript": "^6.0.2",
27
+ "@types/node": "^25.9.1",
28
+ "typescript": "^6.0.3",
26
29
  "@repo/api": "^0.1.0"
27
30
  },
28
31
  "scripts": {
29
32
  "build": "tsc",
30
33
  "dev": "tsc --watch",
31
34
  "clean": "rm -rf .turbo dist node_modules",
35
+ "test:media": "node --import tsx --test test/media-args.test.ts test/media-download.test.ts test/media-poll.test.ts",
32
36
  "typecheck": "tsc --noEmit"
33
37
  }
34
38
  }
@@ -1 +0,0 @@
1
- export declare const listCommand: import("citty").CommandDef<import("citty").ArgsDef>;
@@ -1,23 +0,0 @@
1
- import { defineCommand } from "citty";
2
- import consola from "consola";
3
- import { createClient } from "../lib/api.js";
4
- export const listCommand = defineCommand({
5
- meta: {
6
- name: "list",
7
- description: "List your games",
8
- },
9
- run: async () => {
10
- const client = createClient();
11
- const { builds } = await client.localGame.listBuilds.query({ limit: 50 });
12
- if (builds.length === 0) {
13
- consola.info("No games found");
14
- return;
15
- }
16
- for (const build of builds) {
17
- const fileCount = build.gameBuildFiles.length;
18
- const updated = new Date(build.updatedAt).toLocaleDateString();
19
- const title = build.title ?? "(untitled)";
20
- consola.log(` ${build.id.slice(0, 8)} ${title} ${fileCount} files ${updated}`);
21
- }
22
- },
23
- });
@@ -1,12 +0,0 @@
1
- export declare const rmCommand: import("citty").CommandDef<{
2
- id: {
3
- type: "positional";
4
- description: string;
5
- required: true;
6
- };
7
- force: {
8
- type: "boolean";
9
- description: string;
10
- default: false;
11
- };
12
- }>;
@@ -1,35 +0,0 @@
1
- import { defineCommand } from "citty";
2
- import consola from "consola";
3
- import { createClient } from "../lib/api.js";
4
- export const rmCommand = defineCommand({
5
- meta: {
6
- name: "rm",
7
- description: "Remove a game",
8
- },
9
- args: {
10
- id: {
11
- type: "positional",
12
- description: "Game build ID to remove",
13
- required: true,
14
- },
15
- force: {
16
- type: "boolean",
17
- description: "Skip confirmation",
18
- default: false,
19
- },
20
- },
21
- run: async ({ args }) => {
22
- if (!args.force) {
23
- const confirmed = await consola.prompt(`Remove game ${args.id}?`, {
24
- type: "confirm",
25
- });
26
- if (!confirmed) {
27
- consola.info("Cancelled");
28
- return;
29
- }
30
- }
31
- const client = createClient();
32
- await client.localGame.deleteBuild.mutate({ buildId: args.id });
33
- consola.success(`Removed ${args.id}`);
34
- },
35
- });
@@ -1,8 +0,0 @@
1
- export declare const skillsCommand: import("citty").CommandDef<{
2
- dir: {
3
- type: "positional";
4
- description: string;
5
- required: false;
6
- default: string;
7
- };
8
- }>;
@@ -1,53 +0,0 @@
1
- import { execSync } from "node:child_process";
2
- import { existsSync, mkdirSync, rmSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { defineCommand } from "citty";
5
- import consola from "consola";
6
- const REPO = "kyh/vibedgames";
7
- const SKILLS_PATH = ".claude/skills";
8
- const BRANCH = "main";
9
- export const skillsCommand = defineCommand({
10
- meta: {
11
- name: "skills",
12
- description: "Install vibedgames Claude Code skills into your project",
13
- },
14
- args: {
15
- dir: {
16
- type: "positional",
17
- description: "Project directory",
18
- required: false,
19
- default: ".",
20
- },
21
- },
22
- run: async ({ args }) => {
23
- const projectDir = args.dir;
24
- const targetDir = join(projectDir, SKILLS_PATH);
25
- const tarballUrl = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.tar.gz`;
26
- const tmpDir = join(projectDir, ".vg-skills-tmp");
27
- consola.start("Fetching skills from vibedgames...");
28
- try {
29
- // Download and extract just the skills directory
30
- mkdirSync(tmpDir, { recursive: true });
31
- execSync(`curl -sL "${tarballUrl}" | tar xz --strip-components=3 -C "${tmpDir}" "vibedgames-${BRANCH}/${SKILLS_PATH}"`, { stdio: "pipe" });
32
- // Copy to target
33
- mkdirSync(targetDir, { recursive: true });
34
- execSync(`cp -r "${tmpDir}"/* "${targetDir}"/`, { stdio: "pipe" });
35
- // Count skills
36
- const skills = execSync(`ls "${targetDir}"`, { encoding: "utf-8" })
37
- .trim()
38
- .split("\n")
39
- .filter(Boolean);
40
- consola.success(`Installed ${skills.length} skills to ${targetDir}`);
41
- consola.log(` ${skills.join(", ")}`);
42
- }
43
- catch (err) {
44
- consola.error(err instanceof Error ? err.message : String(err));
45
- process.exit(1);
46
- }
47
- finally {
48
- if (existsSync(tmpDir)) {
49
- rmSync(tmpDir, { recursive: true });
50
- }
51
- }
52
- },
53
- });