@tanstack/ai-fal 1.1.0 → 1.1.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.
- package/dist/esm/adapters/audio.d.ts +1 -0
- package/dist/esm/adapters/audio.js +5 -5
- package/dist/esm/adapters/audio.js.map +1 -1
- package/dist/esm/adapters/files.d.ts +1 -0
- package/dist/esm/adapters/files.js +4 -4
- package/dist/esm/adapters/files.js.map +1 -1
- package/dist/esm/adapters/image.d.ts +1 -0
- package/dist/esm/adapters/image.js +5 -5
- package/dist/esm/adapters/image.js.map +1 -1
- package/dist/esm/adapters/speech.d.ts +1 -0
- package/dist/esm/adapters/speech.js +5 -5
- package/dist/esm/adapters/speech.js.map +1 -1
- package/dist/esm/adapters/transcription.d.ts +1 -0
- package/dist/esm/adapters/transcription.js +5 -5
- package/dist/esm/adapters/transcription.js.map +1 -1
- package/dist/esm/adapters/video.d.ts +2 -1
- package/dist/esm/adapters/video.js +8 -8
- package/dist/esm/adapters/video.js.map +1 -1
- package/dist/esm/client/index.d.ts +65 -0
- package/dist/esm/client/index.js +307 -0
- package/dist/esm/client/index.js.map +1 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/utils/client.d.ts +10 -1
- package/dist/esm/utils/client.js +13 -7
- package/dist/esm/utils/client.js.map +1 -1
- package/dist/esm/utils/configure.d.ts +12 -0
- package/dist/esm/utils/configure.js +20 -0
- package/dist/esm/utils/configure.js.map +1 -0
- package/dist/esm/utils/index.d.ts +2 -1
- package/package.json +5 -4
- package/src/adapters/audio.ts +7 -6
- package/src/adapters/files.ts +5 -4
- package/src/adapters/image.ts +8 -7
- package/src/adapters/speech.ts +7 -6
- package/src/adapters/transcription.ts +8 -7
- package/src/adapters/video.ts +11 -10
- package/src/client/index.ts +456 -0
- package/src/index.ts +1 -1
- package/src/utils/client.ts +12 -4
- package/src/utils/configure.ts +17 -0
- package/src/utils/index.ts +2 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { FalClient as SdkFalClient, QueueClient, StorageClient, ValidationErrorInfo } from '@fal-ai/client';
|
|
2
|
+
/**
|
|
3
|
+
* Config for {@link createFalClient}. These are the `@fal-ai/client` config
|
|
4
|
+
* fields this package uses.
|
|
5
|
+
*/
|
|
6
|
+
export interface FalClientOptions {
|
|
7
|
+
/** Sent as `Authorization: Key <credentials>`. */
|
|
8
|
+
credentials: string;
|
|
9
|
+
fetch: typeof fetch;
|
|
10
|
+
/** In a browser, requests go here with the real URL in `x-fal-target-url`. */
|
|
11
|
+
proxyUrl?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The part of the `@fal-ai/client` client that the adapters call. A real SDK
|
|
15
|
+
* client also fits this type.
|
|
16
|
+
*/
|
|
17
|
+
export type FalClient = Pick<SdkFalClient, 'subscribe'> & {
|
|
18
|
+
queue: Pick<QueueClient, 'submit' | 'status' | 'result' | 'cancel'>;
|
|
19
|
+
storage: Pick<StorageClient, 'upload'>;
|
|
20
|
+
};
|
|
21
|
+
interface ApiErrorArgs<Body> {
|
|
22
|
+
message: string;
|
|
23
|
+
status: number;
|
|
24
|
+
body?: Body;
|
|
25
|
+
requestId?: string;
|
|
26
|
+
timeoutType?: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Thrown when fal answers with a status that is not OK. Same name and fields
|
|
30
|
+
* as the `@fal-ai/client` `ApiError`.
|
|
31
|
+
*/
|
|
32
|
+
export declare class ApiError<Body = unknown> extends Error {
|
|
33
|
+
readonly status: number;
|
|
34
|
+
readonly body: Body | undefined;
|
|
35
|
+
readonly requestId: string;
|
|
36
|
+
readonly timeoutType?: string;
|
|
37
|
+
constructor({ message, status, body, requestId, timeoutType, }: ApiErrorArgs<Body>);
|
|
38
|
+
/** True when the request hit the timeout that the caller asked for. */
|
|
39
|
+
get isUserTimeout(): boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Thrown for a 422 answer. Same name and fields as the `@fal-ai/client`
|
|
43
|
+
* `ValidationError`.
|
|
44
|
+
*/
|
|
45
|
+
export declare class ValidationError extends ApiError<{
|
|
46
|
+
detail?: Array<ValidationErrorInfo> | string;
|
|
47
|
+
}> {
|
|
48
|
+
constructor(args: ApiErrorArgs<{
|
|
49
|
+
detail?: Array<ValidationErrorInfo> | string;
|
|
50
|
+
}>);
|
|
51
|
+
get fieldErrors(): Array<ValidationErrorInfo>;
|
|
52
|
+
getFieldErrors(field: string): ValidationErrorInfo[];
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Create a fal client that talks to the fal queue and storage REST API with
|
|
56
|
+
* `fetch`. It has the same method names, arguments, results, and errors as the
|
|
57
|
+
* `@fal-ai/client` methods the adapters use.
|
|
58
|
+
*
|
|
59
|
+
* @param options credentials, the `fetch` to use, and an optional proxy URL.
|
|
60
|
+
* @example
|
|
61
|
+
* const client = createFalClient({ credentials: 'key', fetch })
|
|
62
|
+
* const { data } = await client.subscribe('fal-ai/flux/dev', { input })
|
|
63
|
+
*/
|
|
64
|
+
export declare function createFalClient(options: FalClientOptions): FalClient;
|
|
65
|
+
export {};
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
//#region src/client/index.ts
|
|
2
|
+
/**
|
|
3
|
+
* Thrown when fal answers with a status that is not OK. Same name and fields
|
|
4
|
+
* as the `@fal-ai/client` `ApiError`.
|
|
5
|
+
*/
|
|
6
|
+
var ApiError = class extends Error {
|
|
7
|
+
status;
|
|
8
|
+
body;
|
|
9
|
+
requestId;
|
|
10
|
+
timeoutType;
|
|
11
|
+
constructor({ message, status, body, requestId, timeoutType }) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "ApiError";
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.body = body;
|
|
16
|
+
this.requestId = requestId || "";
|
|
17
|
+
this.timeoutType = timeoutType;
|
|
18
|
+
}
|
|
19
|
+
/** True when the request hit the timeout that the caller asked for. */
|
|
20
|
+
get isUserTimeout() {
|
|
21
|
+
return this.status === 504 && this.timeoutType === "user";
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Thrown for a 422 answer. Same name and fields as the `@fal-ai/client`
|
|
26
|
+
* `ValidationError`.
|
|
27
|
+
*/
|
|
28
|
+
var ValidationError = class extends ApiError {
|
|
29
|
+
constructor(args) {
|
|
30
|
+
super(args);
|
|
31
|
+
this.name = "ValidationError";
|
|
32
|
+
}
|
|
33
|
+
get fieldErrors() {
|
|
34
|
+
const detail = this.body?.detail;
|
|
35
|
+
if (typeof detail === "string") return [{
|
|
36
|
+
loc: ["body"],
|
|
37
|
+
msg: detail,
|
|
38
|
+
type: "value_error"
|
|
39
|
+
}];
|
|
40
|
+
return detail || [];
|
|
41
|
+
}
|
|
42
|
+
getFieldErrors(field) {
|
|
43
|
+
return this.fieldErrors.filter((error) => error.loc.at(-1) === field);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var RETRYABLE_STATUS_CODES = [
|
|
47
|
+
429,
|
|
48
|
+
502,
|
|
49
|
+
503,
|
|
50
|
+
504
|
|
51
|
+
];
|
|
52
|
+
var DEFAULT_RETRY = {
|
|
53
|
+
maxRetries: 3,
|
|
54
|
+
maxDelay: 3e4,
|
|
55
|
+
statusCodes: RETRYABLE_STATUS_CODES
|
|
56
|
+
};
|
|
57
|
+
var QUEUE_RETRY = {
|
|
58
|
+
...DEFAULT_RETRY,
|
|
59
|
+
maxDelay: 6e4
|
|
60
|
+
};
|
|
61
|
+
var QUEUE_STATUS_RETRY = {
|
|
62
|
+
maxRetries: 5,
|
|
63
|
+
maxDelay: 3e4,
|
|
64
|
+
statusCodes: [...RETRYABLE_STATUS_CODES, 500]
|
|
65
|
+
};
|
|
66
|
+
var NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
67
|
+
"ECONNABORTED",
|
|
68
|
+
"ECONNREFUSED",
|
|
69
|
+
"ECONNRESET",
|
|
70
|
+
"EAI_AGAIN",
|
|
71
|
+
"EHOSTUNREACH",
|
|
72
|
+
"ENETUNREACH",
|
|
73
|
+
"ENOTFOUND",
|
|
74
|
+
"EPIPE",
|
|
75
|
+
"ETIMEDOUT",
|
|
76
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
77
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
78
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
79
|
+
"UND_ERR_SOCKET"
|
|
80
|
+
]);
|
|
81
|
+
var POLL_INTERVAL_MS = 500;
|
|
82
|
+
var MULTIPART_THRESHOLD_BYTES = 94371840;
|
|
83
|
+
var UPLOAD_INITIATE_URL = "https://rest.fal.ai/storage/upload/initiate?storage_type=fal-cdn-v3";
|
|
84
|
+
var ENDPOINT_NAMESPACES = ["workflows", "comfy"];
|
|
85
|
+
var EXPIRATION_SECONDS = {
|
|
86
|
+
never: void 0,
|
|
87
|
+
immediate: 60,
|
|
88
|
+
"1h": 3600,
|
|
89
|
+
"1d": 86400,
|
|
90
|
+
"7d": 604800,
|
|
91
|
+
"30d": 2592e3,
|
|
92
|
+
"1y": 31536e3
|
|
93
|
+
};
|
|
94
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
95
|
+
var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
|
|
96
|
+
function isPlainObject(value) {
|
|
97
|
+
return !!value && Object.getPrototypeOf(value) === Object.prototype;
|
|
98
|
+
}
|
|
99
|
+
/** Transport errors (reset, DNS, socket timeout) are retried. Aborts are not. */
|
|
100
|
+
function isNetworkError(error) {
|
|
101
|
+
const seen = /* @__PURE__ */ new Set();
|
|
102
|
+
let current = error;
|
|
103
|
+
let hasNetworkCode = false;
|
|
104
|
+
while (current && typeof current === "object" && !seen.has(current)) {
|
|
105
|
+
seen.add(current);
|
|
106
|
+
const name = "name" in current ? current.name : void 0;
|
|
107
|
+
const code = "code" in current ? current.code : void 0;
|
|
108
|
+
if (name === "AbortError" || name === "TimeoutError") return false;
|
|
109
|
+
if (typeof code === "string" && NETWORK_ERROR_CODES.has(code)) hasNetworkCode = true;
|
|
110
|
+
current = "cause" in current ? current.cause : void 0;
|
|
111
|
+
}
|
|
112
|
+
return hasNetworkCode || error instanceof TypeError && /fetch failed/i.test(error.message);
|
|
113
|
+
}
|
|
114
|
+
function isRetryable(error, statusCodes) {
|
|
115
|
+
if (error instanceof ApiError) return !error.isUserTimeout && statusCodes.includes(error.status);
|
|
116
|
+
return isNetworkError(error);
|
|
117
|
+
}
|
|
118
|
+
/** Exponential backoff from 1 s, doubled per attempt, capped, with +-25% jitter. */
|
|
119
|
+
function backoffDelay(attempt, maxDelay) {
|
|
120
|
+
const delay = Math.min(1e3 * 2 ** attempt, maxDelay);
|
|
121
|
+
return Math.max(0, delay + .25 * delay * (Math.random() * 2 - 1));
|
|
122
|
+
}
|
|
123
|
+
/** Reads a fal response, or throws `ApiError` / `ValidationError`. */
|
|
124
|
+
async function parseResponse(response) {
|
|
125
|
+
const { status, statusText } = response;
|
|
126
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
127
|
+
const requestId = response.headers.get("x-fal-request-id") || void 0;
|
|
128
|
+
const timeoutType = response.headers.get("x-fal-request-timeout-type") || void 0;
|
|
129
|
+
const isJson = contentType.includes("application/json");
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
if (!isJson) throw new ApiError({
|
|
132
|
+
message: `HTTP ${status}: ${statusText}`,
|
|
133
|
+
status,
|
|
134
|
+
requestId,
|
|
135
|
+
timeoutType
|
|
136
|
+
});
|
|
137
|
+
const body = await response.json();
|
|
138
|
+
throw new (status === 422 ? ValidationError : ApiError)({
|
|
139
|
+
message: body.message || statusText,
|
|
140
|
+
status,
|
|
141
|
+
body,
|
|
142
|
+
requestId,
|
|
143
|
+
timeoutType
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
if (isJson) return response.json();
|
|
147
|
+
if (contentType.includes("application/octet-stream")) return response.arrayBuffer();
|
|
148
|
+
return response.text();
|
|
149
|
+
}
|
|
150
|
+
/** `123-app` becomes `123/app`. Ids that already have a `/` stay as they are. */
|
|
151
|
+
function normalizeEndpointId(id) {
|
|
152
|
+
if (id.includes("/")) return id;
|
|
153
|
+
const match = /^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(id);
|
|
154
|
+
if (!match) throw new Error(`Invalid app id: ${id}. Must be in the format <appOwner>/<appId>`);
|
|
155
|
+
return `${match[1]}/${match[2]}`;
|
|
156
|
+
}
|
|
157
|
+
/** Status and result URLs use only `[namespace/]owner/alias`, not the subpath. */
|
|
158
|
+
function queueAppId(endpointId) {
|
|
159
|
+
const parts = normalizeEndpointId(endpointId).split("/");
|
|
160
|
+
const hasNamespace = ENDPOINT_NAMESPACES.includes(parts[0] ?? "");
|
|
161
|
+
const [owner, alias] = hasNamespace ? parts.slice(1) : parts;
|
|
162
|
+
return `${hasNamespace ? `${parts[0]}/` : ""}${owner}/${alias}`;
|
|
163
|
+
}
|
|
164
|
+
function isFalUrl(url) {
|
|
165
|
+
try {
|
|
166
|
+
return /(fal\.(ai|run))$/.test(new URL(url).host);
|
|
167
|
+
} catch {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function queueUrl(id, path = "", query) {
|
|
172
|
+
const search = query ? `?${new URLSearchParams(query).toString()}` : "";
|
|
173
|
+
const cleanPath = path.replace(/^\//, "").replace(/\/{2,}/, "/");
|
|
174
|
+
if (isFalUrl(id)) return `${id.endsWith("/") ? id : `${id}/`}${cleanPath}${search}`;
|
|
175
|
+
return `${`https://queue.fal.run/${normalizeEndpointId(id)}/${cleanPath}`.replace(/\/$/, "")}${search}`;
|
|
176
|
+
}
|
|
177
|
+
function lifecycleConfig(lifecycle) {
|
|
178
|
+
if (!lifecycle) return void 0;
|
|
179
|
+
const { expiresIn, initialAcl } = lifecycle;
|
|
180
|
+
const seconds = typeof expiresIn === "number" ? expiresIn : expiresIn === void 0 ? void 0 : EXPIRATION_SECONDS[expiresIn];
|
|
181
|
+
const config = {
|
|
182
|
+
...seconds !== void 0 ? { expiration_duration_seconds: seconds } : {},
|
|
183
|
+
...initialAcl !== void 0 ? { initial_acl: initialAcl } : {}
|
|
184
|
+
};
|
|
185
|
+
return Object.keys(config).length > 0 ? config : void 0;
|
|
186
|
+
}
|
|
187
|
+
function uploadFileName(file, contentType) {
|
|
188
|
+
if (file instanceof File && file.name) return file.name;
|
|
189
|
+
const extension = contentType.split("/")[1]?.split(/[-;]/)[0] ?? "bin";
|
|
190
|
+
return `${Date.now()}.${extension}`;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Create a fal client that talks to the fal queue and storage REST API with
|
|
194
|
+
* `fetch`. It has the same method names, arguments, results, and errors as the
|
|
195
|
+
* `@fal-ai/client` methods the adapters use.
|
|
196
|
+
*
|
|
197
|
+
* @param options credentials, the `fetch` to use, and an optional proxy URL.
|
|
198
|
+
* @example
|
|
199
|
+
* const client = createFalClient({ credentials: 'key', fetch })
|
|
200
|
+
* const { data } = await client.subscribe('fal-ai/flux/dev', { input })
|
|
201
|
+
*/
|
|
202
|
+
function createFalClient(options) {
|
|
203
|
+
const { credentials, proxyUrl } = options;
|
|
204
|
+
if (isBrowser() && credentials) console.warn("The fal credentials are exposed in the browser's environment. That's not recommended for production use cases.");
|
|
205
|
+
async function send(method, url, { body, headers, signal, retry = DEFAULT_RETRY } = {}) {
|
|
206
|
+
const useProxy = proxyUrl !== void 0 && isBrowser();
|
|
207
|
+
for (let attempt = 0;; attempt++) try {
|
|
208
|
+
const response = await options.fetch(useProxy ? proxyUrl : url, {
|
|
209
|
+
method,
|
|
210
|
+
headers: {
|
|
211
|
+
...credentials ? { Authorization: `Key ${credentials}` } : {},
|
|
212
|
+
Accept: "application/json",
|
|
213
|
+
"Content-Type": "application/json",
|
|
214
|
+
...headers,
|
|
215
|
+
...useProxy ? { "x-fal-target-url": url } : {}
|
|
216
|
+
},
|
|
217
|
+
signal,
|
|
218
|
+
body: method !== "GET" && body ? JSON.stringify(body) : void 0
|
|
219
|
+
});
|
|
220
|
+
return {
|
|
221
|
+
response,
|
|
222
|
+
data: await parseResponse(response)
|
|
223
|
+
};
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (attempt === retry.maxRetries || !isRetryable(error, retry.statusCodes) || signal?.aborted) throw error;
|
|
226
|
+
await sleep(backoffDelay(attempt, retry.maxDelay));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async function transformInput(input) {
|
|
230
|
+
if (Array.isArray(input)) return Promise.all(input.map((item) => transformInput(item)));
|
|
231
|
+
if (input instanceof Blob) return storage.upload(input);
|
|
232
|
+
if (isPlainObject(input)) {
|
|
233
|
+
const entries = Object.entries(input);
|
|
234
|
+
return Object.fromEntries(await Promise.all(entries.map(async ([key, value]) => [key, await transformInput(value)])));
|
|
235
|
+
}
|
|
236
|
+
return input;
|
|
237
|
+
}
|
|
238
|
+
const storage = { async upload(file, uploadOptions) {
|
|
239
|
+
if (file.size > MULTIPART_THRESHOLD_BYTES) return (await import("@fal-ai/client")).createFalClient(options).storage.upload(file, uploadOptions);
|
|
240
|
+
const contentType = file.type || "application/octet-stream";
|
|
241
|
+
const lifecycle = lifecycleConfig(uploadOptions?.lifecycle);
|
|
242
|
+
const { data } = await send("POST", UPLOAD_INITIATE_URL, {
|
|
243
|
+
body: {
|
|
244
|
+
content_type: contentType,
|
|
245
|
+
file_name: uploadFileName(file, contentType)
|
|
246
|
+
},
|
|
247
|
+
headers: lifecycle ? { "X-Fal-Object-Lifecycle": JSON.stringify(lifecycle) } : {}
|
|
248
|
+
});
|
|
249
|
+
await parseResponse(await options.fetch(data.upload_url, {
|
|
250
|
+
method: "PUT",
|
|
251
|
+
body: file,
|
|
252
|
+
headers: { "Content-Type": contentType }
|
|
253
|
+
}));
|
|
254
|
+
return data.file_url;
|
|
255
|
+
} };
|
|
256
|
+
const queue = {
|
|
257
|
+
async submit(endpointId, { input, abortSignal }) {
|
|
258
|
+
const body = input ? await transformInput(input) : void 0;
|
|
259
|
+
const { data } = await send("POST", queueUrl(endpointId), {
|
|
260
|
+
body,
|
|
261
|
+
headers: { "x-fal-queue-priority": "normal" },
|
|
262
|
+
signal: abortSignal,
|
|
263
|
+
retry: QUEUE_RETRY
|
|
264
|
+
});
|
|
265
|
+
return data;
|
|
266
|
+
},
|
|
267
|
+
async status(endpointId, { requestId, logs = false, abortSignal }) {
|
|
268
|
+
const { data } = await send("GET", queueUrl(queueAppId(endpointId), `/requests/${requestId}/status`, { logs: logs ? "1" : "0" }), {
|
|
269
|
+
signal: abortSignal,
|
|
270
|
+
retry: QUEUE_STATUS_RETRY
|
|
271
|
+
});
|
|
272
|
+
return data;
|
|
273
|
+
},
|
|
274
|
+
async result(endpointId, { requestId, abortSignal }) {
|
|
275
|
+
const { response, data } = await send("GET", queueUrl(queueAppId(endpointId), `/requests/${requestId}`), {
|
|
276
|
+
signal: abortSignal,
|
|
277
|
+
retry: QUEUE_RETRY
|
|
278
|
+
});
|
|
279
|
+
return {
|
|
280
|
+
data,
|
|
281
|
+
requestId: response.headers.get("x-fal-request-id") || ""
|
|
282
|
+
};
|
|
283
|
+
},
|
|
284
|
+
async cancel(endpointId, { requestId, abortSignal }) {
|
|
285
|
+
await send("PUT", queueUrl(queueAppId(endpointId), `/requests/${requestId}/cancel`), { signal: abortSignal });
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
return {
|
|
289
|
+
queue,
|
|
290
|
+
storage,
|
|
291
|
+
async subscribe(endpointId, subscribeOptions) {
|
|
292
|
+
const { request_id: requestId } = await queue.submit(endpointId, subscribeOptions);
|
|
293
|
+
const { abortSignal, logs, onEnqueue } = subscribeOptions;
|
|
294
|
+
onEnqueue?.(requestId);
|
|
295
|
+
while ((await queue.status(endpointId, {
|
|
296
|
+
requestId,
|
|
297
|
+
logs,
|
|
298
|
+
abortSignal
|
|
299
|
+
})).status !== "COMPLETED") await sleep(POLL_INTERVAL_MS);
|
|
300
|
+
return queue.result(endpointId, { requestId });
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
//#endregion
|
|
305
|
+
export { ApiError, ValidationError, createFalClient };
|
|
306
|
+
|
|
307
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/client/index.ts"],"sourcesContent":["import type {\n FalClient as SdkFalClient,\n QueueClient,\n StorageClient,\n StorageSettings,\n ValidationErrorInfo,\n} from '@fal-ai/client'\n\n/**\n * Config for {@link createFalClient}. These are the `@fal-ai/client` config\n * fields this package uses.\n */\nexport interface FalClientOptions {\n /** Sent as `Authorization: Key <credentials>`. */\n credentials: string\n fetch: typeof fetch\n /** In a browser, requests go here with the real URL in `x-fal-target-url`. */\n proxyUrl?: string\n}\n\n/**\n * The part of the `@fal-ai/client` client that the adapters call. A real SDK\n * client also fits this type.\n */\nexport type FalClient = Pick<SdkFalClient, 'subscribe'> & {\n queue: Pick<QueueClient, 'submit' | 'status' | 'result' | 'cancel'>\n storage: Pick<StorageClient, 'upload'>\n}\n\ninterface ApiErrorArgs<Body> {\n message: string\n status: number\n body?: Body\n requestId?: string\n timeoutType?: string\n}\n\n/**\n * Thrown when fal answers with a status that is not OK. Same name and fields\n * as the `@fal-ai/client` `ApiError`.\n */\nexport class ApiError<Body = unknown> extends Error {\n readonly status: number\n readonly body: Body | undefined\n readonly requestId: string\n readonly timeoutType?: string\n\n constructor({\n message,\n status,\n body,\n requestId,\n timeoutType,\n }: ApiErrorArgs<Body>) {\n super(message)\n this.name = 'ApiError'\n this.status = status\n this.body = body\n this.requestId = requestId || ''\n this.timeoutType = timeoutType\n }\n\n /** True when the request hit the timeout that the caller asked for. */\n get isUserTimeout() {\n return this.status === 504 && this.timeoutType === 'user'\n }\n}\n\n/**\n * Thrown for a 422 answer. Same name and fields as the `@fal-ai/client`\n * `ValidationError`.\n */\nexport class ValidationError extends ApiError<{\n detail?: Array<ValidationErrorInfo> | string\n}> {\n constructor(\n args: ApiErrorArgs<{ detail?: Array<ValidationErrorInfo> | string }>,\n ) {\n super(args)\n this.name = 'ValidationError'\n }\n\n get fieldErrors(): Array<ValidationErrorInfo> {\n const detail = this.body?.detail\n if (typeof detail === 'string') {\n return [{ loc: ['body'], msg: detail, type: 'value_error' }]\n }\n return detail || []\n }\n\n getFieldErrors(field: string) {\n return this.fieldErrors.filter((error) => error.loc.at(-1) === field)\n }\n}\n\ninterface RetryPolicy {\n maxRetries: number\n maxDelay: number\n statusCodes: Array<number>\n}\n\nconst RETRYABLE_STATUS_CODES = [429, 502, 503, 504]\nconst DEFAULT_RETRY: RetryPolicy = {\n maxRetries: 3,\n maxDelay: 30_000,\n statusCodes: RETRYABLE_STATUS_CODES,\n}\nconst QUEUE_RETRY: RetryPolicy = { ...DEFAULT_RETRY, maxDelay: 60_000 }\nconst QUEUE_STATUS_RETRY: RetryPolicy = {\n maxRetries: 5,\n maxDelay: 30_000,\n statusCodes: [...RETRYABLE_STATUS_CODES, 500],\n}\n\nconst NETWORK_ERROR_CODES = new Set([\n 'ECONNABORTED',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EAI_AGAIN',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'EPIPE',\n 'ETIMEDOUT',\n 'UND_ERR_BODY_TIMEOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_HEADERS_TIMEOUT',\n 'UND_ERR_SOCKET',\n])\n\nconst POLL_INTERVAL_MS = 500\nconst MULTIPART_THRESHOLD_BYTES = 90 * 1024 * 1024\nconst UPLOAD_INITIATE_URL =\n 'https://rest.fal.ai/storage/upload/initiate?storage_type=fal-cdn-v3'\nconst ENDPOINT_NAMESPACES = ['workflows', 'comfy']\nconst EXPIRATION_SECONDS: Record<string, number | undefined> = {\n never: undefined,\n immediate: 60,\n '1h': 3600,\n '1d': 86400,\n '7d': 604800,\n '30d': 2592000,\n '1y': 31536000,\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nconst isBrowser = () =>\n typeof window !== 'undefined' && typeof window.document !== 'undefined'\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return !!value && Object.getPrototypeOf(value) === Object.prototype\n}\n\n/** Transport errors (reset, DNS, socket timeout) are retried. Aborts are not. */\nfunction isNetworkError(error: unknown) {\n const seen = new Set<unknown>()\n let current = error\n let hasNetworkCode = false\n while (current && typeof current === 'object' && !seen.has(current)) {\n seen.add(current)\n const name = 'name' in current ? current.name : undefined\n const code = 'code' in current ? current.code : undefined\n if (name === 'AbortError' || name === 'TimeoutError') return false\n if (typeof code === 'string' && NETWORK_ERROR_CODES.has(code)) {\n hasNetworkCode = true\n }\n current = 'cause' in current ? current.cause : undefined\n }\n return (\n hasNetworkCode ||\n (error instanceof TypeError && /fetch failed/i.test(error.message))\n )\n}\n\nfunction isRetryable(error: unknown, statusCodes: Array<number>) {\n if (error instanceof ApiError) {\n return !error.isUserTimeout && statusCodes.includes(error.status)\n }\n return isNetworkError(error)\n}\n\n/** Exponential backoff from 1 s, doubled per attempt, capped, with +-25% jitter. */\nfunction backoffDelay(attempt: number, maxDelay: number) {\n const delay = Math.min(1000 * 2 ** attempt, maxDelay)\n return Math.max(0, delay + 0.25 * delay * (Math.random() * 2 - 1))\n}\n\n/** Reads a fal response, or throws `ApiError` / `ValidationError`. */\nasync function parseResponse(response: Response) {\n const { status, statusText } = response\n const contentType = response.headers.get('Content-Type') ?? ''\n const requestId = response.headers.get('x-fal-request-id') || undefined\n const timeoutType =\n response.headers.get('x-fal-request-timeout-type') || undefined\n const isJson = contentType.includes('application/json')\n if (!response.ok) {\n if (!isJson) {\n throw new ApiError({\n message: `HTTP ${status}: ${statusText}`,\n status,\n requestId,\n timeoutType,\n })\n }\n const body = await response.json()\n const ErrorType = status === 422 ? ValidationError : ApiError\n throw new ErrorType({\n message: body.message || statusText,\n status,\n body,\n requestId,\n timeoutType,\n })\n }\n if (isJson) return response.json()\n if (contentType.includes('application/octet-stream')) {\n return response.arrayBuffer()\n }\n return response.text()\n}\n\n/** `123-app` becomes `123/app`. Ids that already have a `/` stay as they are. */\nfunction normalizeEndpointId(id: string) {\n if (id.includes('/')) return id\n const match = /^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(id)\n if (!match) {\n throw new Error(\n `Invalid app id: ${id}. Must be in the format <appOwner>/<appId>`,\n )\n }\n return `${match[1]}/${match[2]}`\n}\n\n/** Status and result URLs use only `[namespace/]owner/alias`, not the subpath. */\nfunction queueAppId(endpointId: string) {\n const parts = normalizeEndpointId(endpointId).split('/')\n const hasNamespace = ENDPOINT_NAMESPACES.includes(parts[0] ?? '')\n const [owner, alias] = hasNamespace ? parts.slice(1) : parts\n return `${hasNamespace ? `${parts[0]}/` : ''}${owner}/${alias}`\n}\n\nfunction isFalUrl(url: string) {\n try {\n return /(fal\\.(ai|run))$/.test(new URL(url).host)\n } catch {\n return false\n }\n}\n\nfunction queueUrl(id: string, path = '', query?: Record<string, string>) {\n const search = query ? `?${new URLSearchParams(query).toString()}` : ''\n const cleanPath = path.replace(/^\\//, '').replace(/\\/{2,}/, '/')\n if (isFalUrl(id)) {\n return `${id.endsWith('/') ? id : `${id}/`}${cleanPath}${search}`\n }\n const url = `https://queue.fal.run/${normalizeEndpointId(id)}/${cleanPath}`\n return `${url.replace(/\\/$/, '')}${search}`\n}\n\nfunction lifecycleConfig(lifecycle: StorageSettings | undefined) {\n if (!lifecycle) return undefined\n const { expiresIn, initialAcl } = lifecycle\n const seconds =\n typeof expiresIn === 'number'\n ? expiresIn\n : expiresIn === undefined\n ? undefined\n : EXPIRATION_SECONDS[expiresIn]\n const config = {\n ...(seconds !== undefined ? { expiration_duration_seconds: seconds } : {}),\n ...(initialAcl !== undefined ? { initial_acl: initialAcl } : {}),\n }\n return Object.keys(config).length > 0 ? config : undefined\n}\n\nfunction uploadFileName(file: Blob, contentType: string) {\n if (file instanceof File && file.name) return file.name\n const extension = contentType.split('/')[1]?.split(/[-;]/)[0] ?? 'bin'\n return `${Date.now()}.${extension}`\n}\n\ninterface SendOptions {\n body?: unknown\n headers?: Record<string, string>\n signal?: AbortSignal\n retry?: RetryPolicy\n}\n\n/**\n * Create a fal client that talks to the fal queue and storage REST API with\n * `fetch`. It has the same method names, arguments, results, and errors as the\n * `@fal-ai/client` methods the adapters use.\n *\n * @param options credentials, the `fetch` to use, and an optional proxy URL.\n * @example\n * const client = createFalClient({ credentials: 'key', fetch })\n * const { data } = await client.subscribe('fal-ai/flux/dev', { input })\n */\nexport function createFalClient(options: FalClientOptions) {\n const { credentials, proxyUrl } = options\n if (isBrowser() && credentials) {\n console.warn(\n \"The fal credentials are exposed in the browser's environment. \" +\n \"That's not recommended for production use cases.\",\n )\n }\n\n async function send(\n method: 'GET' | 'POST' | 'PUT',\n url: string,\n { body, headers, signal, retry = DEFAULT_RETRY }: SendOptions = {},\n ) {\n // Same as the SDK proxy middleware: without a `when` rule it only\n // proxies in a browser.\n const useProxy = proxyUrl !== undefined && isBrowser()\n for (let attempt = 0; ; attempt++) {\n try {\n const response = await options.fetch(useProxy ? proxyUrl : url, {\n method,\n headers: {\n ...(credentials ? { Authorization: `Key ${credentials}` } : {}),\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n ...headers,\n ...(useProxy ? { 'x-fal-target-url': url } : {}),\n },\n signal,\n body: method !== 'GET' && body ? JSON.stringify(body) : undefined,\n })\n return { response, data: await parseResponse(response) }\n } catch (error) {\n const isLastTry =\n attempt === retry.maxRetries ||\n !isRetryable(error, retry.statusCodes) ||\n signal?.aborted\n if (isLastTry) throw error\n await sleep(backoffDelay(attempt, retry.maxDelay))\n }\n }\n }\n\n async function transformInput(input: unknown): Promise<unknown> {\n if (Array.isArray(input)) {\n return Promise.all(input.map((item) => transformInput(item)))\n }\n if (input instanceof Blob) return storage.upload(input)\n if (isPlainObject(input)) {\n const entries = Object.entries(input)\n return Object.fromEntries(\n await Promise.all(\n entries.map(async ([key, value]) => [\n key,\n await transformInput(value),\n ]),\n ),\n )\n }\n return input\n }\n\n const storage: FalClient['storage'] = {\n async upload(file, uploadOptions) {\n if (file.size > MULTIPART_THRESHOLD_BYTES) {\n // ponytail: multipart upload stays in the SDK. Only files over 90 MB\n // load it.\n const sdk = await import('@fal-ai/client')\n return sdk.createFalClient(options).storage.upload(file, uploadOptions)\n }\n const contentType = file.type || 'application/octet-stream'\n const lifecycle = lifecycleConfig(uploadOptions?.lifecycle)\n const { data } = await send('POST', UPLOAD_INITIATE_URL, {\n body: {\n content_type: contentType,\n file_name: uploadFileName(file, contentType),\n },\n headers: lifecycle\n ? { 'X-Fal-Object-Lifecycle': JSON.stringify(lifecycle) }\n : {},\n })\n const uploaded = await options.fetch(data.upload_url, {\n method: 'PUT',\n body: file,\n headers: { 'Content-Type': contentType },\n })\n await parseResponse(uploaded)\n return data.file_url\n },\n }\n\n const queue: FalClient['queue'] = {\n async submit(endpointId, { input, abortSignal }) {\n const body = input ? await transformInput(input) : undefined\n const { data } = await send('POST', queueUrl(endpointId), {\n body,\n headers: { 'x-fal-queue-priority': 'normal' },\n signal: abortSignal,\n retry: QUEUE_RETRY,\n })\n return data\n },\n async status(endpointId, { requestId, logs = false, abortSignal }) {\n const url = queueUrl(\n queueAppId(endpointId),\n `/requests/${requestId}/status`,\n { logs: logs ? '1' : '0' },\n )\n const { data } = await send('GET', url, {\n signal: abortSignal,\n retry: QUEUE_STATUS_RETRY,\n })\n return data\n },\n async result(endpointId, { requestId, abortSignal }) {\n const url = queueUrl(queueAppId(endpointId), `/requests/${requestId}`)\n const { response, data } = await send('GET', url, {\n signal: abortSignal,\n retry: QUEUE_RETRY,\n })\n return {\n data,\n requestId: response.headers.get('x-fal-request-id') || '',\n }\n },\n async cancel(endpointId, { requestId, abortSignal }) {\n const url = queueUrl(\n queueAppId(endpointId),\n `/requests/${requestId}/cancel`,\n )\n await send('PUT', url, { signal: abortSignal })\n },\n }\n\n const client: FalClient = {\n queue,\n storage,\n async subscribe(endpointId, subscribeOptions) {\n const { request_id: requestId } = await queue.submit(\n endpointId,\n subscribeOptions,\n )\n const { abortSignal, logs, onEnqueue } = subscribeOptions\n onEnqueue?.(requestId)\n // Same as the SDK: poll right away, then every 500 ms until COMPLETED.\n while (\n (await queue.status(endpointId, { requestId, logs, abortSignal }))\n .status !== 'COMPLETED'\n ) {\n await sleep(POLL_INTERVAL_MS)\n }\n // The SDK does not pass the abort signal to the result request.\n return queue.result(endpointId, { requestId })\n },\n }\n return client\n}\n"],"mappings":";;;;;AAyCA,IAAa,WAAb,cAA8C,MAAM;CAClD;CACA;CACA;CACA;CAEA,YAAY,EACV,SACA,QACA,MACA,WACA,eACqB;EACrB,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;EACZ,KAAK,YAAY,aAAa;EAC9B,KAAK,cAAc;CACrB;;CAGA,IAAI,gBAAgB;EAClB,OAAO,KAAK,WAAW,OAAO,KAAK,gBAAgB;CACrD;AACF;;;;;AAMA,IAAa,kBAAb,cAAqC,SAElC;CACD,YACE,MACA;EACA,MAAM,IAAI;EACV,KAAK,OAAO;CACd;CAEA,IAAI,cAA0C;EAC5C,MAAM,SAAS,KAAK,MAAM;EAC1B,IAAI,OAAO,WAAW,UACpB,OAAO,CAAC;GAAE,KAAK,CAAC,MAAM;GAAG,KAAK;GAAQ,MAAM;EAAc,CAAC;EAE7D,OAAO,UAAU,CAAC;CACpB;CAEA,eAAe,OAAe;EAC5B,OAAO,KAAK,YAAY,QAAQ,UAAU,MAAM,IAAI,GAAG,EAAE,MAAM,KAAK;CACtE;AACF;AAQA,IAAM,yBAAyB;CAAC;CAAK;CAAK;CAAK;AAAG;AAClD,IAAM,gBAA6B;CACjC,YAAY;CACZ,UAAU;CACV,aAAa;AACf;AACA,IAAM,cAA2B;CAAE,GAAG;CAAe,UAAU;AAAO;AACtE,IAAM,qBAAkC;CACtC,YAAY;CACZ,UAAU;CACV,aAAa,CAAC,GAAG,wBAAwB,GAAG;AAC9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,OAAO,YAAY,EAAE,WAAW,eAAe;GAKnD,MAAM,KAAK,OAJC,SACV,WAAW,UAAU,GACrB,aAAa,UAAU,QAEP,GAAK,EAAE,QAAQ,YAAY,CAAC;EAChD;CACF;CAuBA,OAAO;EApBL;EACA;EACA,MAAM,UAAU,YAAY,kBAAkB;GAC5C,MAAM,EAAE,YAAY,cAAc,MAAM,MAAM,OAC5C,YACA,gBACF;GACA,MAAM,EAAE,aAAa,MAAM,cAAc;GACzC,YAAY,SAAS;GAErB,QACG,MAAM,MAAM,OAAO,YAAY;IAAE;IAAW;IAAM;GAAY,CAAC,EAAA,CAC7D,WAAW,aAEd,MAAM,MAAM,gBAAgB;GAG9B,OAAO,MAAM,OAAO,YAAY,EAAE,UAAU,CAAC;EAC/C;CAEK;AACT"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -7,4 +7,5 @@ export { FalTranscriptionAdapter, falTranscription, } from './adapters/transcrip
|
|
|
7
7
|
export { FalAudioAdapter, falAudio } from './adapters/audio.js';
|
|
8
8
|
export { FalFilesAdapter, falFiles, type FalFilesConfig, } from './adapters/files.js';
|
|
9
9
|
export { type FalImageProviderOptions, type FalVideoProviderOptions, type FalSpeechProviderOptions, type FalTranscriptionProviderOptions, type FalAudioProviderOptions, type FalModel, type FalModelInput, type FalModelOutput, type FalModelImageSize, type FalModelVideoSize, type FalModelVideoDuration, } from './model-meta.js';
|
|
10
|
-
export { getFalApiKeyFromEnv,
|
|
10
|
+
export { getFalApiKeyFromEnv, generateId, type FalClientConfig, } from './utils/client.js';
|
|
11
|
+
export { configureFalClient } from './utils/configure.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { generateId, getFalApiKeyFromEnv } from "./utils/client.js";
|
|
2
2
|
import { FalImageAdapter, falImage } from "./adapters/image.js";
|
|
3
3
|
import { FalVideoAdapter, falVideo } from "./adapters/video.js";
|
|
4
4
|
import { FAL_LIVE_VIDEO_APP, FAL_LIVE_VIDEO_MODELS, FalLiveVideoAdapter, allowedFalLiveVideoProxyTarget, createFalLiveVideo, falLiveVideo, isFalLiveVideoModel } from "./adapters/live.js";
|
|
@@ -6,4 +6,5 @@ import { FalSpeechAdapter, falSpeech } from "./adapters/speech.js";
|
|
|
6
6
|
import { FalTranscriptionAdapter, falTranscription } from "./adapters/transcription.js";
|
|
7
7
|
import { FalAudioAdapter, falAudio } from "./adapters/audio.js";
|
|
8
8
|
import { FalFilesAdapter, falFiles } from "./adapters/files.js";
|
|
9
|
+
import { configureFalClient } from "./utils/configure.js";
|
|
9
10
|
export { FAL_LIVE_VIDEO_APP, FAL_LIVE_VIDEO_MODELS, FalAudioAdapter, FalFilesAdapter, FalImageAdapter, FalLiveVideoAdapter, FalSpeechAdapter, FalTranscriptionAdapter, FalVideoAdapter, allowedFalLiveVideoProxyTarget, configureFalClient, createFalLiveVideo, falAudio, falFiles, falImage, falLiveVideo, falSpeech, falTranscription, falVideo, generateId, getFalApiKeyFromEnv, isFalLiveVideoModel };
|
|
@@ -10,7 +10,16 @@ export interface FalClientConfig {
|
|
|
10
10
|
fetch?: typeof fetch;
|
|
11
11
|
}
|
|
12
12
|
export declare function getFalApiKeyFromEnv(): string;
|
|
13
|
-
export declare function
|
|
13
|
+
export declare function toFalClientOptions(config?: FalClientConfig): {
|
|
14
|
+
proxyUrl?: string | undefined;
|
|
15
|
+
credentials: string;
|
|
16
|
+
fetch: typeof fetch;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Create the fal client for one adapter. Each adapter has its own client, so
|
|
20
|
+
* two adapters with different API keys do not change each other.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createAdapterFalClient(config?: FalClientConfig): import('../client/index.js').FalClient;
|
|
14
23
|
export declare function generateId(prefix: string): string;
|
|
15
24
|
/**
|
|
16
25
|
* Extract a safe file extension from a URL. Strips query strings, URL
|
package/dist/esm/utils/client.js
CHANGED
|
@@ -1,17 +1,23 @@
|
|
|
1
|
+
import { createFalClient } from "../client/index.js";
|
|
1
2
|
import { createBillingFetch } from "./billing.js";
|
|
2
|
-
import { fal } from "@fal-ai/client";
|
|
3
3
|
import { generateId, getApiKeyFromEnv } from "@tanstack/ai-utils";
|
|
4
4
|
//#region src/utils/client.ts
|
|
5
5
|
function getFalApiKeyFromEnv() {
|
|
6
6
|
return getApiKeyFromEnv("FAL_KEY");
|
|
7
7
|
}
|
|
8
|
-
function
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
credentials: apiKey,
|
|
8
|
+
function toFalClientOptions(config) {
|
|
9
|
+
return {
|
|
10
|
+
credentials: config?.apiKey ?? getFalApiKeyFromEnv(),
|
|
12
11
|
fetch: createBillingFetch(config?.fetch),
|
|
13
12
|
...config?.proxyUrl ? { proxyUrl: config.proxyUrl } : {}
|
|
14
|
-
}
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Create the fal client for one adapter. Each adapter has its own client, so
|
|
17
|
+
* two adapters with different API keys do not change each other.
|
|
18
|
+
*/
|
|
19
|
+
function createAdapterFalClient(config) {
|
|
20
|
+
return createFalClient(toFalClientOptions(config));
|
|
15
21
|
}
|
|
16
22
|
function generateId$1(prefix) {
|
|
17
23
|
return generateId(prefix);
|
|
@@ -99,6 +105,6 @@ function arrayBufferToBase64(bytes) {
|
|
|
99
105
|
return btoa(binary);
|
|
100
106
|
}
|
|
101
107
|
//#endregion
|
|
102
|
-
export { arrayBufferToBase64,
|
|
108
|
+
export { arrayBufferToBase64, createAdapterFalClient, dataUrlToBlob, deriveAudioContentType, extractUrlExtension, generateId$1 as generateId, getFalApiKeyFromEnv, toFalClientOptions };
|
|
103
109
|
|
|
104
110
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../../src/utils/client.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../../src/utils/client.ts"],"sourcesContent":["import { generateId as _generateId, getApiKeyFromEnv } from '@tanstack/ai-utils'\nimport { createFalClient } from '../client/index'\nimport { createBillingFetch } from './billing'\n\nexport interface FalClientConfig {\n apiKey: string\n proxyUrl?: string\n /**\n * Override the underlying fetch used for fal requests. The adapter wraps it to\n * read the `x-fal-billable-units` header (see ./billing.ts), so usage capture\n * still works. Defaults to the global `fetch`. Useful for proxying,\n * instrumentation, or pointing requests at a mock in tests.\n */\n fetch?: typeof fetch\n}\n\nexport function getFalApiKeyFromEnv(): string {\n return getApiKeyFromEnv('FAL_KEY')\n}\n\nexport function toFalClientOptions(config?: FalClientConfig) {\n const apiKey = config?.apiKey ?? getFalApiKeyFromEnv()\n return {\n credentials: apiKey,\n // Wrap the (optionally overridden) fetch to read fal's\n // `x-fal-billable-units` header off every response so adapters can surface\n // the billed quantity as `result.usage`. See ./billing.ts.\n fetch: createBillingFetch(config?.fetch),\n ...(config?.proxyUrl ? { proxyUrl: config.proxyUrl } : {}),\n }\n}\n\n/**\n * Create the fal client for one adapter. Each adapter has its own client, so\n * two adapters with different API keys do not change each other.\n */\nexport function createAdapterFalClient(config?: FalClientConfig) {\n return createFalClient(toFalClientOptions(config))\n}\n\nexport function generateId(prefix: string): string {\n return _generateId(prefix)\n}\n\n/**\n * Extract a safe file extension from a URL. Strips query strings, URL\n * fragments, and any trailing slashes, and only returns the extension when\n * it looks like a real one (2-5 alphanumeric chars). Returns undefined\n * otherwise so callers can fall back to a default.\n */\nexport function extractUrlExtension(url: string): string | undefined {\n // Parse via URL when possible so we only look at the pathname and never\n // mistake a TLD (e.g. the `.com` in `https://x.com/`) for a file extension.\n let pathname: string\n try {\n const parsed = new URL(url)\n pathname = parsed.pathname\n } catch {\n // Fall back to treating the input as a raw path when URL parsing fails\n // (e.g. the caller passed a bare path). Still strip ?query and #fragment.\n pathname = url.split('?')[0]?.split('#')[0] ?? url\n }\n // Drop trailing slashes so `/path/audio.mp3/` still yields `mp3`.\n const normalized = pathname.replace(/\\/+$/, '')\n // Require at least one `/` — otherwise we're looking at an empty pathname\n // (bare-host URLs like `https://x.com/` land here after stripping the\n // trailing slash).\n if (!normalized.includes('/')) return undefined\n const lastSegment = normalized.split('/').pop()\n if (!lastSegment) return undefined\n const extension = lastSegment.split('.').pop()\n if (!extension || extension === lastSegment) return undefined\n return /^[a-z0-9]{2,5}$/i.test(extension) ? extension : undefined\n}\n\n/**\n * Derive a reasonable audio content-type. Prefers the explicit MIME (stripped\n * of parameters), then an extension-based lookup for common audio formats,\n * otherwise falls back to audio/mpeg — fal URLs virtually always serve mp3.\n */\nexport function deriveAudioContentType(\n explicitContentType: string | undefined,\n url: string,\n): string {\n const stripped = explicitContentType?.split(';')[0]?.trim()\n if (stripped) return stripped\n\n const ext = extractUrlExtension(url)?.toLowerCase()\n switch (ext) {\n case 'mp3':\n return 'audio/mpeg'\n case 'wav':\n return 'audio/wav'\n case 'ogg':\n case 'oga':\n return 'audio/ogg'\n case 'flac':\n return 'audio/flac'\n case 'aac':\n return 'audio/aac'\n case 'm4a':\n case 'mp4':\n return 'audio/mp4'\n case 'webm':\n return 'audio/webm'\n case undefined:\n default:\n return 'audio/mpeg'\n }\n}\n\n/**\n * Decode a `data:` URL into a Blob so fal-client can auto-upload it via\n * `fal.storage.upload`. fal's inference API rejects data URLs with a 422\n * \"Unsupported data URL\", so we convert them before handing them off.\n *\n * Supports both base64 and URL-encoded data URLs. Returns `undefined` for\n * anything that isn't a data URL, so callers can fall through to other\n * handling (http URLs are passed to fal as-is).\n */\nexport function dataUrlToBlob(value: string): Blob | undefined {\n if (!value.startsWith('data:')) return undefined\n const commaIndex = value.indexOf(',')\n if (commaIndex === -1) return undefined\n\n const header = value.slice(5, commaIndex)\n const payload = value.slice(commaIndex + 1)\n const isBase64 = /;base64$/i.test(header)\n const mimeType = header.split(';')[0] || 'application/octet-stream'\n\n if (isBase64) {\n const binary = atob(payload)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i)\n }\n return new Blob([bytes], { type: mimeType })\n }\n\n return new Blob([decodeURIComponent(payload)], { type: mimeType })\n}\n\n/**\n * Convert an ArrayBuffer to base64 in a cross-runtime way.\n *\n * The naive `btoa(String.fromCharCode(...bytes))` form blows up V8's argument\n * limit (~65k) on realistic audio payloads, so we either use `Buffer` (Node /\n * Bun) or walk the byte array in a single loop (browser).\n */\nexport function arrayBufferToBase64(bytes: ArrayBuffer): string {\n if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {\n return Buffer.from(bytes).toString('base64')\n }\n const view = new Uint8Array(bytes)\n let binary = ''\n for (const byte of view) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary)\n}\n"],"mappings":";;;;AAgBA,SAAgB,sBAA8B;CAC5C,OAAO,iBAAiB,SAAS;AACnC;AAEA,SAAgB,mBAAmB,QAA0B;CAE3D,OAAO;EACL,aAFa,QAAQ,UAAU,oBAAoB;EAMnD,OAAO,mBAAmB,QAAQ,KAAK;EACvC,GAAI,QAAQ,WAAW,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;CAC1D;AACF;;;;;AAMA,SAAgB,uBAAuB,QAA0B;CAC/D,OAAO,gBAAgB,mBAAmB,MAAM,CAAC;AACnD;AAEA,SAAgB,aAAW,QAAwB;CACjD,OAAO,WAAY,MAAM;AAC3B;;;;;;;AAQA,SAAgB,oBAAoB,KAAiC;CAGnE,IAAI;CACJ,IAAI;EAEF,WAAW,IADQ,IAAI,GACZ,CAAA,CAAO;CACpB,QAAQ;EAGN,WAAW,IAAI,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM;CACjD;CAEA,MAAM,aAAa,SAAS,QAAQ,QAAQ,EAAE;CAI9C,IAAI,CAAC,WAAW,SAAS,GAAG,GAAG,OAAO,KAAA;CACtC,MAAM,cAAc,WAAW,MAAM,GAAG,CAAC,CAAC,IAAI;CAC9C,IAAI,CAAC,aAAa,OAAO,KAAA;CACzB,M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C;AACnE;;;;;;;;AASA,SAAgB,oBAAoB,OAA4B;CAC9D,IAAI,OAAO,WAAW,eAAe,OAAO,OAAO,SAAS,YAC1D,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,QAAQ;CAE7C,MAAM,OAAO,IAAI,WAAW,KAAK;CACjC,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,MACjB,UAAU,OAAO,aAAa,IAAI;CAEpC,OAAO,KAAK,MAAM;AACpB"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { FalClientConfig } from './client.js';
|
|
2
|
+
/**
|
|
3
|
+
* Configure the global `fal` client of `@fal-ai/client` with this config, for
|
|
4
|
+
* apps that call `fal` themselves. The adapters do not use the global client.
|
|
5
|
+
*
|
|
6
|
+
* ponytail: this file is the only static import of `@fal-ai/client`. It is a
|
|
7
|
+
* separate module, so a bundle that does not import this function drops it.
|
|
8
|
+
*
|
|
9
|
+
* @param config the API key (or `FAL_KEY` from the environment), an optional
|
|
10
|
+
* proxy URL, and an optional `fetch`.
|
|
11
|
+
*/
|
|
12
|
+
export declare function configureFalClient(config?: FalClientConfig): void;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { toFalClientOptions } from "./client.js";
|
|
2
|
+
import { fal } from "@fal-ai/client";
|
|
3
|
+
//#region src/utils/configure.ts
|
|
4
|
+
/**
|
|
5
|
+
* Configure the global `fal` client of `@fal-ai/client` with this config, for
|
|
6
|
+
* apps that call `fal` themselves. The adapters do not use the global client.
|
|
7
|
+
*
|
|
8
|
+
* ponytail: this file is the only static import of `@fal-ai/client`. It is a
|
|
9
|
+
* separate module, so a bundle that does not import this function drops it.
|
|
10
|
+
*
|
|
11
|
+
* @param config the API key (or `FAL_KEY` from the environment), an optional
|
|
12
|
+
* proxy URL, and an optional `fetch`.
|
|
13
|
+
*/
|
|
14
|
+
function configureFalClient(config) {
|
|
15
|
+
fal.config(toFalClientOptions(config));
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
export { configureFalClient };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=configure.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configure.js","names":[],"sources":["../../../src/utils/configure.ts"],"sourcesContent":["import { fal } from '@fal-ai/client'\nimport { toFalClientOptions } from './client'\nimport type { FalClientConfig } from './client'\n\n/**\n * Configure the global `fal` client of `@fal-ai/client` with this config, for\n * apps that call `fal` themselves. The adapters do not use the global client.\n *\n * ponytail: this file is the only static import of `@fal-ai/client`. It is a\n * separate module, so a bundle that does not import this function drops it.\n *\n * @param config the API key (or `FAL_KEY` from the environment), an optional\n * proxy URL, and an optional `fetch`.\n */\nexport function configureFalClient(config?: FalClientConfig): void {\n fal.config(toFalClientOptions(config))\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAgB,mBAAmB,QAAgC;CACjE,IAAI,OAAO,mBAAmB,MAAM,CAAC;AACvC"}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export { getFalApiKeyFromEnv,
|
|
1
|
+
export { getFalApiKeyFromEnv, generateId, arrayBufferToBase64, dataUrlToBlob, extractUrlExtension, deriveAudioContentType, type FalClientConfig, } from './client.js';
|
|
2
2
|
export { takeBillableUnits, buildFalUsage } from './billing.js';
|
|
3
|
+
export { configureFalClient } from './configure.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-fal",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "fal.ai adapter for TanStack AI image, video, live, audio, speech, and transcription generation.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"import": "./dist/esm/byok.js"
|
|
31
31
|
}
|
|
32
32
|
},
|
|
33
|
+
"sideEffects": false,
|
|
33
34
|
"files": [
|
|
34
35
|
"dist",
|
|
35
36
|
"src"
|
|
@@ -54,15 +55,15 @@
|
|
|
54
55
|
],
|
|
55
56
|
"dependencies": {
|
|
56
57
|
"@fal-ai/client": "^1.10.1",
|
|
57
|
-
"@tanstack/ai-utils": "^1.0
|
|
58
|
+
"@tanstack/ai-utils": "^1.1.0"
|
|
58
59
|
},
|
|
59
60
|
"devDependencies": {
|
|
60
61
|
"@vitest/coverage-v8": "4.1.10",
|
|
61
62
|
"vite": "^8.2.1",
|
|
62
|
-
"@tanstack/ai": "1.
|
|
63
|
+
"@tanstack/ai": "1.2.0"
|
|
63
64
|
},
|
|
64
65
|
"peerDependencies": {
|
|
65
|
-
"@tanstack/ai": "^1.
|
|
66
|
+
"@tanstack/ai": "^1.2.0"
|
|
66
67
|
},
|
|
67
68
|
"scripts": {
|
|
68
69
|
"build": "vite build",
|