Open History to see the last commit
1import { createGeneration } from './create-generation.ts'
2import { reconstructImageResult } from '@tanstack/ai-client'
3import type { Handle } from 'remix/ui'
4import type { ImageGenerationResult } from '@tanstack/ai'
5import type {
6 GenerationPersistenceOptions,
7 ImageGenerateInput,
8} from '@tanstack/ai-client'
9import type {
10 CreateGenerationOptions,
11 CreateGenerationReturn,
12} from './create-generation.ts'
13
14/**
15 * Options for the createGenerateImage helper.
16 *
17 * Handle is the first argument of the helper. It is not part of this type.
18 *
19 * @template TOutput - The output type after optional transform (defaults to ImageGenerationResult)
20 */
21export type CreateGenerateImageOptions<TOutput = ImageGenerationResult> = Omit<
22 CreateGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,
23 'onResult' | 'reconstructResult'
24> & {
25 onResult?: (result: ImageGenerationResult) => TOutput | null | void
26}
27
28/**
29 * Return type for the createGenerateImage helper.
30 *
31 * @template TOutput - The output type (after optional transform)
32 */
33export type CreateGenerateImageReturn<TOutput = ImageGenerationResult> =
34 CreateGenerationReturn<TOutput, ImageGenerateInput>
35
36/**
37 * Creates an image generation helper for Remix setup.
38 *
39 * Supports two transport modes:
40 * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom)
41 * - **Fetcher** — Direct async function call
42 *
43 * Call this in a Remix component setup function. Pass the component Handle as
44 * the first argument.
45 *
46 * @example
47 * ```tsx
48 * import { createGenerateImage } from '@tanstack/ai-remix'
49 * import { fetchServerSentEvents } from '@tanstack/ai-client'
50 * import type { Handle } from 'remix/ui'
51 *
52 * function ImageGenerator(handle: Handle) {
53 * const image = createGenerateImage(handle, {
54 * connection: fetchServerSentEvents('/api/generate/image'),
55 * })
56 *
57 * return () => (
58 * <div>
59 * <button onClick={() => image.generate({ prompt: 'A sunset over mountains' })}>
60 * Generate
61 * </button>
62 * {image.isLoading ? <p>Generating...</p> : null}
63 * {image.result?.images.map((img) => (
64 * <img src={img.url || `data:image/png;base64,${img.b64Json}`} />
65 * ))}
66 * </div>
67 * )
68 * }
69 * ```
70 */
71export function createGenerateImage<TTransformed = void>(
72 handle: Pick<Handle, 'id' | 'update' | 'signal'>,
73 options: Omit<
74 CreateGenerateImageOptions,
75 'onResult' | 'persistence' | 'threadId'
76 > & {
77 onResult?: (result: ImageGenerationResult) => TTransformed
78 } & GenerationPersistenceOptions,
79) {
80 const devtools = {
81 ...options.devtools,
82 hookName: 'createGenerateImage',
83 outputKind: 'image' as const,
84 }
85 return createGeneration<
86 ImageGenerateInput,
87 ImageGenerationResult,
88 TTransformed
89 >(handle, {
90 ...options,
91 devtools,
92 reconstructResult: reconstructImageResult,
93 })
94}