@tanstack/ai-solid 0.15.1 → 0.16.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/README.md +17 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/types.d.ts +29 -3
- package/dist/use-chat.js +81 -5
- package/dist/use-chat.js.map +1 -1
- package/dist/use-generate-audio.d.ts +9 -10
- package/dist/use-generate-audio.js +4 -11
- package/dist/use-generate-audio.js.map +1 -1
- package/dist/use-generate-image.d.ts +9 -10
- package/dist/use-generate-image.js +4 -11
- package/dist/use-generate-image.js.map +1 -1
- package/dist/use-generate-speech.d.ts +9 -10
- package/dist/use-generate-speech.js +4 -11
- package/dist/use-generate-speech.js.map +1 -1
- package/dist/use-generate-video.d.ts +50 -4
- package/dist/use-generate-video.js +54 -23
- package/dist/use-generate-video.js.map +1 -1
- package/dist/use-generation.d.ts +59 -6
- package/dist/use-generation.js +43 -19
- package/dist/use-generation.js.map +1 -1
- package/dist/use-summarize.d.ts +9 -10
- package/dist/use-summarize.js +4 -11
- package/dist/use-summarize.js.map +1 -1
- package/dist/use-transcription.d.ts +9 -10
- package/dist/use-transcription.js +4 -11
- package/dist/use-transcription.js.map +1 -1
- package/package.json +6 -6
- package/src/index.ts +10 -0
- package/src/types.ts +44 -0
- package/src/use-chat.ts +123 -6
- package/src/use-generate-audio.ts +33 -23
- package/src/use-generate-image.ts +33 -23
- package/src/use-generate-speech.ts +32 -23
- package/src/use-generate-video.ts +120 -25
- package/src/use-generation.ts +129 -25
- package/src/use-summarize.ts +34 -23
- package/src/use-transcription.ts +33 -24
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { useGeneration } from "./use-generation.js";
|
|
2
|
+
import { reconstructSpeechResult } from "@tanstack/ai-client";
|
|
2
3
|
|
|
3
4
|
//#region src/use-generate-speech.ts
|
|
4
5
|
/**
|
|
@@ -34,19 +35,11 @@ function useGenerateSpeech(options) {
|
|
|
34
35
|
hookName: "useGenerateSpeech",
|
|
35
36
|
outputKind: "audio"
|
|
36
37
|
};
|
|
37
|
-
|
|
38
|
+
return useGeneration({
|
|
38
39
|
...options,
|
|
39
|
-
devtools
|
|
40
|
+
devtools,
|
|
41
|
+
reconstructResult: reconstructSpeechResult
|
|
40
42
|
});
|
|
41
|
-
return {
|
|
42
|
-
generate,
|
|
43
|
-
result,
|
|
44
|
-
isLoading,
|
|
45
|
-
error,
|
|
46
|
-
status,
|
|
47
|
-
stop,
|
|
48
|
-
reset
|
|
49
|
-
};
|
|
50
43
|
}
|
|
51
44
|
|
|
52
45
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-speech.js","names":[],"sources":["../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for speech generation */\n fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>\n
|
|
1
|
+
{"version":3,"file":"use-generate-speech.js","names":[],"sources":["../src/use-generate-speech.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport { reconstructSpeechResult } from '@tanstack/ai-client'\nimport type {\n UseGenerationOptions,\n UseGenerationReturn,\n} from './use-generation'\nimport type { StreamChunk, TTSResult } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n SpeechGenerateInput,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechOptions<TOutput = TTSResult> extends Pick<\n UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,\n 'persistence' | 'threadId' | 'hydrateGeneration' | 'joinRun'\n> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for speech generation */\n fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>\n /**\n * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).\n */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when speech is generated. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TTSResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateSpeech hook.\n *\n * @template TOutput - The transformed output type (defaults to TTSResult)\n */\nexport interface UseGenerateSpeechReturn<TOutput = TTSResult> extends Omit<\n UseGenerationReturn<TOutput>,\n 'generate'\n> {\n /** Trigger speech generation */\n generate: (input: SpeechGenerateInput) => Promise<void>\n /** The TTS result containing audio data, or null */\n result: Accessor<TOutput | null>\n /** Whether generation is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n}\n\n/**\n * Solid hook for generating speech (text-to-speech) using AI models.\n *\n * @example\n * ```tsx\n * import { useGenerateSpeech } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function SpeechGenerator() {\n * const { generate, result, isLoading } = useGenerateSpeech({\n * connection: fetchServerSentEvents('/api/generate/speech'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ text: 'Hello world', voice: 'alloy' })}>\n * Generate Speech\n * </button>\n * {result() && (\n * <audio src={`data:audio/${result()!.format};base64,${result()!.audio}`} controls />\n * )}\n * </div>\n * )\n * }\n * ```\n */\nexport function useGenerateSpeech<TTransformed = void>(\n options: Omit<\n UseGenerateSpeechOptions,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: TTSResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateSpeechReturn<\n InferGenerationOutputFromReturn<TTSResult, TTransformed>\n> {\n const devtools = {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateSpeech',\n outputKind: 'audio' as const,\n }\n const generation = useGeneration<\n SpeechGenerateInput,\n TTSResult,\n TTransformed\n >({\n ...options,\n devtools,\n reconstructResult: reconstructSpeechResult,\n })\n\n return generation\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,SAAgB,kBACd,SAQA;CACA,MAAM,WAAW;EACf,GAAG,QAAQ;EACX,WAAW;EACX,UAAU;EACV,YAAY;EACb;AAWD,QAVmB,cAIjB;EACA,GAAG;EACH;EACA,mBAAmB;EACpB,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Accessor } from "solid-js";
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo } from "@tanstack/ai-client";
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, GenerationPersistenceOptions, InferGenerationOutputFromReturn, VideoGenerateInput, VideoGenerateResult, VideoStatusInfo } from "@tanstack/ai-client";
|
|
3
3
|
import { StreamChunk } from "@tanstack/ai";
|
|
4
4
|
|
|
5
5
|
//#region src/use-generate-video.d.ts
|
|
@@ -14,12 +14,51 @@ interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
|
|
|
14
14
|
connection?: ConnectConnectionAdapter;
|
|
15
15
|
/** Direct async function that returns a completed video result */
|
|
16
16
|
fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>;
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
19
|
+
*/
|
|
18
20
|
id?: string;
|
|
19
21
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
20
22
|
body?: Record<string, any>;
|
|
21
23
|
/** Display options for TanStack AI Devtools. */
|
|
22
24
|
devtools?: AIDevtoolsDisplayOptions;
|
|
25
|
+
/**
|
|
26
|
+
* How this generation persists across reloads.
|
|
27
|
+
* - Omit / `false`: ephemeral, in-memory only.
|
|
28
|
+
* - `true`: server-driven — on mount the client hydrates the last generation
|
|
29
|
+
* for its `threadId` from the server (needs a connection with a
|
|
30
|
+
* `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
|
|
31
|
+
*/
|
|
32
|
+
persistence?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* The **scope** this generation belongs to: a stable, app-chosen name for the
|
|
35
|
+
* slot successive runs fill — not a link to a chat conversation.
|
|
36
|
+
*
|
|
37
|
+
* The hook starts empty and produces many runs over its life; each gets its
|
|
38
|
+
* own `runId`, but all belong to one scope. Persistence keys on this, so
|
|
39
|
+
* derive it from your own domain and keep it identical across reloads (e.g.
|
|
40
|
+
* `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
|
|
41
|
+
* id on the wire, which the protocol requires.
|
|
42
|
+
*
|
|
43
|
+
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
44
|
+
* scope has nothing to restore to. Optional for ephemeral generations, where
|
|
45
|
+
* it falls back to `id` purely to satisfy the wire.
|
|
46
|
+
*/
|
|
47
|
+
threadId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Server-driven hydration handler for `persistence: true` when the
|
|
50
|
+
* connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
|
|
51
|
+
* `rpcStream()` adapter built without handlers) — typically a one-line
|
|
52
|
+
* server-function call. The connection's own handler takes precedence.
|
|
53
|
+
*/
|
|
54
|
+
hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration'];
|
|
55
|
+
/**
|
|
56
|
+
* Re-attach handler that replays a run still generating to completion on
|
|
57
|
+
* mount, when the connection doesn't carry one. Without it, a restored
|
|
58
|
+
* `running` snapshot surfaces as an (interrupted) error. The connection's
|
|
59
|
+
* own handler takes precedence.
|
|
60
|
+
*/
|
|
61
|
+
joinRun?: ConnectConnectionAdapter['joinRun'];
|
|
23
62
|
/**
|
|
24
63
|
* Callback when video generation completes. Can optionally return a transformed value.
|
|
25
64
|
*
|
|
@@ -63,6 +102,13 @@ interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
63
102
|
stop: () => void;
|
|
64
103
|
/** Clear all state and return to idle */
|
|
65
104
|
reset: () => void;
|
|
105
|
+
/**
|
|
106
|
+
* The id of the generation job currently running, or `null` when nothing is in
|
|
107
|
+
* flight. Each call to `generate` is one job with its own id. Pass it to your
|
|
108
|
+
* own endpoint to cancel or poll the provider job — `stop()` only aborts the
|
|
109
|
+
* local stream, it does not stop work already running on the provider.
|
|
110
|
+
*/
|
|
111
|
+
runId: Accessor<string | null>;
|
|
66
112
|
}
|
|
67
113
|
/**
|
|
68
114
|
* Solid hook for generating videos using AI models.
|
|
@@ -95,9 +141,9 @@ interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
|
|
|
95
141
|
* }
|
|
96
142
|
* ```
|
|
97
143
|
*/
|
|
98
|
-
declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult'> & {
|
|
144
|
+
declare function useGenerateVideo<TTransformed = void>(options: Omit<UseGenerateVideoOptions, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
|
|
99
145
|
onResult?: (result: VideoGenerateResult) => TTransformed;
|
|
100
|
-
}): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
146
|
+
} & GenerationPersistenceOptions): UseGenerateVideoReturn<InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>>;
|
|
101
147
|
//#endregion
|
|
102
148
|
export { UseGenerateVideoOptions, UseGenerateVideoReturn, useGenerateVideo };
|
|
103
149
|
//# sourceMappingURL=use-generate-video.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEffect,
|
|
1
|
+
import { createEffect, createSignal, createUniqueId, onCleanup, onMount, untrack } from "solid-js";
|
|
2
2
|
import { VideoGenerationClient } from "@tanstack/ai-client";
|
|
3
3
|
import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
4
4
|
|
|
@@ -36,17 +36,21 @@ import { createVideoDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
|
36
36
|
*/
|
|
37
37
|
function useGenerateVideo(options) {
|
|
38
38
|
const hookId = createUniqueId();
|
|
39
|
-
const clientId = options.id || hookId;
|
|
40
39
|
const [result, setResult] = createSignal(null);
|
|
41
40
|
const [jobId, setJobId] = createSignal(null);
|
|
42
41
|
const [videoStatus, setVideoStatus] = createSignal(null);
|
|
43
42
|
const [isLoading, setIsLoading] = createSignal(false);
|
|
44
43
|
const [error, setError] = createSignal(void 0);
|
|
45
44
|
const [status, setStatus] = createSignal("idle");
|
|
46
|
-
const
|
|
45
|
+
const [runId, setRunId] = createSignal(null);
|
|
46
|
+
let disposed = false;
|
|
47
|
+
const client = untrack(() => {
|
|
47
48
|
const baseOptions = {
|
|
48
|
-
id: clientId,
|
|
49
49
|
body: options.body,
|
|
50
|
+
...options.threadId !== void 0 ? { threadId: options.threadId } : { id: options.id ?? hookId },
|
|
51
|
+
...options.persistence !== void 0 && { persistence: options.persistence },
|
|
52
|
+
...options.hydrateGeneration !== void 0 && { hydrateGeneration: options.hydrateGeneration },
|
|
53
|
+
...options.joinRun !== void 0 && { joinRun: options.joinRun },
|
|
50
54
|
devtoolsBridgeFactory: createVideoDevtoolsBridge,
|
|
51
55
|
devtools: {
|
|
52
56
|
...options.devtools,
|
|
@@ -55,17 +59,42 @@ function useGenerateVideo(options) {
|
|
|
55
59
|
outputKind: "video"
|
|
56
60
|
},
|
|
57
61
|
onResult: ((r) => options.onResult?.(r)),
|
|
58
|
-
onError: (e) =>
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
62
|
+
onError: (e) => {
|
|
63
|
+
if (!disposed) options.onError?.(e);
|
|
64
|
+
},
|
|
65
|
+
onProgress: (p, m) => {
|
|
66
|
+
if (!disposed) options.onProgress?.(p, m);
|
|
67
|
+
},
|
|
68
|
+
onChunk: (c) => {
|
|
69
|
+
if (!disposed) options.onChunk?.(c);
|
|
70
|
+
},
|
|
71
|
+
onJobCreated: (id) => {
|
|
72
|
+
if (!disposed) options.onJobCreated?.(id);
|
|
73
|
+
},
|
|
74
|
+
onStatusUpdate: (s) => {
|
|
75
|
+
if (!disposed) options.onStatusUpdate?.(s);
|
|
76
|
+
},
|
|
77
|
+
onResultChange: (r) => {
|
|
78
|
+
if (!disposed) setResult(() => r);
|
|
79
|
+
},
|
|
80
|
+
onLoadingChange: (l) => {
|
|
81
|
+
if (!disposed) setIsLoading(l);
|
|
82
|
+
},
|
|
83
|
+
onErrorChange: (e) => {
|
|
84
|
+
if (!disposed) setError(e);
|
|
85
|
+
},
|
|
86
|
+
onStatusChange: (s) => {
|
|
87
|
+
if (!disposed) setStatus(s);
|
|
88
|
+
},
|
|
89
|
+
onJobIdChange: (id) => {
|
|
90
|
+
if (!disposed) setJobId(id);
|
|
91
|
+
},
|
|
92
|
+
onVideoStatusChange: (s) => {
|
|
93
|
+
if (!disposed) setVideoStatus(s);
|
|
94
|
+
},
|
|
95
|
+
onResumeStateChange: (rs) => {
|
|
96
|
+
if (!disposed) setRunId(rs?.runId ?? null);
|
|
97
|
+
}
|
|
69
98
|
};
|
|
70
99
|
if (options.connection) return new VideoGenerationClient({
|
|
71
100
|
...baseOptions,
|
|
@@ -76,25 +105,26 @@ function useGenerateVideo(options) {
|
|
|
76
105
|
fetcher: options.fetcher
|
|
77
106
|
});
|
|
78
107
|
throw new Error("useGenerateVideo requires either a connection or fetcher option");
|
|
79
|
-
}
|
|
108
|
+
});
|
|
80
109
|
createEffect(() => {
|
|
81
110
|
const currentBody = options.body;
|
|
82
|
-
client
|
|
111
|
+
client.updateOptions({ ...currentBody !== void 0 && { body: currentBody } });
|
|
83
112
|
});
|
|
84
113
|
onMount(() => {
|
|
85
|
-
client
|
|
114
|
+
client.mountDevtools();
|
|
86
115
|
});
|
|
87
116
|
onCleanup(() => {
|
|
88
|
-
|
|
117
|
+
disposed = true;
|
|
118
|
+
client.dispose();
|
|
89
119
|
});
|
|
90
120
|
const generate = async (input) => {
|
|
91
|
-
await client
|
|
121
|
+
await client.generate(input);
|
|
92
122
|
};
|
|
93
123
|
const stop = () => {
|
|
94
|
-
client
|
|
124
|
+
client.stop();
|
|
95
125
|
};
|
|
96
126
|
const reset = () => {
|
|
97
|
-
client
|
|
127
|
+
client.reset();
|
|
98
128
|
};
|
|
99
129
|
return {
|
|
100
130
|
generate,
|
|
@@ -105,7 +135,8 @@ function useGenerateVideo(options) {
|
|
|
105
135
|
error,
|
|
106
136
|
status,
|
|
107
137
|
stop,
|
|
108
|
-
reset
|
|
138
|
+
reset,
|
|
139
|
+
runId
|
|
109
140
|
};
|
|
110
141
|
}
|
|
111
142
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generate-video.js","names":[],"sources":["../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createMemo,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when video generation completes. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: VideoGenerateResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: Accessor<TOutput | null>\n /** The current job ID, or null */\n jobId: Accessor<string | null>\n /** Current video generation status info, or null */\n videoStatus: Accessor<VideoStatusInfo | null>\n /** Whether generation/polling is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n}\n\n/**\n * Solid hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading() && videoStatus() && (\n * <p>Status: {videoStatus()!.status} ({videoStatus()!.progress}%)</p>\n * )}\n * {result() && <video src={result()!.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function useGenerateVideo<TTransformed = void>(\n options: Omit<UseGenerateVideoOptions, 'onResult'> & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n },\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const hookId = createUniqueId()\n const clientId = options.id || hookId\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [jobId, setJobId] = createSignal<string | null>(null)\n const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(\n null,\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n\n const client = createMemo(() => {\n // Conditional spread on `body`: VideoGenerationClientOptions.body\n // is a strict optional; EOPT forbids passing `T | undefined`.\n const baseOptions = {\n id: clientId,\n body: options.body,\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateVideo',\n outputKind: 'video' as const,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: VideoGenerateResult) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => options.onError?.(e),\n onProgress: (p: number, m?: string) => options.onProgress?.(p, m),\n onChunk: (c: StreamChunk) => options.onChunk?.(c),\n onJobCreated: (id: string) => options.onJobCreated?.(id),\n onStatusUpdate: (s: VideoStatusInfo) => options.onStatusUpdate?.(s),\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n onJobIdChange: setJobId,\n onVideoStatusChange: setVideoStatus,\n }\n\n if (options.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client().updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n onMount(() => {\n client().mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n client().dispose()\n })\n\n const generate = async (input: VideoGenerateInput) => {\n await client().generate(input)\n }\n\n const stop = () => {\n client().stop()\n }\n\n const reset = () => {\n client().reset()\n }\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHA,SAAgB,iBACd,SAKA;CAKA,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ,MAAM;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,aAAa,kBAAkB,aACpC,KACD;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CAEvE,MAAM,SAAS,iBAAiB;EAG9B,MAAM,cAAc;GAClB,IAAI;GACJ,MAAM,QAAQ;GACd,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACV,YAAY;IACb;GAID,YAAY,MAA2B,QAAQ,WAAW,EAAE;GAG5D,UAAU,MAAa,QAAQ,UAAU,EAAE;GAC3C,aAAa,GAAW,MAAe,QAAQ,aAAa,GAAG,EAAE;GACjE,UAAU,MAAmB,QAAQ,UAAU,EAAE;GACjD,eAAe,OAAe,QAAQ,eAAe,GAAG;GACxD,iBAAiB,MAAuB,QAAQ,iBAAiB,EAAE;GACnE,gBAAgB;GAChB,iBAAiB;GACjB,eAAe;GACf,gBAAgB;GAChB,eAAe;GACf,qBAAqB;GACtB;AAED,MAAI,QAAQ,WACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,kEACD;IACA,CAAC,SAAS,CAAC;AAGd,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,UAAQ,CAAC,cAAc,EACrB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAEF,eAAc;AACZ,UAAQ,CAAC,eAAe;GACxB;AAGF,iBAAgB;AACd,UAAQ,CAAC,SAAS;GAClB;CAEF,MAAM,WAAW,OAAO,UAA8B;AACpD,QAAM,QAAQ,CAAC,SAAS,MAAM;;CAGhC,MAAM,aAAa;AACjB,UAAQ,CAAC,MAAM;;CAGjB,MAAM,cAAc;AAClB,UAAQ,CAAC,OAAO;;AAGlB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"use-generate-video.js","names":[],"sources":["../src/use-generate-video.ts"],"sourcesContent":["import { VideoGenerationClient } from '@tanstack/ai-client'\nimport { createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n InferGenerationOutputFromReturn,\n VideoGenerateInput,\n VideoGenerateResult,\n VideoStatusInfo,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\n */\nexport interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {\n /** Connect-based adapter for streaming transport (server handles polling) */\n connection?: ConnectConnectionAdapter\n /** Direct async function that returns a completed video result */\n fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>\n /**\n * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).\n */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations, where\n * it falls back to `id` purely to satisfy the wire.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n /**\n * Callback when video generation completes. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: VideoGenerateResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback when a video job is created */\n onJobCreated?: (jobId: string) => void\n /** Callback on each status update */\n onStatusUpdate?: (status: VideoStatusInfo) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGenerateVideo hook.\n *\n * @template TOutput - The transformed output type (defaults to VideoGenerateResult)\n */\nexport interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {\n /** Trigger video generation */\n generate: (input: VideoGenerateInput) => Promise<void>\n /** The final video result (with URL), or null */\n result: Accessor<TOutput | null>\n /** The current job ID, or null */\n jobId: Accessor<string | null>\n /** Current video generation status info, or null */\n videoStatus: Accessor<VideoStatusInfo | null>\n /** Whether generation/polling is in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation */\n status: Accessor<GenerationClientState>\n /** Abort the current generation/polling */\n stop: () => void\n /** Clear all state and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Accessor<string | null>\n}\n\n/**\n * Solid hook for generating videos using AI models.\n *\n * Video generation is asynchronous: a job is created, then polled for status\n * until completion. This hook handles the full lifecycle.\n *\n * @example\n * ```tsx\n * import { useGenerateVideo } from '@tanstack/ai-solid'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function VideoGenerator() {\n * const { generate, result, videoStatus, isLoading } = useGenerateVideo({\n * connection: fetchServerSentEvents('/api/generate/video'),\n * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>\n * Generate Video\n * </button>\n * {isLoading() && videoStatus() && (\n * <p>Status: {videoStatus()!.status} ({videoStatus()!.progress}%)</p>\n * )}\n * {result() && <video src={result()!.url} controls />}\n * </div>\n * )\n * }\n * ```\n */\n// `TTransformed` infers from the `onResult` return position so the callback\n// parameter is typed as `VideoGenerateResult` and `result` narrows to the\n// transform's return. See issue #848.\nexport function useGenerateVideo<TTransformed = void>(\n options: Omit<\n UseGenerateVideoOptions,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: VideoGenerateResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerateVideoReturn<\n InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>\n> {\n type TOutput = InferGenerationOutputFromReturn<\n VideoGenerateResult,\n TTransformed\n >\n const hookId = createUniqueId()\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [jobId, setJobId] = createSignal<string | null>(null)\n const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(\n null,\n )\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): VideoGenerationClient<TOutput> => {\n // Conditional spread on `body`: VideoGenerationClientOptions.body\n // is a strict optional; EOPT forbids passing `T | undefined`.\n const baseOptions = {\n body: options.body,\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n ...(options.threadId !== undefined\n ? { threadId: options.threadId }\n : { id: options.id ?? hookId }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n devtoolsBridgeFactory: createVideoDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGenerateVideo',\n outputKind: 'video' as const,\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: VideoGenerateResult) => options.onResult?.(r)) as (\n result: VideoGenerateResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onJobCreated: (id: string) => {\n if (!disposed) options.onJobCreated?.(id)\n },\n onStatusUpdate: (s: VideoStatusInfo) => {\n if (!disposed) options.onStatusUpdate?.(s)\n },\n onResultChange: (r: TOutput | null) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l: boolean) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e: Error | undefined) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s: GenerationClientState) => {\n if (!disposed) setStatus(s)\n },\n onJobIdChange: (id: string | null) => {\n if (!disposed) setJobId(id)\n },\n onVideoStatusChange: (s: VideoStatusInfo | null) => {\n if (!disposed) setVideoStatus(s)\n },\n onResumeStateChange: (rs: { runId: string } | null) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new VideoGenerationClient<TOutput>({\n ...baseOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGenerateVideo requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: VideoGenerateInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\n\n return {\n generate,\n result,\n jobId,\n videoStatus,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsKA,SAAgB,iBACd,SAQA;CAKA,MAAM,SAAS,gBAAgB;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,MAAM,CAAC,aAAa,kBAAkB,aACpC,KACD;CACD,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA8C;EAG3D,MAAM,cAAc;GAClB,MAAM,QAAQ;GAEd,GAAI,QAAQ,aAAa,SACrB,EAAE,UAAU,QAAQ,UAAU,GAC9B,EAAE,IAAI,QAAQ,MAAM,QAAQ;GAChC,GAAI,QAAQ,gBAAgB,UAAa,EACvC,aAAa,QAAQ,aACtB;GACD,GAAI,QAAQ,sBAAsB,UAAa,EAC7C,mBAAmB,QAAQ,mBAC5B;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACV,YAAY;IACb;GAID,YAAY,MAA2B,QAAQ,WAAW,EAAE;GAG5D,UAAU,MAAa;AACrB,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,aAAa,GAAW,MAAe;AACrC,QAAI,CAAC,SAAU,SAAQ,aAAa,GAAG,EAAE;;GAE3C,UAAU,MAAmB;AAC3B,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,eAAe,OAAe;AAC5B,QAAI,CAAC,SAAU,SAAQ,eAAe,GAAG;;GAE3C,iBAAiB,MAAuB;AACtC,QAAI,CAAC,SAAU,SAAQ,iBAAiB,EAAE;;GAE5C,iBAAiB,MAAsB;AACrC,QAAI,CAAC,SAAU,iBAAgB,EAAE;;GAEnC,kBAAkB,MAAe;AAC/B,QAAI,CAAC,SAAU,cAAa,EAAE;;GAEhC,gBAAgB,MAAyB;AACvC,QAAI,CAAC,SAAU,UAAS,EAAE;;GAE5B,iBAAiB,MAA6B;AAC5C,QAAI,CAAC,SAAU,WAAU,EAAE;;GAE7B,gBAAgB,OAAsB;AACpC,QAAI,CAAC,SAAU,UAAS,GAAG;;GAE7B,sBAAsB,MAA8B;AAClD,QAAI,CAAC,SAAU,gBAAe,EAAE;;GAElC,sBAAsB,OAAiC;AACrD,QAAI,CAAC,SAAU,UAAS,IAAI,SAAS,KAAK;;GAE7C;AAED,MAAI,QAAQ,WACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,sBAA+B;GACxC,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,kEACD;GACD;AAGF,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,SAAO,cAAc,EACnB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAIF,eAAc;AACZ,SAAO,eAAe;GACtB;AAGF,iBAAgB;AACd,aAAW;AACX,SAAO,SAAS;GAChB;CAEF,MAAM,WAAW,OAAO,UAA8B;AACpD,QAAM,OAAO,SAAS,MAAM;;CAG9B,MAAM,aAAa;AACjB,SAAO,MAAM;;CAGf,MAAM,cAAc;AAClB,SAAO,OAAO;;AAGhB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
package/dist/use-generation.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Accessor } from "solid-js";
|
|
2
|
-
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutputFromReturn } from "@tanstack/ai-client";
|
|
2
|
+
import { AIDevtoolsDisplayOptions, ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, GenerationPersistenceOptions, GenerationRestoredResult, InferGenerationOutputFromReturn } from "@tanstack/ai-client";
|
|
3
3
|
import { StreamChunk } from "@tanstack/ai";
|
|
4
4
|
|
|
5
5
|
//#region src/use-generation.d.ts
|
|
@@ -18,12 +18,51 @@ interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
18
18
|
connection?: ConnectConnectionAdapter;
|
|
19
19
|
/** Direct async function for one-shot generation (no streaming protocol needed) */
|
|
20
20
|
fetcher?: GenerationFetcher<TInput, TResult>;
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).
|
|
23
|
+
*/
|
|
22
24
|
id?: string;
|
|
23
25
|
/** Additional body parameters to send with connect-based adapter requests */
|
|
24
26
|
body?: Record<string, any>;
|
|
25
27
|
/** Display options for TanStack AI Devtools. */
|
|
26
28
|
devtools?: AIDevtoolsDisplayOptions;
|
|
29
|
+
/**
|
|
30
|
+
* How this generation persists across reloads.
|
|
31
|
+
* - Omit / `false`: ephemeral, in-memory only.
|
|
32
|
+
* - `true`: server-driven — on mount the client hydrates the last generation
|
|
33
|
+
* for its `threadId` from the server (needs a connection with a
|
|
34
|
+
* `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
|
|
35
|
+
*/
|
|
36
|
+
persistence?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* The **scope** this generation belongs to: a stable, app-chosen name for the
|
|
39
|
+
* slot successive runs fill — not a link to a chat conversation.
|
|
40
|
+
*
|
|
41
|
+
* The hook starts empty and produces many runs over its life; each gets its
|
|
42
|
+
* own `runId`, but all belong to one scope. Persistence keys on this, so
|
|
43
|
+
* derive it from your own domain and keep it identical across reloads (e.g.
|
|
44
|
+
* `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
|
|
45
|
+
* id on the wire, which the protocol requires.
|
|
46
|
+
*
|
|
47
|
+
* **Required whenever `persistence` is set** — an app that cannot name the
|
|
48
|
+
* scope has nothing to restore to. Optional for ephemeral generations, where
|
|
49
|
+
* it falls back to `id` purely to satisfy the wire.
|
|
50
|
+
*/
|
|
51
|
+
threadId?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Server-driven hydration handler for `persistence: true` when the
|
|
54
|
+
* connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
|
|
55
|
+
* `rpcStream()` adapter built without handlers) — typically a one-line
|
|
56
|
+
* server-function call. The connection's own handler takes precedence.
|
|
57
|
+
*/
|
|
58
|
+
hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration'];
|
|
59
|
+
/**
|
|
60
|
+
* Re-attach handler that replays a run still generating to completion on
|
|
61
|
+
* mount, when the connection doesn't carry one. Without it, a restored
|
|
62
|
+
* `running` snapshot surfaces as an (interrupted) error. The connection's
|
|
63
|
+
* own handler takes precedence.
|
|
64
|
+
*/
|
|
65
|
+
joinRun?: ConnectConnectionAdapter['joinRun'];
|
|
27
66
|
/**
|
|
28
67
|
* Callback when a result is received. Can optionally return a transformed value.
|
|
29
68
|
*
|
|
@@ -38,15 +77,22 @@ interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
|
|
|
38
77
|
onProgress?: (progress: number, message?: string) => void;
|
|
39
78
|
/** Callback for each stream chunk (connect-based adapter mode only) */
|
|
40
79
|
onChunk?: (chunk: StreamChunk) => void;
|
|
80
|
+
/**
|
|
81
|
+
* @internal Rebuild a typed result from a restored snapshot, injected by each
|
|
82
|
+
* specialized hook (image / speech / audio / transcription / summarize).
|
|
83
|
+
* Forwarded to the client so a server-hydrate restore repaints `result`.
|
|
84
|
+
*/
|
|
85
|
+
reconstructResult?: (restored: GenerationRestoredResult) => TResult | null;
|
|
41
86
|
}
|
|
42
87
|
/**
|
|
43
88
|
* Return type for the useGeneration hook.
|
|
44
89
|
*
|
|
45
90
|
* @template TOutput - The output type (possibly transformed from the raw result)
|
|
91
|
+
* @template TInput - The input type accepted by `generate` (defaults to any object)
|
|
46
92
|
*/
|
|
47
|
-
interface UseGenerationReturn<TOutput> {
|
|
93
|
+
interface UseGenerationReturn<TOutput, TInput extends Record<string, any> = Record<string, any>> {
|
|
48
94
|
/** Trigger a generation request */
|
|
49
|
-
generate: (input:
|
|
95
|
+
generate: (input: TInput) => Promise<void>;
|
|
50
96
|
/** The generation result, or null if not yet generated */
|
|
51
97
|
result: Accessor<TOutput | null>;
|
|
52
98
|
/** Whether a generation is currently in progress */
|
|
@@ -59,6 +105,13 @@ interface UseGenerationReturn<TOutput> {
|
|
|
59
105
|
stop: () => void;
|
|
60
106
|
/** Clear result, error, and return to idle */
|
|
61
107
|
reset: () => void;
|
|
108
|
+
/**
|
|
109
|
+
* The id of the generation job currently running, or `null` when nothing is in
|
|
110
|
+
* flight. Each call to `generate` is one job with its own id. Pass it to your
|
|
111
|
+
* own endpoint to cancel or poll the provider job — `stop()` only aborts the
|
|
112
|
+
* local stream, it does not stop work already running on the provider.
|
|
113
|
+
*/
|
|
114
|
+
runId: Accessor<string | null>;
|
|
62
115
|
}
|
|
63
116
|
/**
|
|
64
117
|
* Generic Solid hook for one-shot generation tasks.
|
|
@@ -80,9 +133,9 @@ interface UseGenerationReturn<TOutput> {
|
|
|
80
133
|
* await generate({ prompt: 'Hello' })
|
|
81
134
|
* ```
|
|
82
135
|
*/
|
|
83
|
-
declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
|
|
136
|
+
declare function useGeneration<TInput extends Record<string, any>, TResult, TTransformed = void>(options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult' | 'persistence' | 'threadId' | 'id'> & {
|
|
84
137
|
onResult?: (result: TResult) => TTransformed;
|
|
85
|
-
}): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed
|
|
138
|
+
} & GenerationPersistenceOptions): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>, TInput>;
|
|
86
139
|
//#endregion
|
|
87
140
|
export { UseGenerationOptions, UseGenerationReturn, useGeneration };
|
|
88
141
|
//# sourceMappingURL=use-generation.d.ts.map
|
package/dist/use-generation.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createEffect,
|
|
1
|
+
import { createEffect, createSignal, createUniqueId, onCleanup, onMount, untrack } from "solid-js";
|
|
2
2
|
import { GenerationClient } from "@tanstack/ai-client";
|
|
3
3
|
import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
4
4
|
|
|
@@ -25,15 +25,20 @@ import { createGenerationDevtoolsBridge } from "@tanstack/ai-client/devtools";
|
|
|
25
25
|
*/
|
|
26
26
|
function useGeneration(options) {
|
|
27
27
|
const hookId = createUniqueId();
|
|
28
|
-
const clientId = options.id || hookId;
|
|
29
28
|
const [result, setResult] = createSignal(null);
|
|
30
29
|
const [isLoading, setIsLoading] = createSignal(false);
|
|
31
30
|
const [error, setError] = createSignal(void 0);
|
|
32
31
|
const [status, setStatus] = createSignal("idle");
|
|
33
|
-
const
|
|
32
|
+
const [runId, setRunId] = createSignal(null);
|
|
33
|
+
let disposed = false;
|
|
34
|
+
const client = untrack(() => {
|
|
34
35
|
const clientOptions = {
|
|
35
|
-
id: clientId,
|
|
36
36
|
body: options.body,
|
|
37
|
+
...options.threadId !== void 0 ? { threadId: options.threadId } : { id: options.id ?? hookId },
|
|
38
|
+
...options.persistence !== void 0 && { persistence: options.persistence },
|
|
39
|
+
...options.hydrateGeneration !== void 0 && { hydrateGeneration: options.hydrateGeneration },
|
|
40
|
+
...options.joinRun !== void 0 && { joinRun: options.joinRun },
|
|
41
|
+
...options.reconstructResult ? { reconstructResult: options.reconstructResult } : {},
|
|
37
42
|
devtoolsBridgeFactory: createGenerationDevtoolsBridge,
|
|
38
43
|
devtools: {
|
|
39
44
|
...options.devtools,
|
|
@@ -41,13 +46,30 @@ function useGeneration(options) {
|
|
|
41
46
|
hookName: "useGeneration"
|
|
42
47
|
},
|
|
43
48
|
onResult: ((r) => options.onResult?.(r)),
|
|
44
|
-
onError: (e) =>
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
onError: (e) => {
|
|
50
|
+
if (!disposed) options.onError?.(e);
|
|
51
|
+
},
|
|
52
|
+
onProgress: (p, m) => {
|
|
53
|
+
if (!disposed) options.onProgress?.(p, m);
|
|
54
|
+
},
|
|
55
|
+
onChunk: (c) => {
|
|
56
|
+
if (!disposed) options.onChunk?.(c);
|
|
57
|
+
},
|
|
58
|
+
onResultChange: (r) => {
|
|
59
|
+
if (!disposed) setResult(() => r);
|
|
60
|
+
},
|
|
61
|
+
onLoadingChange: (l) => {
|
|
62
|
+
if (!disposed) setIsLoading(l);
|
|
63
|
+
},
|
|
64
|
+
onErrorChange: (e) => {
|
|
65
|
+
if (!disposed) setError(e);
|
|
66
|
+
},
|
|
67
|
+
onStatusChange: (s) => {
|
|
68
|
+
if (!disposed) setStatus(s);
|
|
69
|
+
},
|
|
70
|
+
onResumeStateChange: (rs) => {
|
|
71
|
+
if (!disposed) setRunId(rs?.runId ?? null);
|
|
72
|
+
}
|
|
51
73
|
};
|
|
52
74
|
if (options.connection) return new GenerationClient({
|
|
53
75
|
...clientOptions,
|
|
@@ -58,25 +80,26 @@ function useGeneration(options) {
|
|
|
58
80
|
fetcher: options.fetcher
|
|
59
81
|
});
|
|
60
82
|
throw new Error("useGeneration requires either a connection or fetcher option");
|
|
61
|
-
}
|
|
83
|
+
});
|
|
62
84
|
createEffect(() => {
|
|
63
85
|
const currentBody = options.body;
|
|
64
|
-
client
|
|
86
|
+
client.updateOptions({ ...currentBody !== void 0 && { body: currentBody } });
|
|
65
87
|
});
|
|
66
88
|
onMount(() => {
|
|
67
|
-
client
|
|
89
|
+
client.mountDevtools();
|
|
68
90
|
});
|
|
69
91
|
onCleanup(() => {
|
|
70
|
-
|
|
92
|
+
disposed = true;
|
|
93
|
+
client.dispose();
|
|
71
94
|
});
|
|
72
95
|
const generate = async (input) => {
|
|
73
|
-
await client
|
|
96
|
+
await client.generate(input);
|
|
74
97
|
};
|
|
75
98
|
const stop = () => {
|
|
76
|
-
client
|
|
99
|
+
client.stop();
|
|
77
100
|
};
|
|
78
101
|
const reset = () => {
|
|
79
|
-
client
|
|
102
|
+
client.reset();
|
|
80
103
|
};
|
|
81
104
|
return {
|
|
82
105
|
generate,
|
|
@@ -85,7 +108,8 @@ function useGeneration(options) {
|
|
|
85
108
|
error,
|
|
86
109
|
status,
|
|
87
110
|
stop,
|
|
88
|
-
reset
|
|
111
|
+
reset,
|
|
112
|
+
runId
|
|
89
113
|
};
|
|
90
114
|
}
|
|
91
115
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-generation.js","names":["clientOptions: GenerationClientOptions<TInput, TResult, TOutput>"],"sources":["../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createMemo,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGeneration hook.\n *\n * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The transformed output type (defaults to TResult)\n */\nexport interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (possibly transformed from the raw result)\n */\nexport interface UseGenerationReturn<TOutput> {\n /** Trigger a generation request */\n generate: (input: Record<string, any>) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: Accessor<TOutput | null>\n /** Whether a generation is currently in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation client */\n status: Accessor<GenerationClientState>\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * Generic Solid hook for one-shot generation tasks.\n *\n * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,\n * `useTranscription`, and `useSummarize`. You can also use it directly\n * for custom generation types.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The transformed output type (defaults to TResult)\n *\n * @example\n * ```tsx\n * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({\n * connection: fetchServerSentEvents('/api/generate/custom'),\n * })\n *\n * await generate({ prompt: 'Hello' })\n * ```\n */\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function useGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {\n onResult?: (result: TResult) => TTransformed\n },\n): UseGenerationReturn<InferGenerationOutputFromReturn<TResult, TTransformed>> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = createUniqueId()\n const clientId = options.id || hookId\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n\n const client = createMemo(() => {\n // Conditional spread on `body`: `GenerationClientOptions.body` is a\n // strict optional (`body?: Record<string, any>`) and EOPT forbids\n // assigning the source `T | undefined` directly.\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n id: clientId,\n body: options.body,\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGeneration',\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => options.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => options.onError?.(e),\n onProgress: (p: number, m?: string) => options.onProgress?.(p, m),\n onChunk: (c: StreamChunk) => options.onChunk?.(c),\n onResultChange: setResult,\n onLoadingChange: setIsLoading,\n onErrorChange: setError,\n onStatusChange: setStatus,\n }\n\n if (options.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n }, [clientId])\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client().updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n onMount(() => {\n client().mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n client().dispose()\n })\n\n const generate = async (input: TInput) => {\n await client().generate(input)\n }\n\n const stop = () => {\n client().stop()\n }\n\n const reset = () => {\n client().reset()\n }\n\n return {\n generate: generate as (input: Record<string, any>) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,SAAgB,cAKd,SAG6E;CAE7E,MAAM,SAAS,gBAAgB;CAC/B,MAAM,WAAW,QAAQ,MAAM;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CAEvE,MAAM,SAAS,iBAAiB;EAI9B,MAAMA,gBAAmE;GACvE,IAAI;GACJ,MAAM,QAAQ;GACd,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACX;GAID,YAAY,MAAe,QAAQ,WAAW,EAAE;GAGhD,UAAU,MAAa,QAAQ,UAAU,EAAE;GAC3C,aAAa,GAAW,MAAe,QAAQ,aAAa,GAAG,EAAE;GACjE,UAAU,MAAmB,QAAQ,UAAU,EAAE;GACjD,gBAAgB;GAChB,iBAAiB;GACjB,eAAe;GACf,gBAAgB;GACjB;AAED,MAAI,QAAQ,WACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,+DACD;IACA,CAAC,SAAS,CAAC;AAGd,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,UAAQ,CAAC,cAAc,EACrB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAEF,eAAc;AACZ,UAAQ,CAAC,eAAe;GACxB;AAGF,iBAAgB;AACd,UAAQ,CAAC,SAAS;GAClB;CAEF,MAAM,WAAW,OAAO,UAAkB;AACxC,QAAM,QAAQ,CAAC,SAAS,MAAM;;CAGhC,MAAM,aAAa;AACjB,UAAQ,CAAC,MAAM;;CAGjB,MAAM,cAAc;AAClB,UAAQ,CAAC,OAAO;;AAGlB,QAAO;EACK;EACV;EACA;EACA;EACA;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"use-generation.js","names":["clientOptions: GenerationClientOptions<TInput, TResult, TOutput>"],"sources":["../src/use-generation.ts"],"sourcesContent":["import { GenerationClient } from '@tanstack/ai-client'\nimport { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'\nimport {\n createEffect,\n createSignal,\n createUniqueId,\n onCleanup,\n onMount,\n untrack,\n} from 'solid-js'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type {\n AIDevtoolsDisplayOptions,\n ConnectConnectionAdapter,\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n GenerationPersistenceOptions,\n GenerationRestoredResult,\n InferGenerationOutputFromReturn,\n} from '@tanstack/ai-client'\nimport type { Accessor } from 'solid-js'\n\n/**\n * Options for the useGeneration hook.\n *\n * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The transformed output type (defaults to TResult)\n */\nexport interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for one-shot generation (no streaming protocol needed) */\n fetcher?: GenerationFetcher<TInput, TResult>\n /**\n * @deprecated Prefer `threadId`. Only allowed when `threadId` is omitted (see `GenerationPersistenceOptions`).\n */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /** Display options for TanStack AI Devtools. */\n devtools?: AIDevtoolsDisplayOptions\n /**\n * How this generation persists across reloads.\n * - Omit / `false`: ephemeral, in-memory only.\n * - `true`: server-driven — on mount the client hydrates the last generation\n * for its `threadId` from the server (needs a connection with a\n * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.\n */\n persistence?: boolean\n /**\n * The **scope** this generation belongs to: a stable, app-chosen name for the\n * slot successive runs fill — not a link to a chat conversation.\n *\n * The hook starts empty and produces many runs over its life; each gets its\n * own `runId`, but all belong to one scope. Persistence keys on this, so\n * derive it from your own domain and keep it identical across reloads (e.g.\n * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread\n * id on the wire, which the protocol requires.\n *\n * **Required whenever `persistence` is set** — an app that cannot name the\n * scope has nothing to restore to. Optional for ephemeral generations, where\n * it falls back to `id` purely to satisfy the wire.\n */\n threadId?: string\n /**\n * Server-driven hydration handler for `persistence: true` when the\n * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /\n * `rpcStream()` adapter built without handlers) — typically a one-line\n * server-function call. The connection's own handler takes precedence.\n */\n hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']\n /**\n * Re-attach handler that replays a run still generating to completion on\n * mount, when the connection doesn't carry one. Without it, a restored\n * `running` snapshot surfaces as an (interrupted) error. The connection's\n * own handler takes precedence.\n */\n joinRun?: ConnectConnectionAdapter['joinRun']\n /**\n * Callback when a result is received. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n /**\n * @internal Rebuild a typed result from a restored snapshot, injected by each\n * specialized hook (image / speech / audio / transcription / summarize).\n * Forwarded to the client so a server-hydrate restore repaints `result`.\n */\n reconstructResult?: (restored: GenerationRestoredResult) => TResult | null\n}\n\n/**\n * Return type for the useGeneration hook.\n *\n * @template TOutput - The output type (possibly transformed from the raw result)\n * @template TInput - The input type accepted by `generate` (defaults to any object)\n */\nexport interface UseGenerationReturn<\n TOutput,\n TInput extends Record<string, any> = Record<string, any>,\n> {\n /** Trigger a generation request */\n generate: (input: TInput) => Promise<void>\n /** The generation result, or null if not yet generated */\n result: Accessor<TOutput | null>\n /** Whether a generation is currently in progress */\n isLoading: Accessor<boolean>\n /** Current error, if any */\n error: Accessor<Error | undefined>\n /** Current state of the generation client */\n status: Accessor<GenerationClientState>\n /** Abort the current generation */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n /**\n * The id of the generation job currently running, or `null` when nothing is in\n * flight. Each call to `generate` is one job with its own id. Pass it to your\n * own endpoint to cancel or poll the provider job — `stop()` only aborts the\n * local stream, it does not stop work already running on the provider.\n */\n runId: Accessor<string | null>\n}\n\n/**\n * Generic Solid hook for one-shot generation tasks.\n *\n * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,\n * `useTranscription`, and `useSummarize`. You can also use it directly\n * for custom generation types.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n * @template TOutput - The transformed output type (defaults to TResult)\n *\n * @example\n * ```tsx\n * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({\n * connection: fetchServerSentEvents('/api/generate/custom'),\n * })\n *\n * await generate({ prompt: 'Hello' })\n * ```\n */\n// `TTransformed` infers from the `onResult` return position (a covariant\n// inference site that works even for an optional nested property), which types\n// the callback parameter as `TResult` and narrows `result`. Inferring the\n// whole callback as a defaulted type parameter instead collapses to the\n// default, leaving the parameter `any` — a hard error under `strict`. See\n// issue #848.\nexport function useGeneration<\n TInput extends Record<string, any>,\n TResult,\n TTransformed = void,\n>(\n options: Omit<\n UseGenerationOptions<TInput, TResult>,\n 'onResult' | 'persistence' | 'threadId' | 'id'\n > & {\n onResult?: (result: TResult) => TTransformed\n } & GenerationPersistenceOptions,\n): UseGenerationReturn<\n InferGenerationOutputFromReturn<TResult, TTransformed>,\n TInput\n> {\n type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>\n const hookId = createUniqueId()\n\n const [result, setResult] = createSignal<TOutput | null>(null)\n const [isLoading, setIsLoading] = createSignal(false)\n const [error, setError] = createSignal<Error | undefined>(undefined)\n const [status, setStatus] = createSignal<GenerationClientState>('idle')\n const [runId, setRunId] = createSignal<string | null>(null)\n let disposed = false\n\n // Built once. `untrack` keeps the option reads below from subscribing\n // construction to `options.persistence` / `options.devtools` /\n // `options.body`: a re-run would build a second client\n // and orphan the first (only the live one is disposed on cleanup). Later\n // `options.body` changes are pushed through `updateOptions` instead.\n const client = untrack((): GenerationClient<TInput, TResult, TOutput> => {\n // Conditional spread on `body`: `GenerationClientOptions.body` is a\n // strict optional (`body?: Record<string, any>`) and EOPT forbids\n // assigning the source `T | undefined` directly.\n const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {\n body: options.body,\n // Identity: pass `threadId` alone when set (never also pass deprecated `id`).\n ...(options.threadId !== undefined\n ? { threadId: options.threadId }\n : { id: options.id ?? hookId }),\n ...(options.persistence !== undefined && {\n persistence: options.persistence,\n }),\n ...(options.hydrateGeneration !== undefined && {\n hydrateGeneration: options.hydrateGeneration,\n }),\n ...(options.joinRun !== undefined && { joinRun: options.joinRun }),\n ...(options.reconstructResult\n ? { reconstructResult: options.reconstructResult }\n : {}),\n devtoolsBridgeFactory: createGenerationDevtoolsBridge,\n devtools: {\n ...options.devtools,\n framework: 'solid',\n hookName: 'useGeneration',\n },\n // The transform's raw return type (`TTransformed`) and the stored output\n // (`TOutput`, with null/void/undefined stripped) are identical at runtime;\n // the cast bridges the relationship that the conditional type hides.\n onResult: ((r: TResult) => options.onResult?.(r)) as (\n result: TResult,\n ) => TOutput | null | void,\n onError: (e: Error) => {\n if (!disposed) options.onError?.(e)\n },\n onProgress: (p: number, m?: string) => {\n if (!disposed) options.onProgress?.(p, m)\n },\n onChunk: (c: StreamChunk) => {\n if (!disposed) options.onChunk?.(c)\n },\n onResultChange: (r) => {\n if (!disposed) setResult(() => r)\n },\n onLoadingChange: (l) => {\n if (!disposed) setIsLoading(l)\n },\n onErrorChange: (e) => {\n if (!disposed) setError(e)\n },\n onStatusChange: (s) => {\n if (!disposed) setStatus(s)\n },\n onResumeStateChange: (rs) => {\n if (!disposed) setRunId(rs?.runId ?? null)\n },\n }\n\n if (options.connection) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n connection: options.connection,\n })\n }\n\n if (options.fetcher) {\n return new GenerationClient<TInput, TResult, TOutput>({\n ...clientOptions,\n fetcher: options.fetcher,\n })\n }\n\n throw new Error(\n 'useGeneration requires either a connection or fetcher option',\n )\n })\n\n // Sync body changes without recreating client\n createEffect(() => {\n const currentBody = options.body\n client.updateOptions({\n ...(currentBody !== undefined && { body: currentBody }),\n })\n })\n\n // Mount devtools only. Generation runs are never auto-started on mount — a\n // persisted snapshot is hydrated for display, never replayed.\n onMount(() => {\n client.mountDevtools()\n })\n\n // Cleanup on unmount: stop any in-flight requests and unregister devtools\n onCleanup(() => {\n disposed = true\n client.dispose()\n })\n\n const generate = async (input: TInput) => {\n await client.generate(input)\n }\n\n const stop = () => {\n client.stop()\n }\n\n const reset = () => {\n client.reset()\n }\n\n return {\n generate,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n runId,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmKA,SAAgB,cAKd,SASA;CAEA,MAAM,SAAS,gBAAgB;CAE/B,MAAM,CAAC,QAAQ,aAAa,aAA6B,KAAK;CAC9D,MAAM,CAAC,WAAW,gBAAgB,aAAa,MAAM;CACrD,MAAM,CAAC,OAAO,YAAY,aAAgC,OAAU;CACpE,MAAM,CAAC,QAAQ,aAAa,aAAoC,OAAO;CACvE,MAAM,CAAC,OAAO,YAAY,aAA4B,KAAK;CAC3D,IAAI,WAAW;CAOf,MAAM,SAAS,cAA0D;EAIvE,MAAMA,gBAAmE;GACvE,MAAM,QAAQ;GAEd,GAAI,QAAQ,aAAa,SACrB,EAAE,UAAU,QAAQ,UAAU,GAC9B,EAAE,IAAI,QAAQ,MAAM,QAAQ;GAChC,GAAI,QAAQ,gBAAgB,UAAa,EACvC,aAAa,QAAQ,aACtB;GACD,GAAI,QAAQ,sBAAsB,UAAa,EAC7C,mBAAmB,QAAQ,mBAC5B;GACD,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,SAAS;GACjE,GAAI,QAAQ,oBACR,EAAE,mBAAmB,QAAQ,mBAAmB,GAChD,EAAE;GACN,uBAAuB;GACvB,UAAU;IACR,GAAG,QAAQ;IACX,WAAW;IACX,UAAU;IACX;GAID,YAAY,MAAe,QAAQ,WAAW,EAAE;GAGhD,UAAU,MAAa;AACrB,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,aAAa,GAAW,MAAe;AACrC,QAAI,CAAC,SAAU,SAAQ,aAAa,GAAG,EAAE;;GAE3C,UAAU,MAAmB;AAC3B,QAAI,CAAC,SAAU,SAAQ,UAAU,EAAE;;GAErC,iBAAiB,MAAM;AACrB,QAAI,CAAC,SAAU,iBAAgB,EAAE;;GAEnC,kBAAkB,MAAM;AACtB,QAAI,CAAC,SAAU,cAAa,EAAE;;GAEhC,gBAAgB,MAAM;AACpB,QAAI,CAAC,SAAU,UAAS,EAAE;;GAE5B,iBAAiB,MAAM;AACrB,QAAI,CAAC,SAAU,WAAU,EAAE;;GAE7B,sBAAsB,OAAO;AAC3B,QAAI,CAAC,SAAU,UAAS,IAAI,SAAS,KAAK;;GAE7C;AAED,MAAI,QAAQ,WACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,YAAY,QAAQ;GACrB,CAAC;AAGJ,MAAI,QAAQ,QACV,QAAO,IAAI,iBAA2C;GACpD,GAAG;GACH,SAAS,QAAQ;GAClB,CAAC;AAGJ,QAAM,IAAI,MACR,+DACD;GACD;AAGF,oBAAmB;EACjB,MAAM,cAAc,QAAQ;AAC5B,SAAO,cAAc,EACnB,GAAI,gBAAgB,UAAa,EAAE,MAAM,aAAa,EACvD,CAAC;GACF;AAIF,eAAc;AACZ,SAAO,eAAe;GACtB;AAGF,iBAAgB;AACd,aAAW;AACX,SAAO,SAAS;GAChB;CAEF,MAAM,WAAW,OAAO,UAAkB;AACxC,QAAM,OAAO,SAAS,MAAM;;CAG9B,MAAM,aAAa;AACjB,SAAO,MAAM;;CAGf,MAAM,cAAc;AAClB,SAAO,OAAO;;AAGhB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|