@ai-sdk/svelte 3.0.0-canary.9 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +929 -0
  2. package/README.md +5 -5
  3. package/dist/chat.svelte.d.ts +4 -73
  4. package/dist/chat.svelte.d.ts.map +1 -1
  5. package/dist/chat.svelte.js +23 -243
  6. package/dist/completion.svelte.d.ts +2 -9
  7. package/dist/completion.svelte.d.ts.map +1 -1
  8. package/dist/completion.svelte.js +4 -22
  9. package/dist/context-provider.d.ts.map +1 -1
  10. package/dist/context-provider.js +0 -3
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/structured-object.svelte.d.ts +11 -6
  15. package/dist/structured-object.svelte.d.ts.map +1 -1
  16. package/dist/structured-object.svelte.js +17 -7
  17. package/dist/tests/structured-object-synchronization.svelte.d.ts +2 -2
  18. package/dist/utils.svelte.js +1 -1
  19. package/package.json +8 -8
  20. package/src/chat.svelte.ts +32 -331
  21. package/src/completion.svelte.ts +10 -27
  22. package/src/context-provider.ts +0 -4
  23. package/src/index.ts +3 -12
  24. package/src/structured-object.svelte.ts +36 -13
  25. package/src/utils.svelte.ts +1 -1
  26. package/dist/chat-context.svelte.d.ts +0 -14
  27. package/dist/chat-context.svelte.d.ts.map +0 -1
  28. package/dist/chat-context.svelte.js +0 -13
  29. package/dist/completion-context.svelte.d.ts +0 -15
  30. package/dist/completion-context.svelte.d.ts.map +0 -1
  31. package/dist/tests/chat-synchronization.svelte +0 -12
  32. package/dist/tests/chat-synchronization.svelte.d.ts +0 -11
  33. package/dist/tests/chat-synchronization.svelte.d.ts.map +0 -1
  34. package/src/chat-context.svelte.ts +0 -23
  35. package/src/tests/chat-synchronization.svelte +0 -12
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # AI SDK: Svelte provider
2
2
 
3
- [Svelte](https://svelte.dev/) UI components for the [AI SDK](https://sdk.vercel.ai/docs):
3
+ [Svelte](https://svelte.dev/) UI components for the [AI SDK](https://ai-sdk.dev/docs):
4
4
 
5
- - [`Chat`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-chat)
6
- - [`Completion`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion)
7
- - [`StructuredObject`](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-object)
5
+ - [`Chat`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat)
6
+ - [`Completion`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-completion)
7
+ - [`StructuredObject`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-object)
8
8
 
9
- For information on the few ways the Svelte APIs differ from the React ones, see [the docs](https://sdk.vercel.ai/docs/getting-started/svelte#how-does-ai-sdksvelte-differ-from-ai-sdkreact)
9
+ For information on the few ways the Svelte APIs differ from the React ones, see [the docs](https://ai-sdk.dev/docs/getting-started/svelte#how-does-ai-sdksvelte-differ-from-ai-sdkreact)
@@ -1,75 +1,6 @@
1
- import { type UIMessage, type UseChatOptions, type JSONValue, type Message, type CreateMessage, type ChatRequestOptions } from 'ai';
2
- export type ChatOptions = Readonly<Omit<UseChatOptions, 'keepLastMessageOnError'> & {
3
- /**
4
- * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
5
- * Must be at least 1.
6
- * A maximum number is required to prevent infinite loops in the case of misconfigured tools.
7
- * By default, it's set to 1, which means that only a single LLM call is made.
8
- * @default 1
9
- */
10
- maxSteps?: number;
11
- }>;
12
- export type { CreateMessage, Message, UIMessage };
13
- export declare class Chat {
14
- #private;
15
- /**
16
- * The id of the chat. If not provided through the constructor, a random ID will be generated
17
- * using the provided `generateId` function, or a built-in function if not provided.
18
- */
19
- readonly id: string;
20
- /**
21
- * Additional data added on the server via StreamData.
22
- *
23
- * This is writable, so you can use it to transform or clear the chat data.
24
- */
25
- get data(): JSONValue[] | undefined;
26
- set data(value: JSONValue[] | undefined);
27
- /**
28
- * Hook status:
29
- *
30
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
31
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
32
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
33
- * - `error`: An error occurred during the API request, preventing successful completion.
34
- */
35
- get status(): "submitted" | "streaming" | "ready" | "error";
36
- /** The error object of the API request */
37
- get error(): Error | undefined;
38
- /** The current value of the input. Writable, so it can be bound to form inputs. */
39
- input: string;
40
- /**
41
- * Current messages in the chat.
42
- *
43
- * This is writable, which is useful when you want to edit the messages on the client, and then
44
- * trigger {@link reload} to regenerate the AI response.
45
- */
46
- get messages(): UIMessage[];
47
- set messages(value: Message[]);
48
- constructor(options?: ChatOptions);
49
- /**
50
- * Append a user message to the chat list. This triggers the API call to fetch
51
- * the assistant's response.
52
- * @param message The message to append
53
- * @param options Additional options to pass to the API call
54
- */
55
- append: (message: Message | CreateMessage, { data, headers, body, experimental_attachments }?: ChatRequestOptions) => Promise<void>;
56
- /**
57
- * Reload the last AI chat response for the given chat history. If the last
58
- * message isn't from the assistant, it will request the API to generate a
59
- * new response.
60
- */
61
- reload: ({ data, headers, body }?: ChatRequestOptions) => Promise<void>;
62
- /**
63
- * Abort the current request immediately, keep the generated tokens if any.
64
- */
65
- stop: () => void;
66
- /** Form submission handler to automatically reset input and append a user message */
67
- handleSubmit: (event?: {
68
- preventDefault?: () => void;
69
- }, options?: ChatRequestOptions) => Promise<void>;
70
- addToolResult: ({ toolCallId, result, }: {
71
- toolCallId: string;
72
- result: unknown;
73
- }) => Promise<void>;
1
+ import { AbstractChat, type ChatInit, type CreateUIMessage, type UIMessage } from 'ai';
2
+ export type { CreateUIMessage, UIMessage };
3
+ export declare class Chat<UI_MESSAGE extends UIMessage = UIMessage> extends AbstractChat<UI_MESSAGE> {
4
+ constructor(init: ChatInit<UI_MESSAGE>);
74
5
  }
75
6
  //# sourceMappingURL=chat.svelte.d.ts.map
@@ -1 +1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,OAAO,CAAC;KACjB,mBAmBC;CAmHH"}
1
+ {"version":3,"file":"chat.svelte.d.ts","sourceRoot":"","sources":["../src/chat.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,KAAK,QAAQ,EAGb,KAAK,eAAe,EACpB,KAAK,SAAS,EACf,MAAM,IAAI,CAAC;AAEZ,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAE3C,qBAAa,IAAI,CACf,UAAU,SAAS,SAAS,GAAG,SAAS,CACxC,SAAQ,YAAY,CAAC,UAAU,CAAC;gBACpB,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC;CAMvC"}
@@ -1,250 +1,30 @@
1
- import { fillMessageParts, generateId, extractMaxToolInvocationStep, callChatApi, shouldResubmitMessages, prepareAttachmentsForRequest, getMessageParts, updateToolCallResult, isAssistantMessageWithCompletedToolCalls, } from 'ai';
2
- import { isAbortError } from '@ai-sdk/provider-utils';
3
- import { KeyedChatStore, getChatContext, hasChatContext, } from './chat-context.svelte.js';
4
- import { untrack } from 'svelte';
5
- export class Chat {
6
- #options = {};
7
- #api = $derived(this.#options.api ?? '/api/chat');
8
- #generateId = $derived(this.#options.generateId ?? generateId);
9
- #maxSteps = $derived(this.#options.maxSteps ?? 1);
10
- #streamProtocol = $derived(this.#options.streamProtocol ?? 'data');
11
- #keyedStore = $state();
12
- /**
13
- * The id of the chat. If not provided through the constructor, a random ID will be generated
14
- * using the provided `generateId` function, or a built-in function if not provided.
15
- */
16
- id = $derived(this.#options.id ?? this.#generateId());
17
- #store = $derived(this.#keyedStore.get(this.id));
18
- #abortController;
19
- /**
20
- * Additional data added on the server via StreamData.
21
- *
22
- * This is writable, so you can use it to transform or clear the chat data.
23
- */
24
- get data() {
25
- return this.#store.data;
26
- }
27
- set data(value) {
28
- this.#store.data = value;
29
- }
30
- /**
31
- * Hook status:
32
- *
33
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
34
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
35
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
36
- * - `error`: An error occurred during the API request, preventing successful completion.
37
- */
38
- get status() {
39
- return this.#store.status;
40
- }
41
- /** The error object of the API request */
42
- get error() {
43
- return this.#store.error;
44
- }
45
- /** The current value of the input. Writable, so it can be bound to form inputs. */
46
- input = $state();
47
- /**
48
- * Current messages in the chat.
49
- *
50
- * This is writable, which is useful when you want to edit the messages on the client, and then
51
- * trigger {@link reload} to regenerate the AI response.
52
- */
53
- get messages() {
54
- return this.#store.messages;
55
- }
56
- set messages(value) {
57
- untrack(() => (this.#store.messages = fillMessageParts(value)));
1
+ import { AbstractChat, } from 'ai';
2
+ export class Chat extends AbstractChat {
3
+ constructor(init) {
4
+ super({
5
+ ...init,
6
+ state: new SvelteChatState(init.messages),
7
+ });
58
8
  }
59
- constructor(options = {}) {
60
- if (hasChatContext()) {
61
- this.#keyedStore = getChatContext();
62
- }
63
- else {
64
- this.#keyedStore = new KeyedChatStore();
65
- }
66
- this.#options = options;
67
- this.messages = options.initialMessages ?? [];
68
- this.input = options.initialInput ?? '';
9
+ }
10
+ class SvelteChatState {
11
+ messages;
12
+ status = $state('ready');
13
+ error = $state(undefined);
14
+ constructor(messages = []) {
15
+ this.messages = $state(messages);
69
16
  }
70
- /**
71
- * Append a user message to the chat list. This triggers the API call to fetch
72
- * the assistant's response.
73
- * @param message The message to append
74
- * @param options Additional options to pass to the API call
75
- */
76
- append = async (message, { data, headers, body, experimental_attachments } = {}) => {
77
- const attachmentsForRequest = await prepareAttachmentsForRequest(experimental_attachments);
78
- const messages = this.messages.concat({
79
- ...message,
80
- id: message.id ?? this.#generateId(),
81
- createdAt: message.createdAt ?? new Date(),
82
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,
83
- parts: getMessageParts(message),
84
- });
85
- return this.#triggerRequest({ messages, headers, body, data });
86
- };
87
- /**
88
- * Reload the last AI chat response for the given chat history. If the last
89
- * message isn't from the assistant, it will request the API to generate a
90
- * new response.
91
- */
92
- reload = async ({ data, headers, body } = {}) => {
93
- if (this.messages.length === 0) {
94
- return;
95
- }
96
- const lastMessage = this.messages[this.messages.length - 1];
97
- await this.#triggerRequest({
98
- messages: lastMessage.role === 'assistant'
99
- ? this.messages.slice(0, -1)
100
- : this.messages,
101
- headers,
102
- body,
103
- data,
104
- });
17
+ setMessages = (messages) => {
18
+ this.messages = messages;
105
19
  };
106
- /**
107
- * Abort the current request immediately, keep the generated tokens if any.
108
- */
109
- stop = () => {
110
- try {
111
- this.#abortController?.abort();
112
- }
113
- catch {
114
- // ignore
115
- }
116
- finally {
117
- this.#store.status = 'ready';
118
- this.#abortController = undefined;
119
- }
20
+ pushMessage = (message) => {
21
+ this.messages.push(message);
120
22
  };
121
- /** Form submission handler to automatically reset input and append a user message */
122
- handleSubmit = async (event, options = {}) => {
123
- event?.preventDefault?.();
124
- if (!this.input && !options.allowEmptySubmit)
125
- return;
126
- const attachmentsForRequest = await prepareAttachmentsForRequest(options.experimental_attachments);
127
- const messages = this.messages.concat({
128
- id: this.#generateId(),
129
- createdAt: new Date(),
130
- role: 'user',
131
- content: this.input,
132
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,
133
- parts: [{ type: 'text', text: this.input }],
134
- });
135
- const chatRequest = {
136
- messages,
137
- headers: options.headers,
138
- body: options.body,
139
- data: options.data,
140
- };
141
- const request = this.#triggerRequest(chatRequest);
142
- this.input = '';
143
- await request;
144
- };
145
- addToolResult = async ({ toolCallId, result, }) => {
146
- updateToolCallResult({
147
- messages: this.messages,
148
- toolCallId,
149
- toolResult: result,
150
- });
151
- // when the request is ongoing, the auto-submit will be triggered after the request is finished
152
- if (this.#store.status === 'submitted' ||
153
- this.#store.status === 'streaming') {
154
- return;
155
- }
156
- const lastMessage = this.messages[this.messages.length - 1];
157
- if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
158
- await this.#triggerRequest({ messages: this.messages });
159
- }
23
+ popMessage = () => {
24
+ this.messages.pop();
160
25
  };
161
- #triggerRequest = async (chatRequest) => {
162
- this.#store.status = 'submitted';
163
- this.#store.error = undefined;
164
- const messages = fillMessageParts(chatRequest.messages);
165
- const messageCount = messages.length;
166
- const maxStep = extractMaxToolInvocationStep(messages[messages.length - 1]?.toolInvocations);
167
- try {
168
- const abortController = new AbortController();
169
- this.#abortController = abortController;
170
- // Optimistically update messages
171
- this.messages = messages;
172
- const constructedMessagesPayload = this.#options.sendExtraMessageFields
173
- ? messages
174
- : messages.map(({ role, content, experimental_attachments, data, annotations, toolInvocations, parts, }) => ({
175
- role,
176
- content,
177
- ...(experimental_attachments !== undefined && {
178
- experimental_attachments,
179
- }),
180
- ...(data !== undefined && { data }),
181
- ...(annotations !== undefined && { annotations }),
182
- ...(toolInvocations !== undefined && { toolInvocations }),
183
- ...(parts !== undefined && { parts }),
184
- }));
185
- const existingData = this.data ?? [];
186
- await callChatApi({
187
- api: this.#api,
188
- body: {
189
- id: this.id,
190
- messages: constructedMessagesPayload,
191
- data: chatRequest.data,
192
- ...$state.snapshot(this.#options.body),
193
- ...chatRequest.body,
194
- },
195
- streamProtocol: this.#streamProtocol,
196
- credentials: this.#options.credentials,
197
- headers: {
198
- ...this.#options.headers,
199
- ...chatRequest.headers,
200
- },
201
- abortController: () => abortController,
202
- restoreMessagesOnFailure: () => { },
203
- onResponse: this.#options.onResponse,
204
- onUpdate: ({ message, data, replaceLastMessage }) => {
205
- this.#store.status = 'streaming';
206
- this.messages = messages;
207
- if (replaceLastMessage) {
208
- this.messages[this.messages.length - 1] = message;
209
- }
210
- else {
211
- this.messages.push(message);
212
- }
213
- if (data?.length) {
214
- this.data = existingData;
215
- this.data.push(...data);
216
- }
217
- },
218
- onToolCall: this.#options.onToolCall,
219
- onFinish: this.#options.onFinish,
220
- generateId: this.#generateId,
221
- fetch: this.#options.fetch,
222
- // callChatApi calls structuredClone on the message
223
- lastMessage: $state.snapshot(this.messages[this.messages.length - 1]),
224
- });
225
- this.#abortController = undefined;
226
- this.#store.status = 'ready';
227
- }
228
- catch (error) {
229
- if (isAbortError(error)) {
230
- return;
231
- }
232
- const coalescedError = error instanceof Error ? error : new Error(String(error));
233
- if (this.#options.onError) {
234
- this.#options.onError(coalescedError);
235
- }
236
- this.#store.status = 'error';
237
- this.#store.error = coalescedError;
238
- }
239
- // auto-submit when all tool calls in the last assistant message have results
240
- // and assistant has not answered yet
241
- if (shouldResubmitMessages({
242
- originalMaxToolInvocationStep: maxStep,
243
- originalMessageCount: messageCount,
244
- maxSteps: this.#maxSteps,
245
- messages: this.messages,
246
- })) {
247
- await this.#triggerRequest({ messages: this.messages });
248
- }
26
+ replaceMessage = (index, message) => {
27
+ this.messages[index] = message;
249
28
  };
29
+ snapshot = (thing) => $state.snapshot(thing);
250
30
  }
@@ -1,17 +1,10 @@
1
- import { type UseCompletionOptions, type JSONValue, type RequestOptions } from 'ai';
1
+ import { type CompletionRequestOptions, type UseCompletionOptions } from 'ai';
2
2
  export type CompletionOptions = Readonly<UseCompletionOptions>;
3
3
  export declare class Completion {
4
4
  #private;
5
5
  /** The current completion result */
6
6
  get completion(): string;
7
7
  set completion(value: string);
8
- /**
9
- * Additional data added on the server via StreamData.
10
- *
11
- * This is writable, so you can use it to transform or clear the chat data.
12
- */
13
- get data(): JSONValue[];
14
- set data(value: JSONValue[]);
15
8
  /** The error object of the API request */
16
9
  get error(): Error | undefined;
17
10
  /** The current value of the input. Writable, so it can be bound to form inputs. */
@@ -28,7 +21,7 @@ export declare class Completion {
28
21
  /**
29
22
  * Send a new prompt to the API endpoint and update the completion state.
30
23
  */
31
- complete: (prompt: string, options?: RequestOptions) => Promise<string | null | undefined>;
24
+ complete: (prompt: string, options?: CompletionRequestOptions) => Promise<string | null | undefined>;
32
25
  /** Form submission handler to automatically reset input and call the completion API */
33
26
  handleSubmit: (event?: {
34
27
  preventDefault?: () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"completion.svelte.d.ts","sourceRoot":"","sources":["../src/completion.svelte.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H,IAAI,aASF;IAEF;;OAEG;IACH,QAAQ,WAAkB,MAAM,YAAY,wBAAwB,wCAC5B;IAExC,uFAAuF;IACvF,YAAY,WAAkB;QAAE,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;KAAE,mBAK3D;CAkCH"}
@@ -1,4 +1,4 @@
1
- import { generateId, callCompletionApi, } from 'ai';
1
+ import { callCompletionApi, generateId, } from 'ai';
2
2
  import { KeyedCompletionStore, getCompletionContext, hasCompletionContext, } from './completion-context.svelte.js';
3
3
  export class Completion {
4
4
  #options = {};
@@ -15,17 +15,6 @@ export class Completion {
15
15
  set completion(value) {
16
16
  this.#store.completions.set(this.#id, value);
17
17
  }
18
- /**
19
- * Additional data added on the server via StreamData.
20
- *
21
- * This is writable, so you can use it to transform or clear the chat data.
22
- */
23
- get data() {
24
- return this.#store.data;
25
- }
26
- set data(value) {
27
- this.#store.data = value;
28
- }
29
18
  /** The error object of the API request */
30
19
  get error() {
31
20
  return this.#store.error;
@@ -39,12 +28,9 @@ export class Completion {
39
28
  return this.#store.loading;
40
29
  }
41
30
  constructor(options = {}) {
42
- if (hasCompletionContext()) {
43
- this.#keyedStore = getCompletionContext();
44
- }
45
- else {
46
- this.#keyedStore = new KeyedCompletionStore();
47
- }
31
+ this.#keyedStore = hasCompletionContext()
32
+ ? getCompletionContext()
33
+ : new KeyedCompletionStore();
48
34
  this.#options = options;
49
35
  this.completion = options.initialCompletion ?? '';
50
36
  this.input = options.initialInput ?? '';
@@ -91,9 +77,6 @@ export class Completion {
91
77
  setCompletion: completion => {
92
78
  this.completion = completion;
93
79
  },
94
- onData: data => {
95
- this.data.push(...data);
96
- },
97
80
  setLoading: loading => {
98
81
  this.#store.loading = loading;
99
82
  },
@@ -103,7 +86,6 @@ export class Completion {
103
86
  setAbortController: abortController => {
104
87
  this.#abortController = abortController ?? undefined;
105
88
  },
106
- onResponse: this.#options.onResponse,
107
89
  onFinish: this.#options.onFinish,
108
90
  onError: this.#options.onError,
109
91
  });
@@ -1 +1 @@
1
- {"version":3,"file":"context-provider.d.ts","sourceRoot":"","sources":["../src/context-provider.ts"],"names":[],"mappings":"AAUA,wBAAgB,eAAe,SAS9B"}
1
+ {"version":3,"file":"context-provider.d.ts","sourceRoot":"","sources":["../src/context-provider.ts"],"names":[],"mappings":"AASA,wBAAgB,eAAe,SAM9B"}
@@ -1,9 +1,6 @@
1
- import { KeyedChatStore, setChatContext } from './chat-context.svelte.js';
2
1
  import { KeyedCompletionStore, setCompletionContext, } from './completion-context.svelte.js';
3
2
  import { KeyedStructuredObjectStore, setStructuredObjectContext, } from './structured-object-context.svelte.js';
4
3
  export function createAIContext() {
5
- const chatStore = new KeyedChatStore();
6
- setChatContext(chatStore);
7
4
  const completionStore = new KeyedCompletionStore();
8
5
  setCompletionContext(completionStore);
9
6
  const objectStore = new KeyedStructuredObjectStore();
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { Chat, type ChatOptions, type CreateMessage, type Message, type UIMessage, } from './chat.svelte.js';
2
- export { StructuredObject as Experimental_StructuredObject, type Experimental_StructuredObjectOptions, } from './structured-object.svelte.js';
1
+ export { Chat, type CreateUIMessage, type UIMessage } from './chat.svelte.js';
3
2
  export { Completion, type CompletionOptions } from './completion.svelte.js';
4
3
  export { createAIContext } from './context-provider.js';
4
+ export { StructuredObject as Experimental_StructuredObject, type Experimental_StructuredObjectOptions, } from './structured-object.svelte.js';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,OAAO,EACZ,KAAK,SAAS,GACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,gBAAgB,IAAI,6BAA6B,EACjD,KAAK,oCAAoC,GAC1C,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EACL,gBAAgB,IAAI,6BAA6B,EACjD,KAAK,oCAAoC,GAC1C,MAAM,+BAA+B,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { Chat, } from './chat.svelte.js';
2
- export { StructuredObject as Experimental_StructuredObject, } from './structured-object.svelte.js';
1
+ export { Chat } from './chat.svelte.js';
3
2
  export { Completion } from './completion.svelte.js';
4
3
  export { createAIContext } from './context-provider.js';
4
+ export { StructuredObject as Experimental_StructuredObject, } from './structured-object.svelte.js';
@@ -1,7 +1,8 @@
1
- import { type FetchFunction } from '@ai-sdk/provider-utils';
1
+ import { type FetchFunction, type InferSchema } from '@ai-sdk/provider-utils';
2
2
  import { type DeepPartial, type Schema } from 'ai';
3
- import { type z } from 'zod';
4
- export type Experimental_StructuredObjectOptions<RESULT> = {
3
+ import type * as z3 from 'zod/v3';
4
+ import type * as z4 from 'zod/v4';
5
+ export type Experimental_StructuredObjectOptions<SCHEMA extends z3.Schema | z4.core.$ZodType | Schema, RESULT = InferSchema<SCHEMA>> = {
5
6
  /**
6
7
  * The API endpoint. It should stream JSON that matches the schema as chunked text.
7
8
  */
@@ -9,7 +10,7 @@ export type Experimental_StructuredObjectOptions<RESULT> = {
9
10
  /**
10
11
  * A Zod schema that defines the shape of the complete object.
11
12
  */
12
- schema: z.Schema<RESULT, z.ZodTypeDef, unknown> | Schema<RESULT>;
13
+ schema: SCHEMA;
13
14
  /**
14
15
  * An unique identifier. If not provided, a random one will be
15
16
  * generated. When provided, the `useObject` hook with the same `id` will
@@ -54,7 +55,7 @@ export type Experimental_StructuredObjectOptions<RESULT> = {
54
55
  */
55
56
  credentials?: RequestCredentials;
56
57
  };
57
- export declare class StructuredObject<RESULT, INPUT = unknown> {
58
+ export declare class StructuredObject<SCHEMA extends z3.Schema | z4.core.$ZodType | Schema, RESULT = InferSchema<SCHEMA>, INPUT = unknown> {
58
59
  #private;
59
60
  /**
60
61
  * The current value for the generated object. Updated as the API streams JSON chunks.
@@ -66,7 +67,7 @@ export declare class StructuredObject<RESULT, INPUT = unknown> {
66
67
  * Flag that indicates whether an API request is in progress.
67
68
  */
68
69
  get loading(): boolean;
69
- constructor(options: Experimental_StructuredObjectOptions<RESULT>);
70
+ constructor(options: Experimental_StructuredObjectOptions<SCHEMA, RESULT>);
70
71
  /**
71
72
  * Abort the current request immediately, keep the current partial object if any.
72
73
  */
@@ -75,5 +76,9 @@ export declare class StructuredObject<RESULT, INPUT = unknown> {
75
76
  * Calls the API with the provided input as JSON body.
76
77
  */
77
78
  submit: (input: INPUT) => Promise<void>;
79
+ /**
80
+ * Clears the object state.
81
+ */
82
+ clear: () => void;
78
83
  }
79
84
  //# sourceMappingURL=structured-object.svelte.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"structured-object.svelte.d.ts","sourceRoot":"","sources":["../src/structured-object.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,aAAa,EACnB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAIL,KAAK,WAAW,EAChB,KAAK,MAAM,EACZ,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,CAAC;AAQ7B,MAAM,MAAM,oCAAoC,CAAC,MAAM,IAAI;IACzD;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,MAAM,EAAE,CAAC,CAAC,MAAM,CA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,MAAM,IAAI,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAE5C;IAKD,0CAA0C;IAC1C,IAAI,KAAK,sBAER;IAED;;OAEG;IACH,IAAI,OAAO,YAEV;gBAEW,OAAO,EAAE,oCAAoC,CAAC,MAAM,EAAE,MAAM,CAAC;IAUzE;;OAEG;IACH,IAAI,aASF;IAEF;;OAEG;IACH,MAAM,UAAiB,KAAK,mBAqF1B;IAEF;;OAEG;IACH,KAAK,aAGH;CAOH"}
@@ -1,6 +1,5 @@
1
1
  import { generateId, isAbortError, safeValidateTypes, } from '@ai-sdk/provider-utils';
2
2
  import { asSchema, isDeepEqualData, parsePartialJson, } from 'ai';
3
- import {} from 'zod';
4
3
  import { getStructuredObjectContext, hasStructuredObjectContext, KeyedStructuredObjectStore, } from './structured-object-context.svelte.js';
5
4
  export class StructuredObject {
6
5
  #options = {};
@@ -57,9 +56,8 @@ export class StructuredObject {
57
56
  */
58
57
  submit = async (input) => {
59
58
  try {
60
- this.#store.object = undefined; // reset the data
59
+ this.#clearObject();
61
60
  this.#store.loading = true;
62
- this.#store.error = undefined;
63
61
  const abortController = new AbortController();
64
62
  this.#abortController = abortController;
65
63
  const actualFetch = this.#options.fetch ?? fetch;
@@ -82,23 +80,23 @@ export class StructuredObject {
82
80
  let accumulatedText = '';
83
81
  let latestObject = undefined;
84
82
  await response.body.pipeThrough(new TextDecoderStream()).pipeTo(new WritableStream({
85
- write: chunk => {
83
+ write: async (chunk) => {
86
84
  if (abortController?.signal.aborted) {
87
85
  throw new DOMException('Stream aborted', 'AbortError');
88
86
  }
89
87
  accumulatedText += chunk;
90
- const { value } = parsePartialJson(accumulatedText);
88
+ const { value } = await parsePartialJson(accumulatedText);
91
89
  const currentObject = value;
92
90
  if (!isDeepEqualData(latestObject, currentObject)) {
93
91
  latestObject = currentObject;
94
92
  this.#store.object = currentObject;
95
93
  }
96
94
  },
97
- close: () => {
95
+ close: async () => {
98
96
  this.#store.loading = false;
99
97
  this.#abortController = undefined;
100
98
  if (this.#options.onFinish != null) {
101
- const validationResult = safeValidateTypes({
99
+ const validationResult = await safeValidateTypes({
102
100
  value: latestObject,
103
101
  schema: asSchema(this.#options.schema),
104
102
  });
@@ -121,4 +119,16 @@ export class StructuredObject {
121
119
  this.#store.error = coalescedError;
122
120
  }
123
121
  };
122
+ /**
123
+ * Clears the object state.
124
+ */
125
+ clear = () => {
126
+ this.stop();
127
+ this.#clearObject();
128
+ };
129
+ #clearObject = () => {
130
+ this.#store.object = undefined;
131
+ this.#store.error = undefined;
132
+ this.#store.loading = false;
133
+ };
124
134
  }
@@ -11,8 +11,8 @@ declare class __sveltets_Render<RESULT> {
11
11
  slots(): {};
12
12
  bindings(): "";
13
13
  exports(): {
14
- object1: StructuredObject<RESULT, unknown>;
15
- object2: StructuredObject<RESULT, unknown>;
14
+ object1: StructuredObject<z.ZodType<RESULT, z.ZodTypeDef, unknown> | Schema<RESULT>, RESULT, unknown>;
15
+ object2: StructuredObject<z.ZodType<RESULT, z.ZodTypeDef, unknown> | Schema<RESULT>, RESULT, unknown>;
16
16
  };
17
17
  }
18
18
  interface $$IsomorphicComponent {
@@ -1,4 +1,4 @@
1
- import { hasContext, getContext, setContext, untrack } from 'svelte';
1
+ import { getContext, hasContext, setContext, untrack } from 'svelte';
2
2
  import { SvelteMap } from 'svelte/reactivity';
3
3
  export function createContext(name) {
4
4
  const key = Symbol(name);