@valerypopoff/rivet2-core 2.1.4 → 2.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/bundle.cjs +3733 -969
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +605 -16
- package/dist/cjs/webAppRuntime.cjs.map +3 -3
- package/dist/esm/api/createProcessor.js +5 -1
- package/dist/esm/exports.js +3 -0
- package/dist/esm/model/GraphBoundaryEffects.js +13 -0
- package/dist/esm/model/GraphProcessor.js +1127 -82
- package/dist/esm/model/ManagedAsyncBranches.js +28 -0
- package/dist/esm/model/Nodes.js +9 -0
- package/dist/esm/model/ProcessContextBuilder.js +2 -1
- package/dist/esm/model/RecordingPlayer.js +9 -0
- package/dist/esm/model/StoredValueStore.js +226 -0
- package/dist/esm/model/SubprocessorBridge.js +50 -19
- package/dist/esm/model/ToolCallContinuation.js +1 -0
- package/dist/esm/model/UiGraph.js +50 -0
- package/dist/esm/model/UiGraphActionProtocol.js +10 -1
- package/dist/esm/model/UiGraphBrowserRuntime.js +333 -0
- package/dist/esm/model/UiGraphNormalization.js +35 -185
- package/dist/esm/model/UiGraphRendererStyles.js +772 -74
- package/dist/esm/model/UiGraphRuntimeModel.js +230 -14
- package/dist/esm/model/UiGraphSchema.js +91 -0
- package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
- package/dist/esm/model/chat/chatMessages.js +5 -9
- package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
- package/dist/esm/model/chat-v2/index.js +1 -0
- package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
- package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
- package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
- package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
- package/dist/esm/model/nodes/MatchNode.js +7 -7
- package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
- package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
- package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
- package/dist/esm/recording/ExecutionRecorder.js +1 -0
- package/dist/esm/utils/coerceType.js +3 -0
- package/dist/esm/webAppRuntime.js +3 -3
- package/dist/types/api/createProcessor.d.ts +4 -0
- package/dist/types/exports.d.ts +3 -0
- package/dist/types/model/EditorDefinition.d.ts +2 -1
- package/dist/types/model/ExecutorProtocol.d.ts +12 -0
- package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
- package/dist/types/model/GraphProcessor.d.ts +19 -2
- package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
- package/dist/types/model/Nodes.d.ts +5 -2
- package/dist/types/model/ProcessContext.d.ts +15 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
- package/dist/types/model/StoredValueStore.d.ts +55 -0
- package/dist/types/model/SubprocessorBridge.d.ts +4 -2
- package/dist/types/model/ToolCallContinuation.d.ts +13 -0
- package/dist/types/model/UiGraph.d.ts +21 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +51 -0
- package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
- package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
- package/dist/types/model/UiGraphSchema.d.ts +113 -0
- package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
- package/dist/types/model/chat-v2/index.d.ts +1 -0
- package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
- package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
- package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
- package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
- package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
- package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
- package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
- package/dist/types/recording/RecordedEvents.d.ts +5 -0
- package/dist/types/webAppRuntime.d.ts +4 -4
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/webAppRuntime.ts", "../../src/utils/newId.ts", "../../src/model/UiGraph.ts", "../../src/model/GraphProgress.ts", "../../src/model/UiGraphRuntimeModel.ts", "../../src/model/UiGraphActionProtocol.ts", "../../src/model/UiGraphBrowserRuntime.ts"],
|
|
4
|
-
"sourcesContent": ["export type {\n UiComponentId,\n UiGraph,\n UiGraphActionComponent,\n UiGraphChatMessage,\n UiGraphComponent,\n} from './model/UiGraph.js';\nexport type { UiGraphInteractionSnapshot } from './model/UiGraphRuntimeModel.js';\nexport type {\n RivetWebAppClientMessage,\n RivetWebAppRunEvent,\n RivetWebAppServerMessage,\n} from './model/UiGraphActionProtocol.js';\nexport type { GraphProgress } from './model/GraphProgress.js';\nexport type { RivetMarkdownSanitizerPolicy } from './model/MarkdownSanitizationPolicy.js';\nexport {\n createUiGraphChatSubmissionStatePatch,\n getUiGraphActionState,\n getUiGraphChatDraftStateKey,\n} from './model/UiGraph.js';\nexport {\n applyUiGraphStatePatch,\n createUiGraphActionExecutionController,\n createUiGraphInteractionController,\n getUiGraphComponentRenderModel,\n getUiGraphJsonOutputFilename,\n} from './model/UiGraphRuntimeModel.js';\nexport {\n parseRivetWebAppClientMessage,\n parseRivetWebAppServerMessage,\n RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,\n} from './model/UiGraphActionProtocol.js';\nexport { copyUiGraphText, downloadUiGraphJsonOutput } from './model/UiGraphBrowserRuntime.js';\n", "import { nanoid } from 'nanoid/non-secure';\n\nexport function newId<T extends string>(): T {\n return nanoid() as T;\n}\n", "import type { Opaque } from 'type-fest';\nimport type { GraphId } from './NodeGraph.js';\nimport { newId } from '../utils/newId.js';\nimport type { ChatMessage, DataValue } from './DataValue.js';\n\nexport type UiGraphId = Opaque<string, 'UiGraphId'>;\nexport type UiComponentId = Opaque<string, 'UiComponentId'>;\nexport type UiGraphOutputs = Record<string, DataValue>;\nexport const UI_GRAPH_GAP_SIZES = ['small', 'medium', 'large'] as const;\nexport type UiGraphGapSize = (typeof UI_GRAPH_GAP_SIZES)[number];\nexport const UI_GRAPH_OUTPUT_RENDER_MODES = ['text', 'json', 'markdown', 'image'] as const;\nexport type UiGraphOutputRenderMode = (typeof UI_GRAPH_OUTPUT_RENDER_MODES)[number];\n\nexport type UiGraphValueBinding =\n | {\n type: 'state';\n key: string;\n }\n | {\n type: 'literal';\n value: unknown;\n };\n\nexport type UiGraphRunGraphAction = {\n type: 'runGraph';\n graphId?: GraphId;\n inputMappings?: UiGraphInputBinding[];\n inputs?: Record<string, UiGraphValueBinding>;\n outputs?: UiGraphOutputBinding[];\n outputKey?: string;\n outputStateKey?: string;\n};\n\nexport type UiGraphChatRunGraphAction = {\n type: 'runGraph';\n graphId?: GraphId;\n userInputId?: string;\n historyInputId?: string;\n responseOutputId?: string;\n inputMappings?: UiGraphInputBinding[];\n};\n\nexport type UiGraphChatMessage = {\n role: 'assistant' | 'user';\n content: string;\n};\n\nexport type UiGraphInputBinding = {\n inputKey: string;\n stateKey: string;\n};\n\nexport type UiGraphOutputBinding = {\n outputKey?: string;\n stateKey: string;\n};\n\nexport type UiGraphAction = UiGraphRunGraphAction;\n\nexport type UiGraphComponent =\n | {\n id: UiComponentId;\n type: 'text';\n text: string;\n }\n | {\n id: UiComponentId;\n type: 'markdown';\n markdown: string;\n }\n | {\n id: UiComponentId;\n type: 'gap';\n size: UiGraphGapSize;\n }\n | {\n id: UiComponentId;\n type: 'input';\n label: string;\n stateKey: string;\n placeholder?: string;\n defaultValue?: string;\n }\n | {\n id: UiComponentId;\n type: 'textarea';\n label: string;\n stateKey: string;\n placeholder?: string;\n defaultValue?: string;\n }\n | {\n id: UiComponentId;\n type: 'button';\n label: string;\n action: UiGraphAction;\n }\n | {\n id: UiComponentId;\n type: 'chat';\n action: UiGraphChatRunGraphAction;\n placeholder?: string;\n }\n | {\n id: UiComponentId;\n type: 'output';\n label?: string;\n stateKey: string;\n renderAs?: UiGraphOutputRenderMode;\n };\n\nexport type UiGraph = {\n id: UiGraphId;\n name: string;\n description?: string;\n components: UiGraphComponent[];\n};\n\nexport type UiGraphActionComponent = Extract<UiGraphComponent, { type: 'button' | 'chat' }>;\n\nexport function hasValidUiGraphComponentIds(uiGraph: UiGraph): boolean {\n const componentIds = new Set<string>();\n\n for (const component of uiGraph.components) {\n const componentId = typeof component.id === 'string' ? component.id : '';\n if (!componentId.trim() || componentIds.has(componentId)) {\n return false;\n }\n\n componentIds.add(componentId);\n }\n\n return true;\n}\n\n/**\n * Returns an immutable component-ID repair for legacy or externally assembled\n * UI graphs. Full untrusted-data validation belongs to normalizeUiGraph().\n */\nexport function normalizeUiGraphComponentIds(uiGraph: UiGraph): UiGraph {\n if (hasValidUiGraphComponentIds(uiGraph)) {\n return uiGraph;\n }\n\n const reservedIds = new Set(\n uiGraph.components\n .map((component) => (typeof component.id === 'string' ? component.id : ''))\n .filter((componentId) => Boolean(componentId.trim())),\n );\n const usedIds = new Set<string>();\n const graphId = typeof uiGraph.id === 'string' && uiGraph.id.trim() ? uiGraph.id : 'ui-graph';\n const components = uiGraph.components.map((component, index) => {\n const componentId = typeof component.id === 'string' ? component.id : '';\n if (componentId.trim() && !usedIds.has(componentId)) {\n usedIds.add(componentId);\n return component;\n }\n\n const repairedId = getRepairedUiGraphComponentId(graphId, index, reservedIds, usedIds);\n usedIds.add(repairedId);\n return { ...component, id: repairedId as UiComponentId };\n });\n\n return { ...uiGraph, components };\n}\n\nfunction getRepairedUiGraphComponentId(\n graphId: string,\n componentIndex: number,\n reservedIds: ReadonlySet<string>,\n usedIds: ReadonlySet<string>,\n): string {\n const baseId = `${graphId}-component-${componentIndex + 1}`;\n let repairedId = baseId;\n let suffix = 2;\n\n while (reservedIds.has(repairedId) || usedIds.has(repairedId)) {\n repairedId = `${baseId}-${suffix}`;\n suffix += 1;\n }\n\n return repairedId;\n}\n\nexport function createDefaultUiGraph(options: { graphId?: GraphId; name?: string } = {}): UiGraph {\n const promptStateKey = 'input';\n const resultStateKey = 'result';\n\n return {\n id: newId<UiGraphId>(),\n name: options.name ?? 'Untitled web app',\n components: [\n {\n id: newId<UiComponentId>(),\n type: 'markdown',\n markdown: '## New Rivet web app\\n\\nEnter a value and run a graph.',\n },\n {\n id: newId<UiComponentId>(),\n type: 'textarea',\n label: 'Input',\n stateKey: promptStateKey,\n placeholder: 'Type something...',\n },\n {\n id: newId<UiComponentId>(),\n type: 'button',\n label: 'Run graph',\n action: {\n type: 'runGraph',\n graphId: options.graphId,\n inputMappings: [{ inputKey: 'input', stateKey: promptStateKey }],\n outputs: [{ stateKey: resultStateKey }],\n },\n },\n {\n id: newId<UiComponentId>(),\n type: 'output',\n label: 'Result',\n stateKey: resultStateKey,\n renderAs: 'json',\n },\n ],\n };\n}\n\nexport function getUiGraphInitialState(uiGraph: UiGraph): Record<string, unknown> {\n const state: Record<string, unknown> = {};\n\n for (const component of uiGraph.components) {\n if (component.type === 'input' || component.type === 'textarea') {\n state[component.stateKey] = component.defaultValue ?? '';\n } else if (component.type === 'chat') {\n state[getUiGraphChatDraftStateKey(component.id)] = '';\n state[getUiGraphChatMessagesStateKey(component.id)] = [];\n }\n }\n\n return state;\n}\n\nexport function getUiGraphActionComponent(\n uiGraph: UiGraph,\n componentId: UiComponentId,\n): UiGraphActionComponent | undefined {\n return uiGraph.components.find(\n (component): component is UiGraphActionComponent =>\n component.id === componentId && (component.type === 'button' || component.type === 'chat'),\n );\n}\n\nexport function getUiGraphChatDraftStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_draft`;\n}\n\nexport function getUiGraphChatMessagesStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_messages`;\n}\n\nexport function getUiGraphChatMessages(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): UiGraphChatMessage[] {\n const messages = state[getUiGraphChatMessagesStateKey(componentId)];\n return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];\n}\n\nexport function createUiGraphChatSubmissionStatePatch(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n const draftStateKey = getUiGraphChatDraftStateKey(componentId);\n const content = `${state[draftStateKey] ?? ''}`.trim();\n if (!content) {\n return undefined;\n }\n\n return {\n [draftStateKey]: '',\n [getUiGraphChatMessagesStateKey(componentId)]: [\n ...getUiGraphChatMessages(componentId, state),\n { role: 'user', content } satisfies UiGraphChatMessage,\n ],\n };\n}\n\nexport function getUiGraphComponentActionState(\n component: UiGraphActionComponent,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return getUiGraphActionState(component.action, state);\n }\n\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n return {\n ...getUiGraphActionState(component.action, state),\n [messagesStateKey]: getUiGraphChatMessages(component.id, state),\n };\n}\n\nexport function resolveUiGraphComponentActionInputs(\n component: UiGraphActionComponent,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return resolveUiGraphActionInputs(component.action, state);\n }\n\n const messages = getUiGraphChatMessages(component.id, state);\n const latestMessage = messages[messages.length - 1];\n const latestUserMessage = latestMessage?.role === 'user' ? latestMessage : undefined;\n const historyMessages = latestUserMessage ? messages.slice(0, -1) : messages;\n const inputs = resolveUiGraphActionInputs(component.action, state);\n if (component.action.userInputId) {\n inputs[component.action.userInputId] = latestUserMessage?.content ?? '';\n }\n if (component.action.historyInputId) {\n inputs[component.action.historyInputId] = {\n type: 'chat-message[]',\n value: historyMessages.map(toRivetChatMessage),\n } satisfies DataValue;\n }\n return inputs;\n}\n\nexport function resolveUiGraphComponentActionOutputStatePatch(\n component: UiGraphActionComponent,\n outputs: UiGraphOutputs,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return resolveUiGraphActionOutputStatePatch(component.action, outputs);\n }\n\n const outputId = component.action.responseOutputId;\n if (!outputId || !Object.prototype.hasOwnProperty.call(outputs, outputId)) {\n throw new Error(\n outputId\n ? `Graph output \"${outputId}\" was not returned by the target graph.`\n : 'The Chat component has no response graph output.',\n );\n }\n\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n return {\n [messagesStateKey]: [\n ...getUiGraphChatMessages(component.id, state),\n { role: 'assistant', content: getUiGraphChatResponseText(outputs[outputId]!) } satisfies UiGraphChatMessage,\n ],\n };\n}\n\nexport function getUiGraphComponentActionOutputStateKeys(component: UiGraphActionComponent): string[] {\n return component.type === 'button'\n ? getUiGraphActionOutputBindings(component.action)\n .map((binding) => binding.stateKey.trim())\n .filter(Boolean)\n : [getUiGraphChatMessagesStateKey(component.id)];\n}\n\nexport function resolveUiGraphActionInputs(\n action: UiGraphRunGraphAction,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n const inputs: Record<string, unknown> = {};\n\n if (action.inputMappings) {\n for (const binding of action.inputMappings) {\n if (binding.inputKey) {\n inputs[binding.inputKey] = state[binding.stateKey];\n }\n }\n\n return inputs;\n }\n\n for (const [inputId, binding] of Object.entries(action.inputs ?? {})) {\n inputs[inputId] = binding.type === 'state' ? state[binding.key] : binding.value;\n }\n\n return inputs;\n}\n\n/**\n * Selects the UI state that a button action is explicitly allowed to send.\n * Outputs and unrelated form fields stay local to the rendered web app.\n */\nexport function getUiGraphActionState(\n action: UiGraphRunGraphAction,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n return Object.fromEntries(\n [...new Set(getUiGraphActionInputBindings(action).map((binding) => binding.stateKey))]\n .filter(Boolean)\n .filter((stateKey) => Object.prototype.hasOwnProperty.call(state, stateKey))\n .map((stateKey) => [stateKey, state[stateKey]]),\n );\n}\n\nexport function resolveUiGraphActionOutputStateValue(action: UiGraphRunGraphAction, outputs: UiGraphOutputs): unknown {\n if (!action.outputKey) {\n return outputs;\n }\n\n if (!Object.prototype.hasOwnProperty.call(outputs, action.outputKey)) {\n throw new Error(`Graph output \"${action.outputKey}\" was not returned by the target graph.`);\n }\n\n return outputs[action.outputKey]?.value;\n}\n\nexport function resolveUiGraphActionOutputStatePatch(\n action: UiGraphRunGraphAction,\n outputs: UiGraphOutputs,\n): Record<string, unknown> {\n const bindings = getUiGraphActionOutputBindings(action);\n const statePatch: Record<string, unknown> = {};\n\n for (const binding of bindings) {\n const stateKey = binding.stateKey.trim();\n if (!stateKey) {\n continue;\n }\n\n statePatch[stateKey] = resolveUiGraphOutputBindingValue(binding, outputs);\n }\n\n return statePatch;\n}\n\nexport function getUiGraphActionOutputBindings(action: UiGraphRunGraphAction): UiGraphOutputBinding[] {\n if (action.outputs) {\n return action.outputs;\n }\n\n return action.outputStateKey ? [{ outputKey: action.outputKey, stateKey: action.outputStateKey }] : [];\n}\n\nexport function getUiGraphActionInputBindings(action: UiGraphRunGraphAction): UiGraphInputBinding[] {\n if (action.inputMappings) {\n return action.inputMappings;\n }\n\n return Object.entries(action.inputs ?? {}).map(([inputKey, binding]) => ({\n inputKey,\n stateKey: binding.type === 'state' ? binding.key : '',\n }));\n}\n\nfunction resolveUiGraphOutputBindingValue(binding: UiGraphOutputBinding, outputs: UiGraphOutputs): unknown {\n if (!binding.outputKey) {\n return outputs;\n }\n\n if (!Object.prototype.hasOwnProperty.call(outputs, binding.outputKey)) {\n throw new Error(`Graph output \"${binding.outputKey}\" was not returned by the target graph.`);\n }\n\n return outputs[binding.outputKey]?.value;\n}\n\nfunction isUiGraphChatMessage(value: unknown): value is UiGraphChatMessage {\n return (\n value != null &&\n typeof value === 'object' &&\n ((value as UiGraphChatMessage).role === 'user' || (value as UiGraphChatMessage).role === 'assistant') &&\n typeof (value as UiGraphChatMessage).content === 'string'\n );\n}\n\nfunction toRivetChatMessage(message: UiGraphChatMessage): ChatMessage {\n return message.role === 'user'\n ? { type: 'user', message: message.content }\n : {\n type: 'assistant',\n message: message.content,\n function_call: undefined,\n function_calls: undefined,\n };\n}\n\nfunction getUiGraphChatResponseText(output: DataValue): string {\n if (output.type === 'chat-message') {\n const message = output.value.message;\n if (typeof message === 'string') {\n return message;\n }\n return (Array.isArray(message) ? message : [message])\n .flatMap((part) => (typeof part === 'string' ? [part] : []))\n .join('\\n');\n }\n\n if (typeof output.value === 'string') {\n return output.value;\n }\n if (output.value == null) {\n return '';\n }\n\n try {\n return JSON.stringify(output.value, null, 2);\n } catch {\n return String(output.value);\n }\n}\n", "export type GraphProgress = Readonly<{\n message?: string;\n percent?: number;\n}>;\n\nconst MAX_PROGRESS_MESSAGE_LENGTH = 500;\n\n/** Normalizes public graph progress before it crosses executor or web-app transports. */\nexport function normalizeGraphProgress(progress: GraphProgress): GraphProgress | undefined {\n const message =\n typeof progress.message === 'string' ? progress.message.trim().slice(0, MAX_PROGRESS_MESSAGE_LENGTH) : '';\n const percent =\n typeof progress.percent === 'number' && Number.isFinite(progress.percent)\n ? Math.min(100, Math.max(0, progress.percent))\n : undefined;\n\n if (!message && percent == null) {\n return undefined;\n }\n\n return {\n ...(message ? { message } : {}),\n ...(percent == null ? {} : { percent }),\n };\n}\n", "import {\n getUiGraphChatDraftStateKey,\n getUiGraphChatMessages,\n getUiGraphComponentActionOutputStateKeys,\n getUiGraphComponentActionState,\n getUiGraphInitialState,\n type UiComponentId,\n type UiGraph,\n type UiGraphActionComponent,\n type UiGraphChatMessage,\n type UiGraphComponent,\n type UiGraphGapSize,\n type UiGraphOutputRenderMode,\n} from './UiGraph.js';\nimport { normalizeGraphProgress, type GraphProgress } from './GraphProgress.js';\n\nexport type UiGraphOutputRenderModel = {\n hasValue: boolean;\n imageErrorMessage?: string;\n imageSource?: string;\n jsonDownloadValue?: string;\n renderedValue: string;\n renderAs: UiGraphOutputRenderMode;\n};\n\nconst IMAGE_DATA_URL_PATTERN = /^data:(image\\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\\s\\S]+)$/i;\nconst IMAGE_URL_PATTERN = /^(?:https?:\\/\\/|blob:|\\/\\/|\\/|\\.\\.?\\/)/i;\nconst RELATIVE_IMAGE_PATH_PATTERN = /\\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;\n\nexport type UiGraphComponentRenderModel =\n | {\n component: Extract<UiGraphComponent, { type: 'text' }>;\n text: string;\n type: 'text';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'markdown' }>;\n markdown: string;\n type: 'markdown';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'gap' }>;\n size: UiGraphGapSize;\n type: 'gap';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'input' | 'textarea' }>;\n label: string;\n type: 'input' | 'textarea';\n value: string;\n }\n | {\n component: Extract<UiGraphComponent, { type: 'button' }>;\n label: string;\n type: 'button';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'chat' }>;\n draft: string;\n messages: UiGraphChatMessage[];\n type: 'chat';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'output' }>;\n label: string;\n output: UiGraphOutputRenderModel;\n type: 'output';\n };\n\nexport type UiGraphActionExecution = Readonly<{\n componentId: UiComponentId;\n id: number;\n}>;\n\nexport type UiGraphActionExecutionController = {\n begin(component: UiGraphActionComponent): UiGraphActionExecution | undefined;\n finish(execution: UiGraphActionExecution): boolean;\n isCurrent(execution: UiGraphActionExecution): boolean;\n isRunning(componentId: UiComponentId): boolean;\n noteStateWrite(stateKey: string): void;\n resolveStatePatch(\n execution: UiGraphActionExecution,\n statePatch: Record<string, unknown> | undefined,\n ): Record<string, unknown> | undefined;\n reset(): void;\n};\n\nexport type UiGraphInteractionChange = 'action' | 'graph' | 'state';\n\nexport type UiGraphInteractionSnapshot = Readonly<{\n actionErrors: Readonly<Record<string, string>>;\n actionProgress: Readonly<Record<string, GraphProgress>>;\n runningComponentIds: ReadonlySet<UiComponentId>;\n state: Readonly<Record<string, unknown>>;\n}>;\n\nexport type UiGraphActionRunContext = Readonly<{\n abortOtherActions(): void;\n componentId: UiComponentId;\n reportProgress(progress: GraphProgress): void;\n signal: AbortSignal;\n state: Record<string, unknown>;\n}>;\n\nexport type UiGraphActionRunResult = {\n statePatch?: Record<string, unknown>;\n};\n\nexport type UiGraphActionRunner = (context: UiGraphActionRunContext) => Promise<UiGraphActionRunResult>;\n\nexport type UiGraphInteractionController = {\n abortActions(): void;\n cancelAction(componentId: UiComponentId): void;\n detachActions(): void;\n getSnapshot(): UiGraphInteractionSnapshot;\n runAction(component: UiGraphActionComponent, runner: UiGraphActionRunner): Promise<void>;\n setUiGraph(uiGraph: UiGraph): void;\n subscribe(listener: (change: UiGraphInteractionChange) => void): () => void;\n updateState(stateKey: string, value: unknown): void;\n updateStatePatch(statePatch: Record<string, unknown>): void;\n};\n\nexport type UiGraphInteractionControllerOptions = {\n initialState?: Record<string, unknown>;\n};\n\ntype ActiveUiGraphAction = Readonly<{\n abortController: AbortController;\n execution: UiGraphActionExecution;\n}>;\n\n/**\n * Coordinates independent web-app actions without allowing older completions to\n * clear newer loading states or overwrite newer writes to the same UI state key.\n */\nexport function createUiGraphActionExecutionController(): UiGraphActionExecutionController {\n let nextVersion = 0;\n const activeExecutionByComponent = new Map<UiComponentId, number>();\n const latestWriterByStateKey = new Map<string, number>();\n\n return {\n begin(component) {\n if (activeExecutionByComponent.has(component.id)) {\n return undefined;\n }\n\n const execution = { componentId: component.id, id: ++nextVersion };\n activeExecutionByComponent.set(component.id, execution.id);\n\n for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {\n latestWriterByStateKey.set(stateKey, execution.id);\n }\n\n return execution;\n },\n finish(execution) {\n if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {\n return false;\n }\n\n activeExecutionByComponent.delete(execution.componentId);\n return true;\n },\n isCurrent(execution) {\n return activeExecutionByComponent.get(execution.componentId) === execution.id;\n },\n isRunning(componentId) {\n return activeExecutionByComponent.has(componentId);\n },\n noteStateWrite(stateKey) {\n const normalizedStateKey = stateKey.trim();\n if (normalizedStateKey) {\n latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);\n }\n },\n resolveStatePatch(execution, statePatch) {\n if (!statePatch) {\n return undefined;\n }\n\n const applicableEntries = Object.entries(statePatch).filter(\n ([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id,\n );\n return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : undefined;\n },\n reset() {\n activeExecutionByComponent.clear();\n latestWriterByStateKey.clear();\n },\n };\n}\n\n/**\n * Owns mutable web-app interaction state for every renderer. React and direct\n * DOM hosts subscribe to this controller instead of reimplementing action\n * cancellation, loading/error state, and stale state-patch protection.\n */\nexport function createUiGraphInteractionController(\n initialUiGraph: UiGraph,\n options: UiGraphInteractionControllerOptions = {},\n): UiGraphInteractionController {\n let uiGraphId = initialUiGraph.id;\n let state = options.initialState ? { ...options.initialState } : getUiGraphInitialState(initialUiGraph);\n let actionErrors: Record<string, string> = {};\n let actionProgress: Record<string, GraphProgress> = {};\n let snapshot: UiGraphInteractionSnapshot;\n const actionController = createUiGraphActionExecutionController();\n const activeActions = new Map<number, ActiveUiGraphAction>();\n const listeners = new Set<(change: UiGraphInteractionChange) => void>();\n\n const updateSnapshot = (): void => {\n snapshot = {\n actionErrors,\n actionProgress,\n runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),\n state,\n };\n };\n const publish = (change: UiGraphInteractionChange): void => {\n updateSnapshot();\n for (const listener of listeners) {\n listener(change);\n }\n };\n const abortMatchingActions = (\n predicate: (activeAction: ActiveUiGraphAction, executionId: number) => boolean,\n notify: boolean,\n ): boolean => {\n let changed = false;\n for (const [executionId, activeAction] of activeActions) {\n if (!predicate(activeAction, executionId)) {\n continue;\n }\n activeAction.abortController.abort();\n activeActions.delete(executionId);\n actionController.finish(activeAction.execution);\n changed = true;\n }\n if (changed && notify) {\n publish('action');\n }\n return changed;\n };\n const abortAllActions = (notify: boolean): void => {\n let changed = abortMatchingActions(() => true, false);\n actionController.reset();\n if (Object.keys(actionProgress).length > 0) {\n actionProgress = {};\n changed = true;\n }\n if (changed && notify) {\n publish('action');\n }\n };\n const removeActionPresentation = (componentId: UiComponentId): void => {\n if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {\n actionErrors = { ...actionErrors };\n delete actionErrors[componentId];\n }\n if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {\n actionProgress = { ...actionProgress };\n delete actionProgress[componentId];\n }\n };\n\n updateSnapshot();\n\n return {\n abortActions() {\n abortAllActions(true);\n },\n cancelAction(componentId) {\n if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {\n removeActionPresentation(componentId);\n publish('action');\n }\n },\n detachActions() {\n activeActions.clear();\n actionController.reset();\n actionProgress = {};\n updateSnapshot();\n },\n getSnapshot() {\n return snapshot;\n },\n async runAction(component, runner) {\n const execution = actionController.begin(component);\n if (!execution) {\n return;\n }\n\n const abortController = new AbortController();\n activeActions.set(execution.id, { abortController, execution });\n removeActionPresentation(component.id);\n publish('action');\n\n try {\n const result = await runner({\n abortOtherActions: () =>\n abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),\n componentId: component.id,\n reportProgress: (progress) => {\n if (!actionController.isCurrent(execution)) return;\n const normalized = normalizeGraphProgress(progress);\n if (!normalized) return;\n actionProgress = { ...actionProgress, [component.id]: normalized };\n publish('action');\n },\n signal: abortController.signal,\n state: getUiGraphComponentActionState(component, state),\n });\n if (!actionController.isCurrent(execution)) {\n return;\n }\n\n const statePatch = actionController.resolveStatePatch(execution, result.statePatch);\n if (statePatch) {\n state = applyUiGraphStatePatch(state, statePatch);\n }\n } catch (error) {\n if (!abortController.signal.aborted && actionController.isCurrent(execution)) {\n actionErrors = {\n ...actionErrors,\n [component.id]: error instanceof Error ? error.message : String(error),\n };\n }\n } finally {\n if (activeActions.delete(execution.id)) {\n actionController.finish(execution);\n if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {\n actionProgress = { ...actionProgress };\n delete actionProgress[component.id];\n }\n publish('action');\n }\n }\n },\n setUiGraph(nextUiGraph) {\n if (nextUiGraph.id !== uiGraphId) {\n abortAllActions(false);\n uiGraphId = nextUiGraph.id;\n state = getUiGraphInitialState(nextUiGraph);\n actionErrors = {};\n actionProgress = {};\n publish('graph');\n return;\n }\n\n const actionComponentIds = new Set(\n nextUiGraph.components\n .filter((component) => component.type === 'button' || component.type === 'chat')\n .map((component) => component.id),\n );\n let changed = abortMatchingActions(({ execution }) => !actionComponentIds.has(execution.componentId), false);\n const remainingErrors = Object.fromEntries(\n Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId as UiComponentId)),\n );\n const remainingProgress = Object.fromEntries(\n Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId as UiComponentId)),\n );\n if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {\n actionErrors = remainingErrors;\n changed = true;\n }\n if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {\n actionProgress = remainingProgress;\n changed = true;\n }\n if (changed) {\n publish('graph');\n }\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n updateState(stateKey, value) {\n actionController.noteStateWrite(stateKey);\n state = { ...state, [stateKey]: value };\n publish('state');\n },\n updateStatePatch(statePatch) {\n for (const stateKey of Object.keys(statePatch)) {\n actionController.noteStateWrite(stateKey);\n }\n state = applyUiGraphStatePatch(state, statePatch);\n publish('state');\n },\n };\n}\n\nexport function getUiGraphComponentRenderModel(\n component: UiGraphComponent,\n state: Readonly<Record<string, unknown>>,\n): UiGraphComponentRenderModel {\n switch (component.type) {\n case 'text':\n return { component, text: component.text, type: 'text' };\n case 'markdown':\n return { component, markdown: component.markdown, type: 'markdown' };\n case 'gap':\n return { component, size: component.size, type: 'gap' };\n case 'input':\n case 'textarea':\n return {\n component,\n label: getUiGraphComponentLabel(component),\n type: component.type,\n value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,\n };\n case 'button':\n return { component, label: component.label, type: 'button' };\n case 'chat':\n return {\n component,\n draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,\n messages: getUiGraphChatMessages(component.id, state),\n type: 'chat',\n };\n case 'output':\n return {\n component,\n label: getUiGraphComponentLabel(component),\n output: getUiGraphOutputRenderModel(state, component.stateKey, component.renderAs ?? 'text'),\n type: 'output',\n };\n }\n}\n\nexport function getUiGraphComponentLabel(\n component: Extract<UiGraphComponent, { type: 'input' | 'textarea' | 'output' }>,\n): string {\n return component.label || component.stateKey;\n}\n\nexport function getUiGraphOutputRenderModel(\n state: Readonly<Record<string, unknown>>,\n stateKey: string,\n renderAs: UiGraphOutputRenderMode,\n): UiGraphOutputRenderModel {\n const value = state[stateKey];\n const hasValue = hasUiGraphStateValue(state, stateKey);\n const renderedValue = renderUiGraphOutputValue(value, renderAs);\n const imageSource = hasValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;\n const imageErrorMessage =\n hasValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;\n\n return {\n hasValue,\n ...(imageErrorMessage ? { imageErrorMessage } : {}),\n ...(imageSource ? { imageSource } : {}),\n ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: stringifyUiGraphValue(value) } : {}),\n renderedValue,\n renderAs,\n };\n}\n\nexport function hasUiGraphStateValue(state: Readonly<Record<string, unknown>>, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(state, key) && state[key] !== undefined;\n}\n\nexport function renderUiGraphOutputValue(value: unknown, renderAs: UiGraphOutputRenderMode): string {\n if (renderAs === 'json') {\n return stringifyUiGraphValue(value) ?? '';\n }\n\n return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';\n}\n\nexport function getUiGraphImageSource(value: unknown): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const source = value.trim();\n if (!source) {\n return undefined;\n }\n\n const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);\n if (dataUrl) {\n const base64 = normalizeBase64(dataUrl[2]!);\n return base64 ? `data:${normalizeImageMediaType(dataUrl[1]!)};base64,${base64}` : undefined;\n }\n\n const base64 = normalizeBase64(source);\n const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : undefined;\n if (base64 && inferredMediaType) {\n return `data:${inferredMediaType};base64,${base64}`;\n }\n\n if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {\n return undefined;\n }\n\n try {\n const protocol = new URL(source, 'https://rivet.invalid').protocol;\n return protocol === 'http:' || protocol === 'https:' || protocol === 'blob:' ? source : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeBase64(value: string): string | undefined {\n const compact = value.replace(/\\s/g, '');\n return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : undefined;\n}\n\nfunction normalizeImageMediaType(mediaType: string): string {\n const normalized = mediaType.toLowerCase();\n return normalized === 'image/jpg' ? 'image/jpeg' : normalized;\n}\n\nfunction inferBase64ImageMediaType(value: string): string | undefined {\n if (value.startsWith('iVBORw0KGgo')) return 'image/png';\n if (value.startsWith('/9j/')) return 'image/jpeg';\n if (value.startsWith('R0lGODdh') || value.startsWith('R0lGODlh')) return 'image/gif';\n return undefined;\n}\n\nexport function stringifyUiGraphValue(value: unknown): string | undefined {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return '[Unserializable value]';\n }\n}\n\nexport function getUiGraphJsonOutputFilename(appName: string, date = new Date()): string {\n const safeName = appName\n .trim()\n .replace(/[<>:\"/\\\\|?*\\u0000-\\u001F]/g, '-')\n .replace(/\\s+/g, ' ')\n .slice(0, 80);\n\n return `${safeName || 'Rivet web app'} ${formatUiGraphDownloadDateTime(date)}.json`;\n}\n\nexport function formatUiGraphDownloadDateTime(date: Date): string {\n const pad = (value: number) => `${value}`.padStart(2, '0');\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(\n date.getMinutes(),\n )}-${pad(date.getSeconds())}`;\n}\n\nexport function applyUiGraphStatePatch(\n state: Record<string, unknown>,\n statePatch: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n return statePatch ? { ...state, ...statePatch } : state;\n}\n", "import type { UiComponentId } from './UiGraph.js';\nimport { normalizeGraphProgress, type GraphProgress } from './GraphProgress.js';\n\nexport const RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1 as const;\n\nexport type RivetWebAppActionStartMessage = {\n type: 'action.start';\n requestId: string;\n componentId: UiComponentId;\n revisionKey?: string;\n state: Record<string, unknown>;\n};\n\nexport type RivetWebAppActionCancelMessage = {\n type: 'action.cancel';\n runId: string;\n};\n\nexport type RivetWebAppRunResumeMessage = {\n type: 'run.resume';\n runId: string;\n lastSequence: number;\n};\n\nexport type RivetWebAppClientHelloMessage = {\n type: 'client.hello';\n protocolVersion: typeof RIVET_WEB_APP_ACTION_PROTOCOL_VERSION;\n};\n\nexport type RivetWebAppClientMessage =\n | RivetWebAppClientHelloMessage\n | RivetWebAppActionStartMessage\n | RivetWebAppActionCancelMessage\n | RivetWebAppRunResumeMessage;\n\ntype RunEventBase = {\n requestId: string;\n runId: string;\n sequence: number;\n};\n\nexport type RivetWebAppServerMessage =\n | {\n type: 'server.ready';\n protocolVersion: typeof RIVET_WEB_APP_ACTION_PROTOCOL_VERSION;\n }\n | ({ type: 'action.accepted' } & RunEventBase)\n | ({ type: 'action.progress'; progress: GraphProgress } & RunEventBase)\n | ({ type: 'action.completed'; statePatch: Record<string, unknown> } & RunEventBase)\n | ({ type: 'action.failed'; error: string; code?: string } & RunEventBase)\n | ({ type: 'action.cancelled' } & RunEventBase)\n | ({ type: 'action.interrupted'; error: string } & RunEventBase)\n | {\n type: 'action.rejected';\n requestId: string;\n error: string;\n code?: string;\n }\n | {\n type: 'run.rejected';\n runId: string;\n error: string;\n code?: string;\n }\n | {\n type: 'server.draining';\n };\n\nexport type RivetWebAppRunEvent = Exclude<\n RivetWebAppServerMessage,\n { type: 'server.ready' | 'action.rejected' | 'run.rejected' | 'server.draining' }\n>;\n\nexport function parseRivetWebAppClientMessage(value: unknown): RivetWebAppClientMessage | undefined {\n if (!isRecord(value) || typeof value.type !== 'string') return undefined;\n\n switch (value.type) {\n case 'client.hello':\n return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION\n ? { type: value.type, protocolVersion: value.protocolVersion }\n : undefined;\n case 'action.start':\n return isNonEmptyString(value.requestId) &&\n isNonEmptyString(value.componentId) &&\n isRecord(value.state) &&\n (value.revisionKey == null || typeof value.revisionKey === 'string')\n ? {\n type: value.type,\n requestId: value.requestId,\n componentId: value.componentId as UiComponentId,\n state: value.state,\n ...(typeof value.revisionKey === 'string' ? { revisionKey: value.revisionKey } : {}),\n }\n : undefined;\n case 'action.cancel':\n return isNonEmptyString(value.runId) ? { type: value.type, runId: value.runId } : undefined;\n case 'run.resume':\n return isNonEmptyString(value.runId) &&\n typeof value.lastSequence === 'number' &&\n Number.isSafeInteger(value.lastSequence) &&\n value.lastSequence >= 0\n ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence }\n : undefined;\n default:\n return undefined;\n }\n}\n\nexport function parseRivetWebAppServerMessage(value: unknown): RivetWebAppServerMessage | undefined {\n if (!isRecord(value) || typeof value.type !== 'string') return undefined;\n\n if (value.type === 'server.ready') {\n return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION\n ? { type: value.type, protocolVersion: value.protocolVersion }\n : undefined;\n }\n if (value.type === 'server.draining') return { type: value.type };\n if (value.type === 'action.rejected') {\n return isNonEmptyString(value.requestId) && isNonEmptyString(value.error)\n ? {\n type: value.type,\n requestId: value.requestId,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n }\n if (value.type === 'run.rejected') {\n return isNonEmptyString(value.runId) && isNonEmptyString(value.error)\n ? {\n type: value.type,\n runId: value.runId,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n }\n if (!hasRunEventBase(value)) return undefined;\n\n const base = {\n requestId: value.requestId,\n runId: value.runId,\n sequence: value.sequence,\n };\n switch (value.type) {\n case 'action.accepted':\n case 'action.cancelled':\n return { type: value.type, ...base };\n case 'action.progress': {\n if (!isRecord(value.progress)) return undefined;\n const progress = normalizeGraphProgress({\n message: typeof value.progress.message === 'string' ? value.progress.message : undefined,\n percent: typeof value.progress.percent === 'number' ? value.progress.percent : undefined,\n });\n return progress ? { type: value.type, ...base, progress } : undefined;\n }\n case 'action.completed':\n return isRecord(value.statePatch) ? { type: value.type, ...base, statePatch: value.statePatch } : undefined;\n case 'action.failed':\n return isNonEmptyString(value.error)\n ? {\n type: value.type,\n ...base,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n case 'action.interrupted':\n return isNonEmptyString(value.error) ? { type: value.type, ...base, error: value.error } : undefined;\n default:\n return undefined;\n }\n}\n\nexport function isRivetWebAppRunTerminalEvent(event: RivetWebAppRunEvent): boolean {\n return (\n event.type === 'action.completed' ||\n event.type === 'action.failed' ||\n event.type === 'action.cancelled' ||\n event.type === 'action.interrupted'\n );\n}\n\nfunction hasRunEventBase(value: Record<string, unknown>): value is Record<string, unknown> & RunEventBase {\n return (\n isNonEmptyString(value.requestId) &&\n isNonEmptyString(value.runId) &&\n typeof value.sequence === 'number' &&\n Number.isSafeInteger(value.sequence) &&\n value.sequence > 0\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n", "import { getUiGraphJsonOutputFilename } from './UiGraphRuntimeModel.js';\n\n/** Copies rendered web-app output without requiring the modern Clipboard API. */\nexport async function copyUiGraphText(value: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(value);\n return true;\n } catch {\n // Preview hosts and non-secure origins may not expose the Clipboard API.\n }\n\n const textArea = document.createElement('textarea');\n textArea.className = 'rivet-web-app-clipboard-fallback';\n textArea.value = value;\n try {\n document.body.append(textArea);\n textArea.select();\n return document.execCommand?.('copy') ?? false;\n } catch {\n return false;\n } finally {\n textArea.remove();\n }\n}\n\n/** Downloads the exact JSON string rendered by a web-app output component. */\nexport function downloadUiGraphJsonOutput(value: string, appName: string): void {\n const url = URL.createObjectURL(new Blob([value], { type: 'application/json' }));\n try {\n const link = document.createElement('a');\n link.href = url;\n link.download = getUiGraphJsonOutputFilename(appName);\n document.body.append(link);\n link.click();\n link.remove();\n } finally {\n globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,wBAAuB;;;ACkOhB,SAAS,uBAAuB,SAA2C;AAChF,QAAM,QAAiC,CAAC;AAExC,aAAW,aAAa,QAAQ,YAAY;AAC1C,QAAI,UAAU,SAAS,WAAW,UAAU,SAAS,YAAY;AAC/D,YAAM,UAAU,QAAQ,IAAI,UAAU,gBAAgB;AAAA,IACxD,WAAW,UAAU,SAAS,QAAQ;AACpC,YAAM,4BAA4B,UAAU,EAAE,CAAC,IAAI;AACnD,YAAM,+BAA+B,UAAU,EAAE,CAAC,IAAI,CAAC;AAAA,IACzD;AAAA,EACF;AAEA,SAAO;AACT;AAYO,SAAS,4BAA4B,aAAoC;AAC9E,SAAO,gBAAgB,WAAW;AACpC;AAEO,SAAS,+BAA+B,aAAoC;AACjF,SAAO,gBAAgB,WAAW;AACpC;AAEO,SAAS,uBACd,aACA,OACsB;AACtB,QAAM,WAAW,MAAM,+BAA+B,WAAW,CAAC;AAClE,SAAO,MAAM,QAAQ,QAAQ,IAAI,SAAS,OAAO,oBAAoB,IAAI,CAAC;AAC5E;AAEO,SAAS,sCACd,aACA,OACqC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ent": ["export type {\n UiComponentId,\n UiGraph,\n UiGraphActionComponent,\n UiGraphChatMessage,\n UiGraphChatPin,\n UiGraphComponent,\n} from './model/UiGraph.js';\nexport type { UiGraphInteractionSnapshot } from './model/UiGraphRuntimeModel.js';\nexport type {\n RivetWebAppClientMessage,\n RivetWebAppRunEvent,\n RivetWebAppServerMessage,\n} from './model/UiGraphActionProtocol.js';\nexport type { GraphProgress } from './model/GraphProgress.js';\nexport type { RivetMarkdownSanitizerPolicy } from './model/MarkdownSanitizationPolicy.js';\nexport {\n createUiGraphChatHistoryFlushStatePatch,\n createUiGraphChatPinStatePatch,\n createUiGraphChatSubmissionStatePatch,\n getUiGraphActionState,\n getUiGraphChatDraftStateKey,\n getUiGraphChatMessagesStateKey,\n} from './model/UiGraph.js';\nexport {\n applyUiGraphStatePatch,\n createUiGraphActionExecutionController,\n createUiGraphInteractionController,\n getUiGraphComponentRenderModel,\n getUiGraphJsonOutputFilename,\n getUiGraphProgressiveJsonOutputChunks,\n} from './model/UiGraphRuntimeModel.js';\nexport {\n parseRivetWebAppClientMessage,\n parseRivetWebAppServerMessage,\n RIVET_WEB_APP_ACTION_PROTOCOL_VERSION,\n} from './model/UiGraphActionProtocol.js';\nexport {\n copyUiGraphText,\n applyUiGraphWebAppStorageActionPatch,\n applyUiGraphWebAppStoragePatch,\n clearUiGraphChatSearchMatches,\n downloadUiGraphJsonOutput,\n hasUiGraphChatPersistentStateChanged,\n getUiGraphChatPersistentState,\n getUiGraphChatStorageKey,\n getUiGraphWebAppStorageKey,\n highlightUiGraphChatSearchMatches,\n loadUiGraphChatPersistentState,\n loadUiGraphWebAppStorage,\n observeUiGraphOutputResizeBounds,\n revealUiGraphChatElement,\n revealUiGraphChatSearchMatch,\n saveUiGraphChatPersistentState,\n} from './model/UiGraphBrowserRuntime.js';\n", "import { nanoid } from 'nanoid/non-secure';\n\nexport function newId<T extends string>(): T {\n return nanoid() as T;\n}\n", "import type { Opaque } from 'type-fest';\nimport type { GraphId } from './NodeGraph.js';\nimport { newId } from '../utils/newId.js';\nimport type { ChatMessage, DataValue } from './DataValue.js';\n\nexport type UiGraphId = Opaque<string, 'UiGraphId'>;\nexport type UiComponentId = Opaque<string, 'UiComponentId'>;\nexport type UiGraphOutputs = Record<string, DataValue>;\nexport const UI_GRAPH_GAP_SIZES = ['small', 'medium', 'large'] as const;\nexport type UiGraphGapSize = (typeof UI_GRAPH_GAP_SIZES)[number];\nexport const UI_GRAPH_OUTPUT_RENDER_MODES = ['text', 'json', 'markdown', 'image'] as const;\nexport type UiGraphOutputRenderMode = (typeof UI_GRAPH_OUTPUT_RENDER_MODES)[number];\nexport type UiGraphDropdownItem = {\n label: string;\n value: string;\n};\n\nexport type UiGraphValueBinding =\n | {\n type: 'state';\n key: string;\n }\n | {\n type: 'literal';\n value: unknown;\n };\n\nexport type UiGraphRunGraphAction = {\n type: 'runGraph';\n graphId?: GraphId;\n inputMappings?: UiGraphInputBinding[];\n inputs?: Record<string, UiGraphValueBinding>;\n outputs?: UiGraphOutputBinding[];\n outputKey?: string;\n outputStateKey?: string;\n};\n\nexport type UiGraphChatRunGraphAction = {\n type: 'runGraph';\n graphId?: GraphId;\n userInputId?: string;\n historyInputId?: string;\n responseOutputId?: string;\n inputMappings?: UiGraphInputBinding[];\n};\n\nexport type UiGraphChatMessage = {\n role: 'assistant' | 'user';\n content: string;\n};\n\nexport type UiGraphChatPin = {\n messageIndex: number;\n promptMessageIndex?: number;\n prompt?: UiGraphChatMessage;\n response: UiGraphChatMessage;\n};\n\nexport type UiGraphInputBinding = {\n inputKey: string;\n stateKey: string;\n};\n\nexport type UiGraphOutputBinding = {\n outputKey?: string;\n stateKey: string;\n};\n\nexport type UiGraphAction = UiGraphRunGraphAction;\n\nexport type UiGraphComponent =\n | {\n id: UiComponentId;\n type: 'text';\n text: string;\n }\n | {\n id: UiComponentId;\n type: 'markdown';\n markdown: string;\n }\n | {\n id: UiComponentId;\n type: 'gap';\n size: UiGraphGapSize;\n }\n | {\n id: UiComponentId;\n type: 'input';\n label: string;\n stateKey: string;\n placeholder?: string;\n defaultValue?: string;\n }\n | {\n id: UiComponentId;\n type: 'textarea';\n label: string;\n stateKey: string;\n placeholder?: string;\n defaultValue?: string;\n }\n | {\n id: UiComponentId;\n type: 'dropdown';\n label: string;\n stateKey: string;\n items: UiGraphDropdownItem[];\n }\n | {\n id: UiComponentId;\n type: 'button';\n label: string;\n action: UiGraphAction;\n }\n | {\n id: UiComponentId;\n type: 'chat';\n action: UiGraphChatRunGraphAction;\n placeholder?: string;\n }\n | {\n id: UiComponentId;\n type: 'output';\n label?: string;\n stateKey: string;\n renderAs?: UiGraphOutputRenderMode;\n };\n\nexport type UiGraph = {\n id: UiGraphId;\n name: string;\n description?: string;\n components: UiGraphComponent[];\n};\n\nexport type UiGraphActionComponent = Extract<UiGraphComponent, { type: 'button' | 'chat' }>;\n\nexport function hasValidUiGraphComponentIds(uiGraph: UiGraph): boolean {\n const componentIds = new Set<string>();\n\n for (const component of uiGraph.components) {\n const componentId = typeof component.id === 'string' ? component.id : '';\n if (!componentId.trim() || componentIds.has(componentId)) {\n return false;\n }\n\n componentIds.add(componentId);\n }\n\n return true;\n}\n\n/**\n * Returns an immutable component-ID repair for legacy or externally assembled\n * UI graphs. Full untrusted-data validation belongs to normalizeUiGraph().\n */\nexport function normalizeUiGraphComponentIds(uiGraph: UiGraph): UiGraph {\n if (hasValidUiGraphComponentIds(uiGraph)) {\n return uiGraph;\n }\n\n const reservedIds = new Set(\n uiGraph.components\n .map((component) => (typeof component.id === 'string' ? component.id : ''))\n .filter((componentId) => Boolean(componentId.trim())),\n );\n const usedIds = new Set<string>();\n const graphId = typeof uiGraph.id === 'string' && uiGraph.id.trim() ? uiGraph.id : 'ui-graph';\n const components = uiGraph.components.map((component, index) => {\n const componentId = typeof component.id === 'string' ? component.id : '';\n if (componentId.trim() && !usedIds.has(componentId)) {\n usedIds.add(componentId);\n return component;\n }\n\n const repairedId = getRepairedUiGraphComponentId(graphId, index, reservedIds, usedIds);\n usedIds.add(repairedId);\n return { ...component, id: repairedId as UiComponentId };\n });\n\n return { ...uiGraph, components };\n}\n\nfunction getRepairedUiGraphComponentId(\n graphId: string,\n componentIndex: number,\n reservedIds: ReadonlySet<string>,\n usedIds: ReadonlySet<string>,\n): string {\n const baseId = `${graphId}-component-${componentIndex + 1}`;\n let repairedId = baseId;\n let suffix = 2;\n\n while (reservedIds.has(repairedId) || usedIds.has(repairedId)) {\n repairedId = `${baseId}-${suffix}`;\n suffix += 1;\n }\n\n return repairedId;\n}\n\nexport function createDefaultUiGraph(options: { graphId?: GraphId; name?: string } = {}): UiGraph {\n const promptStateKey = 'input';\n const resultStateKey = 'result';\n\n return {\n id: newId<UiGraphId>(),\n name: options.name ?? 'Untitled web app',\n components: [\n {\n id: newId<UiComponentId>(),\n type: 'markdown',\n markdown: '## New Rivet web app\\n\\nEnter a value and run a graph.',\n },\n {\n id: newId<UiComponentId>(),\n type: 'textarea',\n label: 'Input',\n stateKey: promptStateKey,\n placeholder: 'Type something...',\n },\n {\n id: newId<UiComponentId>(),\n type: 'button',\n label: 'Run graph',\n action: {\n type: 'runGraph',\n graphId: options.graphId,\n inputMappings: [{ inputKey: 'input', stateKey: promptStateKey }],\n outputs: [{ stateKey: resultStateKey }],\n },\n },\n {\n id: newId<UiComponentId>(),\n type: 'output',\n label: 'Result',\n stateKey: resultStateKey,\n renderAs: 'json',\n },\n ],\n };\n}\n\nexport function getUiGraphInitialState(uiGraph: UiGraph): Record<string, unknown> {\n const state: Record<string, unknown> = {};\n\n for (const component of uiGraph.components) {\n if (component.type === 'input' || component.type === 'textarea') {\n state[component.stateKey] = component.defaultValue ?? '';\n } else if (component.type === 'dropdown') {\n state[component.stateKey] = '';\n } else if (component.type === 'chat') {\n state[getUiGraphChatDraftStateKey(component.id)] = '';\n state[getUiGraphChatMessagesStateKey(component.id)] = [];\n state[getUiGraphChatPinsStateKey(component.id)] = [];\n }\n }\n\n return state;\n}\n\nexport function getUiGraphActionComponent(\n uiGraph: UiGraph,\n componentId: UiComponentId,\n): UiGraphActionComponent | undefined {\n return uiGraph.components.find(\n (component): component is UiGraphActionComponent =>\n component.id === componentId && (component.type === 'button' || component.type === 'chat'),\n );\n}\n\nexport function getUiGraphChatDraftStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_draft`;\n}\n\nexport function getUiGraphChatMessagesStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_messages`;\n}\n\nexport function getUiGraphChatPinsStateKey(componentId: UiComponentId): string {\n return `__rivet_chat_${componentId}_pins`;\n}\n\nexport function getUiGraphChatMessages(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): UiGraphChatMessage[] {\n const messages = state[getUiGraphChatMessagesStateKey(componentId)];\n return Array.isArray(messages) ? messages.filter(isUiGraphChatMessage) : [];\n}\n\nexport function getUiGraphChatPins(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): UiGraphChatPin[] {\n const messages = getUiGraphChatMessages(componentId, state);\n const storedPins = state[getUiGraphChatPinsStateKey(componentId)];\n const messageIndexes = Array.isArray(storedPins)\n ? [\n ...new Set(\n storedPins.filter(\n (value): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0,\n ),\n ),\n ].sort((left, right) => left - right)\n : [];\n const pinnedIndexes = new Set(messageIndexes);\n const pins: UiGraphChatPin[] = [];\n let prompt: UiGraphChatMessage | undefined;\n let promptMessageIndex: number | undefined;\n\n messages.forEach((message, messageIndex) => {\n if (message.role === 'user') {\n prompt = message;\n promptMessageIndex = messageIndex;\n } else if (pinnedIndexes.has(messageIndex)) {\n pins.push({ messageIndex, prompt, promptMessageIndex, response: message });\n }\n });\n\n return pins;\n}\n\nexport function createUiGraphChatPinStatePatch(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n messageIndex: number,\n): Record<string, unknown> | undefined {\n const messages = getUiGraphChatMessages(componentId, state);\n if (messages[messageIndex]?.role !== 'assistant') {\n return undefined;\n }\n\n const pinsStateKey = getUiGraphChatPinsStateKey(componentId);\n const pinnedIndexes = getUiGraphChatPins(componentId, state).map((pin) => pin.messageIndex);\n return {\n [pinsStateKey]: pinnedIndexes.includes(messageIndex)\n ? pinnedIndexes.filter((index) => index !== messageIndex)\n : [...pinnedIndexes, messageIndex].sort((left, right) => left - right),\n };\n}\n\n/** Clears a Chat's conversation and pins without discarding an unsent draft. */\nexport function createUiGraphChatHistoryFlushStatePatch(componentId: UiComponentId): Record<string, unknown> {\n return {\n [getUiGraphChatMessagesStateKey(componentId)]: [],\n [getUiGraphChatPinsStateKey(componentId)]: [],\n };\n}\n\nexport function createUiGraphChatSubmissionStatePatch(\n componentId: UiComponentId,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> | undefined {\n const draftStateKey = getUiGraphChatDraftStateKey(componentId);\n const content = `${state[draftStateKey] ?? ''}`.trim();\n if (!content) {\n return undefined;\n }\n\n return {\n [draftStateKey]: '',\n [getUiGraphChatMessagesStateKey(componentId)]: [\n ...getUiGraphChatMessages(componentId, state),\n { role: 'user', content } satisfies UiGraphChatMessage,\n ],\n };\n}\n\nexport function getUiGraphComponentActionState(\n component: UiGraphActionComponent,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return getUiGraphActionState(component.action, state);\n }\n\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n return {\n ...getUiGraphActionState(component.action, state),\n [messagesStateKey]: getUiGraphChatMessages(component.id, state),\n };\n}\n\nexport function resolveUiGraphComponentActionInputs(\n component: UiGraphActionComponent,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return resolveUiGraphActionInputs(component.action, state);\n }\n\n const messages = getUiGraphChatMessages(component.id, state);\n const latestMessage = messages[messages.length - 1];\n const latestUserMessage = latestMessage?.role === 'user' ? latestMessage : undefined;\n const historyMessages = latestUserMessage ? messages.slice(0, -1) : messages;\n const inputs = resolveUiGraphActionInputs(component.action, state);\n if (component.action.userInputId) {\n inputs[component.action.userInputId] = latestUserMessage?.content ?? '';\n }\n if (component.action.historyInputId) {\n inputs[component.action.historyInputId] = {\n type: 'chat-message[]',\n value: historyMessages.map(toRivetChatMessage),\n } satisfies DataValue;\n }\n return inputs;\n}\n\nexport function resolveUiGraphComponentActionOutputStatePatch(\n component: UiGraphActionComponent,\n outputs: UiGraphOutputs,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n if (component.type === 'button') {\n return resolveUiGraphActionOutputStatePatch(component.action, outputs);\n }\n\n const outputId = component.action.responseOutputId;\n if (!outputId || !Object.prototype.hasOwnProperty.call(outputs, outputId)) {\n throw new Error(\n outputId\n ? `Graph output \"${outputId}\" was not returned by the target graph.`\n : 'The Chat component has no response graph output.',\n );\n }\n\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n return {\n [messagesStateKey]: [\n ...getUiGraphChatMessages(component.id, state),\n { role: 'assistant', content: getUiGraphChatResponseText(outputs[outputId]!) } satisfies UiGraphChatMessage,\n ],\n };\n}\n\nexport function getUiGraphComponentActionOutputStateKeys(component: UiGraphActionComponent): string[] {\n return component.type === 'button'\n ? getUiGraphActionOutputBindings(component.action)\n .map((binding) => binding.stateKey.trim())\n .filter(Boolean)\n : [getUiGraphChatMessagesStateKey(component.id)];\n}\n\nexport function resolveUiGraphActionInputs(\n action: UiGraphRunGraphAction,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n const inputs: Record<string, unknown> = {};\n\n if (action.inputMappings) {\n for (const binding of action.inputMappings) {\n if (binding.inputKey) {\n inputs[binding.inputKey] = state[binding.stateKey];\n }\n }\n\n return inputs;\n }\n\n for (const [inputId, binding] of Object.entries(action.inputs ?? {})) {\n inputs[inputId] = binding.type === 'state' ? state[binding.key] : binding.value;\n }\n\n return inputs;\n}\n\n/**\n * Selects the UI state that a button action is explicitly allowed to send.\n * Outputs and unrelated form fields stay local to the rendered web app.\n */\nexport function getUiGraphActionState(\n action: UiGraphRunGraphAction,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n return Object.fromEntries(\n [...new Set(getUiGraphActionInputBindings(action).map((binding) => binding.stateKey))]\n .filter(Boolean)\n .filter((stateKey) => Object.prototype.hasOwnProperty.call(state, stateKey))\n .map((stateKey) => [stateKey, state[stateKey]]),\n );\n}\n\nexport function resolveUiGraphActionOutputStateValue(action: UiGraphRunGraphAction, outputs: UiGraphOutputs): unknown {\n if (!action.outputKey) {\n return outputs;\n }\n\n if (!Object.prototype.hasOwnProperty.call(outputs, action.outputKey)) {\n throw new Error(`Graph output \"${action.outputKey}\" was not returned by the target graph.`);\n }\n\n return outputs[action.outputKey]?.value;\n}\n\nexport function resolveUiGraphActionOutputStatePatch(\n action: UiGraphRunGraphAction,\n outputs: UiGraphOutputs,\n): Record<string, unknown> {\n const bindings = getUiGraphActionOutputBindings(action);\n const statePatch: Record<string, unknown> = {};\n\n for (const binding of bindings) {\n const stateKey = binding.stateKey.trim();\n if (!stateKey) {\n continue;\n }\n\n statePatch[stateKey] = resolveUiGraphOutputBindingValue(binding, outputs);\n }\n\n return statePatch;\n}\n\nexport function getUiGraphActionOutputBindings(action: UiGraphRunGraphAction): UiGraphOutputBinding[] {\n if (action.outputs) {\n return action.outputs;\n }\n\n return action.outputStateKey ? [{ outputKey: action.outputKey, stateKey: action.outputStateKey }] : [];\n}\n\nexport function getUiGraphActionInputBindings(action: UiGraphRunGraphAction): UiGraphInputBinding[] {\n if (action.inputMappings) {\n return action.inputMappings;\n }\n\n return Object.entries(action.inputs ?? {}).map(([inputKey, binding]) => ({\n inputKey,\n stateKey: binding.type === 'state' ? binding.key : '',\n }));\n}\n\nfunction resolveUiGraphOutputBindingValue(binding: UiGraphOutputBinding, outputs: UiGraphOutputs): unknown {\n if (!binding.outputKey) {\n return outputs;\n }\n\n if (!Object.prototype.hasOwnProperty.call(outputs, binding.outputKey)) {\n throw new Error(`Graph output \"${binding.outputKey}\" was not returned by the target graph.`);\n }\n\n return outputs[binding.outputKey]?.value;\n}\n\nfunction isUiGraphChatMessage(value: unknown): value is UiGraphChatMessage {\n return (\n value != null &&\n typeof value === 'object' &&\n ((value as UiGraphChatMessage).role === 'user' || (value as UiGraphChatMessage).role === 'assistant') &&\n typeof (value as UiGraphChatMessage).content === 'string'\n );\n}\n\nfunction toRivetChatMessage(message: UiGraphChatMessage): ChatMessage {\n return message.role === 'user'\n ? { type: 'user', message: message.content }\n : {\n type: 'assistant',\n message: message.content,\n function_call: undefined,\n function_calls: undefined,\n };\n}\n\nfunction getUiGraphChatResponseText(output: DataValue): string {\n if (output.type === 'chat-message') {\n const message = output.value.message;\n if (typeof message === 'string') {\n return message;\n }\n return (Array.isArray(message) ? message : [message])\n .flatMap((part) => (typeof part === 'string' ? [part] : []))\n .join('\\n');\n }\n\n if (typeof output.value === 'string') {\n return output.value;\n }\n if (output.value == null) {\n return '';\n }\n\n try {\n return JSON.stringify(output.value, null, 2);\n } catch {\n return String(output.value);\n }\n}\n", "export type GraphProgress = Readonly<{\n message?: string;\n percent?: number;\n}>;\n\nconst MAX_PROGRESS_MESSAGE_LENGTH = 500;\n\n/** Normalizes public graph progress before it crosses executor or web-app transports. */\nexport function normalizeGraphProgress(progress: GraphProgress): GraphProgress | undefined {\n const message =\n typeof progress.message === 'string' ? progress.message.trim().slice(0, MAX_PROGRESS_MESSAGE_LENGTH) : '';\n const percent =\n typeof progress.percent === 'number' && Number.isFinite(progress.percent)\n ? Math.min(100, Math.max(0, progress.percent))\n : undefined;\n\n if (!message && percent == null) {\n return undefined;\n }\n\n return {\n ...(message ? { message } : {}),\n ...(percent == null ? {} : { percent }),\n };\n}\n", "import {\n getUiGraphChatDraftStateKey,\n getUiGraphChatMessages,\n getUiGraphChatPins,\n getUiGraphComponentActionOutputStateKeys,\n getUiGraphComponentActionState,\n getUiGraphInitialState,\n type UiComponentId,\n type UiGraph,\n type UiGraphActionComponent,\n type UiGraphChatMessage,\n type UiGraphChatPin,\n type UiGraphComponent,\n type UiGraphDropdownItem,\n type UiGraphGapSize,\n type UiGraphOutputRenderMode,\n} from './UiGraph.js';\nimport { normalizeGraphProgress, type GraphProgress } from './GraphProgress.js';\n\nexport type UiGraphOutputRenderModel = {\n hasValue: boolean;\n imageErrorMessage?: string;\n imageSource?: string;\n jsonDownloadValue?: string;\n renderedValue: string;\n renderAs: UiGraphOutputRenderMode;\n};\n\nconst IMAGE_DATA_URL_PATTERN = /^data:(image\\/(?:avif|bmp|gif|jpe?g|png|webp));base64,([\\s\\S]+)$/i;\nconst IMAGE_URL_PATTERN = /^(?:https?:\\/\\/|blob:|\\/\\/|\\/|\\.\\.?\\/)/i;\nconst RELATIVE_IMAGE_PATH_PATTERN = /\\.(?:avif|bmp|gif|jpe?g|png|webp)(?:[?#].*)?$/i;\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;\nconst UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD = 128 * 1024;\nconst UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS = 16 * 1024;\nconst UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS = 16 * 1024;\n\nexport type UiGraphComponentRenderModel =\n | {\n component: Extract<UiGraphComponent, { type: 'text' }>;\n text: string;\n type: 'text';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'markdown' }>;\n markdown: string;\n type: 'markdown';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'gap' }>;\n size: UiGraphGapSize;\n type: 'gap';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'input' | 'textarea' }>;\n label: string;\n type: 'input' | 'textarea';\n value: string;\n }\n | {\n component: Extract<UiGraphComponent, { type: 'dropdown' }>;\n items: readonly UiGraphDropdownItem[];\n label: string;\n type: 'dropdown';\n value: string;\n }\n | {\n component: Extract<UiGraphComponent, { type: 'button' }>;\n label: string;\n type: 'button';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'chat' }>;\n draft: string;\n messages: UiGraphChatMessage[];\n pins: UiGraphChatPin[];\n type: 'chat';\n }\n | {\n component: Extract<UiGraphComponent, { type: 'output' }>;\n label: string;\n output: UiGraphOutputRenderModel;\n type: 'output';\n };\n\nexport type UiGraphActionExecution = Readonly<{\n componentId: UiComponentId;\n id: number;\n}>;\n\nexport type UiGraphActionExecutionController = {\n begin(component: UiGraphActionComponent): UiGraphActionExecution | undefined;\n finish(execution: UiGraphActionExecution): boolean;\n isCurrent(execution: UiGraphActionExecution): boolean;\n isRunning(componentId: UiComponentId): boolean;\n noteStateWrite(stateKey: string): void;\n resolveStatePatch(\n execution: UiGraphActionExecution,\n statePatch: Record<string, unknown> | undefined,\n ): Record<string, unknown> | undefined;\n reset(): void;\n};\n\nexport type UiGraphInteractionChange = 'action' | 'graph' | 'presentation' | 'state';\n\nexport type UiGraphInteractionSnapshot = Readonly<{\n actionErrors: Readonly<Record<string, string>>;\n actionProgress: Readonly<Record<string, GraphProgress>>;\n collapsedOutputComponentIds: ReadonlySet<UiComponentId>;\n loadingComponentIds: ReadonlySet<UiComponentId>;\n runningComponentIds: ReadonlySet<UiComponentId>;\n state: Readonly<Record<string, unknown>>;\n}>;\n\nexport type UiGraphActionRunContext = Readonly<{\n abortOtherActions(): void;\n componentId: UiComponentId;\n reportProgress(progress: GraphProgress): void;\n signal: AbortSignal;\n state: Record<string, unknown>;\n}>;\n\nexport type UiGraphActionRunResult = {\n statePatch?: Record<string, unknown>;\n};\n\nexport type UiGraphActionRunner = (context: UiGraphActionRunContext) => Promise<UiGraphActionRunResult>;\n\nexport type UiGraphInteractionController = {\n abortActions(): void;\n cancelAction(componentId: UiComponentId): void;\n detachActions(): void;\n getSnapshot(): UiGraphInteractionSnapshot;\n reset(): void;\n runAction(component: UiGraphActionComponent, runner: UiGraphActionRunner): Promise<void>;\n setUiGraph(uiGraph: UiGraph): void;\n subscribe(listener: (change: UiGraphInteractionChange) => void): () => void;\n toggleOutputCollapsed(componentId: UiComponentId): void;\n updateState(stateKey: string, value: unknown): void;\n updateStatePatch(statePatch: Record<string, unknown>): void;\n};\n\nexport type UiGraphInteractionControllerOptions = {\n initialState?: Record<string, unknown>;\n};\n\ntype ActiveUiGraphAction = Readonly<{\n abortController: AbortController;\n execution: UiGraphActionExecution;\n}>;\n\nconst ACTION_LOADING_DELAY_MS = 300;\n\nfunction getUiGraphActionComponentsById(uiGraph: UiGraph): Map<UiComponentId, UiGraphActionComponent> {\n return new Map(\n uiGraph.components\n .filter(\n (component): component is UiGraphActionComponent => component.type === 'button' || component.type === 'chat',\n )\n .map((component) => [component.id, component]),\n );\n}\n\n/**\n * Action data is persisted as JSON, so its execution contract is limited to\n * primitives, arrays, and plain records. Compare the structure rather than\n * serialized property order: a harmless project reserialization must not\n * cancel an active action, but changing its target or bindings must.\n */\nfunction areUiGraphActionValuesEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) {\n return true;\n }\n if (!left || !right || typeof left !== 'object' || typeof right !== 'object') {\n return false;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => areUiGraphActionValuesEqual(value, right[index]))\n );\n }\n\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(rightRecord, key) &&\n areUiGraphActionValuesEqual(leftRecord[key], rightRecord[key]),\n )\n );\n}\n\nfunction areUiGraphActionComponentsExecutionEquivalent(\n left: UiGraphActionComponent,\n right: UiGraphActionComponent,\n): boolean {\n return left.type === right.type && areUiGraphActionValuesEqual(left.action, right.action);\n}\n\n/**\n * Coordinates independent web-app actions without allowing older completions to\n * clear newer loading states or overwrite newer writes to the same UI state key.\n */\nexport function createUiGraphActionExecutionController(): UiGraphActionExecutionController {\n let nextVersion = 0;\n const activeExecutionByComponent = new Map<UiComponentId, number>();\n const latestWriterByStateKey = new Map<string, number>();\n\n return {\n begin(component) {\n if (activeExecutionByComponent.has(component.id)) {\n return undefined;\n }\n\n const execution = { componentId: component.id, id: ++nextVersion };\n activeExecutionByComponent.set(component.id, execution.id);\n\n for (const stateKey of getUiGraphComponentActionOutputStateKeys(component)) {\n latestWriterByStateKey.set(stateKey, execution.id);\n }\n\n return execution;\n },\n finish(execution) {\n if (activeExecutionByComponent.get(execution.componentId) !== execution.id) {\n return false;\n }\n\n activeExecutionByComponent.delete(execution.componentId);\n return true;\n },\n isCurrent(execution) {\n return activeExecutionByComponent.get(execution.componentId) === execution.id;\n },\n isRunning(componentId) {\n return activeExecutionByComponent.has(componentId);\n },\n noteStateWrite(stateKey) {\n const normalizedStateKey = stateKey.trim();\n if (normalizedStateKey) {\n latestWriterByStateKey.set(normalizedStateKey, ++nextVersion);\n }\n },\n resolveStatePatch(execution, statePatch) {\n if (!statePatch) {\n return undefined;\n }\n\n const applicableEntries = Object.entries(statePatch).filter(\n ([stateKey]) => latestWriterByStateKey.get(stateKey) === execution.id,\n );\n return applicableEntries.length > 0 ? Object.fromEntries(applicableEntries) : undefined;\n },\n reset() {\n activeExecutionByComponent.clear();\n latestWriterByStateKey.clear();\n },\n };\n}\n\n/**\n * Owns mutable web-app interaction state for every renderer. React and direct\n * DOM hosts subscribe to this controller instead of reimplementing action\n * cancellation, loading/error state, and stale state-patch protection.\n */\nexport function createUiGraphInteractionController(\n initialUiGraph: UiGraph,\n options: UiGraphInteractionControllerOptions = {},\n): UiGraphInteractionController {\n let uiGraphId = initialUiGraph.id;\n let actionComponentsById = getUiGraphActionComponentsById(initialUiGraph);\n let outputComponentIds = getUiGraphOutputComponentIds(initialUiGraph);\n let outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(initialUiGraph);\n const initialStateOverride = options.initialState ? { ...options.initialState } : undefined;\n let initialState = normalizeUiGraphDropdownState(\n initialUiGraph,\n initialStateOverride ?? getUiGraphInitialState(initialUiGraph),\n );\n let state = { ...initialState };\n let actionErrors: Record<string, string> = {};\n let actionProgress: Record<string, GraphProgress> = {};\n const collapsedOutputComponentIds = new Set<UiComponentId>();\n let snapshot: UiGraphInteractionSnapshot;\n const actionController = createUiGraphActionExecutionController();\n const activeActions = new Map<number, ActiveUiGraphAction>();\n const loadingActionIds = new Set<number>();\n const loadingDelayTimers = new Map<number, ReturnType<typeof setTimeout>>();\n const listeners = new Set<(change: UiGraphInteractionChange) => void>();\n\n const updateSnapshot = (): void => {\n snapshot = {\n actionErrors,\n actionProgress,\n collapsedOutputComponentIds: new Set(collapsedOutputComponentIds),\n loadingComponentIds: new Set(\n [...activeActions].flatMap(([executionId, { execution }]) =>\n loadingActionIds.has(executionId) ? [execution.componentId] : [],\n ),\n ),\n runningComponentIds: new Set([...activeActions.values()].map(({ execution }) => execution.componentId)),\n state,\n };\n };\n const publish = (change: UiGraphInteractionChange): void => {\n updateSnapshot();\n for (const listener of listeners) {\n listener(change);\n }\n };\n const clearActionLoadingPresentation = (executionId: number): void => {\n const timer = loadingDelayTimers.get(executionId);\n if (timer != null) {\n clearTimeout(timer);\n loadingDelayTimers.delete(executionId);\n }\n loadingActionIds.delete(executionId);\n };\n const delayActionLoadingPresentation = (execution: UiGraphActionExecution): void => {\n loadingDelayTimers.set(\n execution.id,\n setTimeout(() => {\n loadingDelayTimers.delete(execution.id);\n if (!activeActions.has(execution.id) || !actionController.isCurrent(execution)) return;\n loadingActionIds.add(execution.id);\n publish('action');\n }, ACTION_LOADING_DELAY_MS),\n );\n };\n const abortMatchingActions = (\n predicate: (activeAction: ActiveUiGraphAction, executionId: number) => boolean,\n notify: boolean,\n ): boolean => {\n let changed = false;\n for (const [executionId, activeAction] of activeActions) {\n if (!predicate(activeAction, executionId)) {\n continue;\n }\n activeAction.abortController.abort();\n activeActions.delete(executionId);\n clearActionLoadingPresentation(executionId);\n actionController.finish(activeAction.execution);\n changed = true;\n }\n if (changed && notify) {\n publish('action');\n }\n return changed;\n };\n const abortAllActions = (notify: boolean): void => {\n let changed = abortMatchingActions(() => true, false);\n actionController.reset();\n if (Object.keys(actionProgress).length > 0) {\n actionProgress = {};\n changed = true;\n }\n if (changed && notify) {\n publish('action');\n }\n };\n const removeActionPresentation = (componentId: UiComponentId): boolean => {\n let changed = false;\n if (Object.prototype.hasOwnProperty.call(actionErrors, componentId)) {\n actionErrors = { ...actionErrors };\n delete actionErrors[componentId];\n changed = true;\n }\n if (Object.prototype.hasOwnProperty.call(actionProgress, componentId)) {\n actionProgress = { ...actionProgress };\n delete actionProgress[componentId];\n changed = true;\n }\n return changed;\n };\n const expandOutputsForUpdatedState = (\n stateKeys: Iterable<string>,\n nextState: Readonly<Record<string, unknown>>,\n ): void => {\n for (const stateKey of stateKeys) {\n for (const component of outputComponentsByStateKey.get(stateKey) ?? []) {\n if (getUiGraphOutputRenderModel(nextState, stateKey, component.renderAs ?? 'text').hasValue) {\n collapsedOutputComponentIds.delete(component.id);\n }\n }\n }\n };\n\n updateSnapshot();\n\n return {\n abortActions() {\n abortAllActions(true);\n },\n cancelAction(componentId) {\n if (abortMatchingActions(({ execution }) => execution.componentId === componentId, false)) {\n removeActionPresentation(componentId);\n publish('action');\n }\n },\n detachActions() {\n for (const executionId of activeActions.keys()) {\n clearActionLoadingPresentation(executionId);\n }\n activeActions.clear();\n actionController.reset();\n actionProgress = {};\n updateSnapshot();\n },\n getSnapshot() {\n return snapshot;\n },\n reset() {\n abortAllActions(false);\n state = { ...initialState };\n actionErrors = {};\n actionProgress = {};\n collapsedOutputComponentIds.clear();\n publish('state');\n },\n async runAction(component, runner) {\n const execution = actionController.begin(component);\n if (!execution) {\n return;\n }\n\n const abortController = new AbortController();\n activeActions.set(execution.id, { abortController, execution });\n delayActionLoadingPresentation(execution);\n removeActionPresentation(component.id);\n publish('action');\n\n try {\n const result = await runner({\n abortOtherActions: () =>\n abortMatchingActions((_activeAction, executionId) => executionId !== execution.id, true),\n componentId: component.id,\n reportProgress: (progress) => {\n if (!actionController.isCurrent(execution)) return;\n const normalized = normalizeGraphProgress(progress);\n if (!normalized) return;\n actionProgress = { ...actionProgress, [component.id]: normalized };\n publish('action');\n },\n signal: abortController.signal,\n state: getUiGraphComponentActionState(component, state),\n });\n if (!actionController.isCurrent(execution)) {\n return;\n }\n\n const statePatch = actionController.resolveStatePatch(execution, result.statePatch);\n if (statePatch) {\n const nextState = applyUiGraphStatePatch(state, statePatch);\n expandOutputsForUpdatedState(Object.keys(statePatch), nextState);\n state = nextState;\n }\n } catch (error) {\n if (!abortController.signal.aborted && actionController.isCurrent(execution)) {\n actionErrors = {\n ...actionErrors,\n [component.id]: error instanceof Error ? error.message : String(error),\n };\n }\n } finally {\n if (activeActions.delete(execution.id)) {\n clearActionLoadingPresentation(execution.id);\n actionController.finish(execution);\n if (Object.prototype.hasOwnProperty.call(actionProgress, component.id)) {\n actionProgress = { ...actionProgress };\n delete actionProgress[component.id];\n }\n publish('action');\n }\n }\n },\n setUiGraph(nextUiGraph) {\n if (nextUiGraph.id !== uiGraphId) {\n abortAllActions(false);\n uiGraphId = nextUiGraph.id;\n initialState = initialStateOverride ?? getUiGraphInitialState(nextUiGraph);\n state = { ...initialState };\n actionErrors = {};\n actionProgress = {};\n outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);\n outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);\n actionComponentsById = getUiGraphActionComponentsById(nextUiGraph);\n collapsedOutputComponentIds.clear();\n publish('graph');\n return;\n }\n\n if (!initialStateOverride) {\n initialState = getUiGraphInitialState(nextUiGraph);\n }\n\n const normalizedState = normalizeUiGraphDropdownState(nextUiGraph, state);\n const stateChanged = normalizedState !== state;\n if (stateChanged) {\n state = normalizedState;\n }\n\n outputComponentIds = getUiGraphOutputComponentIds(nextUiGraph);\n outputComponentsByStateKey = getUiGraphOutputComponentsByStateKey(nextUiGraph);\n const collapsedOutputIdsBeforeCleanup = collapsedOutputComponentIds.size;\n for (const componentId of collapsedOutputComponentIds) {\n if (!outputComponentIds.has(componentId)) {\n collapsedOutputComponentIds.delete(componentId);\n }\n }\n\n const nextActionComponentsById = getUiGraphActionComponentsById(nextUiGraph);\n const actionComponentIds = new Set(nextActionComponentsById.keys());\n const changedActionComponentIds = new Set(\n [...nextActionComponentsById].flatMap(([componentId, component]) => {\n const previousComponent = actionComponentsById.get(componentId);\n return previousComponent && !areUiGraphActionComponentsExecutionEquivalent(previousComponent, component)\n ? [componentId]\n : [];\n }),\n );\n let changed =\n collapsedOutputComponentIds.size !== collapsedOutputIdsBeforeCleanup ||\n stateChanged ||\n abortMatchingActions(\n ({ execution }) =>\n !actionComponentIds.has(execution.componentId) || changedActionComponentIds.has(execution.componentId),\n false,\n );\n for (const componentId of changedActionComponentIds) {\n changed = removeActionPresentation(componentId) || changed;\n }\n actionComponentsById = nextActionComponentsById;\n const remainingErrors = Object.fromEntries(\n Object.entries(actionErrors).filter(([componentId]) => actionComponentIds.has(componentId as UiComponentId)),\n );\n const remainingProgress = Object.fromEntries(\n Object.entries(actionProgress).filter(([componentId]) => actionComponentIds.has(componentId as UiComponentId)),\n );\n if (Object.keys(remainingErrors).length !== Object.keys(actionErrors).length) {\n actionErrors = remainingErrors;\n changed = true;\n }\n if (Object.keys(remainingProgress).length !== Object.keys(actionProgress).length) {\n actionProgress = remainingProgress;\n changed = true;\n }\n if (changed) {\n publish('graph');\n }\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n toggleOutputCollapsed(componentId) {\n if (!outputComponentIds.has(componentId)) {\n return;\n }\n\n if (collapsedOutputComponentIds.has(componentId)) {\n collapsedOutputComponentIds.delete(componentId);\n } else {\n collapsedOutputComponentIds.add(componentId);\n }\n publish('presentation');\n },\n updateState(stateKey, value) {\n actionController.noteStateWrite(stateKey);\n const nextState = { ...state, [stateKey]: value };\n expandOutputsForUpdatedState([stateKey], nextState);\n state = nextState;\n publish('state');\n },\n updateStatePatch(statePatch) {\n for (const stateKey of Object.keys(statePatch)) {\n actionController.noteStateWrite(stateKey);\n }\n const nextState = applyUiGraphStatePatch(state, statePatch);\n expandOutputsForUpdatedState(Object.keys(statePatch), nextState);\n state = nextState;\n publish('state');\n },\n };\n}\n\nfunction getUiGraphOutputComponentIds(uiGraph: UiGraph): Set<UiComponentId> {\n return new Set(\n uiGraph.components.filter((component) => component.type === 'output').map((component) => component.id),\n );\n}\n\nfunction getUiGraphOutputComponentsByStateKey(\n uiGraph: UiGraph,\n): Map<string, Extract<UiGraphComponent, { type: 'output' }>[]> {\n const componentsByStateKey = new Map<string, Extract<UiGraphComponent, { type: 'output' }>[]>();\n for (const component of uiGraph.components) {\n if (component.type !== 'output') continue;\n const components = componentsByStateKey.get(component.stateKey) ?? [];\n components.push(component);\n componentsByStateKey.set(component.stateKey, components);\n }\n return componentsByStateKey;\n}\n\nfunction normalizeUiGraphDropdownState(\n uiGraph: UiGraph,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n let normalizedState: Record<string, unknown> | undefined;\n\n for (const component of uiGraph.components) {\n if (component.type !== 'dropdown') {\n continue;\n }\n\n const selectedValue = `${state[component.stateKey] ?? ''}`;\n if (selectedValue === '' || component.items.some((item) => item.value === selectedValue)) {\n continue;\n }\n\n normalizedState ??= { ...state };\n normalizedState[component.stateKey] = '';\n }\n\n return normalizedState ?? (state as Record<string, unknown>);\n}\n\nexport function getUiGraphComponentRenderModel(\n component: UiGraphComponent,\n state: Readonly<Record<string, unknown>>,\n): UiGraphComponentRenderModel {\n switch (component.type) {\n case 'text':\n return { component, text: component.text, type: 'text' };\n case 'markdown':\n return { component, markdown: component.markdown, type: 'markdown' };\n case 'gap':\n return { component, size: component.size, type: 'gap' };\n case 'input':\n case 'textarea':\n return {\n component,\n label: getUiGraphComponentLabel(component),\n type: component.type,\n value: `${state[component.stateKey] ?? component.defaultValue ?? ''}`,\n };\n case 'dropdown': {\n const selectedValue = `${state[component.stateKey] ?? ''}`;\n return {\n component,\n items: component.items,\n label: getUiGraphComponentLabel(component),\n type: 'dropdown',\n value: component.items.some((item) => item.value === selectedValue) ? selectedValue : '',\n };\n }\n case 'button':\n return { component, label: component.label, type: 'button' };\n case 'chat':\n return {\n component,\n draft: `${state[getUiGraphChatDraftStateKey(component.id)] ?? ''}`,\n messages: getUiGraphChatMessages(component.id, state),\n pins: getUiGraphChatPins(component.id, state),\n type: 'chat',\n };\n case 'output':\n return {\n component,\n label: getUiGraphComponentLabel(component),\n output: getUiGraphOutputRenderModel(state, component.stateKey, component.renderAs ?? 'text'),\n type: 'output',\n };\n }\n}\n\nexport function getUiGraphComponentLabel(\n component: Extract<UiGraphComponent, { type: 'input' | 'textarea' | 'dropdown' | 'output' }>,\n): string {\n return component.label || component.stateKey;\n}\n\nexport function getUiGraphOutputRenderModel(\n state: Readonly<Record<string, unknown>>,\n stateKey: string,\n renderAs: UiGraphOutputRenderMode,\n): UiGraphOutputRenderModel {\n const value = state[stateKey];\n const renderedValue = renderUiGraphOutputValue(value, renderAs);\n const hasStateValue = hasUiGraphStateValue(state, stateKey);\n const hasImageValue = hasStateValue && value != null && value !== '';\n const imageSource = hasImageValue && renderAs === 'image' ? getUiGraphImageSource(value) : undefined;\n const imageErrorMessage =\n hasImageValue && renderAs === 'image' && !imageSource ? 'Expected an image URL or base64 image.' : undefined;\n const hasValue =\n renderAs === 'image' ? imageSource != null || imageErrorMessage != null : renderedValue.trim().length > 0;\n\n return {\n hasValue,\n ...(imageErrorMessage ? { imageErrorMessage } : {}),\n ...(imageSource ? { imageSource } : {}),\n ...(hasValue && renderAs === 'json' ? { jsonDownloadValue: renderedValue } : {}),\n renderedValue,\n renderAs,\n };\n}\n\nexport function hasUiGraphStateValue(state: Readonly<Record<string, unknown>>, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(state, key) && state[key] !== undefined;\n}\n\nexport function renderUiGraphOutputValue(value: unknown, renderAs: UiGraphOutputRenderMode): string {\n if (renderAs === 'json') {\n return stringifyUiGraphValue(value) ?? '';\n }\n\n return typeof value === 'string' ? value : value == null ? '' : stringifyUiGraphValue(value) ?? '';\n}\n\n/**\n * Splits very large JSON output into append-only DOM text chunks. Appending the\n * chunks lets browser renderers show the first screenful without blocking on\n * layout for every visual line in one huge escaped JSON string.\n */\nexport function getUiGraphProgressiveJsonOutputChunks(value: string): readonly string[] | undefined {\n if (value.length < UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_THRESHOLD) {\n return undefined;\n }\n\n const chunks: string[] = [];\n let offset = 0;\n let chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_INITIAL_CHARS;\n while (offset < value.length) {\n let nextOffset = Math.min(value.length, offset + chunkLength);\n if (\n nextOffset < value.length &&\n isHighSurrogate(value.charCodeAt(nextOffset - 1)) &&\n isLowSurrogate(value.charCodeAt(nextOffset))\n ) {\n nextOffset += 1;\n }\n chunks.push(value.slice(offset, nextOffset));\n offset = nextOffset;\n chunkLength = UI_GRAPH_PROGRESSIVE_JSON_OUTPUT_CHUNK_CHARS;\n }\n\n return chunks;\n}\n\nfunction isHighSurrogate(value: number): boolean {\n return value >= 0xd800 && value <= 0xdbff;\n}\n\nfunction isLowSurrogate(value: number): boolean {\n return value >= 0xdc00 && value <= 0xdfff;\n}\n\nexport function getUiGraphImageSource(value: unknown): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const source = value.trim();\n if (!source) {\n return undefined;\n }\n\n const dataUrl = IMAGE_DATA_URL_PATTERN.exec(source);\n if (dataUrl) {\n const base64 = normalizeBase64(dataUrl[2]!);\n return base64 ? `data:${normalizeImageMediaType(dataUrl[1]!)};base64,${base64}` : undefined;\n }\n\n const base64 = normalizeBase64(source);\n const inferredMediaType = base64 ? inferBase64ImageMediaType(base64) : undefined;\n if (base64 && inferredMediaType) {\n return `data:${inferredMediaType};base64,${base64}`;\n }\n\n if (!IMAGE_URL_PATTERN.test(source) && !RELATIVE_IMAGE_PATH_PATTERN.test(source)) {\n return undefined;\n }\n\n try {\n const protocol = new URL(source, 'https://rivet.invalid').protocol;\n return protocol === 'http:' || protocol === 'https:' || protocol === 'blob:' ? source : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeBase64(value: string): string | undefined {\n const compact = value.replace(/\\s/g, '');\n return compact.length >= 8 && compact.length % 4 !== 1 && BASE64_PATTERN.test(compact) ? compact : undefined;\n}\n\nfunction normalizeImageMediaType(mediaType: string): string {\n const normalized = mediaType.toLowerCase();\n return normalized === 'image/jpg' ? 'image/jpeg' : normalized;\n}\n\nfunction inferBase64ImageMediaType(value: string): string | undefined {\n if (value.startsWith('iVBORw0KGgo')) return 'image/png';\n if (value.startsWith('/9j/')) return 'image/jpeg';\n if (value.startsWith('R0lGODdh') || value.startsWith('R0lGODlh')) return 'image/gif';\n return undefined;\n}\n\nexport function stringifyUiGraphValue(value: unknown): string | undefined {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return '[Unserializable value]';\n }\n}\n\nexport function getUiGraphJsonOutputFilename(appName: string, date = new Date()): string {\n const safeName = appName\n .trim()\n .replace(/[<>:\"/\\\\|?*\\u0000-\\u001F]/g, '-')\n .replace(/\\s+/g, ' ')\n .slice(0, 80);\n\n return `${safeName || 'Rivet web app'} ${formatUiGraphDownloadDateTime(date)}.json`;\n}\n\nexport function formatUiGraphDownloadDateTime(date: Date): string {\n const pad = (value: number) => `${value}`.padStart(2, '0');\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(\n date.getMinutes(),\n )}-${pad(date.getSeconds())}`;\n}\n\nexport function applyUiGraphStatePatch(\n state: Record<string, unknown>,\n statePatch: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n return statePatch ? { ...state, ...statePatch } : state;\n}\n", "import type { UiComponentId } from './UiGraph.js';\nimport { normalizeGraphProgress, type GraphProgress } from './GraphProgress.js';\n\nexport const RIVET_WEB_APP_ACTION_PROTOCOL_VERSION = 1 as const;\n\nexport type RivetWebAppActionStartMessage = {\n type: 'action.start';\n requestId: string;\n componentId: UiComponentId;\n revisionKey?: string;\n state: Record<string, unknown>;\n storage?: Record<string, unknown>;\n};\n\nexport type RivetWebAppActionCancelMessage = {\n type: 'action.cancel';\n runId: string;\n};\n\nexport type RivetWebAppRunResumeMessage = {\n type: 'run.resume';\n runId: string;\n lastSequence: number;\n};\n\nexport type RivetWebAppClientHelloMessage = {\n type: 'client.hello';\n protocolVersion: typeof RIVET_WEB_APP_ACTION_PROTOCOL_VERSION;\n};\n\nexport type RivetWebAppClientMessage =\n | RivetWebAppClientHelloMessage\n | RivetWebAppActionStartMessage\n | RivetWebAppActionCancelMessage\n | RivetWebAppRunResumeMessage;\n\ntype RunEventBase = {\n requestId: string;\n runId: string;\n sequence: number;\n};\n\nexport type RivetWebAppServerMessage =\n | {\n type: 'server.ready';\n protocolVersion: typeof RIVET_WEB_APP_ACTION_PROTOCOL_VERSION;\n }\n | ({ type: 'action.accepted' } & RunEventBase)\n | ({ type: 'action.progress'; progress: GraphProgress } & RunEventBase)\n | ({\n type: 'action.completed';\n statePatch: Record<string, unknown>;\n storagePatch?: Record<string, unknown>;\n } & RunEventBase)\n | ({ type: 'action.failed'; error: string; code?: string } & RunEventBase)\n | ({ type: 'action.cancelled' } & RunEventBase)\n | ({ type: 'action.interrupted'; error: string } & RunEventBase)\n | {\n type: 'action.rejected';\n requestId: string;\n error: string;\n code?: string;\n }\n | {\n type: 'run.rejected';\n runId: string;\n error: string;\n code?: string;\n }\n | {\n type: 'server.draining';\n };\n\nexport type RivetWebAppRunEvent = Exclude<\n RivetWebAppServerMessage,\n { type: 'server.ready' | 'action.rejected' | 'run.rejected' | 'server.draining' }\n>;\n\nexport function parseRivetWebAppClientMessage(value: unknown): RivetWebAppClientMessage | undefined {\n if (!isRecord(value) || typeof value.type !== 'string') return undefined;\n\n switch (value.type) {\n case 'client.hello':\n return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION\n ? { type: value.type, protocolVersion: value.protocolVersion }\n : undefined;\n case 'action.start':\n return isNonEmptyString(value.requestId) &&\n isNonEmptyString(value.componentId) &&\n isRecord(value.state) &&\n (value.storage == null || isRecord(value.storage)) &&\n (value.revisionKey == null || typeof value.revisionKey === 'string')\n ? {\n type: value.type,\n requestId: value.requestId,\n componentId: value.componentId as UiComponentId,\n state: value.state,\n ...(isRecord(value.storage) ? { storage: value.storage } : {}),\n ...(typeof value.revisionKey === 'string' ? { revisionKey: value.revisionKey } : {}),\n }\n : undefined;\n case 'action.cancel':\n return isNonEmptyString(value.runId) ? { type: value.type, runId: value.runId } : undefined;\n case 'run.resume':\n return isNonEmptyString(value.runId) &&\n typeof value.lastSequence === 'number' &&\n Number.isSafeInteger(value.lastSequence) &&\n value.lastSequence >= 0\n ? { type: value.type, runId: value.runId, lastSequence: value.lastSequence }\n : undefined;\n default:\n return undefined;\n }\n}\n\nexport function parseRivetWebAppServerMessage(value: unknown): RivetWebAppServerMessage | undefined {\n if (!isRecord(value) || typeof value.type !== 'string') return undefined;\n\n if (value.type === 'server.ready') {\n return value.protocolVersion === RIVET_WEB_APP_ACTION_PROTOCOL_VERSION\n ? { type: value.type, protocolVersion: value.protocolVersion }\n : undefined;\n }\n if (value.type === 'server.draining') return { type: value.type };\n if (value.type === 'action.rejected') {\n return isNonEmptyString(value.requestId) && isNonEmptyString(value.error)\n ? {\n type: value.type,\n requestId: value.requestId,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n }\n if (value.type === 'run.rejected') {\n return isNonEmptyString(value.runId) && isNonEmptyString(value.error)\n ? {\n type: value.type,\n runId: value.runId,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n }\n if (!hasRunEventBase(value)) return undefined;\n\n const base = {\n requestId: value.requestId,\n runId: value.runId,\n sequence: value.sequence,\n };\n switch (value.type) {\n case 'action.accepted':\n case 'action.cancelled':\n return { type: value.type, ...base };\n case 'action.progress': {\n if (!isRecord(value.progress)) return undefined;\n const progress = normalizeGraphProgress({\n message: typeof value.progress.message === 'string' ? value.progress.message : undefined,\n percent: typeof value.progress.percent === 'number' ? value.progress.percent : undefined,\n });\n return progress ? { type: value.type, ...base, progress } : undefined;\n }\n case 'action.completed':\n return isRecord(value.statePatch) && (value.storagePatch == null || isRecord(value.storagePatch))\n ? {\n type: value.type,\n ...base,\n statePatch: value.statePatch,\n ...(isRecord(value.storagePatch) ? { storagePatch: value.storagePatch } : {}),\n }\n : undefined;\n case 'action.failed':\n return isNonEmptyString(value.error)\n ? {\n type: value.type,\n ...base,\n error: value.error,\n ...(typeof value.code === 'string' ? { code: value.code } : {}),\n }\n : undefined;\n case 'action.interrupted':\n return isNonEmptyString(value.error) ? { type: value.type, ...base, error: value.error } : undefined;\n default:\n return undefined;\n }\n}\n\nexport function isRivetWebAppRunTerminalEvent(event: RivetWebAppRunEvent): boolean {\n return (\n event.type === 'action.completed' ||\n event.type === 'action.failed' ||\n event.type === 'action.cancelled' ||\n event.type === 'action.interrupted'\n );\n}\n\nfunction hasRunEventBase(value: Record<string, unknown>): value is Record<string, unknown> & RunEventBase {\n return (\n isNonEmptyString(value.requestId) &&\n isNonEmptyString(value.runId) &&\n typeof value.sequence === 'number' &&\n Number.isSafeInteger(value.sequence) &&\n value.sequence > 0\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n", "import {\n getUiGraphChatDraftStateKey,\n getUiGraphChatMessages,\n getUiGraphChatMessagesStateKey,\n getUiGraphChatPins,\n getUiGraphChatPinsStateKey,\n type UiGraph,\n} from './UiGraph.js';\nimport { getUiGraphJsonOutputFilename } from './UiGraphRuntimeModel.js';\n\nconst OUTPUT_MAX_HEIGHT_PX = 800;\nconst OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;\nconst OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = '--rivet-web-app-output-resize-min-height';\nconst OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = '--rivet-web-app-output-resize-max-height';\nconst CHAT_SEARCH_MATCH_CLASS = 'rivet-web-app-chat-search-match';\nconst CHAT_SEARCH_ACTIVE_MATCH_CLASS = 'rivet-web-app-chat-search-match-active';\nconst UI_GRAPH_CHAT_STORAGE_PREFIX = 'rivet-web-app-chat-state:v1';\nconst UI_GRAPH_APP_STORAGE_PREFIX = 'rivet-web-app-storage:v1';\n\ntype UiGraphBrowserStorage = Pick<Storage, 'getItem' | 'removeItem' | 'setItem'>;\ntype UiGraphStorageLocation = Pick<Location, 'origin' | 'pathname'>;\n\nconst escapeRegularExpression = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nconst getPixelValue = (value: string, fallback: number): number => {\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed : fallback;\n};\n\nconst setStyleProperty = (element: HTMLElement, property: string, value: string): void => {\n if (element.style.getPropertyValue(property) !== value) {\n element.style.setProperty(property, value);\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst getDefaultUiGraphBrowserStorage = (): UiGraphBrowserStorage | undefined => {\n try {\n return globalThis.localStorage ?? globalThis.window?.localStorage;\n } catch {\n // Embedded, private, and restricted browser contexts can reject storage.\n return undefined;\n }\n};\n\nconst getDefaultUiGraphStorageLocation = (): UiGraphStorageLocation | undefined => {\n try {\n return globalThis.location ?? globalThis.window?.location;\n } catch {\n return undefined;\n }\n};\n\n/** Returns the browser-local key for one app URL and one persisted UI graph. */\nexport function getUiGraphChatStorageKey(\n uiGraph: UiGraph,\n location: UiGraphStorageLocation | undefined = getDefaultUiGraphStorageLocation(),\n): string | undefined {\n if (!location?.origin) {\n return undefined;\n }\n\n const pathname = location.pathname.replace(/\\/+$/, '') || '/';\n return [\n UI_GRAPH_CHAT_STORAGE_PREFIX,\n encodeURIComponent(location.origin),\n encodeURIComponent(pathname),\n encodeURIComponent(uiGraph.id),\n ].join(':');\n}\n\n/** Returns the browser-local key for graph-managed storage owned by one web app. */\nexport function getUiGraphWebAppStorageKey(\n uiGraph: UiGraph,\n location: UiGraphStorageLocation | undefined = getDefaultUiGraphStorageLocation(),\n): string | undefined {\n if (!location?.origin) {\n return undefined;\n }\n\n const pathname = location.pathname.replace(/\\/+$/, '') || '/';\n return [\n UI_GRAPH_APP_STORAGE_PREFIX,\n encodeURIComponent(location.origin),\n encodeURIComponent(pathname),\n encodeURIComponent(uiGraph.id),\n ].join(':');\n}\n\n/** Loads the browser snapshot used by Stored Value nodes for this one web app. */\nexport function loadUiGraphWebAppStorage(\n uiGraph: UiGraph,\n storage: UiGraphBrowserStorage | undefined = getDefaultUiGraphBrowserStorage(),\n location?: UiGraphStorageLocation,\n): Record<string, unknown> {\n const key = getUiGraphWebAppStorageKey(uiGraph, location);\n if (!key || !storage) return {};\n\n try {\n const serialized = storage.getItem(key);\n if (!serialized) return {};\n const value: unknown = JSON.parse(serialized);\n return isRecord(value) ? value : {};\n } catch {\n return {};\n }\n}\n\n/** Merges a successful action's changed keys and persists the complete app-local record. */\nexport function applyUiGraphWebAppStoragePatch(\n uiGraph: UiGraph,\n currentStorage: Readonly<Record<string, unknown>>,\n patch: Readonly<Record<string, unknown>>,\n storage: UiGraphBrowserStorage | undefined = getDefaultUiGraphBrowserStorage(),\n location?: UiGraphStorageLocation,\n): Record<string, unknown> {\n const key = getUiGraphWebAppStorageKey(uiGraph, location);\n if (!key || !storage) {\n throw new Error('Browser storage is unavailable for this web app.');\n }\n\n const nextStorage = { ...currentStorage, ...patch };\n let serialized: string;\n try {\n serialized = JSON.stringify(nextStorage);\n storage.setItem(key, serialized);\n } catch (error) {\n throw new Error('Web app storage could not be saved. Browser storage may be unavailable or full.', {\n cause: error,\n });\n }\n return nextStorage;\n}\n\n/**\n * Applies the keys from one completed action that have not already been superseded.\n * Ordering metadata is committed only after persistence succeeds, so a failed newer\n * write cannot suppress an older successful action that completes later.\n */\nexport function applyUiGraphWebAppStorageActionPatch(\n patch: Readonly<Record<string, unknown>>,\n actionNumber: number,\n appliedActionByKey: Map<string, number>,\n persist: (applicablePatch: Record<string, unknown>) => void,\n): Record<string, unknown> {\n const applicablePatch = Object.fromEntries(\n Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0)),\n );\n const applicableKeys = Object.keys(applicablePatch);\n if (applicableKeys.length === 0) return applicablePatch;\n\n persist(applicablePatch);\n for (const key of applicableKeys) appliedActionByKey.set(key, actionNumber);\n return applicablePatch;\n}\n\n/** Selects and validates the private browser-persisted state of Chat components only. */\nexport function getUiGraphChatPersistentState(\n uiGraph: UiGraph,\n state: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n const persistentState: Record<string, unknown> = {};\n\n for (const component of uiGraph.components) {\n if (component.type !== 'chat') continue;\n\n const draftStateKey = getUiGraphChatDraftStateKey(component.id);\n const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);\n const pinsStateKey = getUiGraphChatPinsStateKey(component.id);\n const draft = state[draftStateKey];\n const messages = getUiGraphChatMessages(component.id, state);\n const pins = getUiGraphChatPins(component.id, state).map((pin) => pin.messageIndex);\n\n if (typeof draft === 'string' && draft) {\n persistentState[draftStateKey] = draft;\n }\n if (messages.length > 0) {\n persistentState[messagesStateKey] = messages;\n }\n if (pins.length > 0) {\n persistentState[pinsStateKey] = pins;\n }\n }\n\n return persistentState;\n}\n\n/**\n * Reports whether a state transition changed the browser-persisted portion of\n * any Chat. Runtime state updates are immutable, so reference comparison keeps\n * action progress and unrelated form edits from serializing a large history.\n */\nexport function hasUiGraphChatPersistentStateChanged(\n uiGraph: UiGraph,\n previousState: Readonly<Record<string, unknown>>,\n nextState: Readonly<Record<string, unknown>>,\n): boolean {\n return uiGraph.components.some((component) => {\n if (component.type !== 'chat') return false;\n\n return (\n previousState[getUiGraphChatDraftStateKey(component.id)] !==\n nextState[getUiGraphChatDraftStateKey(component.id)] ||\n previousState[getUiGraphChatMessagesStateKey(component.id)] !==\n nextState[getUiGraphChatMessagesStateKey(component.id)] ||\n previousState[getUiGraphChatPinsStateKey(component.id)] !== nextState[getUiGraphChatPinsStateKey(component.id)]\n );\n });\n}\n\n/** Loads valid Chat-only state without allowing malformed local storage to affect rendering. */\nexport function loadUiGraphChatPersistentState(\n uiGraph: UiGraph,\n storage: UiGraphBrowserStorage | undefined = getDefaultUiGraphBrowserStorage(),\n location?: UiGraphStorageLocation,\n): Record<string, unknown> {\n const key = getUiGraphChatStorageKey(uiGraph, location);\n if (!key || !storage) {\n return {};\n }\n\n try {\n const serializedState = storage.getItem(key);\n if (!serializedState) {\n return {};\n }\n\n const storedState: unknown = JSON.parse(serializedState);\n return isRecord(storedState) ? getUiGraphChatPersistentState(uiGraph, storedState) : {};\n } catch {\n return {};\n }\n}\n\n/** Persists only Chat draft, conversation, and pins for the current browser app URL. */\nexport function saveUiGraphChatPersistentState(\n uiGraph: UiGraph,\n state: Readonly<Record<string, unknown>>,\n storage: UiGraphBrowserStorage | undefined = getDefaultUiGraphBrowserStorage(),\n location?: UiGraphStorageLocation,\n): void {\n const key = getUiGraphChatStorageKey(uiGraph, location);\n if (!key || !storage) {\n return;\n }\n\n try {\n const persistentState = getUiGraphChatPersistentState(uiGraph, state);\n if (Object.keys(persistentState).length === 0) {\n storage.removeItem(key);\n return;\n }\n\n const serializedState = JSON.stringify(persistentState);\n if (storage.getItem(key) !== serializedState) {\n storage.setItem(key, serializedState);\n }\n } catch {\n // Storage can be unavailable, full, or blocked; Chat itself still works.\n }\n}\n\n/**\n * Limits an expanded Output card's native resize range to one visible content\n * line through its rendered value. Short, naturally-sized outputs have no resize\n * handle because resizing them would only add blank space.\n */\nexport function observeUiGraphOutputResizeBounds(output: HTMLElement): () => void {\n const ownerWindow = output.ownerDocument.defaultView;\n let scheduledFrame: number | undefined;\n\n const sync = () => {\n scheduledFrame = undefined;\n if (!ownerWindow) return;\n const header = output.querySelector<HTMLElement>('.rivet-web-app-output-header');\n const content = output.querySelector<HTMLElement>('.rivet-web-app-output-content');\n const body = output.querySelector<HTMLElement>('.rivet-web-app-output-content-body');\n\n if (!header || !content || !body) {\n output.classList.remove('rivet-web-app-output-resizable');\n output.classList.remove('rivet-web-app-output-scrollable');\n output.style.removeProperty(OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY);\n output.style.removeProperty(OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY);\n return;\n }\n\n const bodyStyle = ownerWindow.getComputedStyle(body);\n const lineHeight = getPixelValue(bodyStyle.lineHeight, getPixelValue(bodyStyle.fontSize, 16) * 1.5);\n const contentStyle = ownerWindow.getComputedStyle(content);\n const contentPadding = getPixelValue(contentStyle.paddingTop, 0) + getPixelValue(contentStyle.paddingBottom, 0);\n const verticalBorder = Math.max(0, output.offsetHeight - output.clientHeight);\n const minimumHeight = Math.ceil(\n header.getBoundingClientRect().height + contentPadding + lineHeight + verticalBorder,\n );\n const naturalHeight = Math.ceil(\n header.getBoundingClientRect().height + contentPadding + Math.max(body.scrollHeight, lineHeight) + verticalBorder,\n );\n const viewportHeight = ownerWindow?.innerHeight ?? OUTPUT_MAX_HEIGHT_PX / OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO;\n const maximumViewportHeight = Math.min(viewportHeight * OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO, OUTPUT_MAX_HEIGHT_PX);\n\n output.classList.toggle('rivet-web-app-output-resizable', naturalHeight > maximumViewportHeight);\n output.classList.toggle('rivet-web-app-output-scrollable', body.scrollHeight > body.clientHeight);\n setStyleProperty(output, OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY, `${minimumHeight}px`);\n setStyleProperty(output, OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY, `${naturalHeight}px`);\n };\n\n const scheduleSync = () => {\n if (scheduledFrame != null) return;\n if (ownerWindow?.requestAnimationFrame) {\n scheduledFrame = ownerWindow.requestAnimationFrame(sync);\n } else {\n sync();\n }\n };\n\n const resizeObserver = ownerWindow?.ResizeObserver ? new ownerWindow.ResizeObserver(scheduleSync) : undefined;\n resizeObserver?.observe(output);\n\n const mutationObserver = ownerWindow?.MutationObserver ? new ownerWindow.MutationObserver(scheduleSync) : undefined;\n mutationObserver?.observe(output, { childList: true, characterData: true, subtree: true });\n output.addEventListener('load', scheduleSync, true);\n ownerWindow?.addEventListener('resize', scheduleSync);\n sync();\n\n return () => {\n if (scheduledFrame != null) ownerWindow?.cancelAnimationFrame(scheduledFrame);\n resizeObserver?.disconnect();\n mutationObserver?.disconnect();\n output.removeEventListener('load', scheduleSync, true);\n ownerWindow?.removeEventListener('resize', scheduleSync);\n };\n}\n\n/** Copies rendered web-app output without requiring the modern Clipboard API. */\nexport async function copyUiGraphText(value: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(value);\n return true;\n } catch {\n // Preview hosts and non-secure origins may not expose the Clipboard API.\n }\n\n const textArea = document.createElement('textarea');\n textArea.className = 'rivet-web-app-clipboard-fallback';\n textArea.value = value;\n try {\n document.body.append(textArea);\n textArea.select();\n return document.execCommand?.('copy') ?? false;\n } catch {\n return false;\n } finally {\n textArea.remove();\n }\n}\n\n/** Downloads the exact JSON string rendered by a web-app output component. */\nexport function downloadUiGraphJsonOutput(value: string, appName: string): void {\n const url = URL.createObjectURL(new Blob([value], { type: 'application/json' }));\n try {\n const link = document.createElement('a');\n link.href = url;\n link.download = getUiGraphJsonOutputFilename(appName);\n document.body.append(link);\n link.click();\n link.remove();\n } finally {\n globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n}\n\n/**\n * Replaces visible chat-message text matches with safe `<mark>` elements. This\n * operates on rendered Markdown DOM rather than source Markdown, so search\n * follows what the user can actually read.\n */\nexport function highlightUiGraphChatSearchMatches(\n messagesElement: HTMLElement,\n query: string,\n requestedActiveIndex = 0,\n): { activeIndex: number; matches: HTMLElement[] } {\n clearUiGraphChatSearchMatches(messagesElement);\n\n const searchText = query.trim();\n if (!searchText) {\n return { activeIndex: -1, matches: [] };\n }\n\n const document = messagesElement.ownerDocument;\n const textNodes: Text[] = [];\n const walker = document.createTreeWalker(messagesElement, 4);\n let node = walker.nextNode();\n while (node) {\n if (node.parentElement?.closest('script, style, textarea')) {\n node = walker.nextNode();\n continue;\n }\n\n textNodes.push(node as Text);\n node = walker.nextNode();\n }\n\n const matches: HTMLElement[] = [];\n for (const textNode of textNodes) {\n const value = textNode.data;\n const ranges: Array<{ end: number; start: number }> = [];\n const expression = new RegExp(escapeRegularExpression(searchText), 'gi');\n for (const match of value.matchAll(expression)) {\n if (match.index != null && match[0]) {\n ranges.push({ start: match.index, end: match.index + match[0].length });\n }\n }\n\n if (ranges.length === 0 || !textNode.parentNode) {\n continue;\n }\n\n const fragment = document.createDocumentFragment();\n let cursor = 0;\n for (const range of ranges) {\n fragment.append(value.slice(cursor, range.start));\n const match = document.createElement('mark');\n match.className = CHAT_SEARCH_MATCH_CLASS;\n match.textContent = value.slice(range.start, range.end);\n fragment.append(match);\n matches.push(match);\n cursor = range.end;\n }\n fragment.append(value.slice(cursor));\n textNode.parentNode.replaceChild(fragment, textNode);\n }\n\n if (matches.length === 0) {\n return { activeIndex: -1, matches };\n }\n\n const activeIndex = ((requestedActiveIndex % matches.length) + matches.length) % matches.length;\n matches[activeIndex]?.classList.add(CHAT_SEARCH_ACTIVE_MATCH_CLASS);\n return { activeIndex, matches };\n}\n\n/** Removes transient chat-search markup without changing the rendered message text. */\nexport function clearUiGraphChatSearchMatches(messagesElement: HTMLElement): void {\n for (const match of messagesElement.querySelectorAll<HTMLElement>(`.${CHAT_SEARCH_MATCH_CLASS}`)) {\n match.replaceWith(messagesElement.ownerDocument.createTextNode(match.textContent ?? ''));\n }\n messagesElement.normalize();\n}\n\n/** Reveals a rendered message or search match inside the chat's own scroll region. */\nexport function revealUiGraphChatElement(\n messagesElement: HTMLElement,\n element: HTMLElement | undefined,\n alignment: 'center' | 'start' = 'center',\n): void {\n if (!element || !messagesElement.contains(element)) {\n return;\n }\n\n const containerRect = messagesElement.getBoundingClientRect();\n const elementRect = element.getBoundingClientRect();\n const maxScrollTop = Math.max(0, messagesElement.scrollHeight - messagesElement.clientHeight);\n const offset =\n elementRect.top -\n containerRect.top -\n (alignment === 'center' ? (messagesElement.clientHeight - elementRect.height) / 2 : 0);\n messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));\n}\n\n/** Centers the active chat-search match inside the chat's own scroll region. */\nexport const revealUiGraphChatSearchMatch = revealUiGraphChatElement;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,wBAAuB;;;ACoPhB,SAAS,uBAAuB,SAA2C;AAChF,QAAM,QAAiC,CAAC;AAExC,aAAW,aAAa,QAAQ,YAAY;AAC1C,QAAI,UAAU,SAAS,WAAW,UAAU,SAAS,YAAY;AAC/D,YAAM,UAAU,QAAQ,IAAI,UAAU,gBAAgB;AAAA,IACxD,WAAW,UAAU,SAAS,YAAY;AACxC,YAAM,UAAU,QAAQ,IAAI;AAAA,IAC9B,WAAW,UAAU,SAAS,QAAQ;AACpC,YAAM,4BAA4B,UAAU,EAAE,CAAC,IAAI;AACnD,YAAM,+BAA+B,UAAU,EAAE,CAAC,IAAI,CAAC;AACvD,YAAM,2BAA2B,UAAU,EAAE,CAAC,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AAEA,SAAO;AACT;AAYO,SAAS,4BAA4B,aAAoC;AAC9E,SAAO,gBAAgB,WAAW;AACpC;AAEO,SAAS,+BAA+B,aAAoC;AACjF,SAAO,gBAAgB,WAAW;AACpC;AAEO,SAAS,2BAA2B,aAAoC;AAC7E,SAAO,gBAAgB,WAAW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F;AAEA,QAAM,gBAAgB,gBAAgB,sBAAsB;AAC5D,QAAM,cAAc,QAAQ,sBAAsB;AAClD,QAAM,eAAe,KAAK,IAAI,GAAG,gBAAgB,eAAe,gBAAgB,YAAY;AAC5F,QAAM,SACJ,YAAY,MACZ,cAAc,OACb,cAAc,YAAY,gBAAgB,eAAe,YAAY,UAAU,IAAI;AACtF,kBAAgB,YAAY,KAAK,IAAI,GAAG,KAAK,IAAI,cAAc,gBAAgB,YAAY,MAAM,CAAC;AACpG;AAGO,IAAM,+BAA+B;",
|
|
6
|
+
"names": ["base64", "isRecord", "document"]
|
|
7
7
|
}
|
|
@@ -50,6 +50,9 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
|
|
|
50
50
|
if (options.onGraphFinish) {
|
|
51
51
|
processor.on('graphFinish', options.onGraphFinish);
|
|
52
52
|
}
|
|
53
|
+
if (options.onGraphOutputsReady) {
|
|
54
|
+
processor.on('graphOutputsReady', options.onGraphOutputsReady);
|
|
55
|
+
}
|
|
53
56
|
if (options.onPartialOutput) {
|
|
54
57
|
processor.on('partialOutput', options.onPartialOutput);
|
|
55
58
|
}
|
|
@@ -79,6 +82,7 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
|
|
|
79
82
|
processor.setExternalFunction(name, fn);
|
|
80
83
|
}
|
|
81
84
|
}
|
|
85
|
+
processor.setStoredValueStore(options.storedValueStore);
|
|
82
86
|
if (options.onUserEvent) {
|
|
83
87
|
for (const [name, fn] of Object.entries(options.onUserEvent)) {
|
|
84
88
|
processor.onUserEvent(name, fn);
|
|
@@ -109,7 +113,7 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
|
|
|
109
113
|
editorExecutionCache: options.editorExecutionCache,
|
|
110
114
|
settings: resolveProcessSettings(options),
|
|
111
115
|
getChatNodeEndpoint: options.getChatNodeEndpoint,
|
|
112
|
-
}, resolvedInputs, resolvedContextValues);
|
|
116
|
+
}, resolvedInputs, resolvedContextValues, { returnWhenGraphOutputsReady: options.returnWhenGraphOutputsReady });
|
|
113
117
|
return outputs;
|
|
114
118
|
},
|
|
115
119
|
};
|
package/dist/esm/exports.js
CHANGED
|
@@ -11,6 +11,9 @@ export * from './model/UiGraphNormalization.js';
|
|
|
11
11
|
export * from './model/UiGraphBindings.js';
|
|
12
12
|
export * from './model/UiGraphRuntimeModel.js';
|
|
13
13
|
export * from './model/UiGraphWebAppStatus.js';
|
|
14
|
+
export * from './model/UiGraphWebAppStorage.js';
|
|
15
|
+
export * from './model/StoredValueStore.js';
|
|
16
|
+
export * from './model/ToolCallContinuation.js';
|
|
14
17
|
export * from './model/UiGraphActionProtocol.js';
|
|
15
18
|
export * from './model/GraphProgress.js';
|
|
16
19
|
export * from './model/UiGraphRendererStyles.js';
|
|
@@ -16,6 +16,18 @@ export function applyFrozenGraphBoundaryEffects(graphOutputs, node, outputValues
|
|
|
16
16
|
}
|
|
17
17
|
return undefined;
|
|
18
18
|
}
|
|
19
|
+
if (node.type === 'setStoredValue') {
|
|
20
|
+
const savedValue = outputValues['saved-value'];
|
|
21
|
+
const key = outputValues['key'];
|
|
22
|
+
const keyValue = key?.type === 'string' ? key.value : undefined;
|
|
23
|
+
if (!keyValue || !savedValue)
|
|
24
|
+
return undefined;
|
|
25
|
+
return {
|
|
26
|
+
type: 'setStoredValue',
|
|
27
|
+
key: keyValue,
|
|
28
|
+
value: savedValue.value,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
19
31
|
if (node.type !== 'setGlobal') {
|
|
20
32
|
return undefined;
|
|
21
33
|
}
|
|
@@ -26,6 +38,7 @@ export function applyFrozenGraphBoundaryEffects(graphOutputs, node, outputValues
|
|
|
26
38
|
return undefined;
|
|
27
39
|
}
|
|
28
40
|
return {
|
|
41
|
+
type: 'setGlobal',
|
|
29
42
|
variableId: variableIdValue,
|
|
30
43
|
value: savedValue,
|
|
31
44
|
};
|