vibedgames 0.0.2 → 0.0.4
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 +16 -2
- package/dist/.tsbuildinfo +1 -0
- package/dist/commands/completions.d.ts +7 -0
- package/dist/commands/completions.js +138 -0
- package/dist/commands/deploy.d.ts +9 -9
- package/dist/commands/deploy.js +6 -0
- package/dist/commands/init.d.ts +20 -0
- package/dist/commands/init.js +89 -0
- package/dist/commands/login.js +2 -2
- package/dist/commands/media.d.ts +1 -0
- package/dist/commands/media.js +401 -0
- package/dist/commands/new.d.ts +26 -0
- package/dist/commands/new.js +229 -0
- package/dist/index.js +11 -3
- package/dist/lib/api.js +14 -7
- package/dist/lib/config-file.js +18 -3
- package/dist/lib/config.js +5 -4
- package/dist/lib/media-args.d.ts +28 -0
- package/dist/lib/media-args.js +199 -0
- package/dist/lib/media-download.d.ts +31 -0
- package/dist/lib/media-download.js +190 -0
- package/dist/lib/media-poll.d.ts +17 -0
- package/dist/lib/media-poll.js +80 -0
- package/dist/lib/media-upload.d.ts +12 -0
- package/dist/lib/media-upload.js +51 -0
- package/dist/lib/types.d.ts +2 -0
- package/dist/lib/types.js +4 -0
- package/package.json +13 -9
- package/dist/commands/list.d.ts +0 -1
- package/dist/commands/list.js +0 -23
- package/dist/commands/rm.d.ts +0 -12
- package/dist/commands/rm.js +0 -35
- package/dist/commands/skills.d.ts +0 -8
- package/dist/commands/skills.js +0 -53
- package/dist/prompt-E6QYABXJ.js +0 -754
package/dist/lib/api.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createTRPCClient, httpBatchLink } from "@trpc/client";
|
|
1
|
+
import { createTRPCClient, httpBatchLink, httpLink, splitLink } from "@trpc/client";
|
|
2
2
|
import superjson from "superjson";
|
|
3
3
|
import { getBaseUrl, getToken } from "./config.js";
|
|
4
4
|
/** Authenticated client — requires a saved session token. */
|
|
@@ -7,20 +7,27 @@ export function createClient() {
|
|
|
7
7
|
if (!token) {
|
|
8
8
|
throw new Error("Not logged in. Run `vg login` to authenticate.");
|
|
9
9
|
}
|
|
10
|
+
const url = `${getBaseUrl()}/api/trpc`;
|
|
11
|
+
const headers = () => ({ Authorization: `Bearer ${token}` });
|
|
10
12
|
return createTRPCClient({
|
|
11
13
|
links: [
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}),
|
|
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 }),
|
|
18
21
|
}),
|
|
19
22
|
],
|
|
20
23
|
});
|
|
21
24
|
}
|
|
22
25
|
/** Unauthenticated client — for login flow. */
|
|
23
26
|
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.
|
|
24
31
|
return createTRPCClient({
|
|
25
32
|
links: [
|
|
26
33
|
httpBatchLink({
|
package/dist/lib/config-file.js
CHANGED
|
@@ -1,9 +1,24 @@
|
|
|
1
1
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
3
|
const FILENAME = "vibedgames.json";
|
|
4
|
+
// Walk from `dir` up toward the filesystem root, stopping at the first
|
|
5
|
+
// vibedgames.json. Lets `vg deploy ./dist` pick up the config from the
|
|
6
|
+
// project root even when the build step doesn't copy it into the output.
|
|
7
|
+
function findConfigPath(dir) {
|
|
8
|
+
let current = resolve(dir);
|
|
9
|
+
while (true) {
|
|
10
|
+
const candidate = join(current, FILENAME);
|
|
11
|
+
if (existsSync(candidate))
|
|
12
|
+
return candidate;
|
|
13
|
+
const parent = dirname(current);
|
|
14
|
+
if (parent === current)
|
|
15
|
+
return null;
|
|
16
|
+
current = parent;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
4
19
|
export function readProjectConfig(dir) {
|
|
5
|
-
const path =
|
|
6
|
-
if (!
|
|
20
|
+
const path = findConfigPath(dir);
|
|
21
|
+
if (!path)
|
|
7
22
|
return null;
|
|
8
23
|
const raw = readFileSync(path, "utf-8");
|
|
9
24
|
const parsed = JSON.parse(raw);
|
package/dist/lib/config.js
CHANGED
|
@@ -36,10 +36,11 @@ export function clearConfig() {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
export function getBaseUrl() {
|
|
39
|
-
return
|
|
40
|
-
getConfig()?.baseUrl ??
|
|
41
|
-
"https://vibedgames.com");
|
|
39
|
+
return process.env.VG_API_URL ?? getConfig()?.baseUrl ?? "https://vibedgames.com";
|
|
42
40
|
}
|
|
43
41
|
export function getToken() {
|
|
44
|
-
|
|
42
|
+
// VG_TOKEN lets local/CI runs authenticate without touching the saved
|
|
43
|
+
// login (e.g. a seeded dev session), so headless testing never clobbers
|
|
44
|
+
// the user's real `vg login` credentials.
|
|
45
|
+
return process.env.VG_TOKEN ?? getConfig()?.token ?? null;
|
|
45
46
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
|
|
3
|
+
* values that look like JSON (true/false/null/numbers/objects/arrays) and
|
|
4
|
+
* leaving everything else as a string. Mirrors genmedia's parse-value
|
|
5
|
+
* behavior so skills targeting that surface produce the same input shapes.
|
|
6
|
+
*
|
|
7
|
+
* Handles both `--key value` and the GNU-style `--key=value`. Without
|
|
8
|
+
* `=` support, `--prompt=hello` would silently send the malformed key
|
|
9
|
+
* `"prompt=hello"` to fal, and `--async=true` would slip past the
|
|
10
|
+
* RUN_RESERVED_FLAGS guard as a bogus model param.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseRunInput(argv: string[]): Record<string, unknown>;
|
|
13
|
+
export type LocalFile = {
|
|
14
|
+
path: string;
|
|
15
|
+
filename: string;
|
|
16
|
+
contentType: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Probe a path the user explicitly asked us to read (e.g.
|
|
20
|
+
* `vg media upload <path>`). Skips the path-shape heuristic so a bare
|
|
21
|
+
* filename with a non-media extension — `model.glb`, `scene.fbx`,
|
|
22
|
+
* `data.ply`, even `LICENSE` — still works.
|
|
23
|
+
*/
|
|
24
|
+
export declare function readExplicitLocalFile(value: string): LocalFile | null;
|
|
25
|
+
export declare function parseDownloadFlag(argv: string[]): {
|
|
26
|
+
mode: "off" | "on";
|
|
27
|
+
template?: string;
|
|
28
|
+
};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, extname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
// `--json`/`--help`/`--quiet` are global; `--async` switches the run path
|
|
5
|
+
// in citty; `--download` takes an optional template. None of them should
|
|
6
|
+
// leak through to fal as model parameters. `--logs` is intentionally NOT
|
|
7
|
+
// here: it's a `vg media status` flag, not a `run` flag, so swallowing it
|
|
8
|
+
// would block users from passing a legitimate `logs` parameter to a
|
|
9
|
+
// model endpoint.
|
|
10
|
+
const RUN_RESERVED_FLAGS = new Set([
|
|
11
|
+
"--json",
|
|
12
|
+
"--help",
|
|
13
|
+
"--quiet",
|
|
14
|
+
"--async",
|
|
15
|
+
"--download",
|
|
16
|
+
]);
|
|
17
|
+
/**
|
|
18
|
+
* Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
|
|
19
|
+
* values that look like JSON (true/false/null/numbers/objects/arrays) and
|
|
20
|
+
* leaving everything else as a string. Mirrors genmedia's parse-value
|
|
21
|
+
* behavior so skills targeting that surface produce the same input shapes.
|
|
22
|
+
*
|
|
23
|
+
* Handles both `--key value` and the GNU-style `--key=value`. Without
|
|
24
|
+
* `=` support, `--prompt=hello` would silently send the malformed key
|
|
25
|
+
* `"prompt=hello"` to fal, and `--async=true` would slip past the
|
|
26
|
+
* RUN_RESERVED_FLAGS guard as a bogus model param.
|
|
27
|
+
*/
|
|
28
|
+
export function parseRunInput(argv) {
|
|
29
|
+
const out = {};
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const arg = argv[i];
|
|
32
|
+
if (!arg || !arg.startsWith("--"))
|
|
33
|
+
continue;
|
|
34
|
+
// POSIX `--` argument terminator: stop interpreting subsequent
|
|
35
|
+
// tokens as flags. Without this guard, `--` itself parses as
|
|
36
|
+
// `{ "": <next token> }` and pollutes the request body.
|
|
37
|
+
if (arg === "--")
|
|
38
|
+
break;
|
|
39
|
+
const eqIdx = arg.indexOf("=");
|
|
40
|
+
const name = eqIdx === -1 ? arg : arg.slice(0, eqIdx);
|
|
41
|
+
const inlineValue = eqIdx === -1 ? undefined : arg.slice(eqIdx + 1);
|
|
42
|
+
if (RUN_RESERVED_FLAGS.has(name)) {
|
|
43
|
+
// --download (without inline value) optionally consumes the next
|
|
44
|
+
// token as its template. With `--download=foo` the value is
|
|
45
|
+
// already attached and we move on without skipping anything.
|
|
46
|
+
if (name === "--download" && inlineValue === undefined) {
|
|
47
|
+
const next = argv[i + 1];
|
|
48
|
+
if (next && !next.startsWith("--"))
|
|
49
|
+
i++;
|
|
50
|
+
}
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const key = name.slice(2);
|
|
54
|
+
if (inlineValue !== undefined) {
|
|
55
|
+
assign(out, key, parseValue(inlineValue));
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const next = argv[i + 1];
|
|
59
|
+
if (next === undefined || next.startsWith("--")) {
|
|
60
|
+
assign(out, key, true);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
assign(out, key, parseValue(next));
|
|
64
|
+
i++;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
function assign(out, key, value) {
|
|
69
|
+
if (key in out) {
|
|
70
|
+
const existing = out[key];
|
|
71
|
+
if (Array.isArray(existing))
|
|
72
|
+
existing.push(value);
|
|
73
|
+
else
|
|
74
|
+
out[key] = [existing, value];
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
out[key] = value;
|
|
78
|
+
}
|
|
79
|
+
function parseValue(raw) {
|
|
80
|
+
if (raw === "true")
|
|
81
|
+
return true;
|
|
82
|
+
if (raw === "false")
|
|
83
|
+
return false;
|
|
84
|
+
if (raw === "null")
|
|
85
|
+
return null;
|
|
86
|
+
if (raw.length > 0 && (raw[0] === "{" || raw[0] === "[")) {
|
|
87
|
+
try {
|
|
88
|
+
return JSON.parse(raw);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return raw;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (/^-?\d+(\.\d+)?$/.test(raw)) {
|
|
95
|
+
const n = Number(raw);
|
|
96
|
+
if (Number.isFinite(n))
|
|
97
|
+
return n;
|
|
98
|
+
}
|
|
99
|
+
return raw;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Probe a path the user explicitly asked us to read (e.g.
|
|
103
|
+
* `vg media upload <path>`). Skips the path-shape heuristic so a bare
|
|
104
|
+
* filename with a non-media extension — `model.glb`, `scene.fbx`,
|
|
105
|
+
* `data.ply`, even `LICENSE` — still works.
|
|
106
|
+
*/
|
|
107
|
+
export function readExplicitLocalFile(value) {
|
|
108
|
+
if (value.startsWith("http://") || value.startsWith("https://"))
|
|
109
|
+
return null;
|
|
110
|
+
if (value.startsWith("data:"))
|
|
111
|
+
return null;
|
|
112
|
+
if (value.length === 0)
|
|
113
|
+
return null;
|
|
114
|
+
const expanded = expandHome(value);
|
|
115
|
+
const abs = isAbsolute(expanded) ? expanded : resolve(expanded);
|
|
116
|
+
let stat;
|
|
117
|
+
try {
|
|
118
|
+
stat = statSync(abs);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (!stat.isFile())
|
|
124
|
+
return null;
|
|
125
|
+
return {
|
|
126
|
+
path: abs,
|
|
127
|
+
filename: basename(abs),
|
|
128
|
+
contentType: contentTypeForPath(abs),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function expandHome(value) {
|
|
132
|
+
// node:path's resolve() doesn't expand `~` — that's a shell feature.
|
|
133
|
+
// We expand it ourselves so quoted paths like `"~/photo.png"` work.
|
|
134
|
+
if (value === "~")
|
|
135
|
+
return homedir();
|
|
136
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
|
137
|
+
return join(homedir(), value.slice(2));
|
|
138
|
+
}
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
function contentTypeForPath(path) {
|
|
142
|
+
// extname splits on basename, so a dotted directory like
|
|
143
|
+
// "/home/user/my.project/texture" correctly yields "" instead of
|
|
144
|
+
// mistaking "project/texture" for the extension.
|
|
145
|
+
const ext = extname(path).slice(1).toLowerCase();
|
|
146
|
+
const map = {
|
|
147
|
+
png: "image/png",
|
|
148
|
+
jpg: "image/jpeg",
|
|
149
|
+
jpeg: "image/jpeg",
|
|
150
|
+
webp: "image/webp",
|
|
151
|
+
gif: "image/gif",
|
|
152
|
+
bmp: "image/bmp",
|
|
153
|
+
tif: "image/tiff",
|
|
154
|
+
tiff: "image/tiff",
|
|
155
|
+
avif: "image/avif",
|
|
156
|
+
mp4: "video/mp4",
|
|
157
|
+
mov: "video/quicktime",
|
|
158
|
+
webm: "video/webm",
|
|
159
|
+
mp3: "audio/mpeg",
|
|
160
|
+
wav: "audio/wav",
|
|
161
|
+
ogg: "audio/ogg",
|
|
162
|
+
flac: "audio/flac",
|
|
163
|
+
m4a: "audio/mp4",
|
|
164
|
+
txt: "text/plain",
|
|
165
|
+
json: "application/json",
|
|
166
|
+
};
|
|
167
|
+
return map[ext] ?? "application/octet-stream";
|
|
168
|
+
}
|
|
169
|
+
export function parseDownloadFlag(argv) {
|
|
170
|
+
let lastIdx = -1;
|
|
171
|
+
let inlineValue;
|
|
172
|
+
for (let i = 0; i < argv.length; i++) {
|
|
173
|
+
const arg = argv[i];
|
|
174
|
+
if (!arg)
|
|
175
|
+
continue;
|
|
176
|
+
if (arg === "--")
|
|
177
|
+
break;
|
|
178
|
+
if (arg === "--download") {
|
|
179
|
+
lastIdx = i;
|
|
180
|
+
inlineValue = undefined;
|
|
181
|
+
}
|
|
182
|
+
else if (arg.startsWith("--download=")) {
|
|
183
|
+
lastIdx = i;
|
|
184
|
+
inlineValue = arg.slice("--download=".length);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (lastIdx === -1)
|
|
188
|
+
return { mode: "off" };
|
|
189
|
+
const candidate = inlineValue ?? argv[lastIdx + 1];
|
|
190
|
+
if (candidate === "false")
|
|
191
|
+
return { mode: "off" };
|
|
192
|
+
if (candidate === undefined ||
|
|
193
|
+
candidate === "" ||
|
|
194
|
+
candidate.startsWith("--") ||
|
|
195
|
+
candidate === "true") {
|
|
196
|
+
return { mode: "on" };
|
|
197
|
+
}
|
|
198
|
+
return { mode: "on", template: candidate };
|
|
199
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
type MediaRef = {
|
|
2
|
+
url: string;
|
|
3
|
+
filename: string;
|
|
4
|
+
contentType: string | null;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Walk a fal result payload and pull out anything that looks like a media
|
|
8
|
+
* output. fal endpoints embed outputs in objects shaped like
|
|
9
|
+
* `{ url, content_type, file_name, ... }`; we accept image/video/audio
|
|
10
|
+
* content types and also fall back to URL extension when content_type is
|
|
11
|
+
* absent (some endpoints omit it).
|
|
12
|
+
*/
|
|
13
|
+
export declare function extractMediaRefs(result: unknown): MediaRef[];
|
|
14
|
+
type DownloadResult = {
|
|
15
|
+
downloaded: string[];
|
|
16
|
+
failed: {
|
|
17
|
+
url: string;
|
|
18
|
+
error: string;
|
|
19
|
+
}[];
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Download all extracted media refs to disk, materializing the path from
|
|
23
|
+
* a template. Supported placeholders: {index}, {name}, {ext}, {request_id}.
|
|
24
|
+
* Falls back to the source filename in the cwd when no template is given.
|
|
25
|
+
*/
|
|
26
|
+
export declare function downloadMedia(opts: {
|
|
27
|
+
refs: MediaRef[];
|
|
28
|
+
template?: string;
|
|
29
|
+
requestId: string;
|
|
30
|
+
}): Promise<DownloadResult>;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, extname, resolve } from "node:path";
|
|
3
|
+
import { isRecord } from "./types.js";
|
|
4
|
+
// Lowercase file extensions we recognize as media when sniffing fal
|
|
5
|
+
// response payloads where `content_type` is missing (some endpoints
|
|
6
|
+
// omit it).
|
|
7
|
+
const MEDIA_EXT = new Set([
|
|
8
|
+
"png", "jpg", "jpeg", "webp", "gif", "bmp", "tif", "tiff", "avif",
|
|
9
|
+
"mp4", "mov", "webm", "mp3", "wav", "ogg", "flac", "m4a",
|
|
10
|
+
]);
|
|
11
|
+
/**
|
|
12
|
+
* Walk a fal result payload and pull out anything that looks like a media
|
|
13
|
+
* output. fal endpoints embed outputs in objects shaped like
|
|
14
|
+
* `{ url, content_type, file_name, ... }`; we accept image/video/audio
|
|
15
|
+
* content types and also fall back to URL extension when content_type is
|
|
16
|
+
* absent (some endpoints omit it).
|
|
17
|
+
*/
|
|
18
|
+
export function extractMediaRefs(result) {
|
|
19
|
+
const seen = new Set();
|
|
20
|
+
const refs = [];
|
|
21
|
+
visit(result, refs, seen);
|
|
22
|
+
return refs;
|
|
23
|
+
}
|
|
24
|
+
// fal stores generated outputs on its own CDN (`X-Fal-Store-IO: 1`) and
|
|
25
|
+
// always serves them over HTTPS. Restrict `--download` candidates to
|
|
26
|
+
// those hosts and that scheme so a fal response can't trick the CLI
|
|
27
|
+
// into fetching arbitrary URLs (e.g. attacker-controlled or
|
|
28
|
+
// internal-network targets) on the user's machine, and can't downgrade
|
|
29
|
+
// to plain HTTP.
|
|
30
|
+
const TRUSTED_HOST_SUFFIXES = [".fal.media", ".fal.run", ".fal.ai"];
|
|
31
|
+
const TRUSTED_HOSTS = new Set(["fal.media", "fal.run", "fal.ai"]);
|
|
32
|
+
function isTrustedFalContentHost(url) {
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = new URL(url);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if (parsed.protocol !== "https:")
|
|
41
|
+
return false;
|
|
42
|
+
const host = parsed.hostname.toLowerCase();
|
|
43
|
+
if (TRUSTED_HOSTS.has(host))
|
|
44
|
+
return true;
|
|
45
|
+
return TRUSTED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));
|
|
46
|
+
}
|
|
47
|
+
function visit(value, refs, seen) {
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
for (const v of value)
|
|
50
|
+
visit(v, refs, seen);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (!isRecord(value))
|
|
54
|
+
return;
|
|
55
|
+
const url = value.url;
|
|
56
|
+
if (typeof url === "string" && isTrustedFalContentHost(url) && !seen.has(url)) {
|
|
57
|
+
const contentType = typeof value.content_type === "string" ? value.content_type.toLowerCase() : null;
|
|
58
|
+
const filenameField = typeof value.file_name === "string" ? sanitizeFilename(value.file_name) : null;
|
|
59
|
+
const ext = filenameField ? extname(filenameField).slice(1).toLowerCase() : extFromUrl(url);
|
|
60
|
+
const looksMedia = contentType !== null ? /^(image|video|audio)\//.test(contentType) : MEDIA_EXT.has(ext);
|
|
61
|
+
if (looksMedia) {
|
|
62
|
+
seen.add(url);
|
|
63
|
+
refs.push({
|
|
64
|
+
url,
|
|
65
|
+
filename: filenameField ?? `output${ext ? "." + ext : ""}`,
|
|
66
|
+
contentType,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const child of Object.values(value))
|
|
71
|
+
visit(child, refs, seen);
|
|
72
|
+
}
|
|
73
|
+
function extFromUrl(url) {
|
|
74
|
+
try {
|
|
75
|
+
const path = new URL(url).pathname;
|
|
76
|
+
const dot = path.lastIndexOf(".");
|
|
77
|
+
return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return "";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Download all extracted media refs to disk, materializing the path from
|
|
85
|
+
* a template. Supported placeholders: {index}, {name}, {ext}, {request_id}.
|
|
86
|
+
* Falls back to the source filename in the cwd when no template is given.
|
|
87
|
+
*/
|
|
88
|
+
export async function downloadMedia(opts) {
|
|
89
|
+
const initial = opts.refs.map((ref, i) => renderTemplate(ref, opts.template, i, opts.requestId));
|
|
90
|
+
// Disambiguate any colliding resolved paths so multi-output runs (e.g.
|
|
91
|
+
// `--num_images 3` where fal returns the same default `file_name` for
|
|
92
|
+
// every output) don't silently overwrite each other on disk. The first
|
|
93
|
+
// occurrence keeps the original name; subsequent collisions get a
|
|
94
|
+
// `_1`, `_2`, … suffix inserted before the extension.
|
|
95
|
+
const targets = disambiguateTargets(initial);
|
|
96
|
+
// Create each unique parent directory once instead of redoing it per ref.
|
|
97
|
+
const dirs = new Set(targets.map((t) => dirname(t)));
|
|
98
|
+
for (const d of dirs)
|
|
99
|
+
mkdirSync(d, { recursive: true });
|
|
100
|
+
const outcomes = await Promise.all(opts.refs.map(async (ref, i) => {
|
|
101
|
+
const target = targets[i];
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetch(ref.url);
|
|
104
|
+
if (!res.ok) {
|
|
105
|
+
return { ok: false, url: ref.url, error: `${res.status} ${res.statusText}` };
|
|
106
|
+
}
|
|
107
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
108
|
+
writeFileSync(target, bytes);
|
|
109
|
+
return { ok: true, target };
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
url: ref.url,
|
|
115
|
+
error: err instanceof Error ? err.message : String(err),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}));
|
|
119
|
+
const downloaded = [];
|
|
120
|
+
const failed = [];
|
|
121
|
+
for (const o of outcomes) {
|
|
122
|
+
if (o.ok)
|
|
123
|
+
downloaded.push(o.target);
|
|
124
|
+
else
|
|
125
|
+
failed.push({ url: o.url, error: o.error });
|
|
126
|
+
}
|
|
127
|
+
return { downloaded, failed };
|
|
128
|
+
}
|
|
129
|
+
// Strip any directory components from a fal-provided file_name so a
|
|
130
|
+
// malicious response can't traverse out of the download target dir.
|
|
131
|
+
// Handle both POSIX and Windows separators regardless of host OS so a
|
|
132
|
+
// `..\\..\\evil` payload sent to a Linux client is still flattened.
|
|
133
|
+
function sanitizeFilename(name) {
|
|
134
|
+
const base = name.replace(/[\\/]+/g, "/").split("/").pop() ?? "";
|
|
135
|
+
if (!base || base === "." || base === "..")
|
|
136
|
+
return null;
|
|
137
|
+
return base;
|
|
138
|
+
}
|
|
139
|
+
function disambiguateTargets(paths) {
|
|
140
|
+
const counts = new Map();
|
|
141
|
+
for (const p of paths)
|
|
142
|
+
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
143
|
+
const seen = new Map();
|
|
144
|
+
return paths.map((p) => {
|
|
145
|
+
if ((counts.get(p) ?? 0) <= 1)
|
|
146
|
+
return p;
|
|
147
|
+
const n = seen.get(p) ?? 0;
|
|
148
|
+
seen.set(p, n + 1);
|
|
149
|
+
if (n === 0)
|
|
150
|
+
return p;
|
|
151
|
+
const ext = extname(p);
|
|
152
|
+
return p.slice(0, p.length - ext.length) + `_${n}` + ext;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function renderTemplate(ref, template, index, requestId) {
|
|
156
|
+
const ext = (() => {
|
|
157
|
+
const fromName = extname(ref.filename).slice(1);
|
|
158
|
+
if (fromName)
|
|
159
|
+
return fromName;
|
|
160
|
+
return extFromUrl(ref.url) || "bin";
|
|
161
|
+
})();
|
|
162
|
+
// String-based stem extraction: a dynamic RegExp built from `ext`
|
|
163
|
+
// would treat any regex metachars in an unusual fal `file_name`
|
|
164
|
+
// (`.`, `+`, `*`) as patterns, potentially stripping the wrong
|
|
165
|
+
// suffix. Plain endsWith is exact and case-insensitive via toLowerCase.
|
|
166
|
+
const lowerName = ref.filename.toLowerCase();
|
|
167
|
+
const dotExt = "." + ext.toLowerCase();
|
|
168
|
+
const stem = lowerName.endsWith(dotExt)
|
|
169
|
+
? ref.filename.slice(0, -dotExt.length) || "output"
|
|
170
|
+
: ref.filename || "output";
|
|
171
|
+
// No template or no placeholder → caller meant either a destination
|
|
172
|
+
// directory (omitted, ".", "./", "../out", "out/") or an explicit
|
|
173
|
+
// output filename (`./out.png`, `frame.mp4`). We disambiguate by
|
|
174
|
+
// looking for an extension on the basename — anything with one is
|
|
175
|
+
// treated as the literal output path; otherwise we resolve into the
|
|
176
|
+
// directory using the ref's filename. The previous all-as-dir
|
|
177
|
+
// behavior wrote `./walk.png/output.png` for `--download ./walk.png`.
|
|
178
|
+
if (!template || !template.includes("{")) {
|
|
179
|
+
if (template && extname(template))
|
|
180
|
+
return resolve(template);
|
|
181
|
+
const dir = template ?? process.cwd();
|
|
182
|
+
return resolve(dir, ref.filename || `output-${index}.${ext}`);
|
|
183
|
+
}
|
|
184
|
+
const rendered = template
|
|
185
|
+
.replaceAll("{index}", String(index))
|
|
186
|
+
.replaceAll("{name}", stem)
|
|
187
|
+
.replaceAll("{ext}", ext)
|
|
188
|
+
.replaceAll("{request_id}", requestId);
|
|
189
|
+
return resolve(rendered);
|
|
190
|
+
}
|
|
@@ -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 {};
|