UNPKG

@ai-sdk/rsc

Version:

[React Server Components](https://react.dev/reference/rsc/server-components) for the [AI SDK](https://ai-sdk.dev/docs):

1 lines 52.2 kB
{"version":3,"sources":["../src/ai-state.tsx","../src/util/create-resolvable-promise.ts","../src/util/is-function.ts","../src/provider.tsx","../src/stream-ui/stream-ui.tsx","../src/util/is-async-generator.ts","../src/util/is-generator.ts","../src/util/constants.ts","../src/streamable-ui/create-suspended-chunk.tsx","../src/streamable-ui/create-streamable-ui.tsx","../src/streamable-value/streamable-value.ts","../src/streamable-value/create-streamable-value.ts"],"sourcesContent":["import * as jsondiffpatch from 'jsondiffpatch';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createResolvablePromise } from './util/create-resolvable-promise';\nimport { isFunction } from './util/is-function';\nimport type {\n AIProvider,\n InferAIState,\n InternalAIStateStorageOptions,\n MutableAIState,\n ValueOrUpdater,\n} from './types';\n\n// It is possible that multiple AI requests get in concurrently, for different\n// AI instances. So ALS is necessary here for a simpler API.\nconst asyncAIStateStorage = new AsyncLocalStorage<{\n currentState: any;\n originalState: any;\n sealed: boolean;\n options: InternalAIStateStorageOptions;\n mutationDeltaPromise?: Promise<any>;\n mutationDeltaResolve?: (v: any) => void;\n}>();\n\nfunction getAIStateStoreOrThrow(message: string) {\n const store = asyncAIStateStorage.getStore();\n if (!store) {\n throw new Error(message);\n }\n return store;\n}\n\nexport function withAIState<S, T>(\n { state, options }: { state: S; options: InternalAIStateStorageOptions },\n fn: () => T,\n): T {\n return asyncAIStateStorage.run(\n {\n currentState: JSON.parse(JSON.stringify(state)), // deep clone object\n originalState: state,\n sealed: false,\n options,\n },\n fn,\n );\n}\n\nexport function getAIStateDeltaPromise() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n return store.mutationDeltaPromise;\n}\n\n// Internal method. This will be called after the AI Action has been returned\n// and you can no longer call `getMutableAIState()` inside any async callbacks\n// created by that Action.\nexport function sealMutableAIState() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n store.sealed = true;\n}\n\n/**\n * Get the current AI state.\n * If `key` is provided, it will return the value of the specified key in the\n * AI state, if it's an object. If it's not an object, it will throw an error.\n *\n * @example const state = getAIState() // Get the entire AI state\n * @example const field = getAIState('key') // Get the value of the key\n */\nfunction getAIState<AI extends AIProvider = any>(): Readonly<\n InferAIState<AI, any>\n>;\nfunction getAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): Readonly<InferAIState<AI, any>[typeof key]>;\nfunction getAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n const store = getAIStateStoreOrThrow(\n '`getAIState` must be called within an AI Action.',\n );\n\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key as keyof typeof store.currentState];\n }\n\n return store.currentState;\n}\n\n/**\n * Get the mutable AI state. Note that you must call `.done()` when finishing\n * updating the AI state.\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.update({ ...state.get(), key: 'value' })\n * state.update((currentState) => ({ ...currentState, key: 'value' }))\n * state.done()\n * ```\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.done({ ...state.get(), key: 'value' }) // Done with a new state\n * ```\n */\nfunction getMutableAIState<AI extends AIProvider = any>(): MutableAIState<\n InferAIState<AI, any>\n>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): MutableAIState<InferAIState<AI, any>[typeof key]>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n type AIState = InferAIState<AI, any>;\n type AIStateWithKey = typeof args extends [key: keyof AIState]\n ? AIState[(typeof args)[0]]\n : AIState;\n type NewStateOrUpdater = ValueOrUpdater<AIStateWithKey>;\n\n const store = getAIStateStoreOrThrow(\n '`getMutableAIState` must be called within an AI Action.',\n );\n\n if (store.sealed) {\n throw new Error(\n \"`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body.\",\n );\n }\n\n if (!store.mutationDeltaPromise) {\n const { promise, resolve } = createResolvablePromise();\n store.mutationDeltaPromise = promise;\n store.mutationDeltaResolve = resolve;\n }\n\n function doUpdate(newState: NewStateOrUpdater, done: boolean) {\n if (args.length > 0) {\n if (typeof store.currentState !== 'object') {\n const key = args[0];\n throw new Error(\n `You can't modify the \"${String(\n key,\n )}\" field of the AI state because it's not an object.`,\n );\n }\n }\n\n if (isFunction(newState)) {\n if (args.length > 0) {\n store.currentState[args[0]] = newState(store.currentState[args[0]]);\n } else {\n store.currentState = newState(store.currentState);\n }\n } else {\n if (args.length > 0) {\n store.currentState[args[0]] = newState;\n } else {\n store.currentState = newState;\n }\n }\n\n store.options.onSetAIState?.({\n key: args.length > 0 ? args[0] : undefined,\n state: store.currentState,\n done,\n });\n }\n\n const mutableState = {\n get: () => {\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key] as Readonly<AIStateWithKey>;\n }\n\n return store.currentState as Readonly<AIState>;\n },\n update: function update(newAIState: NewStateOrUpdater) {\n doUpdate(newAIState, false);\n },\n done: function done(...doneArgs: [] | [NewStateOrUpdater]) {\n if (doneArgs.length > 0) {\n doUpdate(doneArgs[0] as NewStateOrUpdater, true);\n }\n\n const delta = jsondiffpatch.diff(store.originalState, store.currentState);\n store.mutationDeltaResolve!(delta);\n },\n };\n\n return mutableState;\n}\n\nexport { getAIState, getMutableAIState };\n","/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n * - promise: A Promise that can be resolved or rejected externally.\n * - resolve: A function to resolve the Promise with a value of type T.\n * - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (error: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n };\n}\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} True if the value is a function, false otherwise.\n */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n","// This file provides the AI context to all AI Actions via AsyncLocalStorage.\n\nimport * as React from 'react';\nimport { InternalAIProvider } from './rsc-shared.mjs';\nimport {\n withAIState,\n getAIStateDeltaPromise,\n sealMutableAIState,\n} from './ai-state';\nimport type {\n ServerWrappedActions,\n AIAction,\n AIActions,\n AIProvider,\n InternalAIStateStorageOptions,\n OnSetAIState,\n OnGetUIState,\n} from './types';\n\nasync function innerAction<T>(\n {\n action,\n options,\n }: { action: AIAction; options: InternalAIStateStorageOptions },\n state: T,\n ...args: unknown[]\n) {\n 'use server';\n return await withAIState(\n {\n state,\n options,\n },\n async () => {\n const result = await action(...args);\n sealMutableAIState();\n return [getAIStateDeltaPromise() as Promise<T>, result];\n },\n );\n}\n\nfunction wrapAction<T = unknown>(\n action: AIAction,\n options: InternalAIStateStorageOptions,\n) {\n return innerAction.bind(null, { action, options }) as AIAction<T>;\n}\n\nexport function createAI<\n AIState = any,\n UIState = any,\n Actions extends AIActions = {},\n>({\n actions,\n initialAIState,\n initialUIState,\n\n onSetAIState,\n onGetUIState,\n}: {\n actions: Actions;\n initialAIState?: AIState;\n initialUIState?: UIState;\n\n /**\n * This function is called whenever the AI state is updated by an Action.\n * You can use this to persist the AI state to a database, or to send it to a\n * logging service.\n */\n onSetAIState?: OnSetAIState<AIState>;\n\n /**\n * This function is used to retrieve the UI state based on the AI state.\n * For example, to render the initial UI state based on a given AI state, or\n * to sync the UI state when the application is already loaded.\n *\n * If returning `undefined`, the client side UI state will not be updated.\n *\n * This function must be annotated with the `\"use server\"` directive.\n *\n * @example\n * ```tsx\n * onGetUIState: async () => {\n * 'use server';\n *\n * const currentAIState = getAIState();\n * const externalAIState = await loadAIStateFromDatabase();\n *\n * if (currentAIState === externalAIState) return undefined;\n *\n * // Update current AI state and return the new UI state\n * const state = getMutableAIState()\n * state.done(externalAIState)\n *\n * return <div>...</div>;\n * }\n * ```\n */\n onGetUIState?: OnGetUIState<UIState>;\n}) {\n // Wrap all actions with our HoC.\n const wrappedActions: ServerWrappedActions = {};\n for (const name in actions) {\n wrappedActions[name] = wrapAction(actions[name], {\n onSetAIState,\n });\n }\n\n const wrappedSyncUIState = onGetUIState\n ? wrapAction(onGetUIState, {})\n : undefined;\n\n const AI: AIProvider<AIState, UIState, Actions> = async props => {\n if ('useState' in React) {\n // This file must be running on the React Server layer.\n // Ideally we should be using `import \"server-only\"` here but we can have a\n // more customized error message with this implementation.\n throw new Error(\n 'This component can only be used inside Server Components.',\n );\n }\n\n let uiState = props.initialUIState ?? initialUIState;\n let aiState = props.initialAIState ?? initialAIState;\n let aiStateDelta = undefined;\n\n if (wrappedSyncUIState) {\n const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);\n if (newUIState !== undefined) {\n aiStateDelta = newAIStateDelta;\n uiState = newUIState;\n }\n }\n\n return (\n <InternalAIProvider\n wrappedActions={wrappedActions}\n wrappedSyncUIState={wrappedSyncUIState}\n initialUIState={uiState}\n initialAIState={aiState}\n initialAIStatePatch={aiStateDelta}\n >\n {props.children}\n </InternalAIProvider>\n );\n };\n\n return AI;\n}\n","import { LanguageModelV2, LanguageModelV2CallWarning } from '@ai-sdk/provider';\nimport {\n InferSchema,\n ProviderOptions,\n safeParseJSON,\n} from '@ai-sdk/provider-utils';\nimport { ReactNode } from 'react';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport {\n CallWarning,\n FinishReason,\n LanguageModelUsage,\n ToolChoice,\n Prompt,\n CallSettings,\n InvalidToolInputError,\n NoSuchToolError,\n Schema,\n} from 'ai';\nimport {\n standardizePrompt,\n prepareToolsAndToolChoice,\n prepareRetries,\n prepareCallSettings,\n convertToLanguageModelPrompt,\n} from 'ai/internal';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { isAsyncGenerator } from '../util/is-async-generator';\nimport { isGenerator } from '../util/is-generator';\nimport { createStreamableUI } from '../streamable-ui/create-streamable-ui';\n\ntype Streamable = ReactNode | Promise<ReactNode>;\n\ntype Renderer<T extends Array<any>> = (\n ...args: T\n) =>\n | Streamable\n | Generator<Streamable, Streamable, void>\n | AsyncGenerator<Streamable, Streamable, void>;\n\ntype RenderTool<\n INPUT_SCHEMA extends z4.core.$ZodType | z3.Schema | Schema = any,\n> = {\n description?: string;\n inputSchema: INPUT_SCHEMA;\n generate?: Renderer<\n [\n InferSchema<INPUT_SCHEMA>,\n {\n toolName: string;\n toolCallId: string;\n },\n ]\n >;\n};\n\ntype RenderText = Renderer<\n [\n {\n /**\n * The full text content from the model so far.\n */\n content: string;\n\n /**\n * The new appended text content from the model since the last `text` call.\n */\n delta: string;\n\n /**\n * Whether the model is done generating text.\n * If `true`, the `content` will be the final output and this call will be the last.\n */\n done: boolean;\n },\n ]\n>;\n\ntype RenderResult = {\n value: ReactNode;\n} & Awaited<ReturnType<LanguageModelV2['doStream']>>;\n\nconst defaultTextRenderer: RenderText = ({ content }: { content: string }) =>\n content;\n\n/**\n * `streamUI` is a helper function to create a streamable UI from LLMs.\n */\nexport async function streamUI<\n TOOLS extends { [name: string]: z4.core.$ZodType | z3.Schema | Schema } = {},\n>({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n initial,\n text,\n providerOptions,\n onFinish,\n ...settings\n}: CallSettings &\n Prompt & {\n /**\n * The language model to use.\n */\n model: LanguageModelV2;\n\n /**\n * The tools that the model can call. The model needs to support calling tools.\n */\n tools?: {\n [name in keyof TOOLS]: RenderTool<TOOLS[name]>;\n };\n\n /**\n * The tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n text?: RenderText;\n initial?: ReactNode;\n\n /**\nAdditional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n * Callback that is called when the LLM response and the final object validation are finished.\n */\n onFinish?: (event: {\n /**\n * The reason why the generation finished.\n */\n finishReason: FinishReason;\n /**\n * The token usage of the generated response.\n */\n usage: LanguageModelUsage;\n /**\n * The final ui node that was generated.\n */\n value: ReactNode;\n /**\n * Warnings from the model provider (e.g. unsupported settings)\n */\n warnings?: CallWarning[];\n /**\n * Optional response data.\n */\n response?: {\n /**\n * Response headers.\n */\n headers?: Record<string, string>;\n };\n }) => Promise<void> | void;\n }): Promise<RenderResult> {\n // TODO: Remove these errors after the experimental phase.\n if (typeof model === 'string') {\n throw new Error(\n '`model` cannot be a string in `streamUI`. Use the actual model instance instead.',\n );\n }\n if ('functions' in settings) {\n throw new Error(\n '`functions` is not supported in `streamUI`, use `tools` instead.',\n );\n }\n if ('provider' in settings) {\n throw new Error(\n '`provider` is no longer needed in `streamUI`. Use `model` instead.',\n );\n }\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n if ('render' in tool) {\n throw new Error(\n 'Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: ' +\n name,\n );\n }\n }\n }\n\n const ui = createStreamableUI(initial);\n\n // The default text renderer just returns the content as string.\n const textRender = text || defaultTextRenderer;\n\n let finished: Promise<void> | undefined;\n\n let finishEvent: {\n finishReason: FinishReason;\n usage: LanguageModelUsage;\n warnings?: CallWarning[];\n response?: {\n headers?: Record<string, string>;\n };\n } | null = null;\n\n async function render({\n args,\n renderer,\n streamableUI,\n isLastCall = false,\n }: {\n renderer: undefined | Renderer<any>;\n args: [payload: any] | [payload: any, options: any];\n streamableUI: ReturnType<typeof createStreamableUI>;\n isLastCall?: boolean;\n }) {\n if (!renderer) return;\n\n // create a promise that will be resolved when the render call is finished.\n // it is appended to the `finished` promise chain to ensure the render call\n // is finished before the next render call starts.\n const renderFinished = createResolvablePromise<void>();\n finished = finished\n ? finished.then(() => renderFinished.promise)\n : renderFinished.promise;\n\n const rendererResult = renderer(...args);\n\n if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {\n while (true) {\n const { done, value } = await rendererResult.next();\n const node = await value;\n\n if (isLastCall && done) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n\n if (done) break;\n }\n } else {\n const node = await rendererResult;\n\n if (isLastCall) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n }\n\n // resolve the promise to signal that the render call is finished\n renderFinished.resolve(undefined);\n }\n\n const { retry } = prepareRetries({ maxRetries, abortSignal });\n\n const validatedPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n const result = await retry(async () =>\n model.doStream({\n ...prepareCallSettings(settings),\n ...prepareToolsAndToolChoice({\n tools: tools as any,\n toolChoice,\n activeTools: undefined,\n }),\n prompt: await convertToLanguageModelPrompt({\n prompt: validatedPrompt,\n supportedUrls: await model.supportedUrls,\n download: undefined,\n }),\n providerOptions,\n abortSignal,\n headers,\n includeRawChunks: false,\n }),\n );\n\n // For the stream and consume it asynchronously:\n const [stream, forkedStream] = result.stream.tee();\n (async () => {\n try {\n let content = '';\n let hasToolCall = false;\n let warnings: LanguageModelV2CallWarning[] | undefined;\n\n const reader = forkedStream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n switch (value.type) {\n case 'stream-start': {\n warnings = value.warnings;\n break;\n }\n\n case 'text-delta': {\n content += value.delta;\n render({\n renderer: textRender,\n args: [{ content, done: false, delta: value.delta }],\n streamableUI: ui,\n });\n break;\n }\n\n case 'tool-input-start':\n case 'tool-input-delta': {\n hasToolCall = true;\n break;\n }\n\n case 'tool-call': {\n const toolName = value.toolName as keyof TOOLS & string;\n\n if (!tools) {\n throw new NoSuchToolError({ toolName });\n }\n\n const tool = tools[toolName];\n if (!tool) {\n throw new NoSuchToolError({\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n hasToolCall = true;\n const parseResult = await safeParseJSON({\n text: value.input,\n schema: tool.inputSchema,\n });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName,\n toolInput: value.input,\n cause: parseResult.error,\n });\n }\n\n render({\n renderer: tool.generate,\n args: [\n parseResult.value,\n {\n toolName,\n toolCallId: value.toolCallId,\n },\n ],\n streamableUI: ui,\n isLastCall: true,\n });\n\n break;\n }\n\n case 'error': {\n throw value.error;\n }\n\n case 'finish': {\n finishEvent = {\n finishReason: value.finishReason,\n usage: value.usage,\n warnings,\n response: result.response,\n };\n break;\n }\n }\n }\n\n if (!hasToolCall) {\n render({\n renderer: textRender,\n args: [{ content, done: true }],\n streamableUI: ui,\n isLastCall: true,\n });\n }\n\n await finished;\n\n if (finishEvent && onFinish) {\n await onFinish({\n ...finishEvent,\n value: ui.value,\n });\n }\n } catch (error) {\n // During the stream rendering, we don't want to throw the error to the\n // parent scope but only let the React's error boundary to catch it.\n ui.error(error);\n }\n })();\n\n return {\n ...result,\n stream,\n value: ui.value,\n };\n}\n","export function isAsyncGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is AsyncGenerator<T, TReturn, TNext> {\n return (\n value != null && typeof value === 'object' && Symbol.asyncIterator in value\n );\n}\n","export function isGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is Generator<T, TReturn, TNext> {\n return value != null && typeof value === 'object' && Symbol.iterator in value;\n}\n","/**\n * Warning time for notifying developers that a stream is hanging in dev mode\n * using a console.warn.\n */\nexport const HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;\n","import React, { Suspense } from 'react';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\n\n// Recursive type for the chunk.\ntype ChunkType =\n | {\n done: false;\n value: React.ReactNode;\n next: Promise<ChunkType>;\n append?: boolean;\n }\n | {\n done: true;\n value: React.ReactNode;\n };\n\n// Use single letter names for the variables to reduce the size of the RSC payload.\n// `R` for `Row`, `c` for `current`, `n` for `next`.\n// Note: Array construction is needed to access the name R.\nconst R = [\n (async ({\n c: current,\n n: next,\n }: {\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }) => {\n const chunk = await next;\n\n if (chunk.done) {\n return chunk.value;\n }\n\n if (chunk.append) {\n return (\n <>\n {current}\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n </>\n );\n }\n\n return (\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n );\n }) as unknown as React.FC<{\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }>,\n][0];\n\n/**\n * Creates a suspended chunk for React Server Components.\n *\n * This function generates a suspenseful React component that can be dynamically updated.\n * It's useful for streaming updates to the client in a React Server Components context.\n *\n * @param {React.ReactNode} initialValue - The initial value to render while the promise is pending.\n * @returns {Object} An object containing:\n * - row: A React node that renders the suspenseful content.\n * - resolve: A function to resolve the promise with a new value.\n * - reject: A function to reject the promise with an error.\n */\nexport function createSuspendedChunk(initialValue: React.ReactNode): {\n row: React.ReactNode;\n resolve: (value: ChunkType) => void;\n reject: (error: unknown) => void;\n} {\n const { promise, resolve, reject } = createResolvablePromise<ChunkType>();\n\n return {\n row: (\n <Suspense fallback={initialValue}>\n <R c={initialValue} n={promise} />\n </Suspense>\n ),\n resolve,\n reject,\n };\n}\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../util/constants';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { createSuspendedChunk } from './create-suspended-chunk';\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableUIWrapper = {\n /**\n * The value of the streamable UI. This can be returned from a Server Action and received by the client.\n */\n readonly value: React.ReactNode;\n\n /**\n * This method updates the current UI node. It takes a new UI node and replaces the old one.\n */\n update(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to append a new UI node to the end of the old one.\n * Once appended a new UI node, the previous UI node cannot be updated anymore.\n *\n * @example\n * ```jsx\n * const ui = createStreamableUI(<div>hello</div>)\n * ui.append(<div>world</div>)\n *\n * // The UI node will be:\n * // <>\n * // <div>hello</div>\n * // <div>world</div>\n * // </>\n * ```\n */\n append(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to signal that there is an error in the UI stream.\n * It will be thrown on the client side and caught by the nearest error boundary component.\n */\n error(error: any): StreamableUIWrapper;\n\n /**\n * This method marks the UI node as finalized. You can either call it without any parameters or with a new UI node as the final state.\n * Once called, the UI node cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response will be stuck in a loading state.\n */\n done(...args: [React.ReactNode] | []): StreamableUIWrapper;\n};\n\n/**\n * Create a piece of changeable UI that can be streamed to the client.\n * On the client side, it can be rendered as a normal React node.\n */\nfunction createStreamableUI(initialValue?: React.ReactNode) {\n let currentValue = initialValue;\n let closed = false;\n let { row, resolve, reject } = createSuspendedChunk(initialValue);\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': UI stream is already closed.');\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n const streamable: StreamableUIWrapper = {\n value: row,\n update(value: React.ReactNode) {\n assertStream('.update()');\n\n // There is no need to update the value if it's referentially equal.\n if (value === currentValue) {\n warnUnclosedStream();\n return streamable;\n }\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value: currentValue, done: false, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: React.ReactNode) {\n assertStream('.append()');\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value, done: false, append: true, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n reject(error);\n\n return streamable;\n },\n done(...args: [] | [React.ReactNode]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n if (args.length) {\n resolve({ value: args[0], done: true });\n return streamable;\n }\n resolve({ value: currentValue, done: true });\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableUI };\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\n\nexport type StreamablePatch = undefined | [0, string]; // Append string.\n\ndeclare const __internal_curr: unique symbol;\ndeclare const __internal_error: unique symbol;\n\n/**\n * StreamableValue is a value that can be streamed over the network via AI Actions.\n * To read the streamed values, use the `readStreamableValue` or `useStreamableValue` APIs.\n */\nexport type StreamableValue<T = any, E = any> = {\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n type?: typeof STREAMABLE_VALUE_TYPE;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n curr?: T;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n error?: E;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n diff?: StreamablePatch;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n next?: Promise<StreamableValue<T, E>>;\n\n // branded types to maintain type signature after internal properties are stripped.\n [__internal_curr]?: T;\n [__internal_error]?: E;\n};\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../util/constants';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport {\n STREAMABLE_VALUE_TYPE,\n StreamablePatch,\n StreamableValue,\n} from './streamable-value';\n\nconst STREAMABLE_VALUE_INTERNAL_LOCK = Symbol('streamable.value.lock');\n\n/**\n * Create a wrapped, changeable value that can be streamed to the client.\n * On the client side, the value can be accessed via the readStreamableValue() API.\n */\nfunction createStreamableValue<T = any, E = any>(\n initialValue?: T | ReadableStream<T>,\n) {\n const isReadableStream =\n initialValue instanceof ReadableStream ||\n (typeof initialValue === 'object' &&\n initialValue !== null &&\n 'getReader' in initialValue &&\n typeof initialValue.getReader === 'function' &&\n 'locked' in initialValue &&\n typeof initialValue.locked === 'boolean');\n\n if (!isReadableStream) {\n return createStreamableValueImpl<T, E>(initialValue);\n }\n\n const streamableValue = createStreamableValueImpl<T, E>();\n\n // Since the streamable value will be from a readable stream, it's not allowed\n // to update the value manually as that introduces race conditions and\n // unexpected behavior.\n // We lock the value to prevent any updates from the user.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n\n (async () => {\n try {\n // Consume the readable stream and update the value.\n const reader = initialValue.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n\n // Unlock the value to allow updates.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n if (typeof value === 'string') {\n streamableValue.append(value);\n } else {\n streamableValue.update(value);\n }\n // Lock the value again.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n }\n\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.done();\n } catch (e) {\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.error(e);\n }\n })();\n\n return streamableValue;\n}\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableValueWrapper<T, E> = {\n /**\n * The value of the streamable. This can be returned from a Server Action and\n * received by the client. To read the streamed values, use the\n * `readStreamableValue` or `useStreamableValue` APIs.\n */\n readonly value: StreamableValue<T, E>;\n\n /**\n * This method updates the current value with a new one.\n */\n update(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to append a delta string to the current value. It\n * requires the current value of the streamable to be a string.\n *\n * @example\n * ```jsx\n * const streamable = createStreamableValue('hello');\n * streamable.append(' world');\n *\n * // The value will be 'hello world'\n * ```\n */\n append(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to signal that there is an error in the value stream.\n * It will be thrown on the client side when consumed via\n * `readStreamableValue` or `useStreamableValue`.\n */\n error(error: any): StreamableValueWrapper<T, E>;\n\n /**\n * This method marks the value as finalized. You can either call it without\n * any parameters or with a new value as the final state.\n * Once called, the value cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response\n * will be stuck in a loading state.\n */\n done(...args: [T] | []): StreamableValueWrapper<T, E>;\n\n /**\n * @internal This is an internal lock to prevent the value from being\n * updated by the user.\n */\n [STREAMABLE_VALUE_INTERNAL_LOCK]: boolean;\n};\n\nfunction createStreamableValueImpl<T = any, E = any>(initialValue?: T) {\n let closed = false;\n let locked = false;\n let resolvable = createResolvablePromise<StreamableValue<T, E>>();\n\n let currentValue = initialValue;\n let currentError: E | undefined;\n let currentPromise: typeof resolvable.promise | undefined =\n resolvable.promise;\n let currentPatchValue: StreamablePatch;\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': Value stream is already closed.');\n }\n if (locked) {\n throw new Error(\n method + ': Value stream is locked and cannot be updated.',\n );\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n function createWrapped(initialChunk?: boolean): StreamableValue<T, E> {\n // This makes the payload much smaller if there're mutative updates before the first read.\n let init: Partial<StreamableValue<T, E>>;\n\n if (currentError !== undefined) {\n init = { error: currentError };\n } else {\n if (currentPatchValue && !initialChunk) {\n init = { diff: currentPatchValue };\n } else {\n init = { curr: currentValue };\n }\n }\n\n if (currentPromise) {\n init.next = currentPromise;\n }\n\n if (initialChunk) {\n init.type = STREAMABLE_VALUE_TYPE;\n }\n\n return init;\n }\n\n // Update the internal `currentValue` and `currentPatchValue` if needed.\n function updateValueStates(value: T) {\n // If we can only send a patch over the wire, it's better to do so.\n currentPatchValue = undefined;\n if (typeof value === 'string') {\n if (typeof currentValue === 'string') {\n if (value.startsWith(currentValue)) {\n currentPatchValue = [0, value.slice(currentValue.length)];\n }\n }\n }\n\n currentValue = value;\n }\n\n const streamable: StreamableValueWrapper<T, E> = {\n set [STREAMABLE_VALUE_INTERNAL_LOCK](state: boolean) {\n locked = state;\n },\n get value() {\n return createWrapped(true);\n },\n update(value: T) {\n assertStream('.update()');\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n updateValueStates(value);\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: T) {\n assertStream('.append()');\n\n if (\n typeof currentValue !== 'string' &&\n typeof currentValue !== 'undefined'\n ) {\n throw new Error(\n `.append(): The current value is not a string. Received: ${typeof currentValue}`,\n );\n }\n if (typeof value !== 'string') {\n throw new Error(\n `.append(): The value is not a string. Received: ${typeof value}`,\n );\n }\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n if (typeof currentValue === 'string') {\n currentPatchValue = [0, value];\n (currentValue as string) = currentValue + value;\n } else {\n currentPatchValue = undefined;\n currentValue = value;\n }\n\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentError = error;\n currentPromise = undefined;\n\n resolvable.resolve({ error });\n\n return streamable;\n },\n done(...args: [] | [T]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentPromise = undefined;\n\n if (args.length) {\n updateValueStates(args[0]);\n resolvable.resolve(createWrapped());\n return streamable;\n }\n\n resolvable.resolve({});\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableValue };\n"],"mappings":";AAAA,YAAY,mBAAmB;AAC/B,SAAS,yBAAyB;;;ACQ3B,SAAS,0BAId;AACA,MAAI;AACJ,MAAI;AAEJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACrBO,IAAM,aAAa,CAAC,UACzB,OAAO,UAAU;;;AFOnB,IAAM,sBAAsB,IAAI,kBAO7B;AAEH,SAAS,uBAAuB,SAAiB;AAC/C,QAAM,QAAQ,oBAAoB,SAAS;AAC3C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,OAAO;AAAA,EACzB;AACA,SAAO;AACT;AAEO,SAAS,YACd,EAAE,OAAO,QAAQ,GACjB,IACG;AACH,SAAO,oBAAoB;AAAA,IACzB;AAAA,MACE,cAAc,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,MAC9C,eAAe;AAAA,MACf,QAAQ;AAAA,MACR;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,yBAAyB;AACvC,QAAM,QAAQ,uBAAuB,0BAA0B;AAC/D,SAAO,MAAM;AACf;AAKO,SAAS,qBAAqB;AACnC,QAAM,QAAQ,uBAAuB,0BAA0B;AAC/D,QAAM,SAAS;AACjB;AAgBA,SAAS,cACJ,MACH;AACA,QAAM,QAAQ;AAAA,IACZ;AAAA,EACF;AAEA,MAAI,KAAK,SAAS,GAAG;AACnB,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,OAAO,MAAM,iBAAiB,UAAU;AAC1C,YAAM,IAAI;AAAA,QACR,sBAAsB;AAAA,UACpB;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO,MAAM,aAA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