@ai-sdk/svelte 0.0.0-02dba89b-20251009204516

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 (42) hide show
  1. package/CHANGELOG.md +2425 -0
  2. package/LICENSE +13 -0
  3. package/README.md +9 -0
  4. package/dist/chat.svelte.d.ts +6 -0
  5. package/dist/chat.svelte.d.ts.map +1 -0
  6. package/dist/chat.svelte.js +30 -0
  7. package/dist/completion-context.svelte.js +14 -0
  8. package/dist/completion.svelte.d.ts +30 -0
  9. package/dist/completion.svelte.d.ts.map +1 -0
  10. package/dist/completion.svelte.js +93 -0
  11. package/dist/context-provider.d.ts +2 -0
  12. package/dist/context-provider.d.ts.map +1 -0
  13. package/dist/context-provider.js +8 -0
  14. package/dist/index.d.ts +5 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +4 -0
  17. package/dist/structured-object-context.svelte.d.ts +12 -0
  18. package/dist/structured-object-context.svelte.d.ts.map +1 -0
  19. package/dist/structured-object-context.svelte.js +12 -0
  20. package/dist/structured-object.svelte.d.ts +84 -0
  21. package/dist/structured-object.svelte.d.ts.map +1 -0
  22. package/dist/structured-object.svelte.js +134 -0
  23. package/dist/tests/completion-synchronization.svelte +12 -0
  24. package/dist/tests/completion-synchronization.svelte.d.ts +11 -0
  25. package/dist/tests/completion-synchronization.svelte.d.ts.map +1 -0
  26. package/dist/tests/structured-object-synchronization.svelte +22 -0
  27. package/dist/tests/structured-object-synchronization.svelte.d.ts +28 -0
  28. package/dist/tests/structured-object-synchronization.svelte.d.ts.map +1 -0
  29. package/dist/utils.svelte.d.ts +17 -0
  30. package/dist/utils.svelte.d.ts.map +1 -0
  31. package/dist/utils.svelte.js +50 -0
  32. package/package.json +91 -0
  33. package/src/chat.svelte.ts +51 -0
  34. package/src/completion-context.svelte.ts +24 -0
  35. package/src/completion.svelte.ts +116 -0
  36. package/src/context-provider.ts +16 -0
  37. package/src/index.ts +7 -0
  38. package/src/structured-object-context.svelte.ts +27 -0
  39. package/src/structured-object.svelte.ts +253 -0
  40. package/src/tests/completion-synchronization.svelte +12 -0
  41. package/src/tests/structured-object-synchronization.svelte +22 -0
  42. package/src/utils.svelte.ts +66 -0
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023 Vercel, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # AI SDK: Svelte provider
2
+
3
+ [Svelte](https://svelte.dev/) UI components for the [AI SDK](https://ai-sdk.dev/docs):
4
+
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
+
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)
@@ -0,0 +1,6 @@
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>);
5
+ }
6
+ //# sourceMappingURL=chat.svelte.d.ts.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,30 @@
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
+ });
8
+ }
9
+ }
10
+ class SvelteChatState {
11
+ messages;
12
+ status = $state('ready');
13
+ error = $state(undefined);
14
+ constructor(messages = []) {
15
+ this.messages = $state(messages);
16
+ }
17
+ setMessages = (messages) => {
18
+ this.messages = messages;
19
+ };
20
+ pushMessage = (message) => {
21
+ this.messages.push(message);
22
+ };
23
+ popMessage = () => {
24
+ this.messages.pop();
25
+ };
26
+ replaceMessage = (index, message) => {
27
+ this.messages[index] = message;
28
+ };
29
+ snapshot = (thing) => $state.snapshot(thing);
30
+ }
@@ -0,0 +1,14 @@
1
+ import { SvelteMap } from 'svelte/reactivity';
2
+ import { createContext, KeyedStore } from './utils.svelte.js';
3
+ class CompletionStore {
4
+ completions = new SvelteMap();
5
+ data = $state([]);
6
+ loading = $state(false);
7
+ error = $state();
8
+ }
9
+ export class KeyedCompletionStore extends KeyedStore {
10
+ constructor(value) {
11
+ super(CompletionStore, value);
12
+ }
13
+ }
14
+ export const { hasContext: hasCompletionContext, getContext: getCompletionContext, setContext: setCompletionContext, } = createContext('Completion');
@@ -0,0 +1,30 @@
1
+ import { type CompletionRequestOptions, type UseCompletionOptions } from 'ai';
2
+ export type CompletionOptions = Readonly<UseCompletionOptions>;
3
+ export declare class Completion {
4
+ #private;
5
+ /** The current completion result */
6
+ get completion(): string;
7
+ set completion(value: string);
8
+ /** The error object of the API request */
9
+ get error(): Error | undefined;
10
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
11
+ input: string;
12
+ /**
13
+ * Flag that indicates whether an API request is in progress.
14
+ */
15
+ get loading(): boolean;
16
+ constructor(options?: CompletionOptions);
17
+ /**
18
+ * Abort the current request immediately, keep the generated tokens if any.
19
+ */
20
+ stop: () => void;
21
+ /**
22
+ * Send a new prompt to the API endpoint and update the completion state.
23
+ */
24
+ complete: (prompt: string, options?: CompletionRequestOptions) => Promise<string | null | undefined>;
25
+ /** Form submission handler to automatically reset input and call the completion API */
26
+ handleSubmit: (event?: {
27
+ preventDefault?: () => void;
28
+ }) => Promise<void>;
29
+ }
30
+ //# sourceMappingURL=completion.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"completion.svelte.d.ts","sourceRoot":"","sources":["../src/completion.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,EAC1B,MAAM,IAAI,CAAC;AAOZ,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC,oBAAoB,CAAC,CAAC;AAE/D,qBAAa,UAAU;;IASrB,oCAAoC;IACpC,IAAI,UAAU,IAAI,MAAM,CAEvB;IACD,IAAI,UAAU,CAAC,KAAK,EAAE,MAAM,EAE3B;IAED,0CAA0C;IAC1C,IAAI,KAAK,sBAER;IAED,mFAAmF;IACnF,KAAK,SAAqB;IAE1B;;OAEG;IACH,IAAI,OAAO,YAEV;gBAEW,OAAO,GAAE,iBAAsB;IAS3C;;OAEG;IACH,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"}
@@ -0,0 +1,93 @@
1
+ import { callCompletionApi, generateId, } from 'ai';
2
+ import { KeyedCompletionStore, getCompletionContext, hasCompletionContext, } from './completion-context.svelte.js';
3
+ export class Completion {
4
+ #options = {};
5
+ #api = $derived(this.#options.api ?? '/api/completion');
6
+ #id = $derived(this.#options.id ?? generateId());
7
+ #streamProtocol = $derived(this.#options.streamProtocol ?? 'data');
8
+ #keyedStore = $state();
9
+ #store = $derived(this.#keyedStore.get(this.#id));
10
+ #abortController;
11
+ /** The current completion result */
12
+ get completion() {
13
+ return this.#store.completions.get(this.#id) ?? '';
14
+ }
15
+ set completion(value) {
16
+ this.#store.completions.set(this.#id, value);
17
+ }
18
+ /** The error object of the API request */
19
+ get error() {
20
+ return this.#store.error;
21
+ }
22
+ /** The current value of the input. Writable, so it can be bound to form inputs. */
23
+ input = $state();
24
+ /**
25
+ * Flag that indicates whether an API request is in progress.
26
+ */
27
+ get loading() {
28
+ return this.#store.loading;
29
+ }
30
+ constructor(options = {}) {
31
+ this.#keyedStore = hasCompletionContext()
32
+ ? getCompletionContext()
33
+ : new KeyedCompletionStore();
34
+ this.#options = options;
35
+ this.completion = options.initialCompletion ?? '';
36
+ this.input = options.initialInput ?? '';
37
+ }
38
+ /**
39
+ * Abort the current request immediately, keep the generated tokens if any.
40
+ */
41
+ stop = () => {
42
+ try {
43
+ this.#abortController?.abort();
44
+ }
45
+ catch {
46
+ // ignore
47
+ }
48
+ finally {
49
+ this.#store.loading = false;
50
+ this.#abortController = undefined;
51
+ }
52
+ };
53
+ /**
54
+ * Send a new prompt to the API endpoint and update the completion state.
55
+ */
56
+ complete = async (prompt, options) => this.#triggerRequest(prompt, options);
57
+ /** Form submission handler to automatically reset input and call the completion API */
58
+ handleSubmit = async (event) => {
59
+ event?.preventDefault?.();
60
+ if (this.input) {
61
+ await this.complete(this.input);
62
+ }
63
+ };
64
+ #triggerRequest = async (prompt, options) => {
65
+ return callCompletionApi({
66
+ api: this.#api,
67
+ prompt,
68
+ credentials: this.#options.credentials,
69
+ headers: { ...this.#options.headers, ...options?.headers },
70
+ body: {
71
+ ...this.#options.body,
72
+ ...options?.body,
73
+ },
74
+ streamProtocol: this.#streamProtocol,
75
+ fetch: this.#options.fetch,
76
+ // throttle streamed ui updates:
77
+ setCompletion: completion => {
78
+ this.completion = completion;
79
+ },
80
+ setLoading: loading => {
81
+ this.#store.loading = loading;
82
+ },
83
+ setError: error => {
84
+ this.#store.error = error;
85
+ },
86
+ setAbortController: abortController => {
87
+ this.#abortController = abortController ?? undefined;
88
+ },
89
+ onFinish: this.#options.onFinish,
90
+ onError: this.#options.onError,
91
+ });
92
+ };
93
+ }
@@ -0,0 +1,2 @@
1
+ export declare function createAIContext(): void;
2
+ //# sourceMappingURL=context-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-provider.d.ts","sourceRoot":"","sources":["../src/context-provider.ts"],"names":[],"mappings":"AASA,wBAAgB,eAAe,SAM9B"}
@@ -0,0 +1,8 @@
1
+ import { KeyedCompletionStore, setCompletionContext, } from './completion-context.svelte.js';
2
+ import { KeyedStructuredObjectStore, setStructuredObjectContext, } from './structured-object-context.svelte.js';
3
+ export function createAIContext() {
4
+ const completionStore = new KeyedCompletionStore();
5
+ setCompletionContext(completionStore);
6
+ const objectStore = new KeyedStructuredObjectStore();
7
+ setStructuredObjectContext(objectStore);
8
+ }
@@ -0,0 +1,5 @@
1
+ export { Chat, type CreateUIMessage, type UIMessage } from './chat.svelte.js';
2
+ export { Completion, type CompletionOptions } from './completion.svelte.js';
3
+ export { createAIContext } from './context-provider.js';
4
+ export { StructuredObject as Experimental_StructuredObject, type Experimental_StructuredObjectOptions, } from './structured-object.svelte.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
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 ADDED
@@ -0,0 +1,4 @@
1
+ export { Chat } from './chat.svelte.js';
2
+ export { Completion } from './completion.svelte.js';
3
+ export { createAIContext } from './context-provider.js';
4
+ export { StructuredObject as Experimental_StructuredObject, } from './structured-object.svelte.js';
@@ -0,0 +1,12 @@
1
+ import type { DeepPartial } from 'ai';
2
+ import { KeyedStore } from './utils.svelte.js';
3
+ export declare class StructuredObjectStore<RESULT> {
4
+ object: DeepPartial<RESULT> | undefined;
5
+ loading: boolean;
6
+ error: Error | undefined;
7
+ }
8
+ export declare class KeyedStructuredObjectStore extends KeyedStore<StructuredObjectStore<unknown>> {
9
+ constructor(value?: Iterable<readonly [string, StructuredObjectStore<unknown>]> | null | undefined);
10
+ }
11
+ export declare const hasStructuredObjectContext: () => boolean, getStructuredObjectContext: () => KeyedStructuredObjectStore, setStructuredObjectContext: (value: KeyedStructuredObjectStore) => KeyedStructuredObjectStore;
12
+ //# sourceMappingURL=structured-object-context.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-object-context.svelte.d.ts","sourceRoot":"","sources":["../src/structured-object-context.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC;AACtC,OAAO,EAAiB,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE9D,qBAAa,qBAAqB,CAAC,MAAM;IACvC,MAAM,kCAAiC;IACvC,OAAO,UAAiB;IACxB,KAAK,oBAAmB;CACzB;AAED,qBAAa,0BAA2B,SAAQ,UAAU,CACxD,qBAAqB,CAAC,OAAO,CAAC,CAC/B;gBAEG,KAAK,CAAC,EACF,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,GAC3D,IAAI,GACJ,SAAS;CAIhB;AAED,eAAO,MACO,0BAA0B,iBAC1B,0BAA0B,oCAC1B,0BAA0B,mEACyB,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { createContext, KeyedStore } from './utils.svelte.js';
2
+ export class StructuredObjectStore {
3
+ object = $state();
4
+ loading = $state(false);
5
+ error = $state();
6
+ }
7
+ export class KeyedStructuredObjectStore extends KeyedStore {
8
+ constructor(value) {
9
+ super(StructuredObjectStore, value);
10
+ }
11
+ }
12
+ export const { hasContext: hasStructuredObjectContext, getContext: getStructuredObjectContext, setContext: setStructuredObjectContext, } = createContext('StructuredObject');
@@ -0,0 +1,84 @@
1
+ import { type FetchFunction, type InferSchema } from '@ai-sdk/provider-utils';
2
+ import { type DeepPartial, type Schema } from 'ai';
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>> = {
6
+ /**
7
+ * The API endpoint. It should stream JSON that matches the schema as chunked text.
8
+ */
9
+ api: string;
10
+ /**
11
+ * A Zod schema that defines the shape of the complete object.
12
+ */
13
+ schema: SCHEMA;
14
+ /**
15
+ * An unique identifier. If not provided, a random one will be
16
+ * generated. When provided, the `useObject` hook with the same `id` will
17
+ * have shared states across components.
18
+ */
19
+ id?: string;
20
+ /**
21
+ * An optional value for the initial object.
22
+ */
23
+ initialValue?: DeepPartial<RESULT>;
24
+ /**
25
+ * Custom fetch implementation. You can use it as a middleware to intercept requests,
26
+ * or to provide a custom fetch implementation for e.g. testing.
27
+ */
28
+ fetch?: FetchFunction;
29
+ /**
30
+ * Callback that is called when the stream has finished.
31
+ */
32
+ onFinish?: (event: {
33
+ /**
34
+ * The generated object (typed according to the schema).
35
+ * Can be undefined if the final object does not match the schema.
36
+ */
37
+ object: RESULT | undefined;
38
+ /**
39
+ * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
40
+ */
41
+ error: Error | undefined;
42
+ }) => Promise<void> | void;
43
+ /**
44
+ * Callback function to be called when an error is encountered.
45
+ */
46
+ onError?: (error: Error) => void;
47
+ /**
48
+ * Additional HTTP headers to be included in the request.
49
+ */
50
+ headers?: Record<string, string> | Headers;
51
+ /**
52
+ * The credentials mode to be used for the fetch request.
53
+ * Possible values are: 'omit', 'same-origin', 'include'.
54
+ * Defaults to 'same-origin'.
55
+ */
56
+ credentials?: RequestCredentials;
57
+ };
58
+ export declare class StructuredObject<SCHEMA extends z3.Schema | z4.core.$ZodType | Schema, RESULT = InferSchema<SCHEMA>, INPUT = unknown> {
59
+ #private;
60
+ /**
61
+ * The current value for the generated object. Updated as the API streams JSON chunks.
62
+ */
63
+ get object(): DeepPartial<RESULT> | undefined;
64
+ /** The error object of the API request */
65
+ get error(): Error | undefined;
66
+ /**
67
+ * Flag that indicates whether an API request is in progress.
68
+ */
69
+ get loading(): boolean;
70
+ constructor(options: Experimental_StructuredObjectOptions<SCHEMA, RESULT>);
71
+ /**
72
+ * Abort the current request immediately, keep the current partial object if any.
73
+ */
74
+ stop: () => void;
75
+ /**
76
+ * Calls the API with the provided input as JSON body.
77
+ */
78
+ submit: (input: INPUT) => Promise<void>;
79
+ /**
80
+ * Clears the object state.
81
+ */
82
+ clear: () => void;
83
+ }
84
+ //# sourceMappingURL=structured-object.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-object.svelte.d.ts","sourceRoot":"","sources":["../src/structured-object.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAIL,KAAK,WAAW,EAChB,KAAK,MAAM,EACZ,MAAM,IAAI,CAAC;AACZ,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAQlC,MAAM,MAAM,oCAAoC,CA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C;IAUzE;;OAEG;IACH,IAAI,aASF;IAEF;;OAEG;IACH,MAAM,UAAiB,KAAK,mBAqF1B;IAEF;;OAEG;IACH,KAAK,aAGH;CAOH"}
@@ -0,0 +1,134 @@
1
+ import { generateId, isAbortError, safeValidateTypes, } from '@ai-sdk/provider-utils';
2
+ import { asSchema, isDeepEqualData, parsePartialJson, } from 'ai';
3
+ import { getStructuredObjectContext, hasStructuredObjectContext, KeyedStructuredObjectStore, } from './structured-object-context.svelte.js';
4
+ export class StructuredObject {
5
+ #options = {};
6
+ #id = $derived(this.#options.id ?? generateId());
7
+ #keyedStore = $state();
8
+ #store = $derived(this.#keyedStore.get(this.#id));
9
+ #abortController;
10
+ /**
11
+ * The current value for the generated object. Updated as the API streams JSON chunks.
12
+ */
13
+ get object() {
14
+ return this.#store.object;
15
+ }
16
+ set #object(value) {
17
+ this.#store.object = value;
18
+ }
19
+ /** The error object of the API request */
20
+ get error() {
21
+ return this.#store.error;
22
+ }
23
+ /**
24
+ * Flag that indicates whether an API request is in progress.
25
+ */
26
+ get loading() {
27
+ return this.#store.loading;
28
+ }
29
+ constructor(options) {
30
+ if (hasStructuredObjectContext()) {
31
+ this.#keyedStore = getStructuredObjectContext();
32
+ }
33
+ else {
34
+ this.#keyedStore = new KeyedStructuredObjectStore();
35
+ }
36
+ this.#options = options;
37
+ this.#object = options.initialValue;
38
+ }
39
+ /**
40
+ * Abort the current request immediately, keep the current partial object if any.
41
+ */
42
+ stop = () => {
43
+ try {
44
+ this.#abortController?.abort();
45
+ }
46
+ catch {
47
+ // ignore
48
+ }
49
+ finally {
50
+ this.#store.loading = false;
51
+ this.#abortController = undefined;
52
+ }
53
+ };
54
+ /**
55
+ * Calls the API with the provided input as JSON body.
56
+ */
57
+ submit = async (input) => {
58
+ try {
59
+ this.#clearObject();
60
+ this.#store.loading = true;
61
+ const abortController = new AbortController();
62
+ this.#abortController = abortController;
63
+ const actualFetch = this.#options.fetch ?? fetch;
64
+ const response = await actualFetch(this.#options.api, {
65
+ method: 'POST',
66
+ headers: {
67
+ 'Content-Type': 'application/json',
68
+ ...this.#options.headers,
69
+ },
70
+ credentials: this.#options.credentials,
71
+ signal: abortController.signal,
72
+ body: JSON.stringify(input),
73
+ });
74
+ if (!response.ok) {
75
+ throw new Error((await response.text()) ?? 'Failed to fetch the response.');
76
+ }
77
+ if (response.body == null) {
78
+ throw new Error('The response body is empty.');
79
+ }
80
+ let accumulatedText = '';
81
+ let latestObject = undefined;
82
+ await response.body.pipeThrough(new TextDecoderStream()).pipeTo(new WritableStream({
83
+ write: async (chunk) => {
84
+ if (abortController?.signal.aborted) {
85
+ throw new DOMException('Stream aborted', 'AbortError');
86
+ }
87
+ accumulatedText += chunk;
88
+ const { value } = await parsePartialJson(accumulatedText);
89
+ const currentObject = value;
90
+ if (!isDeepEqualData(latestObject, currentObject)) {
91
+ latestObject = currentObject;
92
+ this.#store.object = currentObject;
93
+ }
94
+ },
95
+ close: async () => {
96
+ this.#store.loading = false;
97
+ this.#abortController = undefined;
98
+ if (this.#options.onFinish != null) {
99
+ const validationResult = await safeValidateTypes({
100
+ value: latestObject,
101
+ schema: asSchema(this.#options.schema),
102
+ });
103
+ this.#options.onFinish(validationResult.success
104
+ ? { object: validationResult.value, error: undefined }
105
+ : { object: undefined, error: validationResult.error });
106
+ }
107
+ },
108
+ }));
109
+ }
110
+ catch (error) {
111
+ if (isAbortError(error)) {
112
+ return;
113
+ }
114
+ const coalescedError = error instanceof Error ? error : new Error(String(error));
115
+ if (this.#options.onError) {
116
+ this.#options.onError(coalescedError);
117
+ }
118
+ this.#store.loading = false;
119
+ this.#store.error = coalescedError;
120
+ }
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
+ };
134
+ }
@@ -0,0 +1,12 @@
1
+ <script lang="ts">
2
+ import { Completion } from '../completion.svelte.js';
3
+ import { createAIContext } from '../context-provider.js';
4
+
5
+ let { id }: { id?: string } = $props();
6
+
7
+ createAIContext();
8
+ const completion1 = new Completion({ id });
9
+ const completion2 = new Completion({ id });
10
+
11
+ export { completion1, completion2 };
12
+ </script>
@@ -0,0 +1,11 @@
1
+ import { Completion } from '../completion.svelte.js';
2
+ type $$ComponentProps = {
3
+ id?: string;
4
+ };
5
+ declare const CompletionSynchronization: import("svelte").Component<$$ComponentProps, {
6
+ completion1: Completion;
7
+ completion2: Completion;
8
+ }, "">;
9
+ type CompletionSynchronization = ReturnType<typeof CompletionSynchronization>;
10
+ export default CompletionSynchronization;
11
+ //# sourceMappingURL=completion-synchronization.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"completion-synchronization.svelte.d.ts","sourceRoot":"","sources":["../../src/tests/completion-synchronization.svelte.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAGpD,KAAK,gBAAgB,GAAI;IAAE,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAgB1C,QAAA,MAAM,yBAAyB;;;MAAsC,CAAC;AACtE,KAAK,yBAAyB,GAAG,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAAC;AAC9E,eAAe,yBAAyB,CAAC"}
@@ -0,0 +1,22 @@
1
+ <script lang="ts" generics="RESULT">
2
+ import { createAIContext } from '../context-provider.js';
3
+ import { StructuredObject } from '../structured-object.svelte.js';
4
+ import type { Schema } from 'ai';
5
+ import type { z } from 'zod';
6
+
7
+ let {
8
+ id,
9
+ api,
10
+ schema,
11
+ }: {
12
+ id?: string;
13
+ api: string;
14
+ schema: z.Schema<RESULT, z.ZodTypeDef, unknown> | Schema<RESULT>;
15
+ } = $props();
16
+
17
+ createAIContext();
18
+ const object1 = new StructuredObject({ id, api, schema });
19
+ const object2 = new StructuredObject({ id, api, schema });
20
+
21
+ export { object1, object2 };
22
+ </script>
@@ -0,0 +1,28 @@
1
+ import { StructuredObject } from '../structured-object.svelte.js';
2
+ import type { Schema } from 'ai';
3
+ import type { z } from 'zod';
4
+ declare class __sveltets_Render<RESULT> {
5
+ props(): {
6
+ id?: string;
7
+ api: string;
8
+ schema: z.ZodType<RESULT, z.ZodTypeDef, unknown> | Schema<RESULT>;
9
+ };
10
+ events(): {};
11
+ slots(): {};
12
+ bindings(): "";
13
+ exports(): {
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
+ };
17
+ }
18
+ interface $$IsomorphicComponent {
19
+ new <RESULT>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<RESULT>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<RESULT>['props']>, ReturnType<__sveltets_Render<RESULT>['events']>, ReturnType<__sveltets_Render<RESULT>['slots']>> & {
20
+ $$bindings?: ReturnType<__sveltets_Render<RESULT>['bindings']>;
21
+ } & ReturnType<__sveltets_Render<RESULT>['exports']>;
22
+ <RESULT>(internal: unknown, props: ReturnType<__sveltets_Render<RESULT>['props']> & {}): ReturnType<__sveltets_Render<RESULT>['exports']>;
23
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
24
+ }
25
+ declare const StructuredObjectSynchronization: $$IsomorphicComponent;
26
+ type StructuredObjectSynchronization<RESULT> = InstanceType<typeof StructuredObjectSynchronization<RESULT>>;
27
+ export default StructuredObjectSynchronization;
28
+ //# sourceMappingURL=structured-object-synchronization.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-object-synchronization.svelte.d.ts","sourceRoot":"","sources":["../../src/tests/structured-object-synchronization.svelte.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,KAAK,EAAE,MAA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AC,CAAC,CAAC;AAC9G,eAAe,+BAA+B,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { SvelteMap } from 'svelte/reactivity';
2
+ export declare function createContext<T>(name: string): {
3
+ hasContext: () => boolean;
4
+ getContext: () => T;
5
+ setContext: (value: T) => T;
6
+ };
7
+ export declare function promiseWithResolvers<T>(): {
8
+ promise: Promise<T>;
9
+ resolve: (value: T) => void;
10
+ reject: (reason?: unknown) => void;
11
+ };
12
+ export declare class KeyedStore<T> extends SvelteMap<string, T> {
13
+ #private;
14
+ constructor(itemConstructor: new () => T, value?: Iterable<readonly [string, T]> | null | undefined);
15
+ get(key: string): T;
16
+ }
17
+ //# sourceMappingURL=utils.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.svelte.d.ts","sourceRoot":"","sources":["../src/utils.svelte.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,wBAAgB,aAAa,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM;;;wBAuBrB,CAAC;EAExB;AAED,wBAAgB,oBAAoB,CAAC,CAAC,KAAK;IACzC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,CAAC;IAC5B,MAAM,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;CACpC,CAQA;AAED,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC;;gBAInD,eAAe,EAAE,UAAU,CAAC,EAC5B,KAAK,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS;IAM3D,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC;CAUpB"}