@ai-sdk/react 3.0.47 → 3.0.49
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/CHANGELOG.md +13 -0
- package/package.json +4 -3
- package/src/chat.react.ts +130 -0
- package/src/index.ts +4 -0
- package/src/setup-test-component.tsx +26 -0
- package/src/throttle.ts +8 -0
- package/src/use-chat.ts +173 -0
- package/src/use-chat.ui.test.tsx +2532 -0
- package/src/use-completion.ts +208 -0
- package/src/use-completion.ui.test.tsx +165 -0
- package/src/use-object.ts +269 -0
- package/src/use-object.ui.test.tsx +389 -0
- package/src/util/use-stable-value.ts +18 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CompletionRequestOptions,
|
|
3
|
+
UseCompletionOptions,
|
|
4
|
+
callCompletionApi,
|
|
5
|
+
} from 'ai';
|
|
6
|
+
import { useCallback, useEffect, useId, useRef, useState } from 'react';
|
|
7
|
+
import useSWR from 'swr';
|
|
8
|
+
import { throttle } from './throttle';
|
|
9
|
+
|
|
10
|
+
export type { UseCompletionOptions };
|
|
11
|
+
|
|
12
|
+
export type UseCompletionHelpers = {
|
|
13
|
+
/** The current completion result */
|
|
14
|
+
completion: string;
|
|
15
|
+
/**
|
|
16
|
+
* Send a new prompt to the API endpoint and update the completion state.
|
|
17
|
+
*/
|
|
18
|
+
complete: (
|
|
19
|
+
prompt: string,
|
|
20
|
+
options?: CompletionRequestOptions,
|
|
21
|
+
) => Promise<string | null | undefined>;
|
|
22
|
+
/** The error object of the API request */
|
|
23
|
+
error: undefined | Error;
|
|
24
|
+
/**
|
|
25
|
+
* Abort the current API request but keep the generated tokens.
|
|
26
|
+
*/
|
|
27
|
+
stop: () => void;
|
|
28
|
+
/**
|
|
29
|
+
* Update the `completion` state locally.
|
|
30
|
+
*/
|
|
31
|
+
setCompletion: (completion: string) => void;
|
|
32
|
+
/** The current value of the input */
|
|
33
|
+
input: string;
|
|
34
|
+
/** setState-powered method to update the input value */
|
|
35
|
+
setInput: React.Dispatch<React.SetStateAction<string>>;
|
|
36
|
+
/**
|
|
37
|
+
* An input/textarea-ready onChange handler to control the value of the input
|
|
38
|
+
* @example
|
|
39
|
+
* ```jsx
|
|
40
|
+
* <input onChange={handleInputChange} value={input} />
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
handleInputChange: (
|
|
44
|
+
event:
|
|
45
|
+
| React.ChangeEvent<HTMLInputElement>
|
|
46
|
+
| React.ChangeEvent<HTMLTextAreaElement>,
|
|
47
|
+
) => void;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Form submission handler to automatically reset input and append a user message
|
|
51
|
+
* @example
|
|
52
|
+
* ```jsx
|
|
53
|
+
* <form onSubmit={handleSubmit}>
|
|
54
|
+
* <input onChange={handleInputChange} value={input} />
|
|
55
|
+
* </form>
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
handleSubmit: (event?: { preventDefault?: () => void }) => void;
|
|
59
|
+
|
|
60
|
+
/** Whether the API request is in progress */
|
|
61
|
+
isLoading: boolean;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export function useCompletion({
|
|
65
|
+
api = '/api/completion',
|
|
66
|
+
id,
|
|
67
|
+
initialCompletion = '',
|
|
68
|
+
initialInput = '',
|
|
69
|
+
credentials,
|
|
70
|
+
headers,
|
|
71
|
+
body,
|
|
72
|
+
streamProtocol = 'data',
|
|
73
|
+
fetch,
|
|
74
|
+
onFinish,
|
|
75
|
+
onError,
|
|
76
|
+
experimental_throttle: throttleWaitMs,
|
|
77
|
+
}: UseCompletionOptions & {
|
|
78
|
+
/**
|
|
79
|
+
* Custom throttle wait in ms for the completion and data updates.
|
|
80
|
+
* Default is undefined, which disables throttling.
|
|
81
|
+
*/
|
|
82
|
+
experimental_throttle?: number;
|
|
83
|
+
} = {}): UseCompletionHelpers {
|
|
84
|
+
// Generate an unique id for the completion if not provided.
|
|
85
|
+
const hookId = useId();
|
|
86
|
+
const completionId = id || hookId;
|
|
87
|
+
|
|
88
|
+
// Store the completion state in SWR, using the completionId as the key to share states.
|
|
89
|
+
const { data, mutate } = useSWR<string>([api, completionId], null, {
|
|
90
|
+
fallbackData: initialCompletion,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(
|
|
94
|
+
[completionId, 'loading'],
|
|
95
|
+
null,
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
const [error, setError] = useState<undefined | Error>(undefined);
|
|
99
|
+
const completion = data!;
|
|
100
|
+
|
|
101
|
+
// Abort controller to cancel the current API call.
|
|
102
|
+
const [abortController, setAbortController] =
|
|
103
|
+
useState<AbortController | null>(null);
|
|
104
|
+
|
|
105
|
+
const extraMetadataRef = useRef({
|
|
106
|
+
credentials,
|
|
107
|
+
headers,
|
|
108
|
+
body,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
useEffect(() => {
|
|
112
|
+
extraMetadataRef.current = {
|
|
113
|
+
credentials,
|
|
114
|
+
headers,
|
|
115
|
+
body,
|
|
116
|
+
};
|
|
117
|
+
}, [credentials, headers, body]);
|
|
118
|
+
|
|
119
|
+
const triggerRequest = useCallback(
|
|
120
|
+
async (prompt: string, options?: CompletionRequestOptions) =>
|
|
121
|
+
callCompletionApi({
|
|
122
|
+
api,
|
|
123
|
+
prompt,
|
|
124
|
+
credentials: extraMetadataRef.current.credentials,
|
|
125
|
+
headers: { ...extraMetadataRef.current.headers, ...options?.headers },
|
|
126
|
+
body: {
|
|
127
|
+
...extraMetadataRef.current.body,
|
|
128
|
+
...options?.body,
|
|
129
|
+
},
|
|
130
|
+
streamProtocol,
|
|
131
|
+
fetch,
|
|
132
|
+
// throttle streamed ui updates:
|
|
133
|
+
setCompletion: throttle(
|
|
134
|
+
(completion: string) => mutate(completion, false),
|
|
135
|
+
throttleWaitMs,
|
|
136
|
+
),
|
|
137
|
+
setLoading: mutateLoading,
|
|
138
|
+
setError,
|
|
139
|
+
setAbortController,
|
|
140
|
+
onFinish,
|
|
141
|
+
onError,
|
|
142
|
+
}),
|
|
143
|
+
[
|
|
144
|
+
mutate,
|
|
145
|
+
mutateLoading,
|
|
146
|
+
api,
|
|
147
|
+
extraMetadataRef,
|
|
148
|
+
setAbortController,
|
|
149
|
+
onFinish,
|
|
150
|
+
onError,
|
|
151
|
+
setError,
|
|
152
|
+
streamProtocol,
|
|
153
|
+
fetch,
|
|
154
|
+
throttleWaitMs,
|
|
155
|
+
],
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
const stop = useCallback(() => {
|
|
159
|
+
if (abortController) {
|
|
160
|
+
abortController.abort();
|
|
161
|
+
setAbortController(null);
|
|
162
|
+
}
|
|
163
|
+
}, [abortController]);
|
|
164
|
+
|
|
165
|
+
const setCompletion = useCallback(
|
|
166
|
+
(completion: string) => {
|
|
167
|
+
mutate(completion, false);
|
|
168
|
+
},
|
|
169
|
+
[mutate],
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
const complete = useCallback<UseCompletionHelpers['complete']>(
|
|
173
|
+
async (prompt, options) => {
|
|
174
|
+
return triggerRequest(prompt, options);
|
|
175
|
+
},
|
|
176
|
+
[triggerRequest],
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
const [input, setInput] = useState(initialInput);
|
|
180
|
+
|
|
181
|
+
const handleSubmit = useCallback(
|
|
182
|
+
(event?: { preventDefault?: () => void }) => {
|
|
183
|
+
event?.preventDefault?.();
|
|
184
|
+
return input ? complete(input) : undefined;
|
|
185
|
+
},
|
|
186
|
+
[input, complete],
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
const handleInputChange = useCallback(
|
|
190
|
+
(e: any) => {
|
|
191
|
+
setInput(e.target.value);
|
|
192
|
+
},
|
|
193
|
+
[setInput],
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
completion,
|
|
198
|
+
complete,
|
|
199
|
+
error,
|
|
200
|
+
setCompletion,
|
|
201
|
+
stop,
|
|
202
|
+
input,
|
|
203
|
+
setInput,
|
|
204
|
+
handleInputChange,
|
|
205
|
+
handleSubmit,
|
|
206
|
+
isLoading,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createTestServer,
|
|
3
|
+
TestResponseController,
|
|
4
|
+
} from '@ai-sdk/test-server/with-vitest';
|
|
5
|
+
import '@testing-library/jest-dom/vitest';
|
|
6
|
+
import { screen, waitFor } from '@testing-library/react';
|
|
7
|
+
import userEvent from '@testing-library/user-event';
|
|
8
|
+
import { UIMessageChunk } from 'ai';
|
|
9
|
+
import { setupTestComponent } from './setup-test-component';
|
|
10
|
+
import { useCompletion } from './use-completion';
|
|
11
|
+
import { describe, it, expect, beforeEach } from 'vitest';
|
|
12
|
+
|
|
13
|
+
function formatChunk(part: UIMessageChunk) {
|
|
14
|
+
return `data: ${JSON.stringify(part)}\n\n`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const server = createTestServer({
|
|
18
|
+
'/api/completion': {},
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
describe('stream data stream', () => {
|
|
22
|
+
let onFinishResult: { prompt: string; completion: string } | undefined;
|
|
23
|
+
|
|
24
|
+
setupTestComponent(() => {
|
|
25
|
+
const {
|
|
26
|
+
completion,
|
|
27
|
+
handleSubmit,
|
|
28
|
+
error,
|
|
29
|
+
handleInputChange,
|
|
30
|
+
input,
|
|
31
|
+
isLoading,
|
|
32
|
+
} = useCompletion({
|
|
33
|
+
onFinish(prompt, completion) {
|
|
34
|
+
onFinishResult = { prompt, completion };
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
return (
|
|
39
|
+
<div>
|
|
40
|
+
<div data-testid="loading">{isLoading.toString()}</div>
|
|
41
|
+
<div data-testid="error">{error?.toString()}</div>
|
|
42
|
+
<div data-testid="completion">{completion}</div>
|
|
43
|
+
<form onSubmit={handleSubmit}>
|
|
44
|
+
<input
|
|
45
|
+
data-testid="input"
|
|
46
|
+
value={input}
|
|
47
|
+
placeholder="Say something..."
|
|
48
|
+
onChange={handleInputChange}
|
|
49
|
+
/>
|
|
50
|
+
</form>
|
|
51
|
+
</div>
|
|
52
|
+
);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
beforeEach(() => {
|
|
56
|
+
onFinishResult = undefined;
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('render simple stream', () => {
|
|
60
|
+
beforeEach(async () => {
|
|
61
|
+
server.urls['/api/completion'].response = {
|
|
62
|
+
type: 'stream-chunks',
|
|
63
|
+
chunks: [
|
|
64
|
+
formatChunk({ type: 'text-delta', id: '0', delta: 'Hello' }),
|
|
65
|
+
formatChunk({ type: 'text-delta', id: '0', delta: ',' }),
|
|
66
|
+
formatChunk({ type: 'text-delta', id: '0', delta: ' world' }),
|
|
67
|
+
formatChunk({ type: 'text-delta', id: '0', delta: '.' }),
|
|
68
|
+
],
|
|
69
|
+
};
|
|
70
|
+
await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('should render stream', async () => {
|
|
74
|
+
await waitFor(() => {
|
|
75
|
+
expect(screen.getByTestId('completion')).toHaveTextContent(
|
|
76
|
+
'Hello, world.',
|
|
77
|
+
);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("should call 'onFinish' callback", async () => {
|
|
82
|
+
await waitFor(() => {
|
|
83
|
+
expect(onFinishResult).toEqual({
|
|
84
|
+
prompt: 'hi',
|
|
85
|
+
completion: 'Hello, world.',
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe('loading state', () => {
|
|
92
|
+
it('should show loading state', async () => {
|
|
93
|
+
const controller = new TestResponseController();
|
|
94
|
+
|
|
95
|
+
server.urls['/api/completion'].response = {
|
|
96
|
+
type: 'controlled-stream',
|
|
97
|
+
controller,
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
|
|
101
|
+
|
|
102
|
+
controller.write(
|
|
103
|
+
formatChunk({ type: 'text-delta', id: '0', delta: 'Hello' }),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
await waitFor(() => {
|
|
107
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('true');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
await controller.close();
|
|
111
|
+
|
|
112
|
+
await waitFor(() => {
|
|
113
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('should reset loading state on error', async () => {
|
|
118
|
+
server.urls['/api/completion'].response = {
|
|
119
|
+
type: 'error',
|
|
120
|
+
status: 404,
|
|
121
|
+
body: 'Not found',
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
|
|
125
|
+
|
|
126
|
+
await screen.findByTestId('loading');
|
|
127
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe('text stream', () => {
|
|
133
|
+
setupTestComponent(() => {
|
|
134
|
+
const { completion, handleSubmit, handleInputChange, input } =
|
|
135
|
+
useCompletion({ streamProtocol: 'text' });
|
|
136
|
+
|
|
137
|
+
return (
|
|
138
|
+
<div>
|
|
139
|
+
<div data-testid="completion-text-stream">{completion}</div>
|
|
140
|
+
<form onSubmit={handleSubmit}>
|
|
141
|
+
<input
|
|
142
|
+
data-testid="input-text-stream"
|
|
143
|
+
value={input}
|
|
144
|
+
placeholder="Say something..."
|
|
145
|
+
onChange={handleInputChange}
|
|
146
|
+
/>
|
|
147
|
+
</form>
|
|
148
|
+
</div>
|
|
149
|
+
);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('should render stream', async () => {
|
|
153
|
+
server.urls['/api/completion'].response = {
|
|
154
|
+
type: 'stream-chunks',
|
|
155
|
+
chunks: ['Hello', ',', ' world', '.'],
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
await userEvent.type(screen.getByTestId('input-text-stream'), 'hi{enter}');
|
|
159
|
+
|
|
160
|
+
await screen.findByTestId('completion-text-stream');
|
|
161
|
+
expect(screen.getByTestId('completion-text-stream')).toHaveTextContent(
|
|
162
|
+
'Hello, world.',
|
|
163
|
+
);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FetchFunction,
|
|
3
|
+
FlexibleSchema,
|
|
4
|
+
InferSchema,
|
|
5
|
+
isAbortError,
|
|
6
|
+
Resolvable,
|
|
7
|
+
resolve,
|
|
8
|
+
normalizeHeaders,
|
|
9
|
+
safeValidateTypes,
|
|
10
|
+
} from '@ai-sdk/provider-utils';
|
|
11
|
+
import { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';
|
|
12
|
+
import { useCallback, useId, useRef, useState } from 'react';
|
|
13
|
+
import useSWR from 'swr';
|
|
14
|
+
|
|
15
|
+
// use function to allow for mocking in tests:
|
|
16
|
+
const getOriginalFetch = () => fetch;
|
|
17
|
+
|
|
18
|
+
export type Experimental_UseObjectOptions<
|
|
19
|
+
SCHEMA extends FlexibleSchema,
|
|
20
|
+
RESULT,
|
|
21
|
+
> = {
|
|
22
|
+
/**
|
|
23
|
+
* The API endpoint. It should stream JSON that matches the schema as chunked text.
|
|
24
|
+
*/
|
|
25
|
+
api: string;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A schema that defines the shape of the complete object.
|
|
29
|
+
*/
|
|
30
|
+
schema: SCHEMA;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* An unique identifier. If not provided, a random one will be
|
|
34
|
+
* generated. When provided, the `useObject` hook with the same `id` will
|
|
35
|
+
* have shared states across components.
|
|
36
|
+
*/
|
|
37
|
+
id?: string;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* An optional value for the initial object.
|
|
41
|
+
*/
|
|
42
|
+
initialValue?: DeepPartial<RESULT>;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
Custom fetch implementation. You can use it as a middleware to intercept requests,
|
|
46
|
+
or to provide a custom fetch implementation for e.g. testing.
|
|
47
|
+
*/
|
|
48
|
+
fetch?: FetchFunction;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
Callback that is called when the stream has finished.
|
|
52
|
+
*/
|
|
53
|
+
onFinish?: (event: {
|
|
54
|
+
/**
|
|
55
|
+
The generated object (typed according to the schema).
|
|
56
|
+
Can be undefined if the final object does not match the schema.
|
|
57
|
+
*/
|
|
58
|
+
object: RESULT | undefined;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
|
|
62
|
+
*/
|
|
63
|
+
error: Error | undefined;
|
|
64
|
+
}) => Promise<void> | void;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Callback function to be called when an error is encountered.
|
|
68
|
+
*/
|
|
69
|
+
onError?: (error: Error) => void;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Additional HTTP headers to be included in the request.
|
|
73
|
+
* Can be a static object, a function that returns headers, or an async function
|
|
74
|
+
* for dynamic auth tokens.
|
|
75
|
+
*/
|
|
76
|
+
headers?: Resolvable<Record<string, string> | Headers>;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The credentials mode to be used for the fetch request.
|
|
80
|
+
* Possible values are: 'omit', 'same-origin', 'include'.
|
|
81
|
+
* Defaults to 'same-origin'.
|
|
82
|
+
*/
|
|
83
|
+
credentials?: RequestCredentials;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export type Experimental_UseObjectHelpers<RESULT, INPUT> = {
|
|
87
|
+
/**
|
|
88
|
+
* Calls the API with the provided input as JSON body.
|
|
89
|
+
*/
|
|
90
|
+
submit: (input: INPUT) => void;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The current value for the generated object. Updated as the API streams JSON chunks.
|
|
94
|
+
*/
|
|
95
|
+
object: DeepPartial<RESULT> | undefined;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The error object of the API request if any.
|
|
99
|
+
*/
|
|
100
|
+
error: Error | undefined;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Flag that indicates whether an API request is in progress.
|
|
104
|
+
*/
|
|
105
|
+
isLoading: boolean;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Abort the current request immediately, keep the current partial object if any.
|
|
109
|
+
*/
|
|
110
|
+
stop: () => void;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Clear the object state.
|
|
114
|
+
*/
|
|
115
|
+
clear: () => void;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
function useObject<
|
|
119
|
+
SCHEMA extends FlexibleSchema,
|
|
120
|
+
RESULT = InferSchema<SCHEMA>,
|
|
121
|
+
INPUT = any,
|
|
122
|
+
>({
|
|
123
|
+
api,
|
|
124
|
+
id,
|
|
125
|
+
schema, // required, in the future we will use it for validation
|
|
126
|
+
initialValue,
|
|
127
|
+
fetch,
|
|
128
|
+
onError,
|
|
129
|
+
onFinish,
|
|
130
|
+
headers,
|
|
131
|
+
credentials,
|
|
132
|
+
}: Experimental_UseObjectOptions<
|
|
133
|
+
SCHEMA,
|
|
134
|
+
RESULT
|
|
135
|
+
>): Experimental_UseObjectHelpers<RESULT, INPUT> {
|
|
136
|
+
// Generate an unique id if not provided.
|
|
137
|
+
const hookId = useId();
|
|
138
|
+
const completionId = id ?? hookId;
|
|
139
|
+
|
|
140
|
+
// Store the completion state in SWR, using the completionId as the key to share states.
|
|
141
|
+
const { data, mutate } = useSWR<DeepPartial<RESULT>>(
|
|
142
|
+
[api, completionId],
|
|
143
|
+
null,
|
|
144
|
+
{ fallbackData: initialValue },
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
const [error, setError] = useState<undefined | Error>(undefined);
|
|
148
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
149
|
+
|
|
150
|
+
// Abort controller to cancel the current API call.
|
|
151
|
+
const abortControllerRef = useRef<AbortController | null>(null);
|
|
152
|
+
|
|
153
|
+
const stop = useCallback(() => {
|
|
154
|
+
try {
|
|
155
|
+
abortControllerRef.current?.abort();
|
|
156
|
+
} catch (ignored) {
|
|
157
|
+
} finally {
|
|
158
|
+
setIsLoading(false);
|
|
159
|
+
abortControllerRef.current = null;
|
|
160
|
+
}
|
|
161
|
+
}, []);
|
|
162
|
+
|
|
163
|
+
const submit = async (input: INPUT) => {
|
|
164
|
+
try {
|
|
165
|
+
clearObject();
|
|
166
|
+
|
|
167
|
+
setIsLoading(true);
|
|
168
|
+
|
|
169
|
+
const abortController = new AbortController();
|
|
170
|
+
abortControllerRef.current = abortController;
|
|
171
|
+
|
|
172
|
+
// Resolve headers at request time (supports async functions for dynamic auth tokens)
|
|
173
|
+
const resolvedHeaders = await resolve(headers);
|
|
174
|
+
|
|
175
|
+
const actualFetch = fetch ?? getOriginalFetch();
|
|
176
|
+
const response = await actualFetch(api, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
headers: {
|
|
179
|
+
'Content-Type': 'application/json',
|
|
180
|
+
...normalizeHeaders(resolvedHeaders),
|
|
181
|
+
},
|
|
182
|
+
credentials,
|
|
183
|
+
signal: abortController.signal,
|
|
184
|
+
body: JSON.stringify(input),
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
if (!response.ok) {
|
|
188
|
+
throw new Error(
|
|
189
|
+
(await response.text()) ?? 'Failed to fetch the response.',
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (response.body == null) {
|
|
194
|
+
throw new Error('The response body is empty.');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let accumulatedText = '';
|
|
198
|
+
let latestObject: DeepPartial<RESULT> | undefined = undefined;
|
|
199
|
+
|
|
200
|
+
await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
|
|
201
|
+
new WritableStream<string>({
|
|
202
|
+
async write(chunk) {
|
|
203
|
+
accumulatedText += chunk;
|
|
204
|
+
|
|
205
|
+
const { value } = await parsePartialJson(accumulatedText);
|
|
206
|
+
const currentObject = value as DeepPartial<RESULT>;
|
|
207
|
+
|
|
208
|
+
if (!isDeepEqualData(latestObject, currentObject)) {
|
|
209
|
+
latestObject = currentObject;
|
|
210
|
+
|
|
211
|
+
mutate(currentObject);
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
|
|
215
|
+
async close() {
|
|
216
|
+
setIsLoading(false);
|
|
217
|
+
abortControllerRef.current = null;
|
|
218
|
+
|
|
219
|
+
if (onFinish != null) {
|
|
220
|
+
const validationResult = await safeValidateTypes({
|
|
221
|
+
value: latestObject,
|
|
222
|
+
schema: asSchema(schema),
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
onFinish(
|
|
226
|
+
validationResult.success
|
|
227
|
+
? { object: validationResult.value, error: undefined }
|
|
228
|
+
: { object: undefined, error: validationResult.error },
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
}),
|
|
233
|
+
);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (isAbortError(error)) {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (onError && error instanceof Error) {
|
|
240
|
+
onError(error);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
setIsLoading(false);
|
|
244
|
+
setError(error instanceof Error ? error : new Error(String(error)));
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const clear = () => {
|
|
249
|
+
stop();
|
|
250
|
+
clearObject();
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
const clearObject = () => {
|
|
254
|
+
setError(undefined);
|
|
255
|
+
setIsLoading(false);
|
|
256
|
+
mutate(undefined);
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
return {
|
|
260
|
+
submit,
|
|
261
|
+
object: data,
|
|
262
|
+
error,
|
|
263
|
+
isLoading,
|
|
264
|
+
stop,
|
|
265
|
+
clear,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export const experimental_useObject = useObject;
|