@tanstack/ai-client 0.5.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/generation-client.d.ts +85 -0
- package/dist/esm/generation-client.js +190 -0
- package/dist/esm/generation-client.js.map +1 -0
- package/dist/esm/generation-types.d.ts +209 -0
- package/dist/esm/generation-types.js +14 -0
- package/dist/esm/generation-types.js.map +1 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/sse-parser.d.ts +8 -0
- package/dist/esm/sse-parser.js +51 -0
- package/dist/esm/sse-parser.js.map +1 -0
- package/dist/esm/video-generation-client.d.ts +95 -0
- package/dist/esm/video-generation-client.js +238 -0
- package/dist/esm/video-generation-client.js.map +1 -0
- package/package.json +2 -2
- package/src/generation-client.ts +302 -0
- package/src/generation-types.ts +270 -0
- package/src/index.ts +20 -0
- package/src/sse-parser.ts +76 -0
- package/src/video-generation-client.ts +371 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { ConnectionAdapter } from './connection-adapters.js';
|
|
2
|
+
import { GenerationClientOptions, GenerationClientState, GenerationFetcher } from './generation-types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A lightweight, generic client for one-shot generation tasks
|
|
5
|
+
* (image, speech, transcription, summarize).
|
|
6
|
+
*
|
|
7
|
+
* Supports two transport modes:
|
|
8
|
+
* - **ConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom).
|
|
9
|
+
* Server wraps results in StreamChunk events with CUSTOM event names.
|
|
10
|
+
* - **Fetcher** — Direct async function call. No streaming protocol needed.
|
|
11
|
+
*
|
|
12
|
+
* @template TInput - The input type for the generation request
|
|
13
|
+
* @template TResult - The result type returned by the generation
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* // With ConnectionAdapter (streaming)
|
|
18
|
+
* const client = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({
|
|
19
|
+
* connection: fetchServerSentEvents('/api/generate/image'),
|
|
20
|
+
* onResultChange: setResult,
|
|
21
|
+
* onLoadingChange: setIsLoading,
|
|
22
|
+
* })
|
|
23
|
+
*
|
|
24
|
+
* // With fetcher (direct)
|
|
25
|
+
* const client = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({
|
|
26
|
+
* fetcher: async (input) => {
|
|
27
|
+
* const res = await fetch('/api/generate/image', {
|
|
28
|
+
* method: 'POST',
|
|
29
|
+
* body: JSON.stringify(input),
|
|
30
|
+
* })
|
|
31
|
+
* return res.json()
|
|
32
|
+
* },
|
|
33
|
+
* })
|
|
34
|
+
*
|
|
35
|
+
* await client.generate({ prompt: 'A sunset over mountains' })
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare class GenerationClient<TInput extends Record<string, any>, TResult, TOutput = TResult> {
|
|
39
|
+
private connection;
|
|
40
|
+
private fetcher;
|
|
41
|
+
private body;
|
|
42
|
+
private result;
|
|
43
|
+
private isLoading;
|
|
44
|
+
private error;
|
|
45
|
+
private status;
|
|
46
|
+
private abortController;
|
|
47
|
+
private callbacksRef;
|
|
48
|
+
constructor(options: GenerationClientOptions<TInput, TResult, TOutput> & ({
|
|
49
|
+
connection: ConnectionAdapter;
|
|
50
|
+
fetcher?: never;
|
|
51
|
+
} | {
|
|
52
|
+
fetcher: GenerationFetcher<TInput, TResult>;
|
|
53
|
+
connection?: never;
|
|
54
|
+
}));
|
|
55
|
+
/**
|
|
56
|
+
* Trigger a generation request.
|
|
57
|
+
* Only one generation can be in-flight at a time; calling generate()
|
|
58
|
+
* while already generating will be a no-op.
|
|
59
|
+
*/
|
|
60
|
+
generate(input: TInput): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Process a stream of AG-UI events from the ConnectionAdapter.
|
|
63
|
+
*/
|
|
64
|
+
private processStream;
|
|
65
|
+
/**
|
|
66
|
+
* Abort any in-flight generation request.
|
|
67
|
+
*/
|
|
68
|
+
stop(): void;
|
|
69
|
+
/**
|
|
70
|
+
* Clear the result, error, and return to idle state.
|
|
71
|
+
*/
|
|
72
|
+
reset(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Update options without recreating the client.
|
|
75
|
+
*/
|
|
76
|
+
updateOptions(options: Partial<Pick<GenerationClientOptions<TInput, TResult, TOutput>, 'body' | 'onResult' | 'onError' | 'onProgress' | 'onChunk'>>): void;
|
|
77
|
+
getResult(): TOutput | null;
|
|
78
|
+
getIsLoading(): boolean;
|
|
79
|
+
getError(): Error | undefined;
|
|
80
|
+
getStatus(): GenerationClientState;
|
|
81
|
+
private setResult;
|
|
82
|
+
private setIsLoading;
|
|
83
|
+
private setError;
|
|
84
|
+
private setStatus;
|
|
85
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { GENERATION_EVENTS } from "./generation-types.js";
|
|
2
|
+
import { parseSSEResponse } from "./sse-parser.js";
|
|
3
|
+
class GenerationClient {
|
|
4
|
+
constructor(options) {
|
|
5
|
+
this.result = null;
|
|
6
|
+
this.isLoading = false;
|
|
7
|
+
this.error = void 0;
|
|
8
|
+
this.status = "idle";
|
|
9
|
+
this.abortController = null;
|
|
10
|
+
this.connection = options.connection;
|
|
11
|
+
this.fetcher = options.fetcher;
|
|
12
|
+
this.body = options.body ?? {};
|
|
13
|
+
this.callbacksRef = {
|
|
14
|
+
onResult: options.onResult,
|
|
15
|
+
onError: options.onError,
|
|
16
|
+
onProgress: options.onProgress,
|
|
17
|
+
onChunk: options.onChunk,
|
|
18
|
+
onResultChange: options.onResultChange,
|
|
19
|
+
onLoadingChange: options.onLoadingChange,
|
|
20
|
+
onErrorChange: options.onErrorChange,
|
|
21
|
+
onStatusChange: options.onStatusChange
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Trigger a generation request.
|
|
26
|
+
* Only one generation can be in-flight at a time; calling generate()
|
|
27
|
+
* while already generating will be a no-op.
|
|
28
|
+
*/
|
|
29
|
+
async generate(input) {
|
|
30
|
+
if (this.isLoading) return;
|
|
31
|
+
this.setIsLoading(true);
|
|
32
|
+
this.setStatus("generating");
|
|
33
|
+
this.setError(void 0);
|
|
34
|
+
const abortController = new AbortController();
|
|
35
|
+
this.abortController = abortController;
|
|
36
|
+
const { signal } = abortController;
|
|
37
|
+
try {
|
|
38
|
+
if (this.fetcher) {
|
|
39
|
+
const result = await this.fetcher(input, { signal });
|
|
40
|
+
if (signal.aborted) return;
|
|
41
|
+
if (result instanceof Response) {
|
|
42
|
+
await this.processStream(parseSSEResponse(result, signal));
|
|
43
|
+
} else {
|
|
44
|
+
this.setResult(result);
|
|
45
|
+
this.setStatus("success");
|
|
46
|
+
}
|
|
47
|
+
} else if (this.connection) {
|
|
48
|
+
const mergedData = { ...this.body, ...input };
|
|
49
|
+
const stream = this.connection.connect([], mergedData, signal);
|
|
50
|
+
await this.processStream(stream);
|
|
51
|
+
} else {
|
|
52
|
+
throw new Error(
|
|
53
|
+
"GenerationClient requires either a connection or fetcher option"
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
} catch (err) {
|
|
57
|
+
if (signal.aborted) return;
|
|
58
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
59
|
+
this.setError(error);
|
|
60
|
+
this.setStatus("error");
|
|
61
|
+
this.callbacksRef.onError?.(error);
|
|
62
|
+
} finally {
|
|
63
|
+
this.abortController = null;
|
|
64
|
+
this.setIsLoading(false);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Process a stream of AG-UI events from the ConnectionAdapter.
|
|
69
|
+
*/
|
|
70
|
+
async processStream(source) {
|
|
71
|
+
for await (const chunk of source) {
|
|
72
|
+
if (this.abortController?.signal.aborted) break;
|
|
73
|
+
this.callbacksRef.onChunk?.(chunk);
|
|
74
|
+
switch (chunk.type) {
|
|
75
|
+
case "CUSTOM": {
|
|
76
|
+
if (chunk.name === GENERATION_EVENTS.RESULT) {
|
|
77
|
+
this.setResult(chunk.value);
|
|
78
|
+
} else if (chunk.name === GENERATION_EVENTS.PROGRESS) {
|
|
79
|
+
const { progress, message } = chunk.value;
|
|
80
|
+
this.callbacksRef.onProgress?.(progress, message);
|
|
81
|
+
}
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
case "RUN_FINISHED": {
|
|
85
|
+
this.setStatus("success");
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
case "RUN_ERROR": {
|
|
89
|
+
throw new Error(chunk.error.message);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Abort any in-flight generation request.
|
|
96
|
+
*/
|
|
97
|
+
stop() {
|
|
98
|
+
if (this.abortController) {
|
|
99
|
+
this.abortController.abort();
|
|
100
|
+
this.abortController = null;
|
|
101
|
+
}
|
|
102
|
+
this.setIsLoading(false);
|
|
103
|
+
if (this.status === "generating") {
|
|
104
|
+
this.setStatus("idle");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Clear the result, error, and return to idle state.
|
|
109
|
+
*/
|
|
110
|
+
reset() {
|
|
111
|
+
this.stop();
|
|
112
|
+
this.setResult(null);
|
|
113
|
+
this.setError(void 0);
|
|
114
|
+
this.setStatus("idle");
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Update options without recreating the client.
|
|
118
|
+
*/
|
|
119
|
+
updateOptions(options) {
|
|
120
|
+
if (options.body !== void 0) {
|
|
121
|
+
this.body = options.body ?? {};
|
|
122
|
+
}
|
|
123
|
+
if (options.onResult !== void 0) {
|
|
124
|
+
this.callbacksRef.onResult = options.onResult;
|
|
125
|
+
}
|
|
126
|
+
if (options.onError !== void 0) {
|
|
127
|
+
this.callbacksRef.onError = options.onError;
|
|
128
|
+
}
|
|
129
|
+
if (options.onProgress !== void 0) {
|
|
130
|
+
this.callbacksRef.onProgress = options.onProgress;
|
|
131
|
+
}
|
|
132
|
+
if (options.onChunk !== void 0) {
|
|
133
|
+
this.callbacksRef.onChunk = options.onChunk;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// ===========================
|
|
137
|
+
// Getters
|
|
138
|
+
// ===========================
|
|
139
|
+
getResult() {
|
|
140
|
+
return this.result;
|
|
141
|
+
}
|
|
142
|
+
getIsLoading() {
|
|
143
|
+
return this.isLoading;
|
|
144
|
+
}
|
|
145
|
+
getError() {
|
|
146
|
+
return this.error;
|
|
147
|
+
}
|
|
148
|
+
getStatus() {
|
|
149
|
+
return this.status;
|
|
150
|
+
}
|
|
151
|
+
// ===========================
|
|
152
|
+
// Private state setters
|
|
153
|
+
// ===========================
|
|
154
|
+
setResult(rawResult) {
|
|
155
|
+
if (rawResult === null) {
|
|
156
|
+
this.result = null;
|
|
157
|
+
this.callbacksRef.onResultChange?.(null);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (this.callbacksRef.onResult) {
|
|
161
|
+
const transformed = this.callbacksRef.onResult(rawResult);
|
|
162
|
+
if (transformed === null) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (transformed !== void 0) {
|
|
166
|
+
this.result = transformed;
|
|
167
|
+
this.callbacksRef.onResultChange?.(this.result);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
this.result = rawResult;
|
|
172
|
+
this.callbacksRef.onResultChange?.(this.result);
|
|
173
|
+
}
|
|
174
|
+
setIsLoading(isLoading) {
|
|
175
|
+
this.isLoading = isLoading;
|
|
176
|
+
this.callbacksRef.onLoadingChange?.(isLoading);
|
|
177
|
+
}
|
|
178
|
+
setError(error) {
|
|
179
|
+
this.error = error;
|
|
180
|
+
this.callbacksRef.onErrorChange?.(error);
|
|
181
|
+
}
|
|
182
|
+
setStatus(status) {
|
|
183
|
+
this.status = status;
|
|
184
|
+
this.callbacksRef.onStatusChange?.(status);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export {
|
|
188
|
+
GenerationClient
|
|
189
|
+
};
|
|
190
|
+
//# sourceMappingURL=generation-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generation-client.js","sources":["../../src/generation-client.ts"],"sourcesContent":["import { GENERATION_EVENTS } from './generation-types'\nimport { parseSSEResponse } from './sse-parser'\nimport type { StreamChunk } from '@tanstack/ai'\nimport type { ConnectionAdapter } from './connection-adapters'\nimport type {\n GenerationClientOptions,\n GenerationClientState,\n GenerationFetcher,\n} from './generation-types'\n\n/**\n * Callbacks stored in a ref so hooks can update them without recreating the client.\n */\ninterface GenerationCallbacks<TResult, TOutput> {\n onResult?: (result: TResult) => TOutput | null | void\n onError?: (error: Error) => void\n onProgress?: (progress: number, message?: string) => void\n onChunk?: (chunk: StreamChunk) => void\n onResultChange?: (result: TOutput | null) => void\n onLoadingChange?: (isLoading: boolean) => void\n onErrorChange?: (error: Error | undefined) => void\n onStatusChange?: (status: GenerationClientState) => void\n}\n\n/**\n * A lightweight, generic client for one-shot generation tasks\n * (image, speech, transcription, summarize).\n *\n * Supports two transport modes:\n * - **ConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom).\n * Server wraps results in StreamChunk events with CUSTOM event names.\n * - **Fetcher** — Direct async function call. No streaming protocol needed.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n *\n * @example\n * ```typescript\n * // With ConnectionAdapter (streaming)\n * const client = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({\n * connection: fetchServerSentEvents('/api/generate/image'),\n * onResultChange: setResult,\n * onLoadingChange: setIsLoading,\n * })\n *\n * // With fetcher (direct)\n * const client = new GenerationClient<ImageGenerateInput, ImageGenerationResult>({\n * fetcher: async (input) => {\n * const res = await fetch('/api/generate/image', {\n * method: 'POST',\n * body: JSON.stringify(input),\n * })\n * return res.json()\n * },\n * })\n *\n * await client.generate({ prompt: 'A sunset over mountains' })\n * ```\n */\nexport class GenerationClient<\n TInput extends Record<string, any>,\n TResult,\n TOutput = TResult,\n> {\n private connection: ConnectionAdapter | undefined\n private fetcher: GenerationFetcher<TInput, TResult> | undefined\n private body: Record<string, any>\n private result: TOutput | null = null\n private isLoading = false\n private error: Error | undefined = undefined\n private status: GenerationClientState = 'idle'\n private abortController: AbortController | null = null\n private callbacksRef: GenerationCallbacks<TResult, TOutput>\n\n constructor(\n options: GenerationClientOptions<TInput, TResult, TOutput> &\n (\n | { connection: ConnectionAdapter; fetcher?: never }\n | {\n fetcher: GenerationFetcher<TInput, TResult>\n connection?: never\n }\n ),\n ) {\n this.connection = options.connection\n this.fetcher = options.fetcher\n this.body = options.body ?? {}\n\n this.callbacksRef = {\n onResult: options.onResult,\n onError: options.onError,\n onProgress: options.onProgress,\n onChunk: options.onChunk,\n onResultChange: options.onResultChange,\n onLoadingChange: options.onLoadingChange,\n onErrorChange: options.onErrorChange,\n onStatusChange: options.onStatusChange,\n }\n }\n\n /**\n * Trigger a generation request.\n * Only one generation can be in-flight at a time; calling generate()\n * while already generating will be a no-op.\n */\n async generate(input: TInput): Promise<void> {\n if (this.isLoading) return\n\n this.setIsLoading(true)\n this.setStatus('generating')\n this.setError(undefined)\n\n const abortController = new AbortController()\n this.abortController = abortController\n const { signal } = abortController\n\n try {\n if (this.fetcher) {\n // Direct fetch path\n const result = await this.fetcher(input, { signal })\n if (signal.aborted) return\n if (result instanceof Response) {\n // Server function returned SSE Response — parse stream\n await this.processStream(parseSSEResponse(result, signal))\n } else {\n this.setResult(result)\n this.setStatus('success')\n }\n } else if (this.connection) {\n // ConnectionAdapter streaming path\n const mergedData = { ...this.body, ...input }\n const stream = this.connection.connect([], mergedData, signal)\n await this.processStream(stream)\n } else {\n throw new Error(\n 'GenerationClient requires either a connection or fetcher option',\n )\n }\n } catch (err: any) {\n if (signal.aborted) return\n const error = err instanceof Error ? err : new Error(String(err))\n this.setError(error)\n this.setStatus('error')\n this.callbacksRef.onError?.(error)\n } finally {\n this.abortController = null\n this.setIsLoading(false)\n }\n }\n\n /**\n * Process a stream of AG-UI events from the ConnectionAdapter.\n */\n private async processStream(\n source: AsyncIterable<StreamChunk>,\n ): Promise<void> {\n for await (const chunk of source) {\n if (this.abortController?.signal.aborted) break\n\n this.callbacksRef.onChunk?.(chunk)\n\n switch (chunk.type) {\n case 'CUSTOM': {\n if (chunk.name === GENERATION_EVENTS.RESULT) {\n this.setResult(chunk.value as TResult)\n } else if (chunk.name === GENERATION_EVENTS.PROGRESS) {\n const { progress, message } = chunk.value as {\n progress: number\n message?: string\n }\n this.callbacksRef.onProgress?.(progress, message)\n }\n break\n }\n case 'RUN_FINISHED': {\n this.setStatus('success')\n break\n }\n case 'RUN_ERROR': {\n throw new Error(chunk.error.message)\n }\n }\n }\n }\n\n /**\n * Abort any in-flight generation request.\n */\n stop(): void {\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.setIsLoading(false)\n if (this.status === 'generating') {\n this.setStatus('idle')\n }\n }\n\n /**\n * Clear the result, error, and return to idle state.\n */\n reset(): void {\n this.stop()\n this.setResult(null)\n this.setError(undefined)\n this.setStatus('idle')\n }\n\n /**\n * Update options without recreating the client.\n */\n updateOptions(\n options: Partial<\n Pick<\n GenerationClientOptions<TInput, TResult, TOutput>,\n 'body' | 'onResult' | 'onError' | 'onProgress' | 'onChunk'\n >\n >,\n ): void {\n if (options.body !== undefined) {\n this.body = options.body ?? {}\n }\n if (options.onResult !== undefined) {\n this.callbacksRef.onResult = options.onResult\n }\n if (options.onError !== undefined) {\n this.callbacksRef.onError = options.onError\n }\n if (options.onProgress !== undefined) {\n this.callbacksRef.onProgress = options.onProgress\n }\n if (options.onChunk !== undefined) {\n this.callbacksRef.onChunk = options.onChunk\n }\n }\n\n // ===========================\n // Getters\n // ===========================\n\n getResult(): TOutput | null {\n return this.result\n }\n\n getIsLoading(): boolean {\n return this.isLoading\n }\n\n getError(): Error | undefined {\n return this.error\n }\n\n getStatus(): GenerationClientState {\n return this.status\n }\n\n // ===========================\n // Private state setters\n // ===========================\n\n private setResult(rawResult: TResult | null): void {\n if (rawResult === null) {\n this.result = null\n this.callbacksRef.onResultChange?.(null)\n return\n }\n\n if (this.callbacksRef.onResult) {\n const transformed = this.callbacksRef.onResult(rawResult)\n if (transformed === null) {\n // null return → keep previous result unchanged\n return\n }\n if (transformed !== undefined) {\n // Non-null, non-undefined → use transformed value\n this.result = transformed\n this.callbacksRef.onResultChange?.(this.result)\n return\n }\n }\n\n // No onResult callback, or callback returned void → use raw value\n this.result = rawResult as unknown as TOutput\n this.callbacksRef.onResultChange?.(this.result)\n }\n\n private setIsLoading(isLoading: boolean): void {\n this.isLoading = isLoading\n this.callbacksRef.onLoadingChange?.(isLoading)\n }\n\n private setError(error: Error | undefined): void {\n this.error = error\n this.callbacksRef.onErrorChange?.(error)\n }\n\n private setStatus(status: GenerationClientState): void {\n this.status = status\n this.callbacksRef.onStatusChange?.(status)\n }\n}\n"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { StreamChunk } from '@tanstack/ai';
|
|
2
|
+
import { ConnectionAdapter } from './connection-adapters.js';
|
|
3
|
+
/**
|
|
4
|
+
* Infers the output type from an `onResult` callback's return type.
|
|
5
|
+
*
|
|
6
|
+
* - If the callback returns a concrete type (excluding null/void/undefined), uses that type.
|
|
7
|
+
* - If the callback only returns null/void/undefined, or is not provided, falls back to TResult.
|
|
8
|
+
*
|
|
9
|
+
* @template TResult - The raw result type from the generation
|
|
10
|
+
* @template TFn - The onResult callback type (or undefined if not provided)
|
|
11
|
+
*/
|
|
12
|
+
export type InferGenerationOutput<TResult, TFn> = TFn extends (result: any) => infer R ? [Exclude<R, null | void | undefined>] extends [never] ? TResult : Exclude<R, null | void | undefined> : TResult;
|
|
13
|
+
/**
|
|
14
|
+
* State machine for generation clients.
|
|
15
|
+
* Simpler than ChatClientState since generation is a single request/response cycle.
|
|
16
|
+
*/
|
|
17
|
+
export type GenerationClientState = 'idle' | 'generating' | 'success' | 'error';
|
|
18
|
+
/**
|
|
19
|
+
* Well-known CUSTOM event names used by generation clients.
|
|
20
|
+
* These events are emitted by the server-side streaming helpers
|
|
21
|
+
* and consumed by the client-side GenerationClient.
|
|
22
|
+
*/
|
|
23
|
+
export declare const GENERATION_EVENTS: {
|
|
24
|
+
/** The generation result payload */
|
|
25
|
+
readonly RESULT: "generation:result";
|
|
26
|
+
/** Progress update (0-100) with optional message */
|
|
27
|
+
readonly PROGRESS: "generation:progress";
|
|
28
|
+
/** Video job created with jobId */
|
|
29
|
+
readonly VIDEO_JOB_CREATED: "video:job:created";
|
|
30
|
+
/** Video job status update */
|
|
31
|
+
readonly VIDEO_STATUS: "video:status";
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Options passed to a fetcher function by the generation client.
|
|
35
|
+
*/
|
|
36
|
+
export interface GenerationFetcherOptions {
|
|
37
|
+
/** AbortSignal that is triggered when the user calls `stop()` */
|
|
38
|
+
signal: AbortSignal;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A direct async function that performs a generation request.
|
|
42
|
+
*
|
|
43
|
+
* Can return the result directly, or return a `Response` with an SSE body
|
|
44
|
+
* (e.g., from a TanStack Start server function using `toServerSentEventsResponse()`).
|
|
45
|
+
* When a `Response` is returned, the client will parse it as an SSE stream.
|
|
46
|
+
*
|
|
47
|
+
* @template TInput - The input type for the generation request
|
|
48
|
+
* @template TResult - The result type returned by the generation
|
|
49
|
+
*/
|
|
50
|
+
export type GenerationFetcher<TInput, TResult> = (input: TInput, options?: GenerationFetcherOptions) => Promise<TResult | Response>;
|
|
51
|
+
/**
|
|
52
|
+
* Transport configuration for generation clients.
|
|
53
|
+
* Supports either a ConnectionAdapter (streaming) or a direct fetcher function.
|
|
54
|
+
*/
|
|
55
|
+
export type GenerationTransport<TInput, TResult> = {
|
|
56
|
+
connection: ConnectionAdapter;
|
|
57
|
+
fetcher?: never;
|
|
58
|
+
} | {
|
|
59
|
+
fetcher: GenerationFetcher<TInput, TResult>;
|
|
60
|
+
connection?: never;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Options for the GenerationClient.
|
|
64
|
+
*
|
|
65
|
+
* @template TInput - The input type for the generation request (used by consuming code)
|
|
66
|
+
* @template TResult - The result type returned by the generation
|
|
67
|
+
* @template TOutput - The output type after optional transform (defaults to TResult)
|
|
68
|
+
*/
|
|
69
|
+
export interface GenerationClientOptions<_TInput, TResult, TOutput = TResult> {
|
|
70
|
+
/** Unique identifier for this generation client instance */
|
|
71
|
+
id?: string;
|
|
72
|
+
/** Additional body parameters to send with ConnectionAdapter requests */
|
|
73
|
+
body?: Record<string, any>;
|
|
74
|
+
/**
|
|
75
|
+
* Callback when a result is received. Can optionally return a transformed value
|
|
76
|
+
* that replaces the stored result.
|
|
77
|
+
*
|
|
78
|
+
* - Return a non-null value to transform and store it as the result
|
|
79
|
+
* - Return `null` to keep the previous result unchanged
|
|
80
|
+
* - Return nothing (`void`) to store the raw result as-is
|
|
81
|
+
*/
|
|
82
|
+
onResult?: (result: TResult) => TOutput | null | void;
|
|
83
|
+
/** Callback when an error occurs */
|
|
84
|
+
onError?: (error: Error) => void;
|
|
85
|
+
/** Callback when progress is reported (0-100) */
|
|
86
|
+
onProgress?: (progress: number, message?: string) => void;
|
|
87
|
+
/** Callback for each stream chunk (ConnectionAdapter mode only) */
|
|
88
|
+
onChunk?: (chunk: StreamChunk) => void;
|
|
89
|
+
/** @internal Called when result changes */
|
|
90
|
+
onResultChange?: (result: TOutput | null) => void;
|
|
91
|
+
/** @internal Called when loading state changes */
|
|
92
|
+
onLoadingChange?: (isLoading: boolean) => void;
|
|
93
|
+
/** @internal Called when error state changes */
|
|
94
|
+
onErrorChange?: (error: Error | undefined) => void;
|
|
95
|
+
/** @internal Called when generation status changes */
|
|
96
|
+
onStatusChange?: (status: GenerationClientState) => void;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Video status information returned during job polling.
|
|
100
|
+
*/
|
|
101
|
+
export interface VideoStatusInfo {
|
|
102
|
+
/** Job identifier */
|
|
103
|
+
jobId: string;
|
|
104
|
+
/** Current status of the video generation job */
|
|
105
|
+
status: 'pending' | 'processing' | 'completed' | 'failed';
|
|
106
|
+
/** Progress percentage (0-100), if available */
|
|
107
|
+
progress?: number;
|
|
108
|
+
/** URL to the generated video (when completed) */
|
|
109
|
+
url?: string;
|
|
110
|
+
/** Error message if status is 'failed' */
|
|
111
|
+
error?: string;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Composite result for video generation (job completion).
|
|
115
|
+
*/
|
|
116
|
+
export interface VideoGenerateResult {
|
|
117
|
+
/** Job identifier */
|
|
118
|
+
jobId: string;
|
|
119
|
+
/** Final status */
|
|
120
|
+
status: 'completed';
|
|
121
|
+
/** URL to the generated video */
|
|
122
|
+
url: string;
|
|
123
|
+
/** When the URL expires, if applicable */
|
|
124
|
+
expiresAt?: Date;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Options for the VideoGenerationClient.
|
|
128
|
+
*/
|
|
129
|
+
export interface VideoGenerationClientOptions<TOutput = VideoGenerateResult> extends GenerationClientOptions<VideoGenerateInput, VideoGenerateResult, TOutput> {
|
|
130
|
+
/** Callback when a video job is created */
|
|
131
|
+
onJobCreated?: (jobId: string) => void;
|
|
132
|
+
/** Callback on each status update */
|
|
133
|
+
onStatusUpdate?: (status: VideoStatusInfo) => void;
|
|
134
|
+
/** @internal Called when jobId changes */
|
|
135
|
+
onJobIdChange?: (jobId: string | null) => void;
|
|
136
|
+
/** @internal Called when video status changes */
|
|
137
|
+
onVideoStatusChange?: (status: VideoStatusInfo | null) => void;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Input for image generation.
|
|
141
|
+
*/
|
|
142
|
+
export interface ImageGenerateInput {
|
|
143
|
+
/** Text description of the desired image(s) */
|
|
144
|
+
prompt: string;
|
|
145
|
+
/** Number of images to generate (default: 1) */
|
|
146
|
+
numberOfImages?: number;
|
|
147
|
+
/** Image size in WIDTHxHEIGHT format (e.g., "1024x1024") */
|
|
148
|
+
size?: string;
|
|
149
|
+
/** Model-specific options */
|
|
150
|
+
modelOptions?: Record<string, any>;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Input for text-to-speech generation.
|
|
154
|
+
*/
|
|
155
|
+
export interface SpeechGenerateInput {
|
|
156
|
+
/** The text to convert to speech */
|
|
157
|
+
text: string;
|
|
158
|
+
/** The voice to use for generation */
|
|
159
|
+
voice?: string;
|
|
160
|
+
/** The output audio format */
|
|
161
|
+
format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm';
|
|
162
|
+
/** The speed of the generated audio (0.25 to 4.0) */
|
|
163
|
+
speed?: number;
|
|
164
|
+
/** Model-specific options */
|
|
165
|
+
modelOptions?: Record<string, any>;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Input for audio transcription.
|
|
169
|
+
*/
|
|
170
|
+
export interface TranscriptionGenerateInput {
|
|
171
|
+
/** The audio data to transcribe - can be base64 string, File, or Blob */
|
|
172
|
+
audio: string | File | Blob;
|
|
173
|
+
/** The language of the audio in ISO-639-1 format (e.g., 'en') */
|
|
174
|
+
language?: string;
|
|
175
|
+
/** An optional prompt to guide the transcription */
|
|
176
|
+
prompt?: string;
|
|
177
|
+
/** The format of the transcription output */
|
|
178
|
+
responseFormat?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt';
|
|
179
|
+
/** Model-specific options */
|
|
180
|
+
modelOptions?: Record<string, any>;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Input for text summarization.
|
|
184
|
+
*/
|
|
185
|
+
export interface SummarizeGenerateInput {
|
|
186
|
+
/** The text to summarize */
|
|
187
|
+
text: string;
|
|
188
|
+
/** Maximum length of the summary */
|
|
189
|
+
maxLength?: number;
|
|
190
|
+
/** Style of the summary */
|
|
191
|
+
style?: 'bullet-points' | 'paragraph' | 'concise';
|
|
192
|
+
/** Topics to focus on */
|
|
193
|
+
focus?: Array<string>;
|
|
194
|
+
/** Model-specific options */
|
|
195
|
+
modelOptions?: Record<string, any>;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Input for video generation.
|
|
199
|
+
*/
|
|
200
|
+
export interface VideoGenerateInput {
|
|
201
|
+
/** Text description of the desired video */
|
|
202
|
+
prompt: string;
|
|
203
|
+
/** Video size — format depends on provider (e.g., "16:9", "1280x720") */
|
|
204
|
+
size?: string;
|
|
205
|
+
/** Video duration in seconds */
|
|
206
|
+
duration?: number;
|
|
207
|
+
/** Model-specific options */
|
|
208
|
+
modelOptions?: Record<string, any>;
|
|
209
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const GENERATION_EVENTS = {
|
|
2
|
+
/** The generation result payload */
|
|
3
|
+
RESULT: "generation:result",
|
|
4
|
+
/** Progress update (0-100) with optional message */
|
|
5
|
+
PROGRESS: "generation:progress",
|
|
6
|
+
/** Video job created with jobId */
|
|
7
|
+
VIDEO_JOB_CREATED: "video:job:created",
|
|
8
|
+
/** Video job status update */
|
|
9
|
+
VIDEO_STATUS: "video:status"
|
|
10
|
+
};
|
|
11
|
+
export {
|
|
12
|
+
GENERATION_EVENTS
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=generation-types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generation-types.js","sources":["../../src/generation-types.ts"],"sourcesContent":["import type { StreamChunk } from '@tanstack/ai'\nimport type { ConnectionAdapter } from './connection-adapters'\n\n// ===========================\n// Inference Utilities\n// ===========================\n\n/**\n * Infers the output type from an `onResult` callback's return type.\n *\n * - If the callback returns a concrete type (excluding null/void/undefined), uses that type.\n * - If the callback only returns null/void/undefined, or is not provided, falls back to TResult.\n *\n * @template TResult - The raw result type from the generation\n * @template TFn - The onResult callback type (or undefined if not provided)\n */\nexport type InferGenerationOutput<TResult, TFn> = TFn extends (\n result: any,\n) => infer R\n ? [Exclude<R, null | void | undefined>] extends [never]\n ? TResult\n : Exclude<R, null | void | undefined>\n : TResult\n\n// ===========================\n// State\n// ===========================\n\n/**\n * State machine for generation clients.\n * Simpler than ChatClientState since generation is a single request/response cycle.\n */\nexport type GenerationClientState = 'idle' | 'generating' | 'success' | 'error'\n\n// ===========================\n// Event Constants\n// ===========================\n\n/**\n * Well-known CUSTOM event names used by generation clients.\n * These events are emitted by the server-side streaming helpers\n * and consumed by the client-side GenerationClient.\n */\nexport const GENERATION_EVENTS = {\n /** The generation result payload */\n RESULT: 'generation:result',\n /** Progress update (0-100) with optional message */\n PROGRESS: 'generation:progress',\n /** Video job created with jobId */\n VIDEO_JOB_CREATED: 'video:job:created',\n /** Video job status update */\n VIDEO_STATUS: 'video:status',\n} as const\n\n// ===========================\n// Transport Types\n// ===========================\n\n/**\n * Options passed to a fetcher function by the generation client.\n */\nexport interface GenerationFetcherOptions {\n /** AbortSignal that is triggered when the user calls `stop()` */\n signal: AbortSignal\n}\n\n/**\n * A direct async function that performs a generation request.\n *\n * Can return the result directly, or return a `Response` with an SSE body\n * (e.g., from a TanStack Start server function using `toServerSentEventsResponse()`).\n * When a `Response` is returned, the client will parse it as an SSE stream.\n *\n * @template TInput - The input type for the generation request\n * @template TResult - The result type returned by the generation\n */\nexport type GenerationFetcher<TInput, TResult> = (\n input: TInput,\n options?: GenerationFetcherOptions,\n) => Promise<TResult | Response>\n\n/**\n * Transport configuration for generation clients.\n * Supports either a ConnectionAdapter (streaming) or a direct fetcher function.\n */\nexport type GenerationTransport<TInput, TResult> =\n | { connection: ConnectionAdapter; fetcher?: never }\n | { fetcher: GenerationFetcher<TInput, TResult>; connection?: never }\n\n// ===========================\n// Client Options\n// ===========================\n\n/**\n * Options for the GenerationClient.\n *\n * @template TInput - The input type for the generation request (used by consuming code)\n * @template TResult - The result type returned by the generation\n * @template TOutput - The output type after optional transform (defaults to TResult)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface GenerationClientOptions<_TInput, TResult, TOutput = TResult> {\n /** Unique identifier for this generation client instance */\n id?: string\n\n /** Additional body parameters to send with ConnectionAdapter requests */\n body?: Record<string, any>\n\n /**\n * Callback when a result is received. Can optionally return a transformed value\n * that replaces the stored result.\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 (ConnectionAdapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n\n // Framework state callbacks (set by hooks, not users)\n /** @internal Called when result changes */\n onResultChange?: (result: TOutput | null) => void\n /** @internal Called when loading state changes */\n onLoadingChange?: (isLoading: boolean) => void\n /** @internal Called when error state changes */\n onErrorChange?: (error: Error | undefined) => void\n /** @internal Called when generation status changes */\n onStatusChange?: (status: GenerationClientState) => void\n}\n\n// ===========================\n// Video-Specific Options\n// ===========================\n\n/**\n * Video status information returned during job polling.\n */\nexport interface VideoStatusInfo {\n /** Job identifier */\n jobId: string\n /** Current status of the video generation job */\n status: 'pending' | 'processing' | 'completed' | 'failed'\n /** Progress percentage (0-100), if available */\n progress?: number\n /** URL to the generated video (when completed) */\n url?: string\n /** Error message if status is 'failed' */\n error?: string\n}\n\n/**\n * Composite result for video generation (job completion).\n */\nexport interface VideoGenerateResult {\n /** Job identifier */\n jobId: string\n /** Final status */\n status: 'completed'\n /** URL to the generated video */\n url: string\n /** When the URL expires, if applicable */\n expiresAt?: Date\n}\n\n/**\n * Options for the VideoGenerationClient.\n */\nexport interface VideoGenerationClientOptions<\n TOutput = VideoGenerateResult,\n> extends GenerationClientOptions<\n VideoGenerateInput,\n VideoGenerateResult,\n TOutput\n> {\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\n // Framework state callbacks\n /** @internal Called when jobId changes */\n onJobIdChange?: (jobId: string | null) => void\n /** @internal Called when video status changes */\n onVideoStatusChange?: (status: VideoStatusInfo | null) => void\n}\n\n// ===========================\n// Input Types\n// ===========================\n\n/**\n * Input for image generation.\n */\nexport interface ImageGenerateInput {\n /** Text description of the desired image(s) */\n prompt: string\n /** Number of images to generate (default: 1) */\n numberOfImages?: number\n /** Image size in WIDTHxHEIGHT format (e.g., \"1024x1024\") */\n size?: string\n /** Model-specific options */\n modelOptions?: Record<string, any>\n}\n\n/**\n * Input for text-to-speech generation.\n */\nexport interface SpeechGenerateInput {\n /** The text to convert to speech */\n text: string\n /** The voice to use for generation */\n voice?: string\n /** The output audio format */\n format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'\n /** The speed of the generated audio (0.25 to 4.0) */\n speed?: number\n /** Model-specific options */\n modelOptions?: Record<string, any>\n}\n\n/**\n * Input for audio transcription.\n */\nexport interface TranscriptionGenerateInput {\n /** The audio data to transcribe - can be base64 string, File, or Blob */\n audio: string | File | Blob\n /** The language of the audio in ISO-639-1 format (e.g., 'en') */\n language?: string\n /** An optional prompt to guide the transcription */\n prompt?: string\n /** The format of the transcription output */\n responseFormat?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'\n /** Model-specific options */\n modelOptions?: Record<string, any>\n}\n\n/**\n * Input for text summarization.\n */\nexport interface SummarizeGenerateInput {\n /** The text to summarize */\n text: string\n /** Maximum length of the summary */\n maxLength?: number\n /** Style of the summary */\n style?: 'bullet-points' | 'paragraph' | 'concise'\n /** Topics to focus on */\n focus?: Array<string>\n /** Model-specific options */\n modelOptions?: Record<string, any>\n}\n\n/**\n * Input for video generation.\n */\nexport interface VideoGenerateInput {\n /** Text description of the desired video */\n prompt: string\n /** Video size — format depends on provider (e.g., \"16:9\", \"1280x720\") */\n size?: string\n /** Video duration in seconds */\n duration?: number\n /** Model-specific options */\n modelOptions?: Record<string, any>\n}\n"],"names":[],"mappings":"AA2CO,MAAM,oBAAoB;AAAA;AAAA,EAE/B,QAAQ;AAAA;AAAA,EAER,UAAU;AAAA;AAAA,EAEV,mBAAmB;AAAA;AAAA,EAEnB,cAAc;AAChB;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
export { ChatClient } from './chat-client.js';
|
|
2
|
+
export { GenerationClient } from './generation-client.js';
|
|
3
|
+
export { VideoGenerationClient } from './video-generation-client.js';
|
|
2
4
|
export type { UIMessage, MessagePart, TextPart, ToolCallPart, ToolResultPart, ThinkingPart, ChatClientOptions, ChatRequestBody, InferChatMessages, ChatClientState, MultimodalContent, } from './types.js';
|
|
5
|
+
export type { InferGenerationOutput, GenerationClientState, GenerationClientOptions, GenerationFetcher, GenerationFetcherOptions, GenerationTransport, VideoGenerationClientOptions, VideoStatusInfo, VideoGenerateResult, ImageGenerateInput, SpeechGenerateInput, TranscriptionGenerateInput, SummarizeGenerateInput, VideoGenerateInput, } from './generation-types.js';
|
|
6
|
+
export { GENERATION_EVENTS } from './generation-types.js';
|
|
3
7
|
export { clientTools, createChatClientOptions } from './types.js';
|
|
4
8
|
export type { ExtractToolNames, ExtractToolInput, ExtractToolOutput, } from './tool-types.js';
|
|
5
9
|
export type { AnyClientTool } from '@tanstack/ai';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { ChatClient } from "./chat-client.js";
|
|
2
|
+
import { GenerationClient } from "./generation-client.js";
|
|
3
|
+
import { VideoGenerationClient } from "./video-generation-client.js";
|
|
4
|
+
import { GENERATION_EVENTS } from "./generation-types.js";
|
|
2
5
|
import { clientTools, createChatClientOptions } from "./types.js";
|
|
3
6
|
import { fetchHttpStream, fetchServerSentEvents, rpcStream, stream } from "./connection-adapters.js";
|
|
4
7
|
import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PartialJSONParser, PunctuationStrategy, StreamProcessor, WordBoundaryStrategy, convertMessagesToModelMessages, defaultJSONParser, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, parsePartialJSON, uiMessageToModelMessages } from "@tanstack/ai";
|
|
@@ -6,10 +9,13 @@ export {
|
|
|
6
9
|
BatchStrategy,
|
|
7
10
|
ChatClient,
|
|
8
11
|
CompositeStrategy,
|
|
12
|
+
GENERATION_EVENTS,
|
|
13
|
+
GenerationClient,
|
|
9
14
|
ImmediateStrategy,
|
|
10
15
|
PartialJSONParser,
|
|
11
16
|
PunctuationStrategy,
|
|
12
17
|
StreamProcessor,
|
|
18
|
+
VideoGenerationClient,
|
|
13
19
|
WordBoundaryStrategy,
|
|
14
20
|
clientTools,
|
|
15
21
|
convertMessagesToModelMessages,
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { StreamChunk } from '@tanstack/ai';
|
|
2
|
+
/**
|
|
3
|
+
* Parse a Response body as Server-Sent Events, yielding StreamChunks.
|
|
4
|
+
*
|
|
5
|
+
* Used by GenerationClient to parse SSE Responses returned from fetchers
|
|
6
|
+
* (e.g., TanStack Start server functions using `toServerSentEventsResponse()`).
|
|
7
|
+
*/
|
|
8
|
+
export declare function parseSSEResponse(response: Response, abortSignal?: AbortSignal): AsyncGenerator<StreamChunk>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
async function* readStreamLines(reader, abortSignal) {
|
|
2
|
+
try {
|
|
3
|
+
const decoder = new TextDecoder();
|
|
4
|
+
let buffer = "";
|
|
5
|
+
while (true) {
|
|
6
|
+
if (abortSignal?.aborted) {
|
|
7
|
+
break;
|
|
8
|
+
}
|
|
9
|
+
const { done, value } = await reader.read();
|
|
10
|
+
if (done) break;
|
|
11
|
+
buffer += decoder.decode(value, { stream: true });
|
|
12
|
+
const lines = buffer.split("\n");
|
|
13
|
+
buffer = lines.pop() || "";
|
|
14
|
+
for (const line of lines) {
|
|
15
|
+
if (line.trim()) {
|
|
16
|
+
yield line;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (buffer.trim()) {
|
|
21
|
+
yield buffer;
|
|
22
|
+
}
|
|
23
|
+
} finally {
|
|
24
|
+
reader.releaseLock();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async function* parseSSEResponse(response, abortSignal) {
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`HTTP error! status: ${response.status} ${response.statusText}`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const reader = response.body?.getReader();
|
|
34
|
+
if (!reader) {
|
|
35
|
+
throw new Error("Response body is not readable");
|
|
36
|
+
}
|
|
37
|
+
for await (const line of readStreamLines(reader, abortSignal)) {
|
|
38
|
+
const data = line.startsWith("data: ") ? line.slice(6) : line;
|
|
39
|
+
if (data === "[DONE]") continue;
|
|
40
|
+
try {
|
|
41
|
+
const parsed = JSON.parse(data);
|
|
42
|
+
yield parsed;
|
|
43
|
+
} catch (parseError) {
|
|
44
|
+
console.warn("Failed to parse SSE chunk:", data);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export {
|
|
49
|
+
parseSSEResponse
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=sse-parser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse-parser.js","sources":["../../src/sse-parser.ts"],"sourcesContent":["import type { StreamChunk } from '@tanstack/ai'\n\n/**\n * Read lines from a stream (newline-delimited)\n */\nasync function* readStreamLines(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): AsyncGenerator<string> {\n try {\n const decoder = new TextDecoder()\n let buffer = ''\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while (true) {\n if (abortSignal?.aborted) {\n break\n }\n\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n\n buffer = lines.pop() || ''\n\n for (const line of lines) {\n if (line.trim()) {\n yield line\n }\n }\n }\n\n if (buffer.trim()) {\n yield buffer\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Parse a Response body as Server-Sent Events, yielding StreamChunks.\n *\n * Used by GenerationClient to parse SSE Responses returned from fetchers\n * (e.g., TanStack Start server functions using `toServerSentEventsResponse()`).\n */\nexport async function* parseSSEResponse(\n response: Response,\n abortSignal?: AbortSignal,\n): AsyncGenerator<StreamChunk> {\n if (!response.ok) {\n throw new Error(\n `HTTP error! status: ${response.status} ${response.statusText}`,\n )\n }\n\n const reader = response.body?.getReader()\n if (!reader) {\n throw new Error('Response body is not readable')\n }\n\n for await (const line of readStreamLines(reader, abortSignal)) {\n const data = line.startsWith('data: ') ? line.slice(6) : line\n\n if (data === '[DONE]') continue\n\n try {\n const parsed: StreamChunk = JSON.parse(data)\n yield parsed\n } catch (parseError) {\n console.warn('Failed to parse SSE chunk:', data)\n }\n }\n}\n"],"names":[],"mappings":"AAKA,gBAAgB,gBACd,QACA,aACwB;AACxB,MAAI;AACF,UAAM,UAAU,IAAI,YAAA;AACpB,QAAI,SAAS;AAGb,WAAO,MAAM;AACX,UAAI,aAAa,SAAS;AACxB;AAAA,MACF;AAEA,YAAM,EAAE,MAAM,MAAA,IAAU,MAAM,OAAO,KAAA;AACrC,UAAI,KAAM;AAEV,gBAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,MAAM;AAChD,YAAM,QAAQ,OAAO,MAAM,IAAI;AAE/B,eAAS,MAAM,SAAS;AAExB,iBAAW,QAAQ,OAAO;AACxB,YAAI,KAAK,QAAQ;AACf,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,QAAI,OAAO,QAAQ;AACjB,YAAM;AAAA,IACR;AAAA,EACF,UAAA;AACE,WAAO,YAAA;AAAA,EACT;AACF;AAQA,gBAAuB,iBACrB,UACA,aAC6B;AAC7B,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI;AAAA,MACR,uBAAuB,SAAS,MAAM,IAAI,SAAS,UAAU;AAAA,IAAA;AAAA,EAEjE;AAEA,QAAM,SAAS,SAAS,MAAM,UAAA;AAC9B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AAEA,mBAAiB,QAAQ,gBAAgB,QAAQ,WAAW,GAAG;AAC7D,UAAM,OAAO,KAAK,WAAW,QAAQ,IAAI,KAAK,MAAM,CAAC,IAAI;AAEzD,QAAI,SAAS,SAAU;AAEvB,QAAI;AACF,YAAM,SAAsB,KAAK,MAAM,IAAI;AAC3C,YAAM;AAAA,IACR,SAAS,YAAY;AACnB,cAAQ,KAAK,8BAA8B,IAAI;AAAA,IACjD;AAAA,EACF;AACF;"}
|