@valerypopoff/rivet2-core 2.1.3 → 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 +10138 -5679
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +1214 -0
- package/dist/cjs/webAppRuntime.cjs.map +7 -0
- package/dist/esm/api/createProcessor.js +8 -1
- package/dist/esm/api/streaming.js +6 -0
- package/dist/esm/exports.js +8 -0
- package/dist/esm/integrations/mcp/MCPBase.js +92 -34
- package/dist/esm/model/GraphBoundaryEffects.js +13 -0
- package/dist/esm/model/GraphProcessor.js +1138 -86
- package/dist/esm/model/GraphProgress.js +15 -0
- package/dist/esm/model/ManagedAsyncBranches.js +28 -0
- package/dist/esm/model/Nodes.js +12 -0
- package/dist/esm/model/ProcessContextBuilder.js +3 -1
- package/dist/esm/model/RecordingPlayer.js +19 -0
- package/dist/esm/model/StoredValueStore.js +226 -0
- package/dist/esm/model/SubprocessorBridge.js +50 -18
- package/dist/esm/model/ToolCallContinuation.js +1 -0
- package/dist/esm/model/UiGraph.js +177 -4
- package/dist/esm/model/UiGraphActionProtocol.js +131 -0
- package/dist/esm/model/UiGraphBindings.js +530 -0
- package/dist/esm/model/UiGraphBrowserRuntime.js +373 -0
- package/dist/esm/model/UiGraphNormalization.js +148 -0
- package/dist/esm/model/UiGraphRendererStyles.js +1108 -42
- package/dist/esm/model/UiGraphRuntimeModel.js +518 -2
- package/dist/esm/model/UiGraphSchema.js +91 -0
- package/dist/esm/model/UiGraphWebAppStatus.js +19 -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/ArrayNode.js +2 -13
- package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
- package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
- package/dist/esm/model/nodes/CoalesceNode.js +2 -15
- package/dist/esm/model/nodes/DelayNode.js +3 -14
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
- package/dist/esm/model/nodes/DidRunNode.js +2 -13
- package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
- package/dist/esm/model/nodes/JoinNode.js +2 -13
- package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
- package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
- package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
- package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
- package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
- package/dist/esm/model/nodes/MatchNode.js +7 -7
- package/dist/esm/model/nodes/PassthroughNode.js +3 -14
- package/dist/esm/model/nodes/RaceInputsNode.js +2 -13
- package/dist/esm/model/nodes/ReportProgressNode.js +57 -0
- 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/model/nodes/variadicPortIndex.js +32 -0
- package/dist/esm/plugins/anthropic/anthropic.js +1 -1
- package/dist/esm/recording/ExecutionRecorder.js +6 -0
- package/dist/esm/utils/coerceType.js +3 -0
- package/dist/esm/utils/fetchEventSource.js +16 -17
- package/dist/esm/utils/serialization/serialization.js +4 -0
- package/dist/esm/utils/serialization/serializationUtils.js +8 -27
- package/dist/esm/utils/serialization/serialization_v4.js +3 -3
- package/dist/esm/webAppRuntime.js +4 -2
- package/dist/types/api/createProcessor.d.ts +4 -0
- package/dist/types/api/streaming.d.ts +6 -0
- package/dist/types/exports.d.ts +8 -0
- package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
- package/dist/types/model/EditorDefinition.d.ts +2 -1
- package/dist/types/model/ExecutorProtocol.d.ts +19 -0
- package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
- package/dist/types/model/GraphProcessor.d.ts +26 -2
- package/dist/types/model/GraphProgress.d.ts +6 -0
- package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
- package/dist/types/model/Nodes.d.ts +6 -2
- package/dist/types/model/ProcessContext.d.ts +18 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +3 -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 +63 -9
- package/dist/types/model/UiGraphActionProtocol.d.ts +71 -0
- package/dist/types/model/UiGraphBindings.d.ts +45 -0
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +55 -0
- package/dist/types/model/UiGraphNormalization.d.ts +24 -0
- package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
- package/dist/types/model/UiGraphRuntimeModel.d.ts +97 -6
- package/dist/types/model/UiGraphSchema.d.ts +113 -0
- package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -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/ArrayNode.d.ts +0 -1
- package/dist/types/model/nodes/AssembleMessageNode.d.ts +0 -1
- package/dist/types/model/nodes/AssemblePromptNode.d.ts +0 -1
- package/dist/types/model/nodes/DelayNode.d.ts +0 -1
- package/dist/types/model/nodes/DidRunNode.d.ts +0 -1
- package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
- package/dist/types/model/nodes/JoinNode.d.ts +0 -1
- package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
- package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
- package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
- package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -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/model/nodes/variadicPortIndex.d.ts +4 -0
- package/dist/types/recording/RecordedEvents.d.ts +10 -0
- package/dist/types/webAppRuntime.d.ts +8 -3
- package/package.json +2 -2
- package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
- package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphChatMessagesStateKey, getUiGraphChatPins, getUiGraphChatPinsStateKey, } from './UiGraph.js';
|
|
2
|
+
import { getUiGraphJsonOutputFilename } from './UiGraphRuntimeModel.js';
|
|
3
|
+
const OUTPUT_MAX_HEIGHT_PX = 800;
|
|
4
|
+
const OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
|
|
5
|
+
const OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = '--rivet-web-app-output-resize-min-height';
|
|
6
|
+
const OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = '--rivet-web-app-output-resize-max-height';
|
|
7
|
+
const CHAT_SEARCH_MATCH_CLASS = 'rivet-web-app-chat-search-match';
|
|
8
|
+
const CHAT_SEARCH_ACTIVE_MATCH_CLASS = 'rivet-web-app-chat-search-match-active';
|
|
9
|
+
const UI_GRAPH_CHAT_STORAGE_PREFIX = 'rivet-web-app-chat-state:v1';
|
|
10
|
+
const UI_GRAPH_APP_STORAGE_PREFIX = 'rivet-web-app-storage:v1';
|
|
11
|
+
const escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
12
|
+
const getPixelValue = (value, fallback) => {
|
|
13
|
+
const parsed = Number.parseFloat(value);
|
|
14
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
15
|
+
};
|
|
16
|
+
const setStyleProperty = (element, property, value) => {
|
|
17
|
+
if (element.style.getPropertyValue(property) !== value) {
|
|
18
|
+
element.style.setProperty(property, value);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
22
|
+
const getDefaultUiGraphBrowserStorage = () => {
|
|
23
|
+
try {
|
|
24
|
+
return globalThis.localStorage ?? globalThis.window?.localStorage;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// Embedded, private, and restricted browser contexts can reject storage.
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
const getDefaultUiGraphStorageLocation = () => {
|
|
32
|
+
try {
|
|
33
|
+
return globalThis.location ?? globalThis.window?.location;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/** Returns the browser-local key for one app URL and one persisted UI graph. */
|
|
40
|
+
export function getUiGraphChatStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
|
|
41
|
+
if (!location?.origin) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const pathname = location.pathname.replace(/\/+$/, '') || '/';
|
|
45
|
+
return [
|
|
46
|
+
UI_GRAPH_CHAT_STORAGE_PREFIX,
|
|
47
|
+
encodeURIComponent(location.origin),
|
|
48
|
+
encodeURIComponent(pathname),
|
|
49
|
+
encodeURIComponent(uiGraph.id),
|
|
50
|
+
].join(':');
|
|
51
|
+
}
|
|
52
|
+
/** Returns the browser-local key for graph-managed storage owned by one web app. */
|
|
53
|
+
export function getUiGraphWebAppStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
|
|
54
|
+
if (!location?.origin) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const pathname = location.pathname.replace(/\/+$/, '') || '/';
|
|
58
|
+
return [
|
|
59
|
+
UI_GRAPH_APP_STORAGE_PREFIX,
|
|
60
|
+
encodeURIComponent(location.origin),
|
|
61
|
+
encodeURIComponent(pathname),
|
|
62
|
+
encodeURIComponent(uiGraph.id),
|
|
63
|
+
].join(':');
|
|
64
|
+
}
|
|
65
|
+
/** Loads the browser snapshot used by Stored Value nodes for this one web app. */
|
|
66
|
+
export function loadUiGraphWebAppStorage(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
|
|
67
|
+
const key = getUiGraphWebAppStorageKey(uiGraph, location);
|
|
68
|
+
if (!key || !storage)
|
|
69
|
+
return {};
|
|
70
|
+
try {
|
|
71
|
+
const serialized = storage.getItem(key);
|
|
72
|
+
if (!serialized)
|
|
73
|
+
return {};
|
|
74
|
+
const value = JSON.parse(serialized);
|
|
75
|
+
return isRecord(value) ? value : {};
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return {};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Merges a successful action's changed keys and persists the complete app-local record. */
|
|
82
|
+
export function applyUiGraphWebAppStoragePatch(uiGraph, currentStorage, patch, storage = getDefaultUiGraphBrowserStorage(), location) {
|
|
83
|
+
const key = getUiGraphWebAppStorageKey(uiGraph, location);
|
|
84
|
+
if (!key || !storage) {
|
|
85
|
+
throw new Error('Browser storage is unavailable for this web app.');
|
|
86
|
+
}
|
|
87
|
+
const nextStorage = { ...currentStorage, ...patch };
|
|
88
|
+
let serialized;
|
|
89
|
+
try {
|
|
90
|
+
serialized = JSON.stringify(nextStorage);
|
|
91
|
+
storage.setItem(key, serialized);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
throw new Error('Web app storage could not be saved. Browser storage may be unavailable or full.', {
|
|
95
|
+
cause: error,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return nextStorage;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Applies the keys from one completed action that have not already been superseded.
|
|
102
|
+
* Ordering metadata is committed only after persistence succeeds, so a failed newer
|
|
103
|
+
* write cannot suppress an older successful action that completes later.
|
|
104
|
+
*/
|
|
105
|
+
export function applyUiGraphWebAppStorageActionPatch(patch, actionNumber, appliedActionByKey, persist) {
|
|
106
|
+
const applicablePatch = Object.fromEntries(Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0)));
|
|
107
|
+
const applicableKeys = Object.keys(applicablePatch);
|
|
108
|
+
if (applicableKeys.length === 0)
|
|
109
|
+
return applicablePatch;
|
|
110
|
+
persist(applicablePatch);
|
|
111
|
+
for (const key of applicableKeys)
|
|
112
|
+
appliedActionByKey.set(key, actionNumber);
|
|
113
|
+
return applicablePatch;
|
|
114
|
+
}
|
|
115
|
+
/** Selects and validates the private browser-persisted state of Chat components only. */
|
|
116
|
+
export function getUiGraphChatPersistentState(uiGraph, state) {
|
|
117
|
+
const persistentState = {};
|
|
118
|
+
for (const component of uiGraph.components) {
|
|
119
|
+
if (component.type !== 'chat')
|
|
120
|
+
continue;
|
|
121
|
+
const draftStateKey = getUiGraphChatDraftStateKey(component.id);
|
|
122
|
+
const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
|
|
123
|
+
const pinsStateKey = getUiGraphChatPinsStateKey(component.id);
|
|
124
|
+
const draft = state[draftStateKey];
|
|
125
|
+
const messages = getUiGraphChatMessages(component.id, state);
|
|
126
|
+
const pins = getUiGraphChatPins(component.id, state).map((pin) => pin.messageIndex);
|
|
127
|
+
if (typeof draft === 'string' && draft) {
|
|
128
|
+
persistentState[draftStateKey] = draft;
|
|
129
|
+
}
|
|
130
|
+
if (messages.length > 0) {
|
|
131
|
+
persistentState[messagesStateKey] = messages;
|
|
132
|
+
}
|
|
133
|
+
if (pins.length > 0) {
|
|
134
|
+
persistentState[pinsStateKey] = pins;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return persistentState;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Reports whether a state transition changed the browser-persisted portion of
|
|
141
|
+
* any Chat. Runtime state updates are immutable, so reference comparison keeps
|
|
142
|
+
* action progress and unrelated form edits from serializing a large history.
|
|
143
|
+
*/
|
|
144
|
+
export function hasUiGraphChatPersistentStateChanged(uiGraph, previousState, nextState) {
|
|
145
|
+
return uiGraph.components.some((component) => {
|
|
146
|
+
if (component.type !== 'chat')
|
|
147
|
+
return false;
|
|
148
|
+
return (previousState[getUiGraphChatDraftStateKey(component.id)] !==
|
|
149
|
+
nextState[getUiGraphChatDraftStateKey(component.id)] ||
|
|
150
|
+
previousState[getUiGraphChatMessagesStateKey(component.id)] !==
|
|
151
|
+
nextState[getUiGraphChatMessagesStateKey(component.id)] ||
|
|
152
|
+
previousState[getUiGraphChatPinsStateKey(component.id)] !== nextState[getUiGraphChatPinsStateKey(component.id)]);
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** Loads valid Chat-only state without allowing malformed local storage to affect rendering. */
|
|
156
|
+
export function loadUiGraphChatPersistentState(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
|
|
157
|
+
const key = getUiGraphChatStorageKey(uiGraph, location);
|
|
158
|
+
if (!key || !storage) {
|
|
159
|
+
return {};
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
const serializedState = storage.getItem(key);
|
|
163
|
+
if (!serializedState) {
|
|
164
|
+
return {};
|
|
165
|
+
}
|
|
166
|
+
const storedState = JSON.parse(serializedState);
|
|
167
|
+
return isRecord(storedState) ? getUiGraphChatPersistentState(uiGraph, storedState) : {};
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return {};
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Persists only Chat draft, conversation, and pins for the current browser app URL. */
|
|
174
|
+
export function saveUiGraphChatPersistentState(uiGraph, state, storage = getDefaultUiGraphBrowserStorage(), location) {
|
|
175
|
+
const key = getUiGraphChatStorageKey(uiGraph, location);
|
|
176
|
+
if (!key || !storage) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const persistentState = getUiGraphChatPersistentState(uiGraph, state);
|
|
181
|
+
if (Object.keys(persistentState).length === 0) {
|
|
182
|
+
storage.removeItem(key);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const serializedState = JSON.stringify(persistentState);
|
|
186
|
+
if (storage.getItem(key) !== serializedState) {
|
|
187
|
+
storage.setItem(key, serializedState);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Storage can be unavailable, full, or blocked; Chat itself still works.
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Limits an expanded Output card's native resize range to one visible content
|
|
196
|
+
* line through its rendered value. Short, naturally-sized outputs have no resize
|
|
197
|
+
* handle because resizing them would only add blank space.
|
|
198
|
+
*/
|
|
199
|
+
export function observeUiGraphOutputResizeBounds(output) {
|
|
200
|
+
const ownerWindow = output.ownerDocument.defaultView;
|
|
201
|
+
let scheduledFrame;
|
|
202
|
+
const sync = () => {
|
|
203
|
+
scheduledFrame = undefined;
|
|
204
|
+
if (!ownerWindow)
|
|
205
|
+
return;
|
|
206
|
+
const header = output.querySelector('.rivet-web-app-output-header');
|
|
207
|
+
const content = output.querySelector('.rivet-web-app-output-content');
|
|
208
|
+
const body = output.querySelector('.rivet-web-app-output-content-body');
|
|
209
|
+
if (!header || !content || !body) {
|
|
210
|
+
output.classList.remove('rivet-web-app-output-resizable');
|
|
211
|
+
output.classList.remove('rivet-web-app-output-scrollable');
|
|
212
|
+
output.style.removeProperty(OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY);
|
|
213
|
+
output.style.removeProperty(OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const bodyStyle = ownerWindow.getComputedStyle(body);
|
|
217
|
+
const lineHeight = getPixelValue(bodyStyle.lineHeight, getPixelValue(bodyStyle.fontSize, 16) * 1.5);
|
|
218
|
+
const contentStyle = ownerWindow.getComputedStyle(content);
|
|
219
|
+
const contentPadding = getPixelValue(contentStyle.paddingTop, 0) + getPixelValue(contentStyle.paddingBottom, 0);
|
|
220
|
+
const verticalBorder = Math.max(0, output.offsetHeight - output.clientHeight);
|
|
221
|
+
const minimumHeight = Math.ceil(header.getBoundingClientRect().height + contentPadding + lineHeight + verticalBorder);
|
|
222
|
+
const naturalHeight = Math.ceil(header.getBoundingClientRect().height + contentPadding + Math.max(body.scrollHeight, lineHeight) + verticalBorder);
|
|
223
|
+
const viewportHeight = ownerWindow?.innerHeight ?? OUTPUT_MAX_HEIGHT_PX / OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO;
|
|
224
|
+
const maximumViewportHeight = Math.min(viewportHeight * OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO, OUTPUT_MAX_HEIGHT_PX);
|
|
225
|
+
output.classList.toggle('rivet-web-app-output-resizable', naturalHeight > maximumViewportHeight);
|
|
226
|
+
output.classList.toggle('rivet-web-app-output-scrollable', body.scrollHeight > body.clientHeight);
|
|
227
|
+
setStyleProperty(output, OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY, `${minimumHeight}px`);
|
|
228
|
+
setStyleProperty(output, OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY, `${naturalHeight}px`);
|
|
229
|
+
};
|
|
230
|
+
const scheduleSync = () => {
|
|
231
|
+
if (scheduledFrame != null)
|
|
232
|
+
return;
|
|
233
|
+
if (ownerWindow?.requestAnimationFrame) {
|
|
234
|
+
scheduledFrame = ownerWindow.requestAnimationFrame(sync);
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
sync();
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
const resizeObserver = ownerWindow?.ResizeObserver ? new ownerWindow.ResizeObserver(scheduleSync) : undefined;
|
|
241
|
+
resizeObserver?.observe(output);
|
|
242
|
+
const mutationObserver = ownerWindow?.MutationObserver ? new ownerWindow.MutationObserver(scheduleSync) : undefined;
|
|
243
|
+
mutationObserver?.observe(output, { childList: true, characterData: true, subtree: true });
|
|
244
|
+
output.addEventListener('load', scheduleSync, true);
|
|
245
|
+
ownerWindow?.addEventListener('resize', scheduleSync);
|
|
246
|
+
sync();
|
|
247
|
+
return () => {
|
|
248
|
+
if (scheduledFrame != null)
|
|
249
|
+
ownerWindow?.cancelAnimationFrame(scheduledFrame);
|
|
250
|
+
resizeObserver?.disconnect();
|
|
251
|
+
mutationObserver?.disconnect();
|
|
252
|
+
output.removeEventListener('load', scheduleSync, true);
|
|
253
|
+
ownerWindow?.removeEventListener('resize', scheduleSync);
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/** Copies rendered web-app output without requiring the modern Clipboard API. */
|
|
257
|
+
export async function copyUiGraphText(value) {
|
|
258
|
+
try {
|
|
259
|
+
await navigator.clipboard.writeText(value);
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// Preview hosts and non-secure origins may not expose the Clipboard API.
|
|
264
|
+
}
|
|
265
|
+
const textArea = document.createElement('textarea');
|
|
266
|
+
textArea.className = 'rivet-web-app-clipboard-fallback';
|
|
267
|
+
textArea.value = value;
|
|
268
|
+
try {
|
|
269
|
+
document.body.append(textArea);
|
|
270
|
+
textArea.select();
|
|
271
|
+
return document.execCommand?.('copy') ?? false;
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
textArea.remove();
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/** Downloads the exact JSON string rendered by a web-app output component. */
|
|
281
|
+
export function downloadUiGraphJsonOutput(value, appName) {
|
|
282
|
+
const url = URL.createObjectURL(new Blob([value], { type: 'application/json' }));
|
|
283
|
+
try {
|
|
284
|
+
const link = document.createElement('a');
|
|
285
|
+
link.href = url;
|
|
286
|
+
link.download = getUiGraphJsonOutputFilename(appName);
|
|
287
|
+
document.body.append(link);
|
|
288
|
+
link.click();
|
|
289
|
+
link.remove();
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Replaces visible chat-message text matches with safe `<mark>` elements. This
|
|
297
|
+
* operates on rendered Markdown DOM rather than source Markdown, so search
|
|
298
|
+
* follows what the user can actually read.
|
|
299
|
+
*/
|
|
300
|
+
export function highlightUiGraphChatSearchMatches(messagesElement, query, requestedActiveIndex = 0) {
|
|
301
|
+
clearUiGraphChatSearchMatches(messagesElement);
|
|
302
|
+
const searchText = query.trim();
|
|
303
|
+
if (!searchText) {
|
|
304
|
+
return { activeIndex: -1, matches: [] };
|
|
305
|
+
}
|
|
306
|
+
const document = messagesElement.ownerDocument;
|
|
307
|
+
const textNodes = [];
|
|
308
|
+
const walker = document.createTreeWalker(messagesElement, 4);
|
|
309
|
+
let node = walker.nextNode();
|
|
310
|
+
while (node) {
|
|
311
|
+
if (node.parentElement?.closest('script, style, textarea')) {
|
|
312
|
+
node = walker.nextNode();
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
textNodes.push(node);
|
|
316
|
+
node = walker.nextNode();
|
|
317
|
+
}
|
|
318
|
+
const matches = [];
|
|
319
|
+
for (const textNode of textNodes) {
|
|
320
|
+
const value = textNode.data;
|
|
321
|
+
const ranges = [];
|
|
322
|
+
const expression = new RegExp(escapeRegularExpression(searchText), 'gi');
|
|
323
|
+
for (const match of value.matchAll(expression)) {
|
|
324
|
+
if (match.index != null && match[0]) {
|
|
325
|
+
ranges.push({ start: match.index, end: match.index + match[0].length });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (ranges.length === 0 || !textNode.parentNode) {
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
const fragment = document.createDocumentFragment();
|
|
332
|
+
let cursor = 0;
|
|
333
|
+
for (const range of ranges) {
|
|
334
|
+
fragment.append(value.slice(cursor, range.start));
|
|
335
|
+
const match = document.createElement('mark');
|
|
336
|
+
match.className = CHAT_SEARCH_MATCH_CLASS;
|
|
337
|
+
match.textContent = value.slice(range.start, range.end);
|
|
338
|
+
fragment.append(match);
|
|
339
|
+
matches.push(match);
|
|
340
|
+
cursor = range.end;
|
|
341
|
+
}
|
|
342
|
+
fragment.append(value.slice(cursor));
|
|
343
|
+
textNode.parentNode.replaceChild(fragment, textNode);
|
|
344
|
+
}
|
|
345
|
+
if (matches.length === 0) {
|
|
346
|
+
return { activeIndex: -1, matches };
|
|
347
|
+
}
|
|
348
|
+
const activeIndex = ((requestedActiveIndex % matches.length) + matches.length) % matches.length;
|
|
349
|
+
matches[activeIndex]?.classList.add(CHAT_SEARCH_ACTIVE_MATCH_CLASS);
|
|
350
|
+
return { activeIndex, matches };
|
|
351
|
+
}
|
|
352
|
+
/** Removes transient chat-search markup without changing the rendered message text. */
|
|
353
|
+
export function clearUiGraphChatSearchMatches(messagesElement) {
|
|
354
|
+
for (const match of messagesElement.querySelectorAll(`.${CHAT_SEARCH_MATCH_CLASS}`)) {
|
|
355
|
+
match.replaceWith(messagesElement.ownerDocument.createTextNode(match.textContent ?? ''));
|
|
356
|
+
}
|
|
357
|
+
messagesElement.normalize();
|
|
358
|
+
}
|
|
359
|
+
/** Reveals a rendered message or search match inside the chat's own scroll region. */
|
|
360
|
+
export function revealUiGraphChatElement(messagesElement, element, alignment = 'center') {
|
|
361
|
+
if (!element || !messagesElement.contains(element)) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const containerRect = messagesElement.getBoundingClientRect();
|
|
365
|
+
const elementRect = element.getBoundingClientRect();
|
|
366
|
+
const maxScrollTop = Math.max(0, messagesElement.scrollHeight - messagesElement.clientHeight);
|
|
367
|
+
const offset = elementRect.top -
|
|
368
|
+
containerRect.top -
|
|
369
|
+
(alignment === 'center' ? (messagesElement.clientHeight - elementRect.height) / 2 : 0);
|
|
370
|
+
messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));
|
|
371
|
+
}
|
|
372
|
+
/** Centers the active chat-search match inside the chat's own scroll region. */
|
|
373
|
+
export const revealUiGraphChatSearchMatch = revealUiGraphChatElement;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { normalizeUiGraphComponentIds } from './UiGraph.js';
|
|
2
|
+
import { UI_GRAPH_COMPONENT_SCHEMA, UI_GRAPH_ENVELOPE_SCHEMA } from './UiGraphSchema.js';
|
|
3
|
+
export class UiGraphNormalizationError extends Error {
|
|
4
|
+
issues;
|
|
5
|
+
constructor(issues) {
|
|
6
|
+
super(`Invalid UI graph configuration: ${issues.map(formatUiGraphNormalizationIssue).join('; ')}`);
|
|
7
|
+
this.issues = issues;
|
|
8
|
+
this.name = 'UiGraphNormalizationError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function formatUiGraphNormalizationIssue(issue) {
|
|
12
|
+
return `${issue.path}: ${issue.message}`;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Validates every UI graph and component discriminator while applying only the
|
|
16
|
+
* deterministic component-ID repair supported for legacy project snapshots.
|
|
17
|
+
*/
|
|
18
|
+
export function normalizeUiGraph(value, options = {}) {
|
|
19
|
+
const result = parseUiGraph(value, { ...options, expectedId: undefined });
|
|
20
|
+
if (result.issues.length > 0) {
|
|
21
|
+
throw new UiGraphNormalizationError(result.issues);
|
|
22
|
+
}
|
|
23
|
+
return result.uiGraph;
|
|
24
|
+
}
|
|
25
|
+
export function normalizeUiGraphRecord(value, options = {}) {
|
|
26
|
+
if (!isRecord(value)) {
|
|
27
|
+
throw new UiGraphNormalizationError([{ message: 'must be an object', path: 'Project uiGraphs' }]);
|
|
28
|
+
}
|
|
29
|
+
const issues = [];
|
|
30
|
+
const replacements = new Map();
|
|
31
|
+
const uiGraphEntries = Object.entries(value);
|
|
32
|
+
for (const [uiGraphId, uiGraph] of uiGraphEntries) {
|
|
33
|
+
const result = parseUiGraph(uiGraph, { ...options, expectedId: uiGraphId });
|
|
34
|
+
issues.push(...result.issues);
|
|
35
|
+
if (result.uiGraph && result.uiGraph !== uiGraph) {
|
|
36
|
+
replacements.set(uiGraphId, result.uiGraph);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (issues.length > 0) {
|
|
40
|
+
throw new UiGraphNormalizationError(issues);
|
|
41
|
+
}
|
|
42
|
+
if (replacements.size === 0) {
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
return Object.fromEntries(uiGraphEntries.map(([uiGraphId, uiGraph]) => [uiGraphId, replacements.get(uiGraphId) ?? uiGraph]));
|
|
46
|
+
}
|
|
47
|
+
export function normalizeProjectUiGraphs(project) {
|
|
48
|
+
if (project.uiGraphs === undefined) {
|
|
49
|
+
return project;
|
|
50
|
+
}
|
|
51
|
+
const uiGraphs = normalizeUiGraphRecord(project.uiGraphs);
|
|
52
|
+
return uiGraphs === project.uiGraphs ? project : { ...project, uiGraphs };
|
|
53
|
+
}
|
|
54
|
+
function parseUiGraph(value, options) {
|
|
55
|
+
const graphPath = `UI graph "${getUiGraphLabel(value, options.expectedId)}"`;
|
|
56
|
+
if (!isRecord(value)) {
|
|
57
|
+
return { issues: [{ message: 'must be an object', path: graphPath }] };
|
|
58
|
+
}
|
|
59
|
+
const envelopeResult = UI_GRAPH_ENVELOPE_SCHEMA.safeParse(value);
|
|
60
|
+
const issues = envelopeResult.success ? [] : mapSchemaIssues(envelopeResult.error.issues, graphPath);
|
|
61
|
+
if (options.expectedId !== undefined && typeof value.id === 'string' && value.id !== options.expectedId) {
|
|
62
|
+
issues.push({ message: `must match its project key "${options.expectedId}"`, path: `${graphPath}.id` });
|
|
63
|
+
}
|
|
64
|
+
if (!Array.isArray(value.components)) {
|
|
65
|
+
return { issues };
|
|
66
|
+
}
|
|
67
|
+
validateComponents(value.components, graphPath, options, issues);
|
|
68
|
+
if (issues.length > 0) {
|
|
69
|
+
return { issues };
|
|
70
|
+
}
|
|
71
|
+
const uiGraph = value;
|
|
72
|
+
return {
|
|
73
|
+
issues,
|
|
74
|
+
uiGraph: options.repairComponentIds === false ? uiGraph : normalizeUiGraphComponentIds(uiGraph),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function validateComponents(components, graphPath, options, issues) {
|
|
78
|
+
const repairComponentIds = options.repairComponentIds !== false;
|
|
79
|
+
const usedIds = new Set();
|
|
80
|
+
for (const [index, component] of components.entries()) {
|
|
81
|
+
const componentPath = `${graphPath} component at index ${index}`;
|
|
82
|
+
if (!isRecord(component)) {
|
|
83
|
+
issues.push({ message: 'must be an object', path: componentPath });
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const result = UI_GRAPH_COMPONENT_SCHEMA.safeParse(component);
|
|
87
|
+
if (!result.success) {
|
|
88
|
+
issues.push(...mapComponentSchemaIssues(result.error.issues, componentPath, component.type));
|
|
89
|
+
}
|
|
90
|
+
const rawComponentId = component.id;
|
|
91
|
+
if (rawComponentId !== undefined && typeof rawComponentId !== 'string') {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const componentId = rawComponentId ?? '';
|
|
95
|
+
if (!componentId.trim()) {
|
|
96
|
+
if (!repairComponentIds) {
|
|
97
|
+
issues.push({ message: 'must be a non-empty string', path: `${componentPath}.id` });
|
|
98
|
+
}
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (usedIds.has(componentId)) {
|
|
102
|
+
if (!repairComponentIds) {
|
|
103
|
+
issues.push({ message: `duplicates component id "${componentId}"`, path: `${componentPath}.id` });
|
|
104
|
+
}
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
usedIds.add(componentId);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function mapComponentSchemaIssues(schemaIssues, path, componentType) {
|
|
111
|
+
return schemaIssues.map((issue) => ({
|
|
112
|
+
message: issue.path.length === 1 && issue.path[0] === 'type'
|
|
113
|
+
? typeof componentType === 'string'
|
|
114
|
+
? `has unsupported type "${componentType}"`
|
|
115
|
+
: 'must have a supported string type'
|
|
116
|
+
: issue.message,
|
|
117
|
+
path: formatSchemaPath(path, issue.path),
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
function mapSchemaIssues(schemaIssues, path) {
|
|
121
|
+
return schemaIssues.map((issue) => ({ message: issue.message, path: formatSchemaPath(path, issue.path) }));
|
|
122
|
+
}
|
|
123
|
+
function formatSchemaPath(basePath, schemaPath) {
|
|
124
|
+
let path = basePath;
|
|
125
|
+
for (let index = 0; index < schemaPath.length; index += 1) {
|
|
126
|
+
const segment = schemaPath[index];
|
|
127
|
+
const previous = schemaPath[index - 1];
|
|
128
|
+
if (typeof segment === 'number') {
|
|
129
|
+
path += previous === 'items' ? `[${segment}]` : ` at index ${segment}`;
|
|
130
|
+
}
|
|
131
|
+
else if (typeof previous === 'string' && previous === 'inputs') {
|
|
132
|
+
path += `[${JSON.stringify(segment)}]`;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
path += `.${String(segment)}`;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return path;
|
|
139
|
+
}
|
|
140
|
+
function getUiGraphLabel(value, expectedId) {
|
|
141
|
+
if (expectedId !== undefined) {
|
|
142
|
+
return expectedId;
|
|
143
|
+
}
|
|
144
|
+
return isRecord(value) && typeof value.id === 'string' && value.id.trim() ? value.id : '<unknown>';
|
|
145
|
+
}
|
|
146
|
+
function isRecord(value) {
|
|
147
|
+
return value != null && typeof value === 'object' && !Array.isArray(value);
|
|
148
|
+
}
|