@valerypopoff/rivet2-core 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cjs/bundle.cjs +1430 -669
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +1578 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +7 -0
  5. package/dist/cjs/interpolationSyntax.cjs +186 -0
  6. package/dist/cjs/interpolationSyntax.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  8. package/dist/esm/exports.js +2 -1
  9. package/dist/esm/integrations/CodeRunner.js +5 -0
  10. package/dist/esm/integrations/mcp/MCPBase.js +16 -6
  11. package/dist/esm/interpolationRuntime.js +5 -0
  12. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  13. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  14. package/dist/esm/model/GraphOutputSelection.js +34 -0
  15. package/dist/esm/model/GraphProcessor.js +136 -44
  16. package/dist/esm/model/ProcessContextBuilder.js +2 -0
  17. package/dist/esm/model/RecordingPlayer.js +11 -6
  18. package/dist/esm/model/StoredValueStore.js +4 -3
  19. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  20. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  21. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  22. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  23. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  24. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  25. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  26. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  27. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  28. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  29. package/dist/esm/model/nodes/PromptNode.js +10 -11
  30. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  31. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  32. package/dist/esm/model/nodes/TextNode.js +11 -32
  33. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  34. package/dist/esm/model/nodes/ToolNode.js +33 -16
  35. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  36. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  37. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  38. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  39. package/dist/esm/utils/index.js +2 -0
  40. package/dist/esm/utils/interpolation.js +478 -221
  41. package/dist/esm/utils/interpolationSyntax.js +175 -0
  42. package/dist/esm/utils/jsonPath.js +129 -0
  43. package/dist/types/exports.d.ts +3 -1
  44. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  45. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  46. package/dist/types/interpolationRuntime.d.ts +5 -0
  47. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  48. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  49. package/dist/types/model/GraphProcessor.d.ts +4 -3
  50. package/dist/types/model/ProcessContext.d.ts +3 -2
  51. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  52. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  53. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  54. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  55. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  56. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  57. package/dist/types/utils/index.d.ts +2 -0
  58. package/dist/types/utils/interpolation.d.ts +93 -8
  59. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  60. package/dist/types/utils/jsonPath.d.ts +15 -0
  61. package/package.json +11 -1
@@ -1,13 +1,27 @@
1
+ import { dataTypes } from '../model/DataValue.js';
2
+ import { coerceTypeOptional } from './coerceType.js';
3
+ import { evaluateJsonPath, normalizeJsonPathExpression } from './jsonPath.js';
1
4
  import { dedent } from './misc.js';
2
- import { get as lodashGet } from 'lodash-es';
5
+ import { isInterpolationRegexLiteralStart, isInterpolationSyntaxCharacterEscaped, scanInterpolationTokenSpans, } from './interpolationSyntax.js';
3
6
  export const ESCAPED_TOKEN_REGEX = /\{\{\{([^}]+?)\}\}\}/g;
4
7
  export const ESCAPED_ESCAPED_TOKEN_REGEX = /\\\{\\\{([^}]+?)\\\}\\\}/g;
5
- const EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_ENTRIES = 2048;
6
- const EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_LENGTH = 64 * 1024;
7
- const EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_CHARS = 1024 * 1024;
8
- const extractedInterpolationVariablesCache = new Map();
9
- let extractedInterpolationVariablesCacheTemplateChars = 0;
10
- let lastUncachedInterpolationVariableTemplate;
8
+ const INTERPOLATION_TEMPLATE_CACHE_MAX_ENTRIES = 2048;
9
+ const INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_LENGTH = 64 * 1024;
10
+ const INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_CHARS = 1024 * 1024;
11
+ const INTERPOLATION_TEMPLATE_CACHE_MAX_STORAGE_CHARS = 2 * 1024 * 1024;
12
+ // JavaScript list callbacks can resolve the same expression for every item.
13
+ // Keep this syntax-only cache deliberately smaller than the template cache:
14
+ // values, contexts, and DataValues must never be retained here.
15
+ const INTERPOLATION_EXPRESSION_CACHE_MAX_ENTRIES = 512;
16
+ const INTERPOLATION_EXPRESSION_CACHE_MAX_EXPRESSION_LENGTH = 4 * 1024;
17
+ const INTERPOLATION_EXPRESSION_CACHE_MAX_CHARS = 128 * 1024;
18
+ const interpolationTemplateCache = new Map();
19
+ let cachedInterpolationTemplateChars = 0;
20
+ let cachedInterpolationTemplateStorageChars = 0;
21
+ let lastUncachedInterpolationTemplate;
22
+ const interpolationExpressionCache = new Map();
23
+ let cachedInterpolationExpressionChars = 0;
24
+ const dataValueTypeSet = new Set(dataTypes);
11
25
  const processingFunctions = {
12
26
  indent: (input, spaces = 0) => {
13
27
  const indent = ' '.repeat(spaces);
@@ -23,15 +37,9 @@ const processingFunctions = {
23
37
  .map((line) => `${quotePrefix}${line}`)
24
38
  .join('\n');
25
39
  },
26
- uppercase: (input) => {
27
- return input.toUpperCase();
28
- },
29
- lowercase: (input) => {
30
- return input.toLowerCase();
31
- },
32
- trim: (input) => {
33
- return input.trim();
34
- },
40
+ uppercase: (input) => input.toUpperCase(),
41
+ lowercase: (input) => input.toLowerCase(),
42
+ trim: (input) => input.trim(),
35
43
  truncate: (input, length = 50) => {
36
44
  if (input.length <= length)
37
45
  return input;
@@ -44,12 +52,8 @@ const processingFunctions = {
44
52
  .map((line) => `${indent}- ${line}`)
45
53
  .join('\n');
46
54
  },
47
- sort: (input) => {
48
- return input.split('\n').sort().join('\n');
49
- },
50
- dedent: (input) => {
51
- return dedent(input);
52
- },
55
+ sort: (input) => input.split('\n').sort().join('\n'),
56
+ dedent: (input) => dedent(input),
53
57
  wrap: (input, width = 80) => {
54
58
  const words = input.split(/\s+/);
55
59
  const lines = [];
@@ -69,258 +73,511 @@ const processingFunctions = {
69
73
  return lines.join('\n');
70
74
  },
71
75
  };
72
- // Helper function to check and potentially unwrap a DataValue-like object
76
+ /**
77
+ * Unwrap a Rivet DataValue at an interpolation source boundary. Callers must
78
+ * not recursively apply this to selected JSON properties: an ordinary object
79
+ * inside the value may legitimately have `type` and `value` properties.
80
+ */
73
81
  export function unwrapPotentialDataValue(value) {
74
- if (typeof value === 'object' &&
75
- value !== null &&
76
- typeof value.type === 'string' &&
77
- Object.prototype.hasOwnProperty.call(value, 'value') // More robust check for 'value' property
78
- ) {
82
+ if (isRivetDataValue(value)) {
79
83
  return value.value;
80
84
  }
81
85
  return value;
82
86
  }
83
- // Renamed from resolveExpression, now exported and returns raw value
84
- export function resolveExpressionRawValue(source, expression, sourceType) {
85
- if (!source) {
86
- return undefined;
87
+ function isRivetDataValue(value) {
88
+ return (typeof value === 'object' &&
89
+ value !== null &&
90
+ typeof value.type === 'string' &&
91
+ dataValueTypeSet.has(value.type) &&
92
+ Object.prototype.hasOwnProperty.call(value, 'value'));
93
+ }
94
+ /**
95
+ * Renders a whole interpolation input with the legacy generic interpolation
96
+ * behavior. Text-oriented callers can opt into DataValue string coercion.
97
+ */
98
+ export function stringifyInterpolationSourceValue(value, { coerceDataValueToString = false, unwrapDataValue = true, } = {}) {
99
+ try {
100
+ if (coerceDataValueToString && unwrapDataValue && isRivetDataValue(value)) {
101
+ return coerceTypeOptional(value, 'string') ?? '';
102
+ }
103
+ return String((unwrapDataValue ? unwrapPotentialDataValue(value) : value) ?? '');
104
+ }
105
+ catch {
106
+ // Keep interpolation usable for cyclic values and custom objects whose
107
+ // string conversion throws, matching the prior object fallback.
108
+ return '[object Object]';
87
109
  }
88
- // Regex to capture the main key and the optional path starting with . or [
89
- // Allows for spaces around the key, path, ., and []
90
- // Key: Group 1; Path: Group 2
91
- const match = expression.trim().match(/^([^[.\s]+)\s*(.*)$/);
92
- let key;
93
- let path;
94
- // Check if match is successful AND group 1 (the key) was captured
95
- if (match && typeof match[1] === 'string') {
96
- key = match[1];
97
- const rawPath = match[2]; // Group 2 (the path part, might start with . or [)
98
- // Clean and assign path only if rawPath is not empty
99
- if (rawPath) {
100
- // Clean path: Trim whitespace, then remove spaces around separators '.', '[', ']'
101
- // Preserve the leading '.' or '[' as lodashGet handles them.
102
- path = rawPath.trim().replace(/\s*(\.|\[|\])\s*/g, '$1');
110
+ }
111
+ function findTopLevelProcessorSeparator(rawInner) {
112
+ let quote;
113
+ let regex = false;
114
+ let regexCharacterClass = false;
115
+ let bracketDepth = 0;
116
+ let parenthesisDepth = 0;
117
+ let braceDepth = 0;
118
+ for (let cursor = 0; cursor < rawInner.length; cursor++) {
119
+ const character = rawInner[cursor];
120
+ if (regex) {
121
+ if (character === '[' && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {
122
+ regexCharacterClass = true;
123
+ }
124
+ else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {
125
+ regexCharacterClass = false;
126
+ }
127
+ else if (character === '/' &&
128
+ !regexCharacterClass &&
129
+ !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {
130
+ regex = false;
131
+ }
132
+ continue;
133
+ }
134
+ if (quote) {
135
+ if (character === quote && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {
136
+ quote = undefined;
137
+ }
138
+ continue;
103
139
  }
104
- else {
105
- path = undefined;
140
+ if (character === '/' && isInterpolationRegexLiteralStart(rawInner, cursor)) {
141
+ regex = true;
142
+ regexCharacterClass = false;
143
+ continue;
144
+ }
145
+ if (character === '"' || character === "'" || character === '`') {
146
+ quote = character;
147
+ continue;
148
+ }
149
+ if (character === '[') {
150
+ bracketDepth += 1;
151
+ continue;
152
+ }
153
+ if (character === ']' && bracketDepth > 0) {
154
+ bracketDepth -= 1;
155
+ continue;
156
+ }
157
+ if (character === '(') {
158
+ parenthesisDepth += 1;
159
+ continue;
160
+ }
161
+ if (character === ')' && parenthesisDepth > 0) {
162
+ parenthesisDepth -= 1;
163
+ continue;
164
+ }
165
+ if (character === '{') {
166
+ braceDepth += 1;
167
+ continue;
168
+ }
169
+ if (character === '}' && braceDepth > 0) {
170
+ braceDepth -= 1;
171
+ continue;
172
+ }
173
+ if (character === '|' && bracketDepth === 0 && parenthesisDepth === 0 && braceDepth === 0) {
174
+ return cursor;
106
175
  }
107
176
  }
108
- else {
109
- // If match failed or group 1 wasn't captured (fallback)
110
- // Assume the entire expression is the key and there's no path
111
- key = expression.trim();
112
- path = undefined;
177
+ return undefined;
178
+ }
179
+ function findQuotedStringEnd(value, start) {
180
+ const quote = value[start];
181
+ for (let cursor = start + 1; cursor < value.length; cursor++) {
182
+ if (value[cursor] === quote && !isInterpolationSyntaxCharacterEscaped(value, cursor)) {
183
+ return cursor;
184
+ }
113
185
  }
114
- if (!key) {
115
- // If key is empty after trimming, it's invalid.
186
+ return undefined;
187
+ }
188
+ function parseQuotedBaseReference(expression) {
189
+ if (expression[0] !== '[') {
116
190
  return undefined;
117
191
  }
118
- const topLevelValue = source[key];
119
- if (topLevelValue === undefined) {
120
- return undefined; // Key not found in source
192
+ let cursor = 1;
193
+ while (expression[cursor] === ' ') {
194
+ cursor += 1;
121
195
  }
122
- // Get the base value by potentially unwrapping the top-level value using the shared helper
123
- const baseValue = unwrapPotentialDataValue(topLevelValue);
124
- // If there's a path, try to resolve it using lodashGet on the baseValue
125
- let finalValue;
126
- if (path) {
127
- try {
128
- finalValue = lodashGet(baseValue, path);
129
- // IMPORTANT: After getting a potentially nested value via path,
130
- // we might *still* have a DataValue (if the context stores them nested).
131
- // Unwrap again to be safe.
132
- finalValue = unwrapPotentialDataValue(finalValue);
133
- }
134
- catch (error) {
135
- console.warn(`Error accessing path "${path}" in ${sourceType} value for key "${key}":`, error);
136
- return undefined; // Error during path access
137
- }
196
+ const quote = expression[cursor];
197
+ if (quote !== '"' && quote !== "'") {
198
+ return undefined;
138
199
  }
139
- else {
140
- finalValue = baseValue; // No path, use the (potentially unwrapped) base value
200
+ const quoteEnd = findQuotedStringEnd(expression, cursor);
201
+ if (quoteEnd === undefined) {
202
+ return undefined;
141
203
  }
142
- // Return the raw final value
143
- return finalValue;
204
+ // JSONPath-plus retains the raw content of a bracket-property literal. Use
205
+ // escaping only to find its closing quote, then keep its key untouched so
206
+ // a `\\u` sequence names the same input it would name in JSONPath-plus.
207
+ const baseName = expression.slice(cursor + 1, quoteEnd);
208
+ if (!baseName) {
209
+ return undefined;
210
+ }
211
+ cursor = quoteEnd + 1;
212
+ while (expression[cursor] === ' ') {
213
+ cursor += 1;
214
+ }
215
+ if (expression[cursor] !== ']') {
216
+ return undefined;
217
+ }
218
+ const suffix = expression.slice(cursor + 1).trimStart();
219
+ if (suffix !== '' && !suffix.startsWith('.') && !suffix.startsWith('[')) {
220
+ return undefined;
221
+ }
222
+ return { baseName, suffix: suffix || undefined };
144
223
  }
145
- export function resolveExpressionToString(source, expression, sourceType) {
146
- const finalValue = resolveExpressionRawValue(source, expression, sourceType);
147
- if (finalValue === undefined) {
224
+ function parseBaseReference(expression, source) {
225
+ const trimmedExpression = expression.trim();
226
+ if (!trimmedExpression) {
148
227
  return undefined;
149
228
  }
150
- // Convert the final value to a string for TextNode context
151
- if (typeof finalValue === 'object' && finalValue !== null) {
152
- try {
153
- return JSON.stringify(finalValue);
229
+ const quotedReference = parseQuotedBaseReference(trimmedExpression);
230
+ if (quotedReference) {
231
+ return {
232
+ source,
233
+ baseName: quotedReference.baseName,
234
+ jsonPath: quotedReference.suffix ? normalizeJsonPathExpression(`$${quotedReference.suffix}`) : undefined,
235
+ };
236
+ }
237
+ let suffixStart = -1;
238
+ for (let cursor = 0; cursor < trimmedExpression.length; cursor++) {
239
+ const character = trimmedExpression[cursor];
240
+ if (character === '.' || character === '[') {
241
+ suffixStart = cursor;
242
+ break;
154
243
  }
155
- catch (error) {
156
- console.warn(`Error stringifying object/array in ${sourceType} for expression "${expression}":`, error);
157
- return '[object Object]'; // Fallback
244
+ }
245
+ if (suffixStart === -1) {
246
+ return {
247
+ source,
248
+ baseName: trimmedExpression,
249
+ jsonPath: undefined,
250
+ };
251
+ }
252
+ const baseName = trimmedExpression.slice(0, suffixStart).trim();
253
+ const suffix = normalizeJsonPathExpression(trimmedExpression.slice(suffixStart));
254
+ if (!baseName || (!suffix.startsWith('.') && !suffix.startsWith('['))) {
255
+ return undefined;
256
+ }
257
+ return {
258
+ source,
259
+ baseName,
260
+ jsonPath: `$${suffix}`,
261
+ };
262
+ }
263
+ /**
264
+ * Parses the authored portion of an interpolation token. Paths are always
265
+ * rooted at the selected base value, so `foo.items[0]` becomes input `foo`
266
+ * plus JSONPath `$.items[0]`.
267
+ */
268
+ function parseInterpolationExpressionUncached(trimmedExpression) {
269
+ for (const [prefix, source] of [
270
+ ['@graphInputs', 'graphInputs'],
271
+ ['@context', 'context'],
272
+ ]) {
273
+ if (trimmedExpression.startsWith(`${prefix}.`)) {
274
+ return parseBaseReference(trimmedExpression.slice(prefix.length + 1), source);
275
+ }
276
+ if (trimmedExpression.startsWith(`${prefix}[`)) {
277
+ return parseBaseReference(trimmedExpression.slice(prefix.length), source);
158
278
  }
159
279
  }
160
- // For primitives
161
- return String(finalValue);
280
+ return parseBaseReference(trimmedExpression, 'variable');
162
281
  }
163
- // Helper function to parse processing instructions like "indent 2" or "quote" into function name and parameter
164
- function parseProcessing(instruction) {
165
- const parts = instruction.trim().split(/\s+/);
282
+ /**
283
+ * Returns an immutable syntax record for internal resolution. This cache is
284
+ * intentionally keyed only by expression text; resolved values are always
285
+ * read from the current invocation's sources.
286
+ */
287
+ function getCachedInterpolationExpression(expression) {
288
+ const trimmedExpression = expression.trim();
289
+ if (interpolationExpressionCache.has(trimmedExpression)) {
290
+ return interpolationExpressionCache.get(trimmedExpression);
291
+ }
292
+ const parsed = parseInterpolationExpressionUncached(trimmedExpression);
293
+ if (trimmedExpression.length > INTERPOLATION_EXPRESSION_CACHE_MAX_EXPRESSION_LENGTH) {
294
+ return parsed;
295
+ }
296
+ if (interpolationExpressionCache.size >= INTERPOLATION_EXPRESSION_CACHE_MAX_ENTRIES ||
297
+ cachedInterpolationExpressionChars + trimmedExpression.length > INTERPOLATION_EXPRESSION_CACHE_MAX_CHARS) {
298
+ interpolationExpressionCache.clear();
299
+ cachedInterpolationExpressionChars = 0;
300
+ }
301
+ const immutableParsed = parsed ? Object.freeze({ ...parsed }) : undefined;
302
+ interpolationExpressionCache.set(trimmedExpression, immutableParsed);
303
+ cachedInterpolationExpressionChars += trimmedExpression.length;
304
+ return immutableParsed;
305
+ }
306
+ /**
307
+ * Parses a public interpolation expression. Return a fresh record so callers
308
+ * can safely mutate it without corrupting the internal syntax cache.
309
+ */
310
+ export function parseInterpolationExpression(expression) {
311
+ const parsed = getCachedInterpolationExpression(expression);
312
+ return parsed ? { ...parsed } : undefined;
313
+ }
314
+ /** Splits an interpolation token into its expression, processor chain, and parsed reference. */
315
+ export function parseInterpolationToken(rawInner) {
316
+ const processorSeparator = findTopLevelProcessorSeparator(rawInner);
317
+ const tokenName = (processorSeparator === undefined ? rawInner : rawInner.slice(0, processorSeparator)).trim() || undefined;
318
+ const processingChain = processorSeparator === undefined ? undefined : rawInner.slice(processorSeparator + 1).trim() || undefined;
166
319
  return {
167
- func: parts[0],
168
- param: parts[1] ? parseInt(parts[1], 10) : undefined,
320
+ rawInner,
321
+ tokenName,
322
+ processingChain,
323
+ reference: tokenName ? parseInterpolationExpression(tokenName) : undefined,
169
324
  };
170
325
  }
171
- // Apply a chain of processing functions to a string
172
- function applyProcessing(value, processingChain) {
173
- const instructions = processingChain
174
- .split('|')
175
- .map((instruction) => instruction.trim())
176
- .filter((instruction) => instruction !== '');
177
- return instructions.reduce((result, instruction) => {
178
- const { func, param } = parseProcessing(instruction);
179
- const processingFunc = processingFunctions[func];
180
- if (!processingFunc) {
181
- console.warn(`Unknown processing function: ${func}`);
182
- return result;
326
+ function freezeReference(reference) {
327
+ return reference ? Object.freeze({ ...reference }) : undefined;
328
+ }
329
+ function parseInterpolationTemplateUncached(template) {
330
+ const tokens = scanInterpolationTokenSpans(template).map((span) => {
331
+ const parsedToken = parseInterpolationToken(span.rawInner);
332
+ return Object.freeze({
333
+ ...parsedToken,
334
+ span: Object.freeze({ ...span }),
335
+ reference: freezeReference(parsedToken.reference),
336
+ });
337
+ });
338
+ return Object.freeze({
339
+ template,
340
+ tokens: Object.freeze(tokens),
341
+ });
342
+ }
343
+ function getTemplateStorageChars(template, parsed) {
344
+ return (template.length +
345
+ parsed.tokens.reduce((total, token) => total + token.rawInner.length + (token.tokenName?.length ?? 0), parsed.tokens.length * 48));
346
+ }
347
+ function cacheInterpolationTemplate(template, parsed) {
348
+ if (template.length > INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_LENGTH) {
349
+ return;
350
+ }
351
+ const storageChars = getTemplateStorageChars(template, parsed);
352
+ const reachesCapacity = interpolationTemplateCache.size >= INTERPOLATION_TEMPLATE_CACHE_MAX_ENTRIES ||
353
+ cachedInterpolationTemplateChars + template.length > INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_CHARS ||
354
+ cachedInterpolationTemplateStorageChars + storageChars > INTERPOLATION_TEMPLATE_CACHE_MAX_STORAGE_CHARS;
355
+ if (reachesCapacity) {
356
+ // Avoid miss-by-miss eviction churn. A repeated miss proves this template is hot.
357
+ if (lastUncachedInterpolationTemplate !== template) {
358
+ lastUncachedInterpolationTemplate = template;
359
+ return;
183
360
  }
184
- return processingFunc(result, param);
185
- }, value);
361
+ interpolationTemplateCache.clear();
362
+ cachedInterpolationTemplateChars = 0;
363
+ cachedInterpolationTemplateStorageChars = 0;
364
+ }
365
+ lastUncachedInterpolationTemplate = undefined;
366
+ interpolationTemplateCache.set(template, {
367
+ templateChars: template.length,
368
+ storageChars,
369
+ parsed,
370
+ });
371
+ cachedInterpolationTemplateChars += template.length;
372
+ cachedInterpolationTemplateStorageChars += storageChars;
373
+ }
374
+ /** Returns an immutable, cached syntax representation. It never evaluates values. */
375
+ export function parseInterpolationTemplate(template) {
376
+ const cached = interpolationTemplateCache.get(template);
377
+ if (cached) {
378
+ return cached.parsed;
379
+ }
380
+ const parsed = parseInterpolationTemplateUncached(template);
381
+ if (template.includes('{{')) {
382
+ cacheInterpolationTemplate(template, parsed);
383
+ }
384
+ return parsed;
186
385
  }
187
386
  export function protectEscapedInterpolationTokens(template) {
188
387
  return template.replace(ESCAPED_TOKEN_REGEX, (_match, expression) => `\\{\\{${expression}\\}\\}`);
189
388
  }
190
389
  export function restoreEscapedInterpolationTokens(template) {
191
- return template.replace(ESCAPED_ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`);
390
+ return template
391
+ .replace(ESCAPED_ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`)
392
+ .replace(ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`);
192
393
  }
193
394
  export function findInterpolationTokenSpans(template) {
194
- const spans = [];
195
- let searchIndex = 0;
196
- while (searchIndex < template.length) {
197
- const openIndex = template.indexOf('{{', searchIndex);
198
- if (openIndex === -1) {
199
- break;
200
- }
201
- const closeIndex = template.indexOf('}}', openIndex + 2);
202
- if (closeIndex === -1) {
203
- break;
204
- }
205
- const nestedOpenIndex = template.indexOf('{{', openIndex + 2);
206
- if (nestedOpenIndex !== -1 && nestedOpenIndex < closeIndex) {
207
- searchIndex = nestedOpenIndex;
208
- continue;
209
- }
210
- spans.push({
211
- start: openIndex,
212
- end: closeIndex + 2,
213
- rawInner: template.slice(openIndex + 2, closeIndex),
214
- });
215
- searchIndex = closeIndex + 2;
216
- }
217
- return spans;
395
+ return parseInterpolationTemplate(template).tokens.map((token) => ({ ...token.span }));
218
396
  }
397
+ /** Returns the pre-processor expression, retaining its authored path syntax. */
219
398
  export function getInterpolationTokenName(rawInner) {
220
- const [tokenPart] = rawInner.split('|');
221
- if (!tokenPart) {
222
- return undefined;
223
- }
224
- const token = tokenPart.trim();
225
- return token === '' ? undefined : token;
399
+ return parseInterpolationToken(rawInner).tokenName;
400
+ }
401
+ export function getInterpolationTokenReference(rawInner) {
402
+ return parseInterpolationToken(rawInner).reference;
226
403
  }
227
404
  export function replaceInterpolationTokens(template, getReplacement, options = {}) {
228
- const protectedTemplate = protectEscapedInterpolationTokens(template);
229
- const tokenSpans = findInterpolationTokenSpans(protectedTemplate);
230
- if (tokenSpans.length === 0) {
231
- const restoredTemplate = restoreEscapedInterpolationTokens(protectedTemplate);
405
+ const parsedTemplate = parseInterpolationTemplate(template);
406
+ if (parsedTemplate.tokens.length === 0) {
407
+ const restoredTemplate = restoreEscapedInterpolationTokens(template);
232
408
  return options.trim ? restoredTemplate.trim() : restoredTemplate;
233
409
  }
234
410
  let result = '';
235
411
  let cursor = 0;
236
- for (const tokenSpan of tokenSpans) {
237
- result += protectedTemplate.slice(cursor, tokenSpan.start);
412
+ for (const token of parsedTemplate.tokens) {
413
+ // Restore escaped delimiters only from authored template text. A
414
+ // replacement may deliberately contain `{{{...}}}` or `\\{\\{...\\}\\}` and
415
+ // must be returned unchanged rather than interpreted as template syntax.
416
+ result += restoreEscapedInterpolationTokens(template.slice(cursor, token.span.start));
238
417
  result += getReplacement({
239
- rawInner: tokenSpan.rawInner,
240
- span: tokenSpan,
241
- tokenName: getInterpolationTokenName(tokenSpan.rawInner),
418
+ rawInner: token.rawInner,
419
+ span: { ...token.span },
420
+ tokenName: token.tokenName,
421
+ processingChain: token.processingChain,
422
+ reference: token.reference ? { ...token.reference } : undefined,
242
423
  });
243
- cursor = tokenSpan.end;
244
- }
245
- result += protectedTemplate.slice(cursor);
246
- const restoredResult = restoreEscapedInterpolationTokens(result);
247
- return options.trim ? restoredResult.trim() : restoredResult;
248
- }
249
- export function interpolate(template, variables, graphInputValues, contextValues) {
250
- return replaceInterpolationTokens(template, ({ rawInner }) => {
251
- const parts = rawInner.split('|').map((s) => s.trim());
252
- const expression = parts[0]; // The variable name or path, e.g., @context.foo.bar or myVar
253
- const processingChain = parts.slice(1).join('|'); // e.g., indent 2 | quote
254
- let resolvedValue;
255
- if (expression.startsWith('@graphInputs.')) {
256
- resolvedValue = resolveExpressionToString(graphInputValues, expression.substring('@graphInputs.'.length), 'graphInputs');
257
- }
258
- else if (expression.startsWith('@context.')) {
259
- resolvedValue = resolveExpressionToString(contextValues, expression.substring('@context.'.length), 'context');
260
- }
261
- else {
262
- const simpleVar = variables[expression];
263
- if (simpleVar !== undefined) {
264
- resolvedValue = String(unwrapPotentialDataValue(simpleVar) ?? '');
265
- }
266
- else {
267
- resolvedValue = undefined;
268
- }
269
- }
270
- if (resolvedValue === undefined) {
271
- console.warn(`Interpolation variable or path "${expression}" not found or resolved to undefined.`);
272
- return '';
273
- }
274
- else if (processingChain) {
275
- return applyProcessing(resolvedValue, processingChain);
276
- }
277
- return resolvedValue;
278
- });
424
+ cursor = token.span.end;
425
+ }
426
+ result += restoreEscapedInterpolationTokens(template.slice(cursor));
427
+ return options.trim ? result.trim() : result;
279
428
  }
280
- // Extract all unique variable names from a template string
281
- // Ignores variables starting with @graphInputs. or @context., as they are treated as special references.
282
- export function extractInterpolationVariables(template) {
429
+ /**
430
+ * Discovers connectable interpolation bases in first-occurrence order. Special
431
+ * graph/context references are intentionally omitted because they do not make ports.
432
+ */
433
+ export function extractInterpolationVariableReferences(template) {
283
434
  if (!template.includes('{{')) {
284
435
  return [];
285
436
  }
286
- const cachedVariables = getCachedInterpolationVariables(template);
287
- if (cachedVariables) {
288
- return [...cachedVariables];
289
- }
290
- const protectedTemplate = protectEscapedInterpolationTokens(template);
291
- const variables = new Set();
292
- for (const match of findInterpolationTokenSpans(protectedTemplate)) {
293
- const token = getInterpolationTokenName(match.rawInner);
294
- if (token && !token.startsWith('@graphInputs.') && !token.startsWith('@context.')) {
295
- variables.add(token);
437
+ const discovered = new Map();
438
+ for (const token of parseInterpolationTemplate(template).tokens) {
439
+ const reference = token.reference;
440
+ if (!reference || reference.source !== 'variable') {
441
+ continue;
442
+ }
443
+ const existing = discovered.get(reference.baseName);
444
+ if (existing) {
445
+ existing.hasPath ||= reference.jsonPath !== undefined;
446
+ continue;
296
447
  }
448
+ discovered.set(reference.baseName, {
449
+ baseName: reference.baseName,
450
+ hasPath: reference.jsonPath !== undefined,
451
+ });
297
452
  }
298
- const extractedVariables = Array.from(variables);
299
- cacheInterpolationVariables(template, extractedVariables);
300
- return extractedVariables;
453
+ return Array.from(discovered.values(), (reference) => ({ ...reference }));
301
454
  }
302
- function getCachedInterpolationVariables(template) {
303
- return extractedInterpolationVariablesCache.get(template)?.variables;
455
+ /** Extracts base port names only. Prefer `extractInterpolationVariableReferences` when type selection matters. */
456
+ export function extractInterpolationVariables(template) {
457
+ return extractInterpolationVariableReferences(template).map((reference) => reference.baseName);
304
458
  }
305
- function cacheInterpolationVariables(template, variables) {
306
- if (template.length > EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_LENGTH) {
307
- return;
459
+ function getInterpolationSource(reference, sources) {
460
+ switch (reference.source) {
461
+ case 'variable':
462
+ return sources.variables;
463
+ case 'graphInputs':
464
+ return sources.graphInputValues;
465
+ case 'context':
466
+ return sources.contextValues;
308
467
  }
309
- if (extractedInterpolationVariablesCache.size >= EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_ENTRIES ||
310
- extractedInterpolationVariablesCacheTemplateChars + template.length >
311
- EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_CHARS) {
312
- // Avoid miss-by-miss eviction churn; only reset when a full-cache miss proves hot by repeating immediately.
313
- if (lastUncachedInterpolationVariableTemplate !== template) {
314
- lastUncachedInterpolationVariableTemplate = template;
315
- return;
468
+ }
469
+ /**
470
+ * Resolves one parsed interpolation expression from raw values. JSONPath uses
471
+ * `wrap: false`, matching Destructure exactly; callers decide how to render a
472
+ * missing value or a selected object.
473
+ */
474
+ export function resolveInterpolationExpressionRawValue(expression, sources) {
475
+ const reference = typeof expression === 'string' ? getCachedInterpolationExpression(expression) : expression;
476
+ if (!reference) {
477
+ return undefined;
478
+ }
479
+ const source = getInterpolationSource(reference, sources);
480
+ if (!source || !Object.prototype.hasOwnProperty.call(source, reference.baseName)) {
481
+ return undefined;
482
+ }
483
+ const shouldUnwrapDataValue = reference.source !== 'variable' || sources.unwrapVariableDataValues !== false;
484
+ const baseValue = shouldUnwrapDataValue
485
+ ? unwrapPotentialDataValue(source[reference.baseName])
486
+ : source[reference.baseName];
487
+ if (reference.jsonPath === undefined) {
488
+ return baseValue;
489
+ }
490
+ try {
491
+ return evaluateJsonPath(baseValue, reference.jsonPath, false);
492
+ }
493
+ catch {
494
+ return undefined;
495
+ }
496
+ }
497
+ export function resolveInterpolationTokenRawValue(rawInner, sources) {
498
+ const reference = parseInterpolationToken(rawInner).reference;
499
+ return reference ? resolveInterpolationExpressionRawValue(reference, sources) : undefined;
500
+ }
501
+ /** Backward-compatible special-reference resolver used by existing nodes. */
502
+ export function resolveExpressionRawValue(source, expression, sourceType) {
503
+ return resolveInterpolationExpressionRawValue(`@${sourceType}.${expression}`, {
504
+ graphInputValues: sourceType === 'graphInputs' ? source : undefined,
505
+ contextValues: sourceType === 'context' ? source : undefined,
506
+ });
507
+ }
508
+ function stringifyInterpolationValue(value) {
509
+ if (typeof value === 'object' && value !== null) {
510
+ try {
511
+ return JSON.stringify(value);
512
+ }
513
+ catch (error) {
514
+ console.warn('Error stringifying an interpolation value:', error);
515
+ return '[object Object]';
316
516
  }
317
- extractedInterpolationVariablesCache.clear();
318
- extractedInterpolationVariablesCacheTemplateChars = 0;
319
517
  }
320
- lastUncachedInterpolationVariableTemplate = undefined;
321
- extractedInterpolationVariablesCache.set(template, {
322
- templateLength: template.length,
323
- variables: Object.freeze([...variables]),
518
+ return String(value);
519
+ }
520
+ export function resolveExpressionToString(source, expression, sourceType) {
521
+ const finalValue = resolveExpressionRawValue(source, expression, sourceType);
522
+ return finalValue === undefined ? undefined : stringifyInterpolationValue(finalValue);
523
+ }
524
+ function parseProcessing(instruction) {
525
+ const parts = instruction.trim().split(/\s+/);
526
+ return {
527
+ func: parts[0],
528
+ param: parts[1] ? Number.parseInt(parts[1], 10) : undefined,
529
+ };
530
+ }
531
+ function applyProcessing(value, processingChain) {
532
+ const instructions = processingChain
533
+ .split('|')
534
+ .map((instruction) => instruction.trim())
535
+ .filter((instruction) => instruction !== '');
536
+ return instructions.reduce((result, instruction) => {
537
+ const { func, param } = parseProcessing(instruction);
538
+ const processingFunc = processingFunctions[func];
539
+ if (!processingFunc) {
540
+ console.warn(`Unknown processing function: ${func}`);
541
+ return result;
542
+ }
543
+ return processingFunc(result, param);
544
+ }, value);
545
+ }
546
+ /**
547
+ * Resolves text interpolation. Bare ordinary variables keep the historical
548
+ * string coercion; path-bearing references select raw data first and serialize
549
+ * selected objects/arrays as JSON.
550
+ */
551
+ export function interpolate(template, variables, graphInputValues, contextValues, options = {}) {
552
+ return replaceInterpolationTokens(template, (token) => {
553
+ if (!token.reference) {
554
+ return '';
555
+ }
556
+ const resolvedValue = resolveInterpolationExpressionRawValue(token.reference, {
557
+ variables,
558
+ graphInputValues,
559
+ contextValues,
560
+ unwrapVariableDataValues: options.unwrapVariableDataValues,
561
+ });
562
+ if (resolvedValue === undefined) {
563
+ console.warn(`Interpolation variable or path "${token.tokenName}" not found or resolved to undefined.`);
564
+ return '';
565
+ }
566
+ const isBareOrdinaryVariable = token.reference.source === 'variable' && token.reference.jsonPath === undefined;
567
+ const stringValue = isBareOrdinaryVariable
568
+ ? stringifyInterpolationSourceValue(variables[token.reference.baseName], {
569
+ coerceDataValueToString: options.coerceBareVariableDataValues,
570
+ unwrapDataValue: options.unwrapVariableDataValues !== false,
571
+ })
572
+ : stringifyInterpolationValue(resolvedValue);
573
+ return token.processingChain ? applyProcessing(stringValue, token.processingChain) : stringValue;
574
+ });
575
+ }
576
+ /** Runtime helper injected into JavaScript runners without exposing the whole Rivet API. */
577
+ export function resolveCodeInterpolationExpression(inputs, expression, graphInputValues, contextValues) {
578
+ return resolveInterpolationExpressionRawValue(expression, {
579
+ variables: inputs,
580
+ graphInputValues,
581
+ contextValues,
324
582
  });
325
- extractedInterpolationVariablesCacheTemplateChars += template.length;
326
583
  }