vidspotai-shared 1.0.134 → 1.0.135

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,34 @@
1
+ import { IModelSchema } from "../types";
2
+ /**
3
+ * fal.ai-HOSTED video generators — served by FalVideoService
4
+ * (services/aiGen/providers/fal/falVideo.service.ts) over fal's queue API.
5
+ *
6
+ * ─── Kling 4.0 / 4.0 Flash ────────────────────────────────────────────────
7
+ * Kling's native 4.0 API isn't available to us yet (kling.ai/dev/pricing
8
+ * 2026-10-27 lists it "Coming Soon"; resource packs don't cover it), so 4.0
9
+ * ships through fal. Endpoints (schemas pulled 2026-10-27 from
10
+ * fal.ai/api/openapi/queue/openapi.json?endpoint_id=…):
11
+ * fal-ai/kling-video/v4/text-to-video prompt|multi_prompt, 3–30s, 16:9/9:16/1:1/21:9, 720p|1080p
12
+ * fal-ai/kling-video/v4/image-to-video start_image_url (+end, ≤8 middle keyframes); ratio follows the frame
13
+ * fal-ai/kling-video/v4/reference-to-video ≤10 image_urls, ≤5 video_urls (30s total), @Image1/@Video1 citations
14
+ * fal-ai/kling-video/v4/flash/text-to-video 3–20s, 720p only
15
+ * fal-ai/kling-video/v4/flash/image-to-video
16
+ * `resolution` defaults to 1080p on fal — FalVideoService ALWAYS sends it so
17
+ * a std request can't silently bill at the 1080p rate.
18
+ * Native stereo audio is always on (no toggle) → listed in chains.ts AUDIO_MODELS
19
+ * rather than declaring an `audio` field.
20
+ *
21
+ * Pricing verified 2026-10-27 against https://api.fal.ai/v1/models/pricing:
22
+ * v4 text/image/reference-to-video $0.157 / output-second (720p base)
23
+ * v4 flash text/image-to-video $0.094 / output-second (720p only)
24
+ * 1080p = 1.5× (matches Kling's own preview units: 1.0 vs 1.5 units/s).
25
+ *
26
+ * Live-verified 2026-10-27 via FalVideoService: v4 text-to-video (5s 16:9
27
+ * 720p → 5.04s 1280x720 + stereo AAC, ~5 min) and v4 image-to-video (3s →
28
+ * 3.04s, ~6 min). The queue's status/result base is the OWNER app
29
+ * (`fal-ai/kling-video`), not the sub-endpoint — taken from status_url.
30
+ * With a reference VIDEO, fal (like Kling) bills 0.6× the rate on
31
+ * (output × 2) when input ≤ output, else (input + output) seconds.
32
+ */
33
+ export declare const falVideoConfigs: Record<string, IModelSchema>;
34
+ //# sourceMappingURL=falVideo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"falVideo.d.ts","sourceRoot":"","sources":["../../../../src/globals/aiModels/providers/falVideo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAKxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAsExD,CAAC"}
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.falVideoConfigs = void 0;
4
+ const range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i);
5
+ /**
6
+ * fal.ai-HOSTED video generators — served by FalVideoService
7
+ * (services/aiGen/providers/fal/falVideo.service.ts) over fal's queue API.
8
+ *
9
+ * ─── Kling 4.0 / 4.0 Flash ────────────────────────────────────────────────
10
+ * Kling's native 4.0 API isn't available to us yet (kling.ai/dev/pricing
11
+ * 2026-10-27 lists it "Coming Soon"; resource packs don't cover it), so 4.0
12
+ * ships through fal. Endpoints (schemas pulled 2026-10-27 from
13
+ * fal.ai/api/openapi/queue/openapi.json?endpoint_id=…):
14
+ * fal-ai/kling-video/v4/text-to-video prompt|multi_prompt, 3–30s, 16:9/9:16/1:1/21:9, 720p|1080p
15
+ * fal-ai/kling-video/v4/image-to-video start_image_url (+end, ≤8 middle keyframes); ratio follows the frame
16
+ * fal-ai/kling-video/v4/reference-to-video ≤10 image_urls, ≤5 video_urls (30s total), @Image1/@Video1 citations
17
+ * fal-ai/kling-video/v4/flash/text-to-video 3–20s, 720p only
18
+ * fal-ai/kling-video/v4/flash/image-to-video
19
+ * `resolution` defaults to 1080p on fal — FalVideoService ALWAYS sends it so
20
+ * a std request can't silently bill at the 1080p rate.
21
+ * Native stereo audio is always on (no toggle) → listed in chains.ts AUDIO_MODELS
22
+ * rather than declaring an `audio` field.
23
+ *
24
+ * Pricing verified 2026-10-27 against https://api.fal.ai/v1/models/pricing:
25
+ * v4 text/image/reference-to-video $0.157 / output-second (720p base)
26
+ * v4 flash text/image-to-video $0.094 / output-second (720p only)
27
+ * 1080p = 1.5× (matches Kling's own preview units: 1.0 vs 1.5 units/s).
28
+ *
29
+ * Live-verified 2026-10-27 via FalVideoService: v4 text-to-video (5s 16:9
30
+ * 720p → 5.04s 1280x720 + stereo AAC, ~5 min) and v4 image-to-video (3s →
31
+ * 3.04s, ~6 min). The queue's status/result base is the OWNER app
32
+ * (`fal-ai/kling-video`), not the sub-endpoint — taken from status_url.
33
+ * With a reference VIDEO, fal (like Kling) bills 0.6× the rate on
34
+ * (output × 2) when input ≤ output, else (input + output) seconds.
35
+ */
36
+ exports.falVideoConfigs = {
37
+ "fal-kling-v4.0": {
38
+ modelId: "fal-ai/kling-video/v4",
39
+ type: ["text-to-video", "image-to-video"],
40
+ tier: "T3",
41
+ fields: {
42
+ prompt: { required: true },
43
+ aspectRatio: { allowedValues: ["16:9", "9:16", "1:1", "21:9"] },
44
+ // Every integer 3–30 is legal; billed per delivered second.
45
+ duration: { allowedValues: range(3, 30), default: 5 },
46
+ // std→720p, pro→1080p (Kling's own equivalence). Explicit resolution wins.
47
+ mode: { allowedValues: ["std", "pro"] },
48
+ resolution: { allowedValues: ["720p", "1080p"], default: "720p" },
49
+ inputImageUrl: {}, // → start_image_url
50
+ lastFrameImageUrl: {}, // → end_image_url
51
+ referenceImageUrls: { max: 10 }, // → reference-to-video image_urls (@Image1…)
52
+ referenceVideoUrls: { max: 5 }, // → reference-to-video video_urls (@Video1…)
53
+ multiShot: {}, // → multi_prompt[] (≤512 chars/shot)
54
+ },
55
+ concurrentRequests: 5,
56
+ pollIntervalMs: 10000,
57
+ // 30s 1080p generations run long on fal's queue.
58
+ pollTimeoutMs: 30 * 60000,
59
+ cost: {
60
+ perSecondByResolution: { "720p": 0.157, "1080p": 0.2355 },
61
+ videoInputPerSecondByResolution: { "720p": 0.0942, "1080p": 0.1413 },
62
+ },
63
+ guidance: {
64
+ quality: 5,
65
+ speed: 3,
66
+ bestFor: "Kling's newest flagship: long single takes up to 30s, native stereo audio, up to 10 keyframes, and Omni reference (10 images + 5 videos cited as @Image1/@Video1). Best Kling for cinematic, multi-shot storytelling.",
67
+ notes: "Audio is always on and included in the price. 1080p costs 1.5× 720p. A reference video bills on input+output seconds. No 4K yet.",
68
+ },
69
+ },
70
+ // GATED 2026-10-27: a live smoke test of both fal Flash endpoints
71
+ // (flash/text-to-video 3s 9:16, flash/image-to-video 3s) returned fal's
72
+ // canned schema-example clips (12s, 16:9, byte-identical file sizes
73
+ // 3478246 / 2953131) instead of a generation — Flash isn't really live on
74
+ // fal yet. Set KLING_V4_FLASH_LIVE=true (Doppler + Railway) only after a
75
+ // re-test returns a real clip at the requested duration/ratio.
76
+ "fal-kling-v4.0-flash": {
77
+ modelId: "fal-ai/kling-video/v4/flash",
78
+ type: ["text-to-video", "image-to-video"],
79
+ tier: "T2",
80
+ gatedByEnv: "KLING_V4_FLASH_LIVE",
81
+ fields: {
82
+ prompt: { required: true },
83
+ aspectRatio: { allowedValues: ["16:9", "9:16", "1:1", "21:9"] },
84
+ duration: { allowedValues: range(3, 20), default: 5 },
85
+ mode: { allowedValues: ["std"] },
86
+ resolution: { allowedValues: ["720p"], default: "720p" },
87
+ inputImageUrl: {}, // → start_image_url
88
+ },
89
+ concurrentRequests: 5,
90
+ pollIntervalMs: 10000,
91
+ pollTimeoutMs: 20 * 60000,
92
+ cost: {
93
+ perSecondByResolution: { "720p": 0.094 },
94
+ },
95
+ guidance: {
96
+ quality: 4,
97
+ speed: 5,
98
+ bestFor: "Fast, budget Kling 4.0: text or image to video up to 20s with native audio at 720p. Great for drafts, social clips and high-volume B-roll.",
99
+ notes: "720p only, no end frame or references. About 40% cheaper than Kling 4.0.",
100
+ },
101
+ },
102
+ };
@@ -0,0 +1,39 @@
1
+ import { EVideoMode } from "../../types";
2
+ import { BaseAiGenProviderService } from "../baseAiGenProvider.service";
3
+ import { CreditUsageParams, VideoGenerationParams, VideoGenerationResult, VideoStatusParams, VideoStatusResult } from "../types";
4
+ /**
5
+ * Output resolution actually sent to fal. An explicit, allowed `resolution`
6
+ * wins; otherwise mode maps std→720p, pro→1080p (Kling's own equivalence).
7
+ * Flash is 720p-only. Exported so billing prices the SAME resolution the
8
+ * request carried — fal's default is 1080p, so never leave it implicit.
9
+ */
10
+ export declare function resolveFalKlingResolution(modelKey: string, resolution?: string, mode?: EVideoMode | string): "720p" | "1080p";
11
+ /**
12
+ * Generic fal.ai video-generation provider. Today it serves Kling 4.0 and
13
+ * Kling 4.0 Flash (configs in globals/aiModels/providers/falVideo.ts), routing
14
+ * each request to the matching fal sub-endpoint:
15
+ * reference images/videos → v4/reference-to-video (not on Flash)
16
+ * a start frame → v4[/flash]/image-to-video
17
+ * otherwise → v4[/flash]/text-to-video
18
+ *
19
+ * The stored task is `<queue app path>|<request_id>`: fal's queue
20
+ * status/result URLs depend on the app path, which differs per sub-endpoint,
21
+ * so the poller needs it back. The path is taken from the submit response's
22
+ * `status_url` when present (fal's own canonical form), else the endpoint id.
23
+ */
24
+ export declare class FalVideoService extends BaseAiGenProviderService {
25
+ private readonly apiKey;
26
+ constructor();
27
+ private headers;
28
+ private buildRequest;
29
+ generateVideo(params: VideoGenerationParams): Promise<VideoGenerationResult>;
30
+ checkVideoStatus({ task, outputFilename, outputFilePath, }: VideoStatusParams): Promise<VideoStatusResult>;
31
+ /**
32
+ * Per second at the resolution the request sends. With a reference video
33
+ * fal/Kling bill a lower rate on (output × 2) when the input is no longer
34
+ * than the output, else (input + output) seconds. An unknown input length
35
+ * falls back to output × 2 (the input ≤ output case).
36
+ */
37
+ getCreditUsed({ modelKey, mode, resolution, duration, multiClip, inputType, hasInputVideo, inputVideoDurationSec, creditFloor, }: CreditUsageParams): number;
38
+ }
39
+ //# sourceMappingURL=falVideo.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"falVideo.service.d.ts","sourceRoot":"","sources":["../../../../../src/services/aiGen/providers/fal/falVideo.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAoClB;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,MAAM,EACnB,IAAI,CAAC,EAAE,UAAU,GAAG,MAAM,GACzB,MAAM,GAAG,OAAO,CAKlB;AAsBD;;;;;;;;;;;;GAYG;AACH,qBAAa,eAAgB,SAAQ,wBAAwB;IAC3D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;;IAUhC,OAAO,CAAC,OAAO;IAMf,OAAO,CAAC,YAAY;IA6Dd,aAAa,CAAC,MAAM,EAAE,qBAAqB,GAAG,OAAO,CAAC,qBAAqB,CAAC;IA0C5E,gBAAgB,CAAC,EACrB,IAAI,EACJ,cAAc,EACd,cAAyB,GAC1B,EAAE,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAsDjD;;;;;OAKG;IACH,aAAa,CAAC,EACZ,QAAQ,EACR,IAAI,EACJ,UAAU,EACV,QAAY,EACZ,SAAiB,EACjB,SAAS,EACT,aAAa,EACb,qBAAqB,EACrB,WAAW,GACZ,EAAE,iBAAiB,GAAG,MAAM;CAwB9B"}
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FalVideoService = void 0;
4
+ exports.resolveFalKlingResolution = resolveFalKlingResolution;
5
+ const aiModels_1 = require("../../../../globals/aiModels");
6
+ const types_1 = require("../../../../globals/types");
7
+ const storage_1 = require("../../../../libs/storage");
8
+ const errors_1 = require("../../../../utils/errors");
9
+ const helpers_1 = require("../../../../utils/helpers");
10
+ const logger_1 = require("../../../../utils/logger");
11
+ const transientRetry_1 = require("../../transientRetry");
12
+ const types_2 = require("../../types");
13
+ const baseAiGenProvider_service_1 = require("../baseAiGenProvider.service");
14
+ const falUpscale_service_1 = require("./falUpscale.service");
15
+ const QUEUE_BASE_URL = "https://queue.fal.run";
16
+ /** Separator between the queue app path and the request id in the stored task. */
17
+ const TASK_SEP = "|";
18
+ /** fal v4 multi_prompt per-shot cap (KlingV4Shot.prompt maxLength). */
19
+ const SHOT_PROMPT_MAX = 512;
20
+ /** fal v4 `prompt` maxLength. */
21
+ const PROMPT_MAX = 26000;
22
+ const FLASH_KEYS = new Set([aiModels_1.EVideoGenModels.FAL_KLING_V4_0_FLASH]);
23
+ /**
24
+ * Output resolution actually sent to fal. An explicit, allowed `resolution`
25
+ * wins; otherwise mode maps std→720p, pro→1080p (Kling's own equivalence).
26
+ * Flash is 720p-only. Exported so billing prices the SAME resolution the
27
+ * request carried — fal's default is 1080p, so never leave it implicit.
28
+ */
29
+ function resolveFalKlingResolution(modelKey, resolution, mode) {
30
+ if (FLASH_KEYS.has(modelKey))
31
+ return "720p";
32
+ const r = resolution?.toLowerCase();
33
+ if (r === "720p" || r === "1080p")
34
+ return r;
35
+ return mode === types_2.EVideoMode.PROFESSIONAL ? "1080p" : "720p";
36
+ }
37
+ /**
38
+ * Canonical shots → fal `multi_prompt[]`. Missing per-shot durations split
39
+ * the requested total evenly (integers, ≥1s each); the clip length fal
40
+ * renders is the sum of the shot durations.
41
+ */
42
+ function toFalShots(shots, totalDuration) {
43
+ const missing = shots.filter((s) => !s.duration).length;
44
+ const declared = shots.reduce((sum, s) => sum + (s.duration ?? 0), 0);
45
+ const fill = missing > 0 ? Math.max(1, Math.floor((totalDuration - declared) / missing)) : 0;
46
+ return shots.map((s, i) => {
47
+ if (s.prompt.length > SHOT_PROMPT_MAX) {
48
+ throw new errors_1.UserFacingError(`Shot ${i + 1} prompt is ${s.prompt.length} characters; Kling 4.0 allows ${SHOT_PROMPT_MAX} per shot.`, errors_1.USER_FACING_ERROR_CODES.PROMPT_TOO_LONG);
49
+ }
50
+ return { prompt: s.prompt, duration: Math.max(1, Math.round(s.duration ?? fill)) };
51
+ });
52
+ }
53
+ /**
54
+ * Generic fal.ai video-generation provider. Today it serves Kling 4.0 and
55
+ * Kling 4.0 Flash (configs in globals/aiModels/providers/falVideo.ts), routing
56
+ * each request to the matching fal sub-endpoint:
57
+ * reference images/videos → v4/reference-to-video (not on Flash)
58
+ * a start frame → v4[/flash]/image-to-video
59
+ * otherwise → v4[/flash]/text-to-video
60
+ *
61
+ * The stored task is `<queue app path>|<request_id>`: fal's queue
62
+ * status/result URLs depend on the app path, which differs per sub-endpoint,
63
+ * so the poller needs it back. The path is taken from the submit response's
64
+ * `status_url` when present (fal's own canonical form), else the endpoint id.
65
+ */
66
+ class FalVideoService extends baseAiGenProvider_service_1.BaseAiGenProviderService {
67
+ constructor() {
68
+ super();
69
+ if (!process.env.FAL_KEY) {
70
+ throw new Error("Missing FAL_KEY in environment variables");
71
+ }
72
+ this.apiKey = process.env.FAL_KEY;
73
+ }
74
+ headers(json) {
75
+ const h = { Authorization: `Key ${this.apiKey}` };
76
+ if (json)
77
+ h["Content-Type"] = "application/json";
78
+ return h;
79
+ }
80
+ buildRequest(params) {
81
+ const modelKey = params.modelKey;
82
+ const config = aiModels_1.aiModelConfigs[modelKey];
83
+ if (!config?.modelId) {
84
+ throw new Error(`FalVideoService: no fal model config for "${modelKey}"`);
85
+ }
86
+ const isFlash = FLASH_KEYS.has(modelKey);
87
+ const refImages = params.referenceImageUrls?.filter(Boolean) ?? [];
88
+ const refVideos = params.referenceVideoUrls?.filter(Boolean) ?? [];
89
+ let endpoint;
90
+ if (refImages.length > 0 || refVideos.length > 0) {
91
+ if (isFlash) {
92
+ throw new errors_1.UserFacingError("Kling 4.0 Flash doesn't take reference images or videos — use Kling 4.0 for Omni reference.", errors_1.USER_FACING_ERROR_CODES.CAPABILITY_MISMATCH);
93
+ }
94
+ endpoint = "reference-to-video";
95
+ }
96
+ else if (params.inputImageUrl) {
97
+ endpoint = "image-to-video";
98
+ }
99
+ else {
100
+ endpoint = "text-to-video";
101
+ }
102
+ const duration = Math.round(params.duration ?? 5);
103
+ const body = {
104
+ resolution: resolveFalKlingResolution(modelKey, params.resolution, params.mode),
105
+ };
106
+ if (params.multiShot && params.multiShot.length > 0 && !isFlash) {
107
+ body.multi_prompt = toFalShots(params.multiShot, duration);
108
+ }
109
+ else {
110
+ const prompt = params.prompt ?? "";
111
+ if (prompt.length > PROMPT_MAX) {
112
+ throw new errors_1.UserFacingError(`Prompt is ${prompt.length} characters; Kling 4.0 allows ${PROMPT_MAX}.`, errors_1.USER_FACING_ERROR_CODES.PROMPT_TOO_LONG);
113
+ }
114
+ body.prompt = prompt;
115
+ body.duration = duration;
116
+ }
117
+ if (endpoint === "text-to-video") {
118
+ if (params.aspectRatio)
119
+ body.aspect_ratio = params.aspectRatio;
120
+ }
121
+ else if (endpoint === "image-to-video") {
122
+ // Output ratio follows the start frame — fal's i2v takes no aspect_ratio.
123
+ body.start_image_url = params.inputImageUrl;
124
+ if (params.lastFrameImageUrl && !isFlash)
125
+ body.end_image_url = params.lastFrameImageUrl;
126
+ }
127
+ else {
128
+ if (refImages.length > 0)
129
+ body.image_urls = refImages.slice(0, 10);
130
+ if (refVideos.length > 0)
131
+ body.video_urls = refVideos.slice(0, 5);
132
+ if (params.inputImageUrl)
133
+ body.start_image_url = params.inputImageUrl;
134
+ if (params.lastFrameImageUrl)
135
+ body.end_image_url = params.lastFrameImageUrl;
136
+ body.aspect_ratio = params.aspectRatio ?? "auto";
137
+ }
138
+ return { endpointId: `${config.modelId}/${endpoint}`, body };
139
+ }
140
+ async generateVideo(params) {
141
+ const { endpointId, body } = this.buildRequest(params);
142
+ return (0, transientRetry_1.withTransientRetry)("fal:generateVideo", async () => {
143
+ const resp = await fetch(`${QUEUE_BASE_URL}/${endpointId}`, {
144
+ method: "POST",
145
+ headers: this.headers(true),
146
+ body: JSON.stringify(body),
147
+ });
148
+ if (!resp.ok) {
149
+ throw (0, falUpscale_service_1.classifyFalHttpError)(resp.status, await resp.text(), "generateVideo");
150
+ }
151
+ const data = (await resp.json());
152
+ if (!data.request_id) {
153
+ throw new Error(`fal ${endpointId} did not return a request_id`);
154
+ }
155
+ const appPath = appPathFromStatusUrl(data.status_url) ?? endpointId;
156
+ logger_1.logger.info("fal video submitted", {
157
+ modelKey: params.modelKey,
158
+ endpointId,
159
+ appPath,
160
+ requestId: data.request_id,
161
+ });
162
+ return {
163
+ status: types_1.EVideoSceneStatus.TRIGGERED,
164
+ task: `${appPath}${TASK_SEP}${data.request_id}`,
165
+ };
166
+ }, {
167
+ onRetry: ({ attempt, maxAttempts, backoffMs, err }) => logger_1.logger.warn("fal generateVideo transient error — retrying", {
168
+ attempt,
169
+ maxAttempts,
170
+ backoffMs,
171
+ message: err.message,
172
+ }),
173
+ });
174
+ }
175
+ async checkVideoStatus({ task, outputFilename, outputFilePath = "videos", }) {
176
+ const sep = task.lastIndexOf(TASK_SEP);
177
+ if (sep <= 0) {
178
+ return { status: types_1.EVideoSceneStatus.FAILED, errorMessage: `Malformed fal video task "${task}"` };
179
+ }
180
+ const appPath = task.slice(0, sep);
181
+ const requestId = task.slice(sep + 1);
182
+ const statusResp = await fetch(`${QUEUE_BASE_URL}/${appPath}/requests/${requestId}/status`, {
183
+ headers: this.headers(false),
184
+ });
185
+ if (!statusResp.ok) {
186
+ throw (0, falUpscale_service_1.classifyFalHttpError)(statusResp.status, await statusResp.text(), "checkVideoStatus");
187
+ }
188
+ const statusData = (await statusResp.json());
189
+ const normalized = (statusData.status ?? "").toUpperCase();
190
+ // fal reports a failed job as COMPLETED + `error` — no separate FAILED state.
191
+ if (normalized === "COMPLETED" && statusData.error) {
192
+ return { status: types_1.EVideoSceneStatus.FAILED, errorMessage: statusData.error };
193
+ }
194
+ if (normalized !== "COMPLETED") {
195
+ return { status: types_1.EVideoSceneStatus.PENDING };
196
+ }
197
+ const resultResp = await fetch(`${QUEUE_BASE_URL}/${appPath}/requests/${requestId}`, {
198
+ headers: this.headers(false),
199
+ });
200
+ if (!resultResp.ok) {
201
+ const text = await resultResp.text();
202
+ // A 4xx on the result (e.g. 422 validation / content checker) is the
203
+ // job's terminal failure, not a transport problem — fail the scene.
204
+ if (resultResp.status >= 400 && resultResp.status < 500 && ![401, 403, 429].includes(resultResp.status)) {
205
+ return { status: types_1.EVideoSceneStatus.FAILED, errorMessage: `fal video failed (${resultResp.status}): ${text.slice(0, 500)}` };
206
+ }
207
+ throw (0, falUpscale_service_1.classifyFalHttpError)(resultResp.status, text, "checkVideoStatus:result");
208
+ }
209
+ const result = (await resultResp.json());
210
+ if (!result.video?.url) {
211
+ const detail = typeof result.detail === "string" ? result.detail : JSON.stringify(result.detail ?? "");
212
+ return { status: types_1.EVideoSceneStatus.FAILED, errorMessage: result.error ?? (detail || "fal video returned no output") };
213
+ }
214
+ const assetResp = await fetch(result.video.url);
215
+ if (!assetResp.ok) {
216
+ // Throw (not FAILED) so the outer poller retries — the video exists.
217
+ throw new Error(`Failed to download fal video: ${assetResp.status}`);
218
+ }
219
+ const buffer = Buffer.from(await assetResp.arrayBuffer());
220
+ // mediaStorage: GCS write + best-effort R2 mirror (zero-egress delivery).
221
+ const signedUrl = await storage_1.mediaStorage.put(`${outputFilePath}/${outputFilename}.mp4`, buffer, "video/mp4");
222
+ return { status: types_1.EVideoSceneStatus.COMPLETED, videoUrl: signedUrl };
223
+ }
224
+ /**
225
+ * Per second at the resolution the request sends. With a reference video
226
+ * fal/Kling bill a lower rate on (output × 2) when the input is no longer
227
+ * than the output, else (input + output) seconds. An unknown input length
228
+ * falls back to output × 2 (the input ≤ output case).
229
+ */
230
+ getCreditUsed({ modelKey, mode, resolution, duration = 5, multiClip = false, inputType, hasInputVideo, inputVideoDurationSec, creditFloor, }) {
231
+ const cost = aiModels_1.aiModelConfigs[modelKey]?.cost;
232
+ const res = resolveFalKlingResolution(modelKey, resolution, mode);
233
+ const applyFloor = !multiClip;
234
+ if (inputType === "video" || hasInputVideo) {
235
+ const rate = cost?.videoInputPerSecondByResolution?.[res];
236
+ if (rate !== undefined) {
237
+ const inputSec = inputVideoDurationSec ?? duration;
238
+ const billedSec = inputSec <= duration ? duration * 2 : inputSec + duration;
239
+ return (0, helpers_1.getCreditsFromCost)(rate * billedSec, applyFloor, creditFloor);
240
+ }
241
+ }
242
+ const perSecond = cost?.perSecondByResolution?.[res];
243
+ if (perSecond === undefined) {
244
+ logger_1.logger.warn(`fal video getCreditUsed: no cost for modelKey="${modelKey}" res="${res}" — returning fallback`, {
245
+ modelKey,
246
+ res,
247
+ });
248
+ return (0, helpers_1.getCreditsFromCost)(0.2355 * duration, applyFloor, creditFloor);
249
+ }
250
+ return (0, helpers_1.getCreditsFromCost)(perSecond * duration, applyFloor, creditFloor);
251
+ }
252
+ }
253
+ exports.FalVideoService = FalVideoService;
254
+ /** "https://queue.fal.run/fal-ai/kling-video/requests/<id>/status" → "fal-ai/kling-video". */
255
+ function appPathFromStatusUrl(statusUrl) {
256
+ if (!statusUrl)
257
+ return undefined;
258
+ try {
259
+ const path = new URL(statusUrl).pathname.replace(/^\/+/, "");
260
+ const idx = path.indexOf("/requests/");
261
+ return idx > 0 ? path.slice(0, idx) : undefined;
262
+ }
263
+ catch {
264
+ return undefined;
265
+ }
266
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vidspotai-shared",
3
- "version": "1.0.134",
3
+ "version": "1.0.135",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "exports": {