Open History to see the last commit
1import { createServerFn } from '@tanstack/react-start'
2import { falImage, falVideo } from '@tanstack/ai-fal'
3import { geminiImage, geminiVideo } from '@tanstack/ai-gemini'
4import { grokImage, grokVideo } from '@tanstack/ai-grok'
5import {
6 BYTEPLUS_VIDEO_MODELS,
7 byteplusImage,
8 byteplusVideo,
9 getBytePlusVideoDurationOptions,
10 resolveBytePlusVideoResolution,
11 supportsLastFrame,
12 supportsReferenceMedia,
13} from '@tanstack/ai-byteplus'
14import {
15 generateImage,
16 generateVideo,
17 toServerSentEventsResponse,
18} from '@tanstack/ai'
19
20import type { StreamChunk } from '@tanstack/ai'
21import type {
22 BytePlusVideoModel,
23 BytePlusVideoModelOrString,
24 BytePlusVideoProviderOptions,
25 BytePlusVideoResolution,
26} from '@tanstack/ai-byteplus'
27import type {
28 ImagePart,
29 MediaInputMetadata,
30 MediaPrompt,
31 TextPart,
32 VideoPart,
33} from '@tanstack/ai/client'
34import type { OmniTaskMode } from './models'
35import type { SeedanceCapability, SeedanceJobOptions } from './seedance'
36import { SEEDANCE_RESOLUTION_TIERS } from './seedance'
37
38/** A prompt restricted to text — accepted by every (incl. text-only) model. */
39type TextPrompt = string | Array<TextPart>
40/** A prompt of text + image parts — accepted by image-conditioned models. */
41type ImagePrompt = string | Array<TextPart | ImagePart<MediaInputMetadata>>
42/** A prompt of text + image + video parts — Gemini Omni Flash accepts all three. */
43type OmniPrompt =
44 | string
45 | Array<
46 TextPart | ImagePart<MediaInputMetadata> | VideoPart<MediaInputMetadata>
47 >
48
49/** True when the prompt carries text — a non-empty string or any prompt part. */
50function hasPromptContent(prompt: MediaPrompt): boolean {
51 return typeof prompt === 'string'
52 ? prompt.trim().length > 0
53 : prompt.length > 0
54}
55
56/**
57 * Narrows a wire `MediaPrompt` to a text + image prompt for image-conditioned
58 * models, throwing on any other part kind (video/audio) so unsupported inputs
59 * fail fast rather than being silently dropped.
60 */
61function asImagePrompt(prompt: MediaPrompt): ImagePrompt {
62 if (typeof prompt === 'string') return prompt
63 return prompt.map((part) => {
64 if (part.type === 'text' || part.type === 'image') return part
65 throw new Error(`Unsupported prompt part for image model: ${part.type}`)
66 })
67}
68
69/**
70 * Narrows a wire `MediaPrompt` to a text-only prompt, throwing if any image /
71 * video / audio part is present (text-to-image models can't accept inputs).
72 */
73function asTextPrompt(prompt: MediaPrompt): TextPrompt {
74 if (typeof prompt === 'string') return prompt
75 return prompt.map((part) => {
76 if (part.type === 'text') return part
77 throw new Error(
78 `Model does not support image inputs (received ${part.type} part)`,
79 )
80 })
81}
82
83/**
84 * Narrows a wire `MediaPrompt` for Gemini Omni Flash, which accepts text,
85 * image, and video prompt parts (audio would be the only rejected kind).
86 */
87function asOmniPrompt(prompt: MediaPrompt): OmniPrompt {
88 if (typeof prompt === 'string') return prompt
89 return prompt.map((part) => {
90 if (part.type === 'text' || part.type === 'image' || part.type === 'video')
91 return part
92 throw new Error(`Unsupported prompt part for Omni Flash: ${part.type}`)
93 })
94}
95
96/**
97 * Like `asImagePrompt`, but additionally requires at least one image part —
98 * image-to-video endpoints need a start frame.
99 */
100function asImageToVideoPrompt(
101 prompt: MediaPrompt,
102): Array<TextPart | ImagePart<MediaInputMetadata>> {
103 const narrowed = asImagePrompt(prompt)
104 if (
105 typeof narrowed === 'string' ||
106 !narrowed.some((part) => part.type === 'image')
107 ) {
108 throw new Error('Start image is required for image-to-video')
109 }
110 return narrowed
111}
112
113/**
114 * Poll cadence for the streamed video lifecycle. The server holds the request
115 * open and polls the provider itself, so this is the rate at which
116 * `video:status` events reach the browser's `useGenerateVideo`.
117 */
118const VIDEO_POLL_INTERVAL_MS = 4000
119
120export const generateImageFn = createServerFn({ method: 'POST' })
121 .inputValidator((data: { prompt: MediaPrompt; model: string }) => {
122 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
123 if (!data.model) throw new Error('Model is required')
124 return data
125 })
126 .handler(async ({ data }) => {
127 // NOTE: Use string literals when instantiating adapters to preserve type safety
128 // The Fal adapater also accepts any string for very latest models which is why new models appear to accept any paramater
129 // Pass size information in modelOptions for the Fal adapter instead of size to be sure you are using the correct resolution
130
131 switch (data.model) {
132 case 'fal-ai/nano-banana-pro': {
133 return generateImage({
134 adapter: falImage('fal-ai/nano-banana-pro'),
135 prompt: asTextPrompt(data.prompt),
136 numberOfImages: 1,
137 size: '16:9_4K',
138 modelOptions: {
139 output_format: 'jpeg',
140 },
141 })
142 }
143 case 'xai/grok-imagine-image': {
144 // NOTE: fal's generated `size` type for this model only offers
145 // `16:9_1K` / `16:9_4K`, but the live API rejects those resolutions
146 // ("Input should be '1k' or '2k'") — fal's published enum is out of
147 // sync with its API, so `'16:9_4K'` type-checks yet 422s at runtime.
148 // Pass aspect_ratio via modelOptions and let the endpoint pick its
149 // default resolution, which both type-checks and works at runtime.
150 return generateImage({
151 adapter: falImage('xai/grok-imagine-image'),
152 prompt: asTextPrompt(data.prompt),
153 numberOfImages: 1,
154 modelOptions: { aspect_ratio: '16:9' },
155 })
156 }
157 case 'grok-imagine-image': {
158 // Direct xAI Imagine API (XAI_API_KEY) via the native grokImage
159 // adapter — no fal in between. The grok-imagine models accept image
160 // prompt parts for image-conditioned generation, so we narrow with
161 // asImagePrompt. Sizing uses the aspect-ratio template.
162 return generateImage({
163 adapter: grokImage('grok-imagine-image'),
164 prompt: asImagePrompt(data.prompt),
165 numberOfImages: 1,
166 size: '16:9',
167 })
168 }
169 case 'grok-imagine-image-quality': {
170 return generateImage({
171 adapter: grokImage('grok-imagine-image-quality'),
172 prompt: asImagePrompt(data.prompt),
173 numberOfImages: 1,
174 size: '16:9',
175 })
176 }
177 case 'fal-ai/flux-2/klein/9b': {
178 // NOTE: Newer models are untyped (at the moment)
179 return generateImage({
180 adapter: falImage('fal-ai/flux-2/klein/9b'),
181 prompt: asTextPrompt(data.prompt),
182 numberOfImages: 1,
183 size: 'landscape_16_9',
184 })
185 }
186 case 'fal-ai/z-image/turbo': {
187 return generateImage({
188 adapter: falImage('fal-ai/z-image/turbo'),
189 prompt: asTextPrompt(data.prompt),
190 numberOfImages: 1,
191 size: 'landscape_16_9',
192 modelOptions: {
193 acceleration: 'high',
194 enable_prompt_expansion: true,
195 },
196 })
197 }
198 case 'gemini-3.1-flash-image-preview': {
199 return generateImage({
200 adapter: geminiImage('gemini-3.1-flash-image-preview'),
201 prompt: asImagePrompt(data.prompt),
202 numberOfImages: 1,
203 size: '16:9_4K',
204 })
205 }
206 case 'gemini-3-pro-image-preview': {
207 return generateImage({
208 adapter: geminiImage('gemini-3-pro-image-preview'),
209 prompt: asImagePrompt(data.prompt),
210 numberOfImages: 1,
211 size: '16:9_4K',
212 })
213 }
214 case 'imagen-4.0-ultra-generate-001': {
215 return generateImage({
216 adapter: geminiImage('imagen-4.0-ultra-generate-001'),
217 prompt: asTextPrompt(data.prompt),
218 numberOfImages: 1,
219 size: '1024x1024',
220 })
221 }
222 case 'imagen-4.0-generate-001': {
223 return generateImage({
224 adapter: geminiImage('imagen-4.0-generate-001'),
225 prompt: asTextPrompt(data.prompt),
226 numberOfImages: 1,
227 size: '1024x1024',
228 })
229 }
230 case 'imagen-4.0-fast-generate-001': {
231 return generateImage({
232 adapter: geminiImage('imagen-4.0-fast-generate-001'),
233 prompt: asTextPrompt(data.prompt),
234 numberOfImages: 1,
235 size: '1024x1024',
236 })
237 }
238 case 'dola-seedream-5-0-pro-260628': {
239 // BytePlus Seedream via ModelArk (ARK_API_KEY). `size` is either a
240 // 1K/2K/4K token or an explicit WIDTHxHEIGHT string — never both.
241 // Seedream models accept reference images, so image prompt parts are
242 // passed straight through.
243 return generateImage({
244 adapter: byteplusImage('dola-seedream-5-0-pro-260628'),
245 prompt: asImagePrompt(data.prompt),
246 numberOfImages: 1,
247 size: '2K',
248 })
249 }
250 default:
251 throw new Error(`Unknown model: ${data.model}`)
252 }
253 })
254
255/** What the browser sends for one video generation. */
256interface VideoRequest {
257 prompt: MediaPrompt
258 model: string
259 /**
260 * Gemini Omni Flash conversational editing: the jobId (interaction id)
261 * of a prior Omni generation to refine. Ignored by other models.
262 */
263 previousInteractionId?: string
264 /**
265 * Gemini Omni Flash generation controls (ignored by other models):
266 * clip duration in seconds (3-10, fractional OK, default 10), output
267 * aspect ratio, and an optional task-mode pin — omit `task` to let
268 * the model infer the mode from the prompt and attachments.
269 */
270 omniOptions?: {
271 duration?: number
272 aspectRatio?: '16:9' | '9:16'
273 task?: OmniTaskMode
274 }
275}
276
277/**
278 * The full create → poll → complete lifecycle for one model, as a chunk
279 * stream. `stream: true` is what moves the polling loop to the server: the
280 * browser's `useGenerateVideo` reads job id, status and result off these
281 * chunks instead of running its own timer.
282 */
283function videoStreamForModel(data: VideoRequest): AsyncIterable<StreamChunk> {
284 // Image-to-video models receive the start frame as a prompt part
285 // (role: 'start_frame') — the fal adapter routes it to the endpoint's
286 // start-image field. Text-to-video models take the text prompt only.
287 switch (data.model) {
288 // Text-to-video models
289 case 'fal-ai/kling-video/v3/pro/text-to-video': {
290 return generateVideo({
291 stream: true,
292 pollingInterval: VIDEO_POLL_INTERVAL_MS,
293 adapter: falVideo('fal-ai/kling-video/v3/pro/text-to-video'),
294 prompt: asTextPrompt(data.prompt),
295 size: '16:9',
296 modelOptions: {
297 duration: '5',
298 },
299 })
300 }
301 case 'fal-ai/veo3.1': {
302 // NOTE pass aspect ratio, resolution, and duration in model options
303 // This makes use of existing types and avoids type errors
304 return generateVideo({
305 stream: true,
306 pollingInterval: VIDEO_POLL_INTERVAL_MS,
307 adapter: falVideo('fal-ai/veo3.1'),
308 prompt: asTextPrompt(data.prompt),
309 size: '16:9_1080p',
310 modelOptions: {
311 duration: '4s',
312 },
313 })
314 }
315 case 'xai/grok-imagine-video/text-to-video': {
316 return generateVideo({
317 stream: true,
318 pollingInterval: VIDEO_POLL_INTERVAL_MS,
319 adapter: falVideo('xai/grok-imagine-video/text-to-video'),
320 prompt: asTextPrompt(data.prompt),
321 size: '16:9_720p',
322 modelOptions: {
323 duration: 5,
324 },
325 })
326 }
327 case 'grok-imagine-video': {
328 // Direct xAI Imagine API (XAI_API_KEY) — no fal in between. The base
329 // grok-imagine-video (v1.0) supports text-to-video; durations are
330 // 1-15 integer seconds. Completed jobs report usage.unitsBilled
331 // (billed seconds) and usage.cost (exact USD).
332 return generateVideo({
333 stream: true,
334 pollingInterval: VIDEO_POLL_INTERVAL_MS,
335 adapter: grokVideo('grok-imagine-video'),
336 prompt: asTextPrompt(data.prompt),
337 size: '16:9_720p',
338 duration: 5,
339 })
340 }
341 case 'dreamina-seedance-2-0-260128': {
342 // BytePlus Seedance via ModelArk (ARK_API_KEY). `size` is a "ratio" or
343 // "ratio_resolution" template; durations are 4-15 integer seconds.
344 // Seedance option applicability is per model and Ark 400s on an
345 // inapplicable field, so no service_tier/frames/camera_fixed here —
346 // the 2.0 family rejects all three.
347 return generateVideo({
348 stream: true,
349 pollingInterval: VIDEO_POLL_INTERVAL_MS,
350 adapter: byteplusVideo('dreamina-seedance-2-0-260128'),
351 prompt: asTextPrompt(data.prompt),
352 size: '16:9_720p',
353 duration: 5,
354 })
355 }
356 case 'fal-ai/ltx-2.3/text-to-video/fast': {
357 return generateVideo({
358 stream: true,
359 pollingInterval: VIDEO_POLL_INTERVAL_MS,
360 adapter: falVideo('fal-ai/ltx-2.3/text-to-video/fast'),
361 prompt: asTextPrompt(data.prompt),
362 size: '16:9_2160p',
363 })
364 }
365 // Image-to-video models
366 case 'fal-ai/kling-video/v3/pro/image-to-video': {
367 return generateVideo({
368 stream: true,
369 pollingInterval: VIDEO_POLL_INTERVAL_MS,
370 adapter: falVideo('fal-ai/kling-video/v3/pro/image-to-video'),
371 prompt: asImageToVideoPrompt(data.prompt),
372 modelOptions: {
373 generate_audio: true,
374 duration: '5',
375 },
376 })
377 }
378 case 'fal-ai/veo3.1/image-to-video': {
379 return generateVideo({
380 stream: true,
381 pollingInterval: VIDEO_POLL_INTERVAL_MS,
382 adapter: falVideo('fal-ai/veo3.1/image-to-video'),
383 prompt: asImageToVideoPrompt(data.prompt),
384 size: '16:9_1080p',
385 modelOptions: {
386 duration: '4s',
387 },
388 })
389 }
390 case 'xai/grok-imagine-video/image-to-video': {
391 return generateVideo({
392 stream: true,
393 pollingInterval: VIDEO_POLL_INTERVAL_MS,
394 adapter: falVideo('xai/grok-imagine-video/image-to-video'),
395 prompt: asImageToVideoPrompt(data.prompt),
396 size: '16:9_720p',
397 modelOptions: {
398 duration: 5,
399 },
400 })
401 }
402 case 'grok-imagine-video-1.5/image-to-video': {
403 // Direct xAI Imagine API. The starting frame is supplied as an image
404 // prompt part (asImageToVideoPrompt requires one); the grokVideo
405 // adapter forwards it to the Imagine endpoint as the start frame.
406 return generateVideo({
407 stream: true,
408 pollingInterval: VIDEO_POLL_INTERVAL_MS,
409 adapter: grokVideo('grok-imagine-video-1.5'),
410 prompt: asImageToVideoPrompt(data.prompt),
411 size: '16:9_720p',
412 duration: 5,
413 })
414 }
415 case 'fal-ai/ltx-2.3/image-to-video/fast': {
416 return generateVideo({
417 stream: true,
418 pollingInterval: VIDEO_POLL_INTERVAL_MS,
419 adapter: falVideo('fal-ai/ltx-2.3/image-to-video/fast'),
420 prompt: asImageToVideoPrompt(data.prompt),
421 size: '16:9_2160p',
422 })
423 }
424 // Gemini Omni Flash (Interactions API, GEMINI_API_KEY). One model
425 // serves both UI entries; it accepts text, image, AND video prompt
426 // parts (sent as interaction content blocks: images, then videos,
427 // then text). Clips are 3–10s at 720p (default 10s when `duration`
428 // is omitted); `size` is the output aspect ratio. Passing
429 // `previous_interaction_id` chains a prompt onto a prior generation
430 // for conversational editing.
431 case 'gemini-omni-flash-preview':
432 case 'gemini-omni-flash-preview/image-to-video': {
433 const prompt = asOmniPrompt(data.prompt)
434 if (
435 data.model.endsWith('/image-to-video') &&
436 !data.previousInteractionId &&
437 (typeof prompt === 'string' ||
438 !prompt.some((part) => part.type === 'image'))
439 ) {
440 throw new Error('Start image is required for image-to-video')
441 }
442 const { duration, aspectRatio, task } = data.omniOptions ?? {}
443 return generateVideo({
444 stream: true,
445 pollingInterval: VIDEO_POLL_INTERVAL_MS,
446 adapter: geminiVideo('gemini-omni-flash-preview'),
447 prompt,
448 size: aspectRatio ?? '16:9',
449 ...(duration !== undefined ? { duration } : {}),
450 ...(data.previousInteractionId || task
451 ? {
452 modelOptions: {
453 ...(data.previousInteractionId
454 ? { previous_interaction_id: data.previousInteractionId }
455 : {}),
456 ...(task
457 ? { generation_config: { video_config: { task } } }
458 : {}),
459 },
460 }
461 : {}),
462 })
463 }
464 default:
465 throw new Error(`Unknown video model: ${data.model}`)
466 }
467}
468
469/**
470 * Streams one video generation as Server-Sent Events. `useGenerateVideo`
471 * takes this straight as its `fetcher`: the client parses the SSE body it
472 * returns, so the job id, every status update and the final url all arrive on
473 * the one request — no client-side polling loop and no job ids to thread
474 * through the UI.
475 */
476export const generateVideoFn = createServerFn({ method: 'POST' })
477 .inputValidator((data: VideoRequest) => {
478 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
479 if (!data.model) throw new Error('Model is required')
480 return data
481 })
482 // A rejected model / missing start frame throws out of `videoStreamForModel`
483 // before any stream exists, which surfaces as a plain server-function error
484 // (the hook reports it through `error`) rather than a stream that opens only
485 // to fail.
486 .handler(({ data }) => toServerSentEventsResponse(videoStreamForModel(data)))
487
488// ============================================================================
489// Seedance Studio — BytePlus ModelArk direct (ARK_API_KEY, server-side only)
490// ============================================================================
491
492/**
493 * The tiers a model accepts. `resolveBytePlusVideoResolution` is the package's
494 * exported gate for exactly this decision — it throws on a tier the model does
495 * not offer — so probing it keeps one source of truth for a matrix that is
496 * neither uniform nor guessable (there is no 2K tier anywhere, and 4k exists
497 * only on `dreamina-seedance-2-0-260128`).
498 */
499function acceptedResolutions(
500 model: BytePlusVideoModel,
501): Array<BytePlusVideoResolution> {
502 const accepted = SEEDANCE_RESOLUTION_TIERS.filter((tier) => {
503 try {
504 resolveBytePlusVideoResolution(model, tier)
505 return true
506 } catch {
507 return false
508 }
509 })
510
511 // Using a throw as the predicate means *any* change to that function's
512 // contract reads as "no tier is supported". Every Seedance model offers at
513 // least 480p and 720p, so an empty list is drift, not a real answer —
514 // without this the Studio would silently fall back to a hardcoded '720p'
515 // and build requests on a guess. The route has an errorComponent for
516 // exactly this.
517 if (accepted.length === 0) {
518 throw new Error(
519 `Seedance capability probe returned no resolution tiers for "${model}". ` +
520 `resolveBytePlusVideoResolution's contract has probably changed — the ` +
521 `Studio's controls cannot be built from this.`,
522 )
523 }
524 return accepted
525}
526
527/**
528 * Per-model capability table for the Seedance Studio, read out of the adapter
529 * package on the server. No API key is involved: these are static metadata
530 * lookups, not calls to Ark.
531 */
532export const getSeedanceCapabilitiesFn = createServerFn({
533 method: 'GET',
534}).handler(
535 (): Array<SeedanceCapability> =>
536 BYTEPLUS_VIDEO_MODELS.map((model) => {
537 const durations = getBytePlusVideoDurationOptions(model)
538 if (durations.kind !== 'range') {
539 throw new Error(
540 `Expected a duration range for ${model}, got "${durations.kind}"`,
541 )
542 }
543 return {
544 model,
545 resolutions: acceptedResolutions(model),
546 duration: {
547 min: durations.min,
548 max: durations.max,
549 step: durations.step ?? 1,
550 },
551 supportsLastFrame: supportsLastFrame(model),
552 supportsReferenceMedia: supportsReferenceMedia(model),
553 }
554 }),
555)
556
557/** What the studio sends for one Seedance generation. */
558interface SeedanceRequest {
559 prompt: MediaPrompt
560 // Open by design: the studio's advanced field takes an id this package
561 // has no metadata for, which the adapter forwards ungated for Ark to judge.
562 model: BytePlusVideoModelOrString
563 options?: SeedanceJobOptions
564}
565
566/**
567 * Ceiling on how long the server will sit on a Seedance task. Generous
568 * because the flex tier is an offline batch queue where a task routinely
569 * waits many minutes before it even starts.
570 */
571const SEEDANCE_MAX_DURATION_MS = 30 * 60_000
572/** Seedance tasks are slow; polling faster only burns Ark quota. */
573const SEEDANCE_POLL_INTERVAL_MS = 5000
574
575/** The create → poll → complete lifecycle for one Seedance task. */
576function seedanceStream(data: SeedanceRequest): AsyncIterable<StreamChunk> {
577 const options = data.options ?? {}
578
579 // The studio's camelCase controls map one-to-one onto the provider's own
580 // request fields. Applicability is per model and Ark 400s on a field the
581 // model doesn't take (it does not ignore it), so the client only sends
582 // what the selected model accepts — see `SEEDANCE_MODELS` in lib/seedance.
583 //
584 // `ratio` / `resolution` are typed against the tiers this package knows,
585 // so a custom model id sends its sizing through the generic `size`
586 // template instead (see `SeedanceJobOptions.size`).
587 const modelOptions: BytePlusVideoProviderOptions = {
588 ...(options.size === undefined &&
589 options.ratio !== undefined && { ratio: options.ratio }),
590 ...(options.size === undefined &&
591 options.resolution !== undefined && {
592 resolution: options.resolution,
593 }),
594 // `-1` (let the model choose the length) is only reachable through
595 // provider options: the generic `duration` gets snapped into range.
596 ...(options.duration === -1 && { duration: -1 }),
597 ...(options.frames !== undefined && { frames: options.frames }),
598 ...(options.seed !== undefined && { seed: options.seed }),
599 ...(options.watermark !== undefined && { watermark: options.watermark }),
600 ...(options.generateAudio !== undefined && {
601 generate_audio: options.generateAudio,
602 }),
603 ...(options.cameraFixed !== undefined && {
604 camera_fixed: options.cameraFixed,
605 }),
606 ...(options.serviceTier !== undefined && {
607 service_tier: options.serviceTier,
608 }),
609 ...(options.draft !== undefined && { draft: options.draft }),
610 ...(options.priority !== undefined && { priority: options.priority }),
611 }
612
613 // `frames` takes precedence over `duration` server-side, so never send
614 // both; `-1` already went through modelOptions above.
615 const duration =
616 options.frames === undefined &&
617 options.duration !== undefined &&
618 options.duration > 0
619 ? options.duration
620 : undefined
621
622 return generateVideo({
623 // For a model this package knows, the adapter snaps `duration` into its
624 // range and validates the resolution tier, prompt roles and
625 // frame/reference exclusivity before anything reaches Ark. For a custom
626 // id every one of those guards is off by design: the duration goes
627 // through verbatim and Ark is the authority.
628 adapter: byteplusVideo(data.model),
629 // Passed through un-narrowed, unlike the other generators: Seedance's
630 // reference mode takes video and audio parts as well as images (the
631 // template presets send both), and which of them a given model allows is
632 // the adapter's call — its error names the model and the part.
633 prompt: data.prompt,
634 ...(options.size !== undefined && { size: options.size }),
635 ...(duration !== undefined && { duration }),
636 modelOptions,
637 stream: true,
638 pollingInterval: SEEDANCE_POLL_INTERVAL_MS,
639 maxDuration: SEEDANCE_MAX_DURATION_MS,
640 })
641}
642
643/**
644 * Streams one Seedance task as Server-Sent Events, for the studio's
645 * `useGenerateVideo`. The browser never sees ARK_API_KEY or a job id it has
646 * to poll with — the server does the waiting and reports status on the wire.
647 */
648export const generateSeedanceVideoFn = createServerFn({ method: 'POST' })
649 .inputValidator((data: SeedanceRequest) => {
650 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
651 if (!data.model) throw new Error('Model is required')
652 return data
653 })
654 .handler(({ data }) => toServerSentEventsResponse(seedanceStream(data)))