@ai-sdk/react 2.0.0-alpha.1 → 2.0.0-alpha.10

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 CHANGED
@@ -1,5 +1,103 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 2.0.0-alpha.10
4
+
5
+ ### Major Changes
6
+
7
+ - 98f25e5: chore (ui): remove managed chat inputs
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [98f25e5]
12
+ - Updated dependencies [7bb58d4]
13
+ - ai@5.0.0-alpha.10
14
+ - @ai-sdk/provider-utils@3.0.0-alpha.10
15
+
16
+ ## 2.0.0-alpha.9
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies [8255639]
21
+ - Updated dependencies [9ae327d]
22
+ - ai@5.0.0-alpha.9
23
+ - @ai-sdk/provider-utils@3.0.0-alpha.9
24
+
25
+ ## 2.0.0-alpha.8
26
+
27
+ ### Patch Changes
28
+
29
+ - Updated dependencies [4fef487]
30
+ - Updated dependencies [6b1c55c]
31
+ - Updated dependencies [2e4f9e4]
32
+ - Updated dependencies [c25cbce]
33
+ - @ai-sdk/provider-utils@3.0.0-alpha.8
34
+ - ai@5.0.0-alpha.8
35
+
36
+ ## 2.0.0-alpha.7
37
+
38
+ ### Patch Changes
39
+
40
+ - Updated dependencies [db345da]
41
+ - Updated dependencies [9b0da33]
42
+ - Updated dependencies [247ee0c]
43
+ - ai@5.0.0-alpha.7
44
+ - @ai-sdk/provider-utils@3.0.0-alpha.7
45
+
46
+ ## 2.0.0-alpha.6
47
+
48
+ ### Patch Changes
49
+
50
+ - Updated dependencies [0d2c085]
51
+ - Updated dependencies [48a7606]
52
+ - ai@5.0.0-alpha.6
53
+ - @ai-sdk/provider-utils@3.0.0-alpha.6
54
+
55
+ ## 2.0.0-alpha.5
56
+
57
+ ### Patch Changes
58
+
59
+ - Updated dependencies [655cf3c]
60
+ - Updated dependencies [1675396]
61
+ - Updated dependencies [cf9af6e]
62
+ - Updated dependencies [ef256ed]
63
+ - Updated dependencies [1ed0287]
64
+ - Updated dependencies [825e8d7]
65
+ - Updated dependencies [7324c21]
66
+ - ai@5.0.0-alpha.5
67
+
68
+ ## 2.0.0-alpha.4
69
+
70
+ ### Patch Changes
71
+
72
+ - 6b14724: chore (ai/react): add experimental throttle back to useChat
73
+ - Updated dependencies [b32c141]
74
+ - Updated dependencies [72d7d72]
75
+ - Updated dependencies [9315076]
76
+ - Updated dependencies [7d97ab6]
77
+ - Updated dependencies [37a916d]
78
+ - Updated dependencies [5f2b3d4]
79
+ - ai@5.0.0-alpha.4
80
+ - @ai-sdk/provider-utils@3.0.0-alpha.4
81
+
82
+ ## 2.0.0-alpha.3
83
+
84
+ ### Patch Changes
85
+
86
+ - Updated dependencies [ab7ccef]
87
+ - Updated dependencies [257224b]
88
+ - Updated dependencies [0463011]
89
+ - Updated dependencies [d306260]
90
+ - ai@5.0.0-alpha.3
91
+ - @ai-sdk/provider-utils@3.0.0-alpha.3
92
+
93
+ ## 2.0.0-alpha.2
94
+
95
+ ### Patch Changes
96
+
97
+ - Updated dependencies [82aa95d]
98
+ - ai@5.0.0-alpha.2
99
+ - @ai-sdk/provider-utils@3.0.0-alpha.2
100
+
3
101
  ## 2.0.0-alpha.1
4
102
 
5
103
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,78 +1,36 @@
1
- import { UIDataTypesSchemas, UIMessage, InferUIDataTypes, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
- export { CreateUIMessage, UIMessage, UseChatOptions, UseCompletionOptions } from 'ai';
3
- import { FetchFunction } from '@ai-sdk/provider-utils';
4
- import z from 'zod';
1
+ import { UIDataPartSchemas, AbstractChat, ChatInit, UIMessage, InferUIDataParts, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
+ export { CreateUIMessage, UIMessage, UseCompletionOptions } from 'ai';
3
+ import { FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
4
+ import * as z3 from 'zod/v3';
5
+ import * as z4 from 'zod/v4/core';
5
6
 
6
- type UseChatHelpers<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas> = {
7
+ declare class Chat<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> extends AbstractChat<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS> {
8
+ constructor({ messages, ...init }: ChatInit<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>);
9
+ }
10
+
11
+ type UseChatHelpers<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
7
12
  /**
8
13
  * The id of the chat.
9
14
  */
10
- readonly chatId: string;
11
- /**
12
- * Hook status:
13
- *
14
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
15
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
16
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
17
- * - `error`: An error occurred during the API request, preventing successful completion.
18
- */
19
- readonly status: 'submitted' | 'streaming' | 'ready' | 'error';
20
- /** Current messages in the chat */
21
- readonly messages: UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[];
22
- /** The error object of the API request */
23
- readonly error: undefined | Error;
24
- /**
25
- * Append a user message to the chat list. This triggers the API call to fetch
26
- * the assistant's response.
27
- *
28
- * @param message The message to append
29
- * @param options Additional options to pass to the API call
30
- */
31
- append: (message: CreateUIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>, options?: ChatRequestOptions) => Promise<void>;
32
- /**
33
- * Reload the last AI chat response for the given chat history. If the last
34
- * message isn't from the assistant, it will request the API to generate a
35
- * new response.
36
- */
37
- reload: (chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
38
- /**
39
- * Abort the current request immediately, keep the generated tokens if any.
40
- */
41
- stop: () => void;
42
- /**
43
- * Resume an ongoing chat generation stream. This does not resume an aborted generation.
44
- */
45
- experimental_resume: () => void;
15
+ readonly id: string;
46
16
  /**
47
17
  * Update the `messages` state locally. This is useful when you want to
48
18
  * edit the messages on the client, and then trigger the `reload` method
49
19
  * manually to regenerate the AI response.
50
20
  */
51
- setMessages: (messages: UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[] | ((messages: UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[]) => UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[])) => void;
52
- /** The current value of the input */
53
- input: string;
54
- /** setState-powered method to update the input value */
55
- setInput: React.Dispatch<React.SetStateAction<string>>;
56
- /** An input/textarea-ready onChange handler to control the value of the input */
57
- handleInputChange: (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
58
- /** Form submission handler to automatically reset input and append a user message */
59
- handleSubmit: (event?: {
60
- preventDefault?: () => void;
61
- }, chatRequestOptions?: ChatRequestOptions & {
62
- files?: FileList | FileUIPart[];
63
- }) => void;
64
- addToolResult: ({ toolCallId, result, }: {
65
- toolCallId: string;
66
- result: any;
67
- }) => void;
68
- };
69
- declare function useChat<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas>({ chatId, initialInput, onToolCall, onFinish, onError, generateId, experimental_throttle: throttleWaitMs, chatStore: chatStoreArg, }?: UseChatOptions<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> & {
21
+ setMessages: (messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[] | ((messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]) => UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[])) => void;
22
+ error: Error | undefined;
23
+ } & Pick<AbstractChat<MESSAGE_METADATA, DATA_PART_SCHEMAS>, 'sendMessage' | 'reload' | 'stop' | 'experimental_resume' | 'addToolResult' | 'status' | 'messages'>;
24
+ type UseChatOptions<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = ({
25
+ chat: Chat<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>;
26
+ } | ChatInit<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>) & {
70
27
  /**
71
28
  Custom throttle wait in ms for the chat messages and data updates.
72
29
  Default is undefined, which disables throttling.
73
30
  */
74
31
  experimental_throttle?: number;
75
- }): UseChatHelpers<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>;
32
+ };
33
+ declare function useChat<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas>({ experimental_throttle: throttleWaitMs, ...options }?: UseChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>): UseChatHelpers<MESSAGE_METADATA, DATA_PART_SCHEMAS>;
76
34
 
77
35
  type UseCompletionHelpers = {
78
36
  /** The current completion result */
@@ -126,7 +84,7 @@ declare function useCompletion({ api, id, initialCompletion, initialInput, crede
126
84
  experimental_throttle?: number;
127
85
  }): UseCompletionHelpers;
128
86
 
129
- type Experimental_UseObjectOptions<RESULT> = {
87
+ type Experimental_UseObjectOptions<SCHEMA extends z4.$ZodType | z3.Schema | Schema, RESULT> = {
130
88
  /**
131
89
  * The API endpoint. It should stream JSON that matches the schema as chunked text.
132
90
  */
@@ -134,7 +92,7 @@ type Experimental_UseObjectOptions<RESULT> = {
134
92
  /**
135
93
  * A Zod schema that defines the shape of the complete object.
136
94
  */
137
- schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;
95
+ schema: SCHEMA;
138
96
  /**
139
97
  * An unique identifier. If not provided, a random one will be
140
98
  * generated. When provided, the `useObject` hook with the same `id` will
@@ -201,8 +159,8 @@ type Experimental_UseObjectHelpers<RESULT, INPUT> = {
201
159
  */
202
160
  stop: () => void;
203
161
  };
204
- declare function useObject<RESULT, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
205
- initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
162
+ declare function useObject<SCHEMA extends z4.$ZodType | z3.Schema | Schema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
163
+ initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
206
164
  declare const experimental_useObject: typeof useObject;
207
165
 
208
- export { Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };
166
+ export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseChatOptions, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };
package/dist/index.d.ts CHANGED
@@ -1,78 +1,36 @@
1
- import { UIDataTypesSchemas, UIMessage, InferUIDataTypes, CreateUIMessage, ChatRequestOptions, FileUIPart, UseChatOptions, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
- export { CreateUIMessage, UIMessage, UseChatOptions, UseCompletionOptions } from 'ai';
3
- import { FetchFunction } from '@ai-sdk/provider-utils';
4
- import z from 'zod';
1
+ import { UIDataPartSchemas, AbstractChat, ChatInit, UIMessage, InferUIDataParts, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
2
+ export { CreateUIMessage, UIMessage, UseCompletionOptions } from 'ai';
3
+ import { FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
4
+ import * as z3 from 'zod/v3';
5
+ import * as z4 from 'zod/v4/core';
5
6
 
6
- type UseChatHelpers<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas> = {
7
+ declare class Chat<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> extends AbstractChat<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS> {
8
+ constructor({ messages, ...init }: ChatInit<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>);
9
+ }
10
+
11
+ type UseChatHelpers<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
7
12
  /**
8
13
  * The id of the chat.
9
14
  */
10
- readonly chatId: string;
11
- /**
12
- * Hook status:
13
- *
14
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
15
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
16
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
17
- * - `error`: An error occurred during the API request, preventing successful completion.
18
- */
19
- readonly status: 'submitted' | 'streaming' | 'ready' | 'error';
20
- /** Current messages in the chat */
21
- readonly messages: UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[];
22
- /** The error object of the API request */
23
- readonly error: undefined | Error;
24
- /**
25
- * Append a user message to the chat list. This triggers the API call to fetch
26
- * the assistant's response.
27
- *
28
- * @param message The message to append
29
- * @param options Additional options to pass to the API call
30
- */
31
- append: (message: CreateUIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>, options?: ChatRequestOptions) => Promise<void>;
32
- /**
33
- * Reload the last AI chat response for the given chat history. If the last
34
- * message isn't from the assistant, it will request the API to generate a
35
- * new response.
36
- */
37
- reload: (chatRequestOptions?: ChatRequestOptions) => Promise<string | null | undefined>;
38
- /**
39
- * Abort the current request immediately, keep the generated tokens if any.
40
- */
41
- stop: () => void;
42
- /**
43
- * Resume an ongoing chat generation stream. This does not resume an aborted generation.
44
- */
45
- experimental_resume: () => void;
15
+ readonly id: string;
46
16
  /**
47
17
  * Update the `messages` state locally. This is useful when you want to
48
18
  * edit the messages on the client, and then trigger the `reload` method
49
19
  * manually to regenerate the AI response.
50
20
  */
51
- setMessages: (messages: UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[] | ((messages: UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[]) => UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[])) => void;
52
- /** The current value of the input */
53
- input: string;
54
- /** setState-powered method to update the input value */
55
- setInput: React.Dispatch<React.SetStateAction<string>>;
56
- /** An input/textarea-ready onChange handler to control the value of the input */
57
- handleInputChange: (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
58
- /** Form submission handler to automatically reset input and append a user message */
59
- handleSubmit: (event?: {
60
- preventDefault?: () => void;
61
- }, chatRequestOptions?: ChatRequestOptions & {
62
- files?: FileList | FileUIPart[];
63
- }) => void;
64
- addToolResult: ({ toolCallId, result, }: {
65
- toolCallId: string;
66
- result: any;
67
- }) => void;
68
- };
69
- declare function useChat<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas>({ chatId, initialInput, onToolCall, onFinish, onError, generateId, experimental_throttle: throttleWaitMs, chatStore: chatStoreArg, }?: UseChatOptions<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> & {
21
+ setMessages: (messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[] | ((messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]) => UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[])) => void;
22
+ error: Error | undefined;
23
+ } & Pick<AbstractChat<MESSAGE_METADATA, DATA_PART_SCHEMAS>, 'sendMessage' | 'reload' | 'stop' | 'experimental_resume' | 'addToolResult' | 'status' | 'messages'>;
24
+ type UseChatOptions<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = ({
25
+ chat: Chat<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>;
26
+ } | ChatInit<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>) & {
70
27
  /**
71
28
  Custom throttle wait in ms for the chat messages and data updates.
72
29
  Default is undefined, which disables throttling.
73
30
  */
74
31
  experimental_throttle?: number;
75
- }): UseChatHelpers<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>;
32
+ };
33
+ declare function useChat<MESSAGE_METADATA = unknown, DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas>({ experimental_throttle: throttleWaitMs, ...options }?: UseChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS>): UseChatHelpers<MESSAGE_METADATA, DATA_PART_SCHEMAS>;
76
34
 
77
35
  type UseCompletionHelpers = {
78
36
  /** The current completion result */
@@ -126,7 +84,7 @@ declare function useCompletion({ api, id, initialCompletion, initialInput, crede
126
84
  experimental_throttle?: number;
127
85
  }): UseCompletionHelpers;
128
86
 
129
- type Experimental_UseObjectOptions<RESULT> = {
87
+ type Experimental_UseObjectOptions<SCHEMA extends z4.$ZodType | z3.Schema | Schema, RESULT> = {
130
88
  /**
131
89
  * The API endpoint. It should stream JSON that matches the schema as chunked text.
132
90
  */
@@ -134,7 +92,7 @@ type Experimental_UseObjectOptions<RESULT> = {
134
92
  /**
135
93
  * A Zod schema that defines the shape of the complete object.
136
94
  */
137
- schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;
95
+ schema: SCHEMA;
138
96
  /**
139
97
  * An unique identifier. If not provided, a random one will be
140
98
  * generated. When provided, the `useObject` hook with the same `id` will
@@ -201,8 +159,8 @@ type Experimental_UseObjectHelpers<RESULT, INPUT> = {
201
159
  */
202
160
  stop: () => void;
203
161
  };
204
- declare function useObject<RESULT, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
205
- initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
162
+ declare function useObject<SCHEMA extends z4.$ZodType | z3.Schema | Schema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
163
+ initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
206
164
  declare const experimental_useObject: typeof useObject;
207
165
 
208
- export { Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };
166
+ export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseChatOptions, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };
package/dist/index.js CHANGED
@@ -26,10 +26,29 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var __accessCheck = (obj, member, msg) => {
30
+ if (!member.has(obj))
31
+ throw TypeError("Cannot " + msg);
32
+ };
33
+ var __privateGet = (obj, member, getter) => {
34
+ __accessCheck(obj, member, "read from private field");
35
+ return getter ? getter.call(obj) : member.get(obj);
36
+ };
37
+ var __privateAdd = (obj, member, value) => {
38
+ if (member.has(obj))
39
+ throw TypeError("Cannot add the same private member more than once");
40
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
41
+ };
42
+ var __privateSet = (obj, member, value, setter) => {
43
+ __accessCheck(obj, member, "write to private field");
44
+ setter ? setter.call(obj, value) : member.set(obj, value);
45
+ return value;
46
+ };
29
47
 
30
48
  // src/index.ts
31
49
  var src_exports = {};
32
50
  __export(src_exports, {
51
+ Chat: () => Chat,
33
52
  experimental_useObject: () => experimental_useObject,
34
53
  useChat: () => useChat,
35
54
  useCompletion: () => useCompletion
@@ -37,163 +56,118 @@ __export(src_exports, {
37
56
  module.exports = __toCommonJS(src_exports);
38
57
 
39
58
  // src/use-chat.ts
40
- var import_ai = require("ai");
41
59
  var import_react = require("react");
60
+
61
+ // src/chat.react.ts
62
+ var import_ai = require("ai");
63
+ var _messages;
64
+ var ReactChatState = class {
65
+ constructor(messages = []) {
66
+ __privateAdd(this, _messages, void 0);
67
+ this.status = "ready";
68
+ this.error = void 0;
69
+ this.pushMessage = (message) => {
70
+ __privateSet(this, _messages, this.messages.concat(message));
71
+ };
72
+ this.popMessage = () => {
73
+ __privateSet(this, _messages, this.messages.slice(0, -1));
74
+ };
75
+ this.replaceMessage = (index, message) => {
76
+ __privateSet(this, _messages, [
77
+ ...__privateGet(this, _messages).slice(0, index),
78
+ message,
79
+ ...__privateGet(this, _messages).slice(index + 1)
80
+ ]);
81
+ };
82
+ this.snapshot = (value) => structuredClone(value);
83
+ __privateSet(this, _messages, messages);
84
+ }
85
+ get messages() {
86
+ return __privateGet(this, _messages);
87
+ }
88
+ set messages(messages) {
89
+ __privateSet(this, _messages, [...messages]);
90
+ }
91
+ };
92
+ _messages = new WeakMap();
93
+ var Chat = class extends import_ai.AbstractChat {
94
+ constructor({
95
+ messages,
96
+ ...init
97
+ }) {
98
+ super({ ...init, state: new ReactChatState(messages) });
99
+ }
100
+ };
101
+
102
+ // src/throttle.ts
103
+ var import_throttleit = __toESM(require("throttleit"));
104
+ function throttle(fn, waitMs) {
105
+ return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
106
+ }
107
+
108
+ // src/use-chat.ts
42
109
  function useChat({
43
- chatId,
44
- initialInput = "",
45
- onToolCall,
46
- onFinish,
47
- onError,
48
- generateId = import_ai.generateId,
49
110
  experimental_throttle: throttleWaitMs,
50
- chatStore: chatStoreArg
111
+ ...options
51
112
  } = {}) {
52
- const [hookId] = (0, import_react.useState)(generateId);
53
- const stableChatId = chatId != null ? chatId : hookId;
54
- const chatStore = (0, import_react.useRef)(
55
- chatStoreArg != null ? chatStoreArg : (0, import_ai.defaultChatStore)({
56
- api: "/api/chat",
57
- generateId
58
- })
59
- );
60
- if (!chatStore.current.hasChat(stableChatId)) {
61
- chatStore.current.addChat(stableChatId, []);
62
- }
113
+ const chatRef = (0, import_react.useRef)("chat" in options ? options.chat : new Chat(options));
63
114
  const subscribe = (0, import_react.useCallback)(
64
115
  ({
65
116
  onStoreChange,
66
117
  eventType
67
- }) => {
68
- return chatStore.current.subscribe({
69
- onChatChanged: (event) => {
70
- if (event.chatId !== stableChatId || event.type !== eventType) {
71
- return;
72
- }
73
- onStoreChange();
74
- }
75
- });
76
- },
77
- [chatStore, stableChatId]
118
+ }) => chatRef.current.subscribe({
119
+ onChange: (event) => {
120
+ if (event.type !== eventType)
121
+ return;
122
+ onStoreChange();
123
+ }
124
+ }),
125
+ [chatRef]
78
126
  );
79
127
  const addToolResult = (0, import_react.useCallback)(
80
- (options) => chatStore.current.addToolResult({ chatId: stableChatId, ...options }),
81
- [chatStore, stableChatId]
82
- );
83
- const stopStream = (0, import_react.useCallback)(() => {
84
- chatStore.current.stopStream({ chatId: stableChatId });
85
- }, [chatStore, stableChatId]);
86
- const error = (0, import_react.useSyncExternalStore)(
87
- (callback) => subscribe({
88
- onStoreChange: callback,
89
- eventType: "chat-status-changed"
90
- }),
91
- () => chatStore.current.getError(stableChatId),
92
- () => chatStore.current.getError(stableChatId)
128
+ (options2) => chatRef.current.addToolResult(options2),
129
+ [chatRef]
93
130
  );
94
131
  const status = (0, import_react.useSyncExternalStore)(
95
132
  (callback) => subscribe({
96
133
  onStoreChange: callback,
97
- eventType: "chat-status-changed"
134
+ eventType: "status-changed"
98
135
  }),
99
- () => chatStore.current.getStatus(stableChatId),
100
- () => chatStore.current.getStatus(stableChatId)
136
+ () => chatRef.current.status,
137
+ () => chatRef.current.status
101
138
  );
102
- const messages = (0, import_react.useSyncExternalStore)(
139
+ const subscribeToChatStoreForMessages = (0, import_react.useCallback)(
103
140
  (callback) => {
104
141
  return subscribe({
105
- onStoreChange: callback,
106
- eventType: "chat-messages-changed"
142
+ onStoreChange: throttleWaitMs ? throttle(callback, throttleWaitMs) : callback,
143
+ eventType: "messages-changed"
107
144
  });
108
145
  },
109
- () => chatStore.current.getMessages(stableChatId),
110
- () => chatStore.current.getMessages(stableChatId)
111
- );
112
- const append = (0, import_react.useCallback)(
113
- (message, { headers, body } = {}) => chatStore.current.submitMessage({
114
- chatId: stableChatId,
115
- message,
116
- headers,
117
- body,
118
- onError,
119
- onToolCall,
120
- onFinish
121
- }),
122
- [chatStore, stableChatId, onError, onToolCall, onFinish]
146
+ [subscribe, throttleWaitMs]
123
147
  );
124
- const reload = (0, import_react.useCallback)(
125
- async ({ headers, body } = {}) => chatStore.current.resubmitLastUserMessage({
126
- chatId: stableChatId,
127
- headers,
128
- body,
129
- onError,
130
- onToolCall,
131
- onFinish
132
- }),
133
- [chatStore, stableChatId, onError, onToolCall, onFinish]
134
- );
135
- const stop = (0, import_react.useCallback)(() => stopStream(), [stopStream]);
136
- const experimental_resume = (0, import_react.useCallback)(
137
- async () => chatStore.current.resumeStream({
138
- chatId: stableChatId,
139
- onError,
140
- onToolCall,
141
- onFinish
142
- }),
143
- [chatStore, stableChatId, onError, onToolCall, onFinish]
148
+ const messages = (0, import_react.useSyncExternalStore)(
149
+ (callback) => subscribeToChatStoreForMessages(callback),
150
+ () => chatRef.current.messages,
151
+ () => chatRef.current.messages
144
152
  );
145
153
  const setMessages = (0, import_react.useCallback)(
146
154
  (messagesParam) => {
147
155
  if (typeof messagesParam === "function") {
148
156
  messagesParam = messagesParam(messages);
149
157
  }
150
- chatStore.current.setMessages({
151
- id: stableChatId,
152
- messages: messagesParam
153
- });
158
+ chatRef.current.messages = messagesParam;
154
159
  },
155
- [stableChatId, messages]
160
+ [chatRef, messages]
156
161
  );
157
- const [input, setInput] = (0, import_react.useState)(initialInput);
158
- const handleSubmit = (0, import_react.useCallback)(
159
- async (event, options = {}) => {
160
- var _a;
161
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
162
- const fileParts = Array.isArray(options == null ? void 0 : options.files) ? options.files : await (0, import_ai.convertFileListToFileUIParts)(options == null ? void 0 : options.files);
163
- if (!input && fileParts.length === 0)
164
- return;
165
- append(
166
- {
167
- id: generateId(),
168
- role: "user",
169
- metadata: void 0,
170
- parts: [...fileParts, { type: "text", text: input }]
171
- },
172
- {
173
- headers: options.headers,
174
- body: options.body
175
- }
176
- );
177
- setInput("");
178
- },
179
- [input, generateId, append]
180
- );
181
- const handleInputChange = (e) => {
182
- setInput(e.target.value);
183
- };
184
162
  return {
163
+ id: chatRef.current.id,
185
164
  messages,
186
- chatId: stableChatId,
187
165
  setMessages,
188
- error,
189
- append,
190
- reload,
191
- stop,
192
- experimental_resume,
193
- input,
194
- setInput,
195
- handleInputChange,
196
- handleSubmit,
166
+ sendMessage: chatRef.current.sendMessage,
167
+ reload: chatRef.current.reload,
168
+ stop: chatRef.current.stop,
169
+ error: chatRef.current.error,
170
+ experimental_resume: chatRef.current.experimental_resume,
197
171
  status,
198
172
  addToolResult
199
173
  };
@@ -203,14 +177,6 @@ function useChat({
203
177
  var import_ai2 = require("ai");
204
178
  var import_react2 = require("react");
205
179
  var import_swr = __toESM(require("swr"));
206
-
207
- // src/throttle.ts
208
- var import_throttleit = __toESM(require("throttleit"));
209
- function throttle(fn, waitMs) {
210
- return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
211
- }
212
-
213
- // src/use-completion.ts
214
180
  function useCompletion({
215
181
  api = "/api/completion",
216
182
  id,
@@ -448,6 +414,7 @@ function useObject({
448
414
  var experimental_useObject = useObject;
449
415
  // Annotate the CommonJS export names for ESM import in node:
450
416
  0 && (module.exports = {
417
+ Chat,
451
418
  experimental_useObject,
452
419
  useChat,
453
420
  useCompletion
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/use-completion.ts","../src/throttle.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import { Validator } from '@ai-sdk/provider-utils';\nimport {\n ChatStore,\n convertFileListToFileUIParts,\n defaultChatStore,\n generateId as generateIdFunc,\n InferUIDataTypes,\n UIDataTypesSchemas,\n type ChatRequestOptions,\n type ChatStoreEvent,\n type CreateUIMessage,\n type FileUIPart,\n type UIMessage,\n type UseChatOptions,\n} from 'ai';\nimport { useCallback, useRef, useState, useSyncExternalStore } from 'react';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers<\n MESSAGE_METADATA = unknown,\n DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas,\n> = {\n /**\n * The id of the chat.\n */\n readonly chatId: string;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n readonly status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Current messages in the chat */\n readonly messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[];\n\n /** The error object of the API request */\n readonly error: undefined | Error;\n\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n *\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: CreateUIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >,\n options?: ChatRequestOptions,\n ) => Promise<void>;\n\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[]),\n ) => void;\n\n /** The current value of the input */\n input: string;\n\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n\n /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n};\n\nexport function useChat<\n MESSAGE_METADATA = unknown,\n DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas,\n>({\n chatId,\n initialInput = '',\n onToolCall,\n onFinish,\n onError,\n generateId = generateIdFunc,\n experimental_throttle: throttleWaitMs,\n chatStore: chatStoreArg,\n}: UseChatOptions<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseChatHelpers<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const stableChatId = chatId ?? hookId;\n\n // chat store setup\n // TODO enable as arg\n const chatStore = useRef(\n chatStoreArg ??\n defaultChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>({\n api: '/api/chat',\n generateId,\n }),\n );\n\n // ensure the chat is in the store\n if (!chatStore.current.hasChat(stableChatId)) {\n chatStore.current.addChat(stableChatId, []);\n }\n\n const subscribe = useCallback(\n ({\n onStoreChange,\n eventType,\n }: {\n onStoreChange: () => void;\n eventType: ChatStoreEvent['type'];\n }) => {\n return chatStore.current.subscribe({\n onChatChanged: event => {\n if (event.chatId !== stableChatId || event.type !== eventType) {\n return;\n }\n\n onStoreChange();\n },\n });\n },\n [chatStore, stableChatId],\n );\n\n const addToolResult = useCallback(\n (\n options: Omit<\n Parameters<\n ChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>['addToolResult']\n >[0],\n 'chatId'\n >,\n ) => chatStore.current.addToolResult({ chatId: stableChatId, ...options }),\n [chatStore, stableChatId],\n );\n\n const stopStream = useCallback(() => {\n chatStore.current.stopStream({ chatId: stableChatId });\n }, [chatStore, stableChatId]);\n\n const error = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'chat-status-changed',\n }),\n () => chatStore.current.getError(stableChatId),\n () => chatStore.current.getError(stableChatId),\n );\n\n const status = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'chat-status-changed',\n }),\n () => chatStore.current.getStatus(stableChatId),\n () => chatStore.current.getStatus(stableChatId),\n );\n\n const messages = useSyncExternalStore(\n callback => {\n return subscribe({\n onStoreChange: callback,\n eventType: 'chat-messages-changed',\n });\n },\n () => chatStore.current.getMessages(stableChatId),\n () => chatStore.current.getMessages(stableChatId),\n );\n\n const append = useCallback(\n (\n message: CreateUIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >,\n { headers, body }: ChatRequestOptions = {},\n ) =>\n chatStore.current.submitMessage({\n chatId: stableChatId,\n message,\n headers,\n body,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, stableChatId, onError, onToolCall, onFinish],\n );\n\n const reload = useCallback(\n async ({ headers, body }: ChatRequestOptions = {}) =>\n chatStore.current.resubmitLastUserMessage({\n chatId: stableChatId,\n headers,\n body,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, stableChatId, onError, onToolCall, onFinish],\n );\n const stop = useCallback(() => stopStream(), [stopStream]);\n\n const experimental_resume = useCallback(\n async () =>\n chatStore.current.resumeStream({\n chatId: stableChatId,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, stableChatId, onError, onToolCall, onFinish],\n );\n\n const setMessages = useCallback(\n (\n messagesParam:\n | UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(messages);\n }\n\n chatStore.current.setMessages({\n id: stableChatId,\n messages: messagesParam,\n });\n },\n [stableChatId, messages],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n ) => {\n event?.preventDefault?.();\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n if (!input && fileParts.length === 0) return;\n\n append(\n {\n id: generateId(),\n role: 'user',\n metadata: undefined,\n parts: [...fileParts, { type: 'text', text: input }],\n },\n {\n headers: options.headers,\n body: options.body,\n },\n );\n\n setInput('');\n },\n [input, generateId, append],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n return {\n messages,\n chatId: stableChatId,\n setMessages,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n status,\n addToolResult,\n };\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,gBAaO;AACP,mBAAoE;AAmH7D,SAAS,QAGd;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa,UAAAA;AAAA,EACb,uBAAuB;AAAA,EACvB,WAAW;AACb,IAMI,CAAC,GAAwD;AAE3D,QAAM,CAAC,MAAM,QAAI,uBAAS,UAAU;AAGpC,QAAM,eAAe,0BAAU;AAI/B,QAAM,gBAAY;AAAA,IAChB,0CACE,4BAAsD;AAAA,MACpD,KAAK;AAAA,MACL;AAAA,IACF,CAAC;AAAA,EACL;AAGA,MAAI,CAAC,UAAU,QAAQ,QAAQ,YAAY,GAAG;AAC5C,cAAU,QAAQ,QAAQ,cAAc,CAAC,CAAC;AAAA,EAC5C;AAEA,QAAM,gBAAY;AAAA,IAChB,CAAC;AAAA,MACC;AAAA,MACA;AAAA,IACF,MAGM;AACJ,aAAO,UAAU,QAAQ,UAAU;AAAA,QACjC,eAAe,WAAS;AACtB,cAAI,MAAM,WAAW,gBAAgB,MAAM,SAA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zD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASE,QAAO;AACd,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["generateIdFunc","import_ai","import_react","throttleFunction","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n AbstractChat,\n ChatInit as BaseChatInit,\n ChatEvent,\n InferUIDataParts,\n UIDataPartSchemas,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\nimport { throttle } from './throttle';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<\n MESSAGE_METADATA = unknown,\n DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<MESSAGE_METADATA, DATA_PART_SCHEMAS>,\n | 'sendMessage'\n | 'reload'\n | 'stop'\n | 'experimental_resume'\n | 'addToolResult'\n | 'status'\n | 'messages'\n>;\n\nexport type UseChatOptions<\n MESSAGE_METADATA = unknown,\n DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n> = (\n | { chat: Chat<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> }\n | BaseChatInit<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n};\n\nexport function useChat<\n MESSAGE_METADATA = unknown,\n DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n>({\n experimental_throttle: throttleWaitMs,\n ...options\n}: UseChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS> = {}): UseChatHelpers<\n MESSAGE_METADATA,\n DATA_PART_SCHEMAS\n> {\n const chatRef = useRef('chat' in options ? options.chat : new Chat(options));\n\n const subscribe = useCallback(\n ({\n onStoreChange,\n eventType,\n }: {\n onStoreChange: () => void;\n eventType: ChatEvent['type'];\n }) =>\n chatRef.current.subscribe({\n onChange: event => {\n if (event.type !== eventType) return;\n onStoreChange();\n },\n }),\n [chatRef],\n );\n\n const addToolResult = useCallback(\n (\n options: Parameters<\n Chat<MESSAGE_METADATA, DATA_PART_SCHEMAS>['addToolResult']\n >[0],\n ) => chatRef.current.addToolResult(options),\n [chatRef],\n );\n\n const status = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'status-changed',\n }),\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const subscribeToChatStoreForMessages = useCallback(\n (callback: () => void) => {\n return subscribe({\n onStoreChange: throttleWaitMs\n ? throttle(callback, throttleWaitMs)\n : callback,\n eventType: 'messages-changed',\n });\n },\n [subscribe, throttleWaitMs],\n );\n\n const messages = useSyncExternalStore(\n callback => subscribeToChatStoreForMessages(callback),\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const setMessages = useCallback(\n (\n messagesParam:\n | UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(messages);\n }\n\n chatRef.current.messages = messagesParam;\n },\n [chatRef, messages],\n );\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n reload: chatRef.current.reload,\n stop: chatRef.current.stop,\n error: chatRef.current.error,\n experimental_resume: chatRef.current.experimental_resume,\n status,\n addToolResult,\n };\n}\n","import {\n AbstractChat,\n ChatInit,\n ChatState,\n ChatStatus,\n UIDataPartSchemas,\n UIDataTypes,\n UIMessage,\n} from 'ai';\n\nclass ReactChatState<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes>\n implements ChatState<MESSAGE_METADATA, DATA_TYPES>\n{\n #messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];\n status: ChatStatus = 'ready';\n error: Error | undefined = undefined;\n\n constructor(messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[] = []) {\n this.#messages = messages;\n }\n\n get messages() {\n return this.#messages;\n }\n\n set messages(messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[]) {\n this.#messages = [...messages];\n }\n\n pushMessage = (message: UIMessage<MESSAGE_METADATA, DATA_TYPES>) => {\n this.#messages = this.messages.concat(message);\n };\n\n popMessage = () => {\n this.#messages = this.messages.slice(0, -1);\n };\n\n replaceMessage = (\n index: number,\n message: UIMessage<MESSAGE_METADATA, DATA_TYPES>,\n ) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n message,\n ...this.#messages.slice(index + 1),\n ];\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n}\n\nexport class Chat<\n MESSAGE_METADATA,\n UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n> extends AbstractChat<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS> {\n constructor({\n messages,\n ...init\n }: ChatInit<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>) {\n super({ ...init, state: new ReactChatState(messages) });\n }\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4/core';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends z4.$ZodType | z3.Schema | Schema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<\n SCHEMA extends z4.$ZodType | z3.Schema | Schema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,mBAA0D;;;ACT1D,gBAQO;AARP;AAUA,IAAM,iBAAN,MAEA;AAAA,EAKE,YAAY,WAAsD,CAAC,GAAG;AAJtE;AACA,kBAAqB;A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AS,KAAK,YAAY,IAAI,kBAAkB,CAAC,EAAE;AAAA,QACvD,IAAI,eAAuB;AAAA,UACzB,MAAM,MAAM,OAAO;AACjB,+BAAmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,UAAM,6BAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,KAAC,4BAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,UAAM,yCAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,YAAQ,qBAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASE,QAAO;AACd,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["throttleFunction","options","import_ai","import_react","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
package/dist/index.mjs CHANGED
@@ -1,165 +1,137 @@
1
+ var __accessCheck = (obj, member, msg) => {
2
+ if (!member.has(obj))
3
+ throw TypeError("Cannot " + msg);
4
+ };
5
+ var __privateGet = (obj, member, getter) => {
6
+ __accessCheck(obj, member, "read from private field");
7
+ return getter ? getter.call(obj) : member.get(obj);
8
+ };
9
+ var __privateAdd = (obj, member, value) => {
10
+ if (member.has(obj))
11
+ throw TypeError("Cannot add the same private member more than once");
12
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ };
14
+ var __privateSet = (obj, member, value, setter) => {
15
+ __accessCheck(obj, member, "write to private field");
16
+ setter ? setter.call(obj, value) : member.set(obj, value);
17
+ return value;
18
+ };
19
+
1
20
  // src/use-chat.ts
21
+ import { useCallback, useRef, useSyncExternalStore } from "react";
22
+
23
+ // src/chat.react.ts
2
24
  import {
3
- convertFileListToFileUIParts,
4
- defaultChatStore,
5
- generateId as generateIdFunc
25
+ AbstractChat
6
26
  } from "ai";
7
- import { useCallback, useRef, useState, useSyncExternalStore } from "react";
27
+ var _messages;
28
+ var ReactChatState = class {
29
+ constructor(messages = []) {
30
+ __privateAdd(this, _messages, void 0);
31
+ this.status = "ready";
32
+ this.error = void 0;
33
+ this.pushMessage = (message) => {
34
+ __privateSet(this, _messages, this.messages.concat(message));
35
+ };
36
+ this.popMessage = () => {
37
+ __privateSet(this, _messages, this.messages.slice(0, -1));
38
+ };
39
+ this.replaceMessage = (index, message) => {
40
+ __privateSet(this, _messages, [
41
+ ...__privateGet(this, _messages).slice(0, index),
42
+ message,
43
+ ...__privateGet(this, _messages).slice(index + 1)
44
+ ]);
45
+ };
46
+ this.snapshot = (value) => structuredClone(value);
47
+ __privateSet(this, _messages, messages);
48
+ }
49
+ get messages() {
50
+ return __privateGet(this, _messages);
51
+ }
52
+ set messages(messages) {
53
+ __privateSet(this, _messages, [...messages]);
54
+ }
55
+ };
56
+ _messages = new WeakMap();
57
+ var Chat = class extends AbstractChat {
58
+ constructor({
59
+ messages,
60
+ ...init
61
+ }) {
62
+ super({ ...init, state: new ReactChatState(messages) });
63
+ }
64
+ };
65
+
66
+ // src/throttle.ts
67
+ import throttleFunction from "throttleit";
68
+ function throttle(fn, waitMs) {
69
+ return waitMs != null ? throttleFunction(fn, waitMs) : fn;
70
+ }
71
+
72
+ // src/use-chat.ts
8
73
  function useChat({
9
- chatId,
10
- initialInput = "",
11
- onToolCall,
12
- onFinish,
13
- onError,
14
- generateId = generateIdFunc,
15
74
  experimental_throttle: throttleWaitMs,
16
- chatStore: chatStoreArg
75
+ ...options
17
76
  } = {}) {
18
- const [hookId] = useState(generateId);
19
- const stableChatId = chatId != null ? chatId : hookId;
20
- const chatStore = useRef(
21
- chatStoreArg != null ? chatStoreArg : defaultChatStore({
22
- api: "/api/chat",
23
- generateId
24
- })
25
- );
26
- if (!chatStore.current.hasChat(stableChatId)) {
27
- chatStore.current.addChat(stableChatId, []);
28
- }
77
+ const chatRef = useRef("chat" in options ? options.chat : new Chat(options));
29
78
  const subscribe = useCallback(
30
79
  ({
31
80
  onStoreChange,
32
81
  eventType
33
- }) => {
34
- return chatStore.current.subscribe({
35
- onChatChanged: (event) => {
36
- if (event.chatId !== stableChatId || event.type !== eventType) {
37
- return;
38
- }
39
- onStoreChange();
40
- }
41
- });
42
- },
43
- [chatStore, stableChatId]
82
+ }) => chatRef.current.subscribe({
83
+ onChange: (event) => {
84
+ if (event.type !== eventType)
85
+ return;
86
+ onStoreChange();
87
+ }
88
+ }),
89
+ [chatRef]
44
90
  );
45
91
  const addToolResult = useCallback(
46
- (options) => chatStore.current.addToolResult({ chatId: stableChatId, ...options }),
47
- [chatStore, stableChatId]
48
- );
49
- const stopStream = useCallback(() => {
50
- chatStore.current.stopStream({ chatId: stableChatId });
51
- }, [chatStore, stableChatId]);
52
- const error = useSyncExternalStore(
53
- (callback) => subscribe({
54
- onStoreChange: callback,
55
- eventType: "chat-status-changed"
56
- }),
57
- () => chatStore.current.getError(stableChatId),
58
- () => chatStore.current.getError(stableChatId)
92
+ (options2) => chatRef.current.addToolResult(options2),
93
+ [chatRef]
59
94
  );
60
95
  const status = useSyncExternalStore(
61
96
  (callback) => subscribe({
62
97
  onStoreChange: callback,
63
- eventType: "chat-status-changed"
98
+ eventType: "status-changed"
64
99
  }),
65
- () => chatStore.current.getStatus(stableChatId),
66
- () => chatStore.current.getStatus(stableChatId)
100
+ () => chatRef.current.status,
101
+ () => chatRef.current.status
67
102
  );
68
- const messages = useSyncExternalStore(
103
+ const subscribeToChatStoreForMessages = useCallback(
69
104
  (callback) => {
70
105
  return subscribe({
71
- onStoreChange: callback,
72
- eventType: "chat-messages-changed"
106
+ onStoreChange: throttleWaitMs ? throttle(callback, throttleWaitMs) : callback,
107
+ eventType: "messages-changed"
73
108
  });
74
109
  },
75
- () => chatStore.current.getMessages(stableChatId),
76
- () => chatStore.current.getMessages(stableChatId)
110
+ [subscribe, throttleWaitMs]
77
111
  );
78
- const append = useCallback(
79
- (message, { headers, body } = {}) => chatStore.current.submitMessage({
80
- chatId: stableChatId,
81
- message,
82
- headers,
83
- body,
84
- onError,
85
- onToolCall,
86
- onFinish
87
- }),
88
- [chatStore, stableChatId, onError, onToolCall, onFinish]
89
- );
90
- const reload = useCallback(
91
- async ({ headers, body } = {}) => chatStore.current.resubmitLastUserMessage({
92
- chatId: stableChatId,
93
- headers,
94
- body,
95
- onError,
96
- onToolCall,
97
- onFinish
98
- }),
99
- [chatStore, stableChatId, onError, onToolCall, onFinish]
100
- );
101
- const stop = useCallback(() => stopStream(), [stopStream]);
102
- const experimental_resume = useCallback(
103
- async () => chatStore.current.resumeStream({
104
- chatId: stableChatId,
105
- onError,
106
- onToolCall,
107
- onFinish
108
- }),
109
- [chatStore, stableChatId, onError, onToolCall, onFinish]
112
+ const messages = useSyncExternalStore(
113
+ (callback) => subscribeToChatStoreForMessages(callback),
114
+ () => chatRef.current.messages,
115
+ () => chatRef.current.messages
110
116
  );
111
117
  const setMessages = useCallback(
112
118
  (messagesParam) => {
113
119
  if (typeof messagesParam === "function") {
114
120
  messagesParam = messagesParam(messages);
115
121
  }
116
- chatStore.current.setMessages({
117
- id: stableChatId,
118
- messages: messagesParam
119
- });
120
- },
121
- [stableChatId, messages]
122
- );
123
- const [input, setInput] = useState(initialInput);
124
- const handleSubmit = useCallback(
125
- async (event, options = {}) => {
126
- var _a;
127
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
128
- const fileParts = Array.isArray(options == null ? void 0 : options.files) ? options.files : await convertFileListToFileUIParts(options == null ? void 0 : options.files);
129
- if (!input && fileParts.length === 0)
130
- return;
131
- append(
132
- {
133
- id: generateId(),
134
- role: "user",
135
- metadata: void 0,
136
- parts: [...fileParts, { type: "text", text: input }]
137
- },
138
- {
139
- headers: options.headers,
140
- body: options.body
141
- }
142
- );
143
- setInput("");
122
+ chatRef.current.messages = messagesParam;
144
123
  },
145
- [input, generateId, append]
124
+ [chatRef, messages]
146
125
  );
147
- const handleInputChange = (e) => {
148
- setInput(e.target.value);
149
- };
150
126
  return {
127
+ id: chatRef.current.id,
151
128
  messages,
152
- chatId: stableChatId,
153
129
  setMessages,
154
- error,
155
- append,
156
- reload,
157
- stop,
158
- experimental_resume,
159
- input,
160
- setInput,
161
- handleInputChange,
162
- handleSubmit,
130
+ sendMessage: chatRef.current.sendMessage,
131
+ reload: chatRef.current.reload,
132
+ stop: chatRef.current.stop,
133
+ error: chatRef.current.error,
134
+ experimental_resume: chatRef.current.experimental_resume,
163
135
  status,
164
136
  addToolResult
165
137
  };
@@ -169,16 +141,8 @@ function useChat({
169
141
  import {
170
142
  callCompletionApi
171
143
  } from "ai";
172
- import { useCallback as useCallback2, useEffect, useId, useRef as useRef2, useState as useState2 } from "react";
144
+ import { useCallback as useCallback2, useEffect, useId, useRef as useRef2, useState } from "react";
173
145
  import useSWR from "swr";
174
-
175
- // src/throttle.ts
176
- import throttleFunction from "throttleit";
177
- function throttle(fn, waitMs) {
178
- return waitMs != null ? throttleFunction(fn, waitMs) : fn;
179
- }
180
-
181
- // src/use-completion.ts
182
146
  function useCompletion({
183
147
  api = "/api/completion",
184
148
  id,
@@ -202,9 +166,9 @@ function useCompletion({
202
166
  [completionId, "loading"],
203
167
  null
204
168
  );
205
- const [error, setError] = useState2(void 0);
169
+ const [error, setError] = useState(void 0);
206
170
  const completion = data;
207
- const [abortController, setAbortController] = useState2(null);
171
+ const [abortController, setAbortController] = useState(null);
208
172
  const extraMetadataRef = useRef2({
209
173
  credentials,
210
174
  headers,
@@ -272,7 +236,7 @@ function useCompletion({
272
236
  },
273
237
  [triggerRequest]
274
238
  );
275
- const [input, setInput] = useState2(initialInput);
239
+ const [input, setInput] = useState(initialInput);
276
240
  const handleSubmit = useCallback2(
277
241
  (event) => {
278
242
  var _a;
@@ -311,7 +275,7 @@ import {
311
275
  isDeepEqualData,
312
276
  parsePartialJson
313
277
  } from "ai";
314
- import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState3 } from "react";
278
+ import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
315
279
  import useSWR2 from "swr";
316
280
  var getOriginalFetch = () => fetch;
317
281
  function useObject({
@@ -333,8 +297,8 @@ function useObject({
333
297
  null,
334
298
  { fallbackData: initialValue }
335
299
  );
336
- const [error, setError] = useState3(void 0);
337
- const [isLoading, setIsLoading] = useState3(false);
300
+ const [error, setError] = useState2(void 0);
301
+ const [isLoading, setIsLoading] = useState2(false);
338
302
  const abortControllerRef = useRef3(null);
339
303
  const stop = useCallback3(() => {
340
304
  var _a;
@@ -422,6 +386,7 @@ function useObject({
422
386
  }
423
387
  var experimental_useObject = useObject;
424
388
  export {
389
+ Chat,
425
390
  experimental_useObject,
426
391
  useChat,
427
392
  useCompletion
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/use-completion.ts","../src/throttle.ts","../src/use-object.ts"],"sourcesContent":["import { Validator } from '@ai-sdk/provider-utils';\nimport {\n ChatStore,\n convertFileListToFileUIParts,\n defaultChatStore,\n generateId as generateIdFunc,\n InferUIDataTypes,\n UIDataTypesSchemas,\n type ChatRequestOptions,\n type ChatStoreEvent,\n type CreateUIMessage,\n type FileUIPart,\n type UIMessage,\n type UseChatOptions,\n} from 'ai';\nimport { useCallback, useRef, useState, useSyncExternalStore } from 'react';\n\nexport type { CreateUIMessage, UIMessage, UseChatOptions };\n\nexport type UseChatHelpers<\n MESSAGE_METADATA = unknown,\n DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas,\n> = {\n /**\n * The id of the chat.\n */\n readonly chatId: string;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n readonly status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Current messages in the chat */\n readonly messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[];\n\n /** The error object of the API request */\n readonly error: undefined | Error;\n\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n *\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: CreateUIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >,\n options?: ChatRequestOptions,\n ) => Promise<void>;\n\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Resume an ongoing chat generation stream. This does not resume an aborted generation.\n */\n experimental_resume: () => void;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[]),\n ) => void;\n\n /** The current value of the input */\n input: string;\n\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n\n /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n },\n ) => void;\n\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n};\n\nexport function useChat<\n MESSAGE_METADATA = unknown,\n DATA_TYPE_SCHEMAS extends UIDataTypesSchemas = UIDataTypesSchemas,\n>({\n chatId,\n initialInput = '',\n onToolCall,\n onFinish,\n onError,\n generateId = generateIdFunc,\n experimental_throttle: throttleWaitMs,\n chatStore: chatStoreArg,\n}: UseChatOptions<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseChatHelpers<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const stableChatId = chatId ?? hookId;\n\n // chat store setup\n // TODO enable as arg\n const chatStore = useRef(\n chatStoreArg ??\n defaultChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>({\n api: '/api/chat',\n generateId,\n }),\n );\n\n // ensure the chat is in the store\n if (!chatStore.current.hasChat(stableChatId)) {\n chatStore.current.addChat(stableChatId, []);\n }\n\n const subscribe = useCallback(\n ({\n onStoreChange,\n eventType,\n }: {\n onStoreChange: () => void;\n eventType: ChatStoreEvent['type'];\n }) => {\n return chatStore.current.subscribe({\n onChatChanged: event => {\n if (event.chatId !== stableChatId || event.type !== eventType) {\n return;\n }\n\n onStoreChange();\n },\n });\n },\n [chatStore, stableChatId],\n );\n\n const addToolResult = useCallback(\n (\n options: Omit<\n Parameters<\n ChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>['addToolResult']\n >[0],\n 'chatId'\n >,\n ) => chatStore.current.addToolResult({ chatId: stableChatId, ...options }),\n [chatStore, stableChatId],\n );\n\n const stopStream = useCallback(() => {\n chatStore.current.stopStream({ chatId: stableChatId });\n }, [chatStore, stableChatId]);\n\n const error = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'chat-status-changed',\n }),\n () => chatStore.current.getError(stableChatId),\n () => chatStore.current.getError(stableChatId),\n );\n\n const status = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'chat-status-changed',\n }),\n () => chatStore.current.getStatus(stableChatId),\n () => chatStore.current.getStatus(stableChatId),\n );\n\n const messages = useSyncExternalStore(\n callback => {\n return subscribe({\n onStoreChange: callback,\n eventType: 'chat-messages-changed',\n });\n },\n () => chatStore.current.getMessages(stableChatId),\n () => chatStore.current.getMessages(stableChatId),\n );\n\n const append = useCallback(\n (\n message: CreateUIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >,\n { headers, body }: ChatRequestOptions = {},\n ) =>\n chatStore.current.submitMessage({\n chatId: stableChatId,\n message,\n headers,\n body,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, stableChatId, onError, onToolCall, onFinish],\n );\n\n const reload = useCallback(\n async ({ headers, body }: ChatRequestOptions = {}) =>\n chatStore.current.resubmitLastUserMessage({\n chatId: stableChatId,\n headers,\n body,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, stableChatId, onError, onToolCall, onFinish],\n );\n const stop = useCallback(() => stopStream(), [stopStream]);\n\n const experimental_resume = useCallback(\n async () =>\n chatStore.current.resumeStream({\n chatId: stableChatId,\n onError,\n onToolCall,\n onFinish,\n }),\n [chatStore, stableChatId, onError, onToolCall, onFinish],\n );\n\n const setMessages = useCallback(\n (\n messagesParam:\n | UIMessage<MESSAGE_METADATA, InferUIDataTypes<DATA_TYPE_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataTypes<DATA_TYPE_SCHEMAS>\n >[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(messages);\n }\n\n chatStore.current.setMessages({\n id: stableChatId,\n messages: messagesParam,\n });\n },\n [stableChatId, messages],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions & {\n files?: FileList | FileUIPart[];\n } = {},\n ) => {\n event?.preventDefault?.();\n\n const fileParts = Array.isArray(options?.files)\n ? options.files\n : await convertFileListToFileUIParts(options?.files);\n\n if (!input && fileParts.length === 0) return;\n\n append(\n {\n id: generateId(),\n role: 'user',\n metadata: undefined,\n parts: [...fileParts, { type: 'text', text: input }],\n },\n {\n headers: options.headers,\n body: options.body,\n },\n );\n\n setInput('');\n },\n [input, generateId, append],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n return {\n messages,\n chatId: stableChatId,\n setMessages,\n error,\n append,\n reload,\n stop,\n experimental_resume,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n status,\n addToolResult,\n };\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<RESULT, INPUT = any>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";AACA;AAAA,EAEE;AAAA,EACA;AAAA,EACA,cAAc;AAAA,OAST;AACP,SAAS,aAAa,QAAQ,UAAU,4BAA4B;AAmH7D,SAAS,QAGd;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,WAAW;AACb,IAMI,CAAC,GAAwD;AAE3D,QAAM,CAAC,MAAM,IAAI,SAAS,UAAU;AAGpC,QAAM,eAAe,0BAAU;AAI/B,QAAM,YAAY;AAAA,IAChB,sCACE,iBAAsD;AAAA,MACpD,KAAK;AAAA,MACL;AAAA,IACF,CAAC;AAAA,EACL;AAGA,MAAI,CAAC,UAAU,QAAQ,QAAQ,YAAY,GAAG;AAC5C,cAAU,QAAQ,QAAQ,cAAc,CAAC,CAAC;AAAA,EAC5C;AAEA,QAAM,YAAY;AAAA,IAChB,CAAC;AAAA,MACC;AAAA,MACA;AAAA,IACF,MAGM;AACJ,aAAO,UAAU,QAAQ,UAAU;AAAA,QACjC,eAAe,WAAS;AACtB,cAAI,MAAM,WAAW,gBAAgB,MAAM,SAAS,WAAW;AAC7D;AAAA,UACF;AAEA,wBAAc;AAAA,QAChB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA,CAAC,WAAW,YAAY;AAAA,EAC1B;AAEA,QAAM,gBAAgB;AAAA,IACpB,CACE,YAMG,UAAU,QAAQ,cAAc,EAAE,QAAQ,cAAc,GAAG,QAAQ,CAAC;AAAA,IACzE,CAAC,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AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useRef","useState","fetch","useState","useRef","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit as BaseChatInit,\n ChatEvent,\n InferUIDataParts,\n UIDataPartSchemas,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\nimport { throttle } from './throttle';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<\n MESSAGE_METADATA = unknown,\n DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages:\n | UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<MESSAGE_METADATA, DATA_PART_SCHEMAS>,\n | 'sendMessage'\n | 'reload'\n | 'stop'\n | 'experimental_resume'\n | 'addToolResult'\n | 'status'\n | 'messages'\n>;\n\nexport type UseChatOptions<\n MESSAGE_METADATA = unknown,\n DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n> = (\n | { chat: Chat<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> }\n | BaseChatInit<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n};\n\nexport function useChat<\n MESSAGE_METADATA = unknown,\n DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n>({\n experimental_throttle: throttleWaitMs,\n ...options\n}: UseChatOptions<MESSAGE_METADATA, DATA_PART_SCHEMAS> = {}): UseChatHelpers<\n MESSAGE_METADATA,\n DATA_PART_SCHEMAS\n> {\n const chatRef = useRef('chat' in options ? options.chat : new Chat(options));\n\n const subscribe = useCallback(\n ({\n onStoreChange,\n eventType,\n }: {\n onStoreChange: () => void;\n eventType: ChatEvent['type'];\n }) =>\n chatRef.current.subscribe({\n onChange: event => {\n if (event.type !== eventType) return;\n onStoreChange();\n },\n }),\n [chatRef],\n );\n\n const addToolResult = useCallback(\n (\n options: Parameters<\n Chat<MESSAGE_METADATA, DATA_PART_SCHEMAS>['addToolResult']\n >[0],\n ) => chatRef.current.addToolResult(options),\n [chatRef],\n );\n\n const status = useSyncExternalStore(\n callback =>\n subscribe({\n onStoreChange: callback,\n eventType: 'status-changed',\n }),\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const subscribeToChatStoreForMessages = useCallback(\n (callback: () => void) => {\n return subscribe({\n onStoreChange: throttleWaitMs\n ? throttle(callback, throttleWaitMs)\n : callback,\n eventType: 'messages-changed',\n });\n },\n [subscribe, throttleWaitMs],\n );\n\n const messages = useSyncExternalStore(\n callback => subscribeToChatStoreForMessages(callback),\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const setMessages = useCallback(\n (\n messagesParam:\n | UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_PART_SCHEMAS>>[]\n | ((\n messages: UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[],\n ) => UIMessage<\n MESSAGE_METADATA,\n InferUIDataParts<DATA_PART_SCHEMAS>\n >[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(messages);\n }\n\n chatRef.current.messages = messagesParam;\n },\n [chatRef, messages],\n );\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n reload: chatRef.current.reload,\n stop: chatRef.current.stop,\n error: chatRef.current.error,\n experimental_resume: chatRef.current.experimental_resume,\n status,\n addToolResult,\n };\n}\n","import {\n AbstractChat,\n ChatInit,\n ChatState,\n ChatStatus,\n UIDataPartSchemas,\n UIDataTypes,\n UIMessage,\n} from 'ai';\n\nclass ReactChatState<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes>\n implements ChatState<MESSAGE_METADATA, DATA_TYPES>\n{\n #messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];\n status: ChatStatus = 'ready';\n error: Error | undefined = undefined;\n\n constructor(messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[] = []) {\n this.#messages = messages;\n }\n\n get messages() {\n return this.#messages;\n }\n\n set messages(messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[]) {\n this.#messages = [...messages];\n }\n\n pushMessage = (message: UIMessage<MESSAGE_METADATA, DATA_TYPES>) => {\n this.#messages = this.messages.concat(message);\n };\n\n popMessage = () => {\n this.#messages = this.messages.slice(0, -1);\n };\n\n replaceMessage = (\n index: number,\n message: UIMessage<MESSAGE_METADATA, DATA_TYPES>,\n ) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n message,\n ...this.#messages.slice(index + 1),\n ];\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n}\n\nexport class Chat<\n MESSAGE_METADATA,\n UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas,\n> extends AbstractChat<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS> {\n constructor({\n messages,\n ...init\n }: ChatInit<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>) {\n super({ ...init, state: new ReactChatState(messages) });\n }\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4/core';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends z4.$ZodType | z3.Schema | Schema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n};\n\nfunction useObject<\n SCHEMA extends z4.$ZodType | z3.Schema | Schema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AASA,SAAS,aAAa,QAAQ,4BAA4B;;;ACT1D;AAAA,EACE;AAAA,OAOK;AARP;AAUA,IAAM,iBAAN,MAEA;AAAA,EAKE,YAAY,WAAsD,CAAC,GAAG;AAJtE;AACA,kBAAqB;AACrB,iBAA2B;AAc3B,uBAAc,CAAC,YAAqD;AAClE,yBAAK,WAAY,KAAK,SAAS,OAAO,OAAO;AAAA,IAC/C;AAEA,sBAAa,MAAM;AACjB,yBAAK,WAAY,KAAK,SAAS,MAAM,GAAG,EAAE;AAAA,IAC5C;AAEA,0BAAiB,CACf,OACA,YACG;AACH,yBAAK,WAAY;AAAA,Q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AmB;AAEnB,kBAAM,EAAE,MAAM,IAAI,MAAM,iBAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,CAAC,gBAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,MAAM,kBAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,QAAQ,SAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASC,QAAO;AACd,UAAI,aAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["options","useCallback","useRef","fetch","useRef","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "2.0.0-alpha.1",
3
+ "version": "2.0.0-alpha.10",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "swr": "^2.2.5",
23
23
  "throttleit": "2.1.0",
24
- "ai": "5.0.0-alpha.1",
25
- "@ai-sdk/provider-utils": "3.0.0-alpha.1"
24
+ "ai": "5.0.0-alpha.10",
25
+ "@ai-sdk/provider-utils": "3.0.0-alpha.10"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@testing-library/jest-dom": "^6.6.3",
@@ -37,13 +37,13 @@
37
37
  "react-dom": "^18",
38
38
  "tsup": "^7.2.0",
39
39
  "typescript": "5.8.3",
40
- "zod": "3.24.4",
40
+ "zod": "3.25.49",
41
41
  "@vercel/ai-tsconfig": "0.0.0",
42
42
  "eslint-config-vercel-ai": "0.0.0"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "react": "^18 || ^19 || ^19.0.0-rc",
46
- "zod": "^3.23.8"
46
+ "zod": "^3.25.49"
47
47
  },
48
48
  "peerDependenciesMeta": {
49
49
  "zod": {
@@ -70,7 +70,7 @@
70
70
  ],
71
71
  "scripts": {
72
72
  "build": "pnpm clean && tsup --tsconfig tsconfig.build.json",
73
- "build:watch": "pnpm clean && tsup --watch",
73
+ "build:watch": "pnpm clean && tsup --watch --tsconfig tsconfig.build.json",
74
74
  "clean": "rm -rf dist *.tsbuildinfo",
75
75
  "lint": "eslint \"./**/*.ts*\"",
76
76
  "type-check": "tsc --build",