@valerypopoff/rivet2-core 2.4.0 → 2.6.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 (82) hide show
  1. package/dist/cjs/bundle.cjs +1800 -753
  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/AgentResponseTrace.js +8 -3
  13. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  14. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  15. package/dist/esm/model/GraphOutputSelection.js +34 -0
  16. package/dist/esm/model/GraphProcessor.js +177 -50
  17. package/dist/esm/model/ProcessContextBuilder.js +4 -1
  18. package/dist/esm/model/RecordingPlayer.js +46 -14
  19. package/dist/esm/model/SplitRunProcessor.js +37 -16
  20. package/dist/esm/model/StoredValueStore.js +4 -3
  21. package/dist/esm/model/UiGraphRendererStyles.js +20 -0
  22. package/dist/esm/model/chat/aiSdkStreaming.js +3 -2
  23. package/dist/esm/model/chat-v2/aiSdkBridge.js +63 -5
  24. package/dist/esm/model/chat-v2/chatV2Pipeline.js +66 -3
  25. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +20 -7
  26. package/dist/esm/model/chat-v2/llmProfileFallback.js +12 -4
  27. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  28. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  29. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  30. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  31. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  32. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  33. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  34. package/dist/esm/model/nodes/LLMChatV2Node.js +30 -4
  35. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  36. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  37. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  38. package/dist/esm/model/nodes/PromptNode.js +10 -11
  39. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  40. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  41. package/dist/esm/model/nodes/TextNode.js +11 -32
  42. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  43. package/dist/esm/model/nodes/ToolNode.js +33 -16
  44. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  45. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  46. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  47. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  48. package/dist/esm/recording/ExecutionRecorder.js +55 -23
  49. package/dist/esm/utils/index.js +2 -0
  50. package/dist/esm/utils/interpolation.js +478 -221
  51. package/dist/esm/utils/interpolationSyntax.js +175 -0
  52. package/dist/esm/utils/jsonPath.js +129 -0
  53. package/dist/types/exports.d.ts +3 -1
  54. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  55. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  56. package/dist/types/interpolationRuntime.d.ts +5 -0
  57. package/dist/types/model/AgentResponseTrace.d.ts +2 -0
  58. package/dist/types/model/ExecutorProtocol.d.ts +4 -0
  59. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  60. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  61. package/dist/types/model/GraphProcessor.d.ts +12 -3
  62. package/dist/types/model/ProcessContext.d.ts +9 -2
  63. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  64. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  65. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  66. package/dist/types/model/chat/aiSdkStreaming.d.ts +1 -1
  67. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +1 -1
  68. package/dist/types/model/chat-v2/chatV2Types.d.ts +29 -0
  69. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +5 -1
  70. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  71. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  72. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  73. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  74. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  75. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  76. package/dist/types/recording/ExecutionRecorder.d.ts +6 -1
  77. package/dist/types/recording/RecordedEvents.d.ts +2 -0
  78. package/dist/types/utils/index.d.ts +2 -0
  79. package/dist/types/utils/interpolation.d.ts +93 -8
  80. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  81. package/dist/types/utils/jsonPath.d.ts +15 -0
  82. package/package.json +11 -1
@@ -10,7 +10,7 @@ import {} from '../ProcessContext.js';
10
10
  import {} from '../../index.js';
11
11
  import { dedent } from 'ts-dedent';
12
12
  import { getError } from '../../utils/errors.js';
13
- import { applyGraphBoundaryPortOrder, buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, getRequestedGraphOutputNodeIds, } from '../GraphBoundaryCache.js';
13
+ import { applyGraphBoundaryPortOrder, buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, } from '../GraphBoundaryCache.js';
14
14
  export class SubGraphNodeImpl extends NodeImpl {
15
15
  static create() {
16
16
  const chartNode = {
@@ -26,6 +26,7 @@ export class SubGraphNodeImpl extends NodeImpl {
26
26
  graphId: '',
27
27
  useErrorOutput: false,
28
28
  useAsGraphPartialOutput: false,
29
+ skipUnusedOutputs: false,
29
30
  },
30
31
  };
31
32
  return chartNode;
@@ -65,6 +66,13 @@ export class SubGraphNodeImpl extends NodeImpl {
65
66
  label: 'Use Error Output',
66
67
  dataKey: 'useErrorOutput',
67
68
  },
69
+ {
70
+ type: 'toggle',
71
+ label: 'Skip unused outputs',
72
+ dataKey: 'skipUnusedOutputs',
73
+ helperMessage: 'Only run branches needed by connected outputs. Skipped branches also skip their side effects and errors. ' +
74
+ 'Runs the full subgraph for Run to here, partial-output forwarding, or a connected Error output.',
75
+ },
68
76
  ];
69
77
  if (this.data.graphId) {
70
78
  const boundary = getGraphBoundary(context.project, this.data.graphId);
@@ -104,30 +112,25 @@ export class SubGraphNodeImpl extends NodeImpl {
104
112
  }
105
113
  const boundary = context.getGraphBoundary?.(project, this.data.graphId) ?? getGraphBoundary(project, this.data.graphId);
106
114
  const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
107
- const shouldRunWholeGraph = !GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED ||
115
+ const shouldRunWholeGraph = this.data.skipUnusedOutputs !== true ||
108
116
  context.isDirectRunTarget ||
109
117
  this.data.useAsGraphPartialOutput === true ||
110
118
  (this.data.useErrorOutput === true && context.activeOutputPortIds.has('error'));
111
- const requestedGraphOutputNodeIds = shouldRunWholeGraph
112
- ? []
113
- : getRequestedGraphOutputNodeIds(boundary, context.activeOutputPortIds);
114
- if (!shouldRunWholeGraph && requestedGraphOutputNodeIds.length === 0) {
115
- return buildSkippedSubgraphOutputs(boundary, this.data.useErrorOutput);
119
+ const requestedGraphOutputIds = shouldRunWholeGraph
120
+ ? undefined
121
+ : boundary.outputs.filter((output) => context.activeOutputPortIds.has(output.portId)).map((output) => output.id);
122
+ if (requestedGraphOutputIds?.length === 0) {
123
+ return buildOptimizedSubgraphOutputs(boundary, [], {}, 0, this.data.useErrorOutput);
116
124
  }
117
125
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });
118
- if (!shouldRunWholeGraph) {
119
- subGraphProcessor.runToNodeIds = requestedGraphOutputNodeIds;
120
- }
121
126
  try {
122
127
  const startTime = Date.now();
123
- const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);
124
- const outputs = shouldRunWholeGraph
125
- ? graphOutputs
126
- : {
127
- ...buildExcludedGraphBoundaryOutputs(boundary),
128
- ...graphOutputs,
129
- };
128
+ const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues, requestedGraphOutputIds ? { requestedGraphOutputIds } : undefined);
130
129
  const duration = Date.now() - startTime;
130
+ if (requestedGraphOutputIds) {
131
+ return buildOptimizedSubgraphOutputs(boundary, requestedGraphOutputIds, graphOutputs, duration, this.data.useErrorOutput);
132
+ }
133
+ const outputs = graphOutputs;
131
134
  if (this.data.useErrorOutput) {
132
135
  outputs['error'] = {
133
136
  type: 'control-flow-excluded',
@@ -156,21 +159,32 @@ export class SubGraphNodeImpl extends NodeImpl {
156
159
  }
157
160
  }
158
161
  export const subGraphNode = nodeDefinition(SubGraphNodeImpl, 'Subgraph');
159
- function buildSkippedSubgraphOutputs(boundary, useErrorOutput) {
162
+ function buildOptimizedSubgraphOutputs(boundary, requestedOutputIds, graphOutputs, duration, useErrorOutput) {
160
163
  const outputs = buildExcludedGraphBoundaryOutputs(boundary);
164
+ for (const outputId of requestedOutputIds) {
165
+ if (Object.hasOwn(graphOutputs, outputId)) {
166
+ outputs[outputId] = graphOutputs[outputId];
167
+ }
168
+ else {
169
+ // Missing requested values must remain missing: downstream optional inputs
170
+ // may use defaults, whereas an excluded value would skip their node.
171
+ delete outputs[outputId];
172
+ }
173
+ }
161
174
  if (useErrorOutput) {
162
175
  outputs['error'] = {
163
176
  type: 'control-flow-excluded',
164
177
  value: undefined,
165
178
  };
166
179
  }
167
- outputs['cost'] = {
168
- type: 'number',
169
- value: 0,
170
- };
171
- outputs['duration'] = {
172
- type: 'number',
173
- value: 0,
174
- };
180
+ // Authored boundary values retain ownership of metric-named ports, including
181
+ // exclusions. An unrequested Graph Output may still run as another output's
182
+ // dependency, so do not copy arbitrary child results into the caller map.
183
+ if (!boundary.outputs.some((output) => output.id === 'cost')) {
184
+ outputs['cost'] = graphOutputs['cost'] ?? { type: 'number', value: 0 };
185
+ }
186
+ if (!boundary.outputs.some((output) => output.id === 'duration')) {
187
+ outputs['duration'] = { type: 'number', value: duration };
188
+ }
175
189
  return outputs;
176
190
  }
@@ -5,26 +5,9 @@ import { nodeDefinition } from '../NodeDefinition.js';
5
5
  import {} from '../DataValue.js';
6
6
  import {} from '../../index.js';
7
7
  import { dedent } from 'ts-dedent';
8
- import { coerceTypeOptional } from '../../utils/coerceType.js';
9
- import { extractInterpolationVariables, interpolate } from '../../utils/interpolation.js';
8
+ import { extractInterpolationVariableReferences, interpolate } from '../../utils/interpolation.js';
10
9
  import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
11
- const MAX_BODY_PREVIEW_LINES = 15;
12
- const MAX_BODY_PREVIEW_LINE_LENGTH = 240;
13
- const MAX_BODY_PREVIEW_CHARS = 3000;
14
- function buildTextNodeBodyPreview(text) {
15
- const allLines = text.split('\n');
16
- const previewLines = allLines.slice(0, MAX_BODY_PREVIEW_LINES).map((line) => line.length > MAX_BODY_PREVIEW_LINE_LENGTH ? `${line.slice(0, MAX_BODY_PREVIEW_LINE_LENGTH)}...` : line);
17
- const omittedLines = allLines.length > MAX_BODY_PREVIEW_LINES;
18
- let previewText = previewLines.join('\n').trim();
19
- if (previewText.length > MAX_BODY_PREVIEW_CHARS) {
20
- previewText = previewText.slice(0, MAX_BODY_PREVIEW_CHARS).trimEnd();
21
- return previewText.length === 0 ? '...' : `${previewText}\n...`;
22
- }
23
- if (omittedLines) {
24
- return previewText.length === 0 ? '...' : `${previewText}\n...`;
25
- }
26
- return previewText;
27
- }
10
+ import { buildNodeBodyPreview } from './nodeBodyPreview.js';
28
11
  export class TextNodeImpl extends NodeImpl {
29
12
  static create() {
30
13
  const chartNode = {
@@ -45,12 +28,12 @@ export class TextNodeImpl extends NodeImpl {
45
28
  }
46
29
  getInputDefinitions() {
47
30
  // Extract inputs from text, everything like {{input}}
48
- const inputNames = extractInterpolationVariables(this.data.text);
49
- return (inputNames?.map((inputName) => createInterpolationInputDefinition({
50
- interpolationName: inputName,
51
- dataType: 'string',
31
+ const inputReferences = extractInterpolationVariableReferences(this.data.text);
32
+ return inputReferences.map(({ baseName, hasPath }) => createInterpolationInputDefinition({
33
+ interpolationName: baseName,
34
+ dataType: hasPath ? 'any' : 'string',
52
35
  required: false,
53
- })) ?? []);
36
+ }));
54
37
  }
55
38
  getOutputDefinitions() {
56
39
  return [
@@ -89,17 +72,13 @@ export class TextNodeImpl extends NodeImpl {
89
72
  type: 'colorized',
90
73
  language: 'prompt-interpolation-markdown',
91
74
  theme: 'prompt-interpolation',
92
- text: buildTextNodeBodyPreview(this.data.text),
75
+ text: buildNodeBodyPreview(this.data.text),
93
76
  };
94
77
  }
95
78
  async process(inputs, context) {
96
- const inputMap = Object.keys(inputs).reduce((acc, key) => {
97
- const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';
98
- acc[key] = stringValue;
99
- return acc;
100
- }, {});
101
- let outputValue = interpolate(this.chartNode.data.text, inputMap, context.graphInputNodeValues, // Pass graph inputs
102
- context.contextValues);
79
+ let outputValue = interpolate(this.chartNode.data.text, inputs, context.graphInputNodeValues, // Pass graph inputs
80
+ context.contextValues, // Pass context values
81
+ { coerceBareVariableDataValues: true });
103
82
  if (this.chartNode.data.normalizeLineEndings) {
104
83
  outputValue = outputValue.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
105
84
  }
@@ -6,7 +6,7 @@ import {} from '../DataValue.js';
6
6
  import {} from '../EditorDefinition.js';
7
7
  import { dedent } from 'ts-dedent';
8
8
  import { coerceTypeOptional } from '../../utils/coerceType.js';
9
- import { extractInterpolationVariables, interpolate } from '../../utils/interpolation.js';
9
+ import { interpolate } from '../../utils/interpolation.js';
10
10
  import { get, sortBy } from 'lodash-es';
11
11
  export class ToTreeNodeImpl extends NodeImpl {
12
12
  static create() {
@@ -89,7 +89,7 @@ export class ToTreeNodeImpl extends NodeImpl {
89
89
  group: ['Text'],
90
90
  };
91
91
  }
92
- buildTree(objects, parentPath = '', level = 0, isLast = true) {
92
+ buildTree(objects, parentPath = '', level = 0, isLast = true, interpolationContext) {
93
93
  if (!Array.isArray(objects) || objects.length === 0)
94
94
  return '';
95
95
  let result = '';
@@ -100,28 +100,21 @@ export class ToTreeNodeImpl extends NodeImpl {
100
100
  const isLastItem = index === sortedObjects.length - 1;
101
101
  const prefix = level === 0 ? '' : isLast ? '└── ' : '├── ';
102
102
  const indent = level === 0 ? '' : ' '.repeat(level - 1) + (isLast ? ' ' : '│ ');
103
- // Get all potential interpolation variables from the format string
104
- const matches = extractInterpolationVariables(this.data.format);
105
- const interpolationVars = matches.reduce((acc, match) => {
106
- const key = match;
107
- acc[key] = String(get(obj, key, ''));
108
- return acc;
109
- }, {});
110
- const formattedNode = interpolate(this.data.format, interpolationVars);
103
+ const formattedNode = interpolate(this.data.format, obj != null && typeof obj === 'object' ? obj : {}, interpolationContext?.graphInputNodeValues, interpolationContext?.contextValues, { unwrapVariableDataValues: false });
111
104
  // Add this node to the result
112
105
  result += indent + prefix + formattedNode + '\n';
113
106
  // Process children if they exist
114
107
  const children = get(obj, this.data.childrenProperty);
115
108
  if (Array.isArray(children) && children.length > 0) {
116
109
  const newPath = parentPath ? `${parentPath}/${formattedNode}` : formattedNode;
117
- result += this.buildTree(children, newPath, level + 1, isLastItem);
110
+ result += this.buildTree(children, newPath, level + 1, isLastItem, interpolationContext);
118
111
  }
119
112
  });
120
113
  return result;
121
114
  }
122
- async process(inputs) {
115
+ async process(inputs, context) {
123
116
  const objects = coerceTypeOptional(inputs['objects'], 'object[]') ?? [];
124
- const treeOutput = this.buildTree(objects);
117
+ const treeOutput = this.buildTree(objects, '', 0, true, context);
125
118
  return {
126
119
  ['tree']: {
127
120
  type: 'string',
@@ -5,11 +5,26 @@ import { nodeDefinition } from '../NodeDefinition.js';
5
5
  import { dedent } from 'ts-dedent';
6
6
  import {} from '../EditorDefinition.js';
7
7
  import {} from '../NodeBodySpec.js';
8
- import { extractInterpolationVariables, interpolate } from '../../utils/interpolation.js';
8
+ import { extractInterpolationVariableReferences, interpolate } from '../../utils/interpolation.js';
9
9
  import { keys } from '../../utils/typeSafety.js';
10
- import { coerceTypeOptional, coerceType } from '../../utils/coerceType.js';
10
+ import { coerceType } from '../../utils/coerceType.js';
11
11
  import { getInputOrData } from '../../utils/index.js';
12
12
  import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
13
+ import { buildNodeBodyPreview } from './nodeBodyPreview.js';
14
+ const TOOL_NODE_BODY_PREVIEW_MAX_LINES = 14;
15
+ /**
16
+ * Splits Tool's bounded canvas preview into its label/value row and its text body.
17
+ *
18
+ * The combined source preview deliberately uses one fewer line than Text to
19
+ * compensate for the custom header's visual separator.
20
+ */
21
+ export function getToolNodeBodyPreview(data) {
22
+ const [name = '', ...descriptionLines] = buildNodeBodyPreview(`${data.name}\n${data.description}`, TOOL_NODE_BODY_PREVIEW_MAX_LINES).split('\n');
23
+ return {
24
+ name,
25
+ description: descriptionLines.join('\n'),
26
+ };
27
+ }
13
28
  export class GptFunctionNodeImpl extends NodeImpl {
14
29
  static create() {
15
30
  const chartNode = {
@@ -60,17 +75,17 @@ export class GptFunctionNodeImpl extends NodeImpl {
60
75
  description: 'The schema of the tool that the LLM will see as available to call',
61
76
  });
62
77
  }
63
- const inputNames = this.data.useSchemaInput ? [] : extractInterpolationVariables(this.data.schema);
78
+ const inputReferences = this.data.useSchemaInput ? [] : extractInterpolationVariableReferences(this.data.schema);
64
79
  inputs = [
65
80
  ...inputs,
66
- ...(inputNames?.map((inputName) => {
81
+ ...inputReferences.map(({ baseName, hasPath }) => {
67
82
  return createInterpolationInputDefinition({
68
- id: `input-${inputName}`,
69
- interpolationName: inputName,
70
- dataType: 'string',
71
- description: `An interpolated value in the schema named '${inputName}'`,
83
+ id: `input-${baseName}`,
84
+ interpolationName: baseName,
85
+ dataType: hasPath ? 'any' : 'string',
86
+ description: `An interpolated value in the schema named '${baseName}'`,
72
87
  });
73
- }) ?? []),
88
+ }),
74
89
  ];
75
90
  return inputs;
76
91
  }
@@ -142,9 +157,12 @@ export class GptFunctionNodeImpl extends NodeImpl {
142
157
  ];
143
158
  }
144
159
  getBody() {
160
+ const preview = getToolNodeBodyPreview(this.data);
145
161
  return {
146
- type: 'markdown',
147
- text: `**${this.data.name}**\n${this.data.description}`,
162
+ type: 'colorized',
163
+ language: 'prompt-interpolation-markdown',
164
+ theme: 'prompt-interpolation',
165
+ text: [preview.name, preview.description].filter(Boolean).join('\n'),
148
166
  };
149
167
  }
150
168
  static getUIData() {
@@ -157,7 +175,7 @@ export class GptFunctionNodeImpl extends NodeImpl {
157
175
  group: ['AI'],
158
176
  };
159
177
  }
160
- async process(inputs) {
178
+ async process(inputs, context) {
161
179
  const name = getInputOrData(this.data, inputs, 'name');
162
180
  const description = getInputOrData(this.data, inputs, 'description');
163
181
  const resultHandling = this.data.resultHandling === 'return-direct' ? 'return-direct' : 'continue';
@@ -167,14 +185,13 @@ export class GptFunctionNodeImpl extends NodeImpl {
167
185
  }
168
186
  else {
169
187
  const inputMap = keys(inputs)
170
- .filter((key) => key.startsWith('input'))
188
+ .filter((key) => key.startsWith('input-'))
171
189
  .reduce((acc, key) => {
172
- const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';
173
190
  const interpolationKey = key.slice('input-'.length);
174
- acc[interpolationKey] = stringValue;
191
+ acc[interpolationKey] = inputs[key];
175
192
  return acc;
176
193
  }, {});
177
- const interpolated = interpolate(this.data.schema, inputMap);
194
+ const interpolated = interpolate(this.data.schema, inputMap, context?.graphInputNodeValues, context?.contextValues, { coerceBareVariableDataValues: true });
178
195
  schema = JSON.parse(interpolated);
179
196
  }
180
197
  return {
@@ -1,10 +1,9 @@
1
1
  import { dedent } from 'ts-dedent';
2
- import { buildClonedInputValueAssignments, buildJsValueInterpolatedSource, buildJsValueInputClonePreamble, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
2
+ import { buildClonedInputValueAssignments, buildJsValueInterpolatedSource, buildJsValueInputClonePreamble, buildJsValuePreview, getJsValueInterpolationCodeRunnerOptions, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
3
3
  const MAX_CALLBACK_PREVIEW_BODY_LINES = 13;
4
4
  const JS_LIST_CALLBACK_SIGNATURE = '(item, index, array)';
5
5
  export const JS_LIST_CALLBACK_LOCAL_NAMES = new Set(['item', 'index', 'array']);
6
6
  const JS_LIST_INPUTS_IDENTIFIER = '__jsListInputs';
7
- const JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER = 'jsListInputCloneCache';
8
7
  const JS_LIST_CODE_RUNNER_OPTIONS = {
9
8
  includeFetch: false,
10
9
  includeRequire: false,
@@ -35,27 +34,33 @@ function buildJSListRuntimePreamble(interpolationContext) {
35
34
  return dedent `
36
35
  const assertSynchronousCallbackResult = ${assertSynchronousCallbackResult.toString()};
37
36
  ${buildJsValueInputClonePreamble({
38
- cacheIdentifier: JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER,
37
+ cacheIdentifier: interpolationContext.cloneCacheIdentifier,
38
+ contextIdentifier: interpolationContext.contextIdentifier,
39
+ graphInputsIdentifier: interpolationContext.graphInputsIdentifier,
39
40
  inputsIdentifier: interpolationContext.inputsIdentifier,
40
41
  })}
41
- const array = cloneJsInputValue(inputs.array?.value, ${JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER});
42
- ${buildClonedInputValueAssignments(interpolationContext.inputNames, interpolationContext.inputsIdentifier, JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER)}
42
+ const array = cloneJsInputValue(inputs.array?.value, ${interpolationContext.cloneCacheIdentifier});
43
+ ${buildClonedInputValueAssignments(interpolationContext.inputNames, interpolationContext.inputsIdentifier, interpolationContext.cloneCacheIdentifier)}
43
44
  `;
44
45
  }
45
- function buildJSListCallbackRuntimeSource(callbackBody, inputsIdentifier) {
46
- return buildJsValueInterpolatedSource(callbackBody, inputsIdentifier, {
46
+ function buildJSListCallbackRuntimeSource(callbackBody, interpolationContext) {
47
+ return buildJsValueInterpolatedSource(callbackBody, interpolationContext, {
47
48
  localIdentifiers: JS_LIST_CALLBACK_LOCAL_NAMES,
48
49
  });
49
50
  }
50
51
  function sanitizeJSListError(error, callbackBody, nodeName) {
51
- const { inputNames, inputsIdentifier } = getJSListInterpolationContext(callbackBody);
52
+ const interpolationContext = getJSListInterpolationContext(callbackBody);
52
53
  const fallbackLabel = `${nodeName} input`;
53
- return sanitizeGeneratedJsValueError(error, inputNames, inputsIdentifier, fallbackLabel);
54
+ return sanitizeGeneratedJsValueError(error, interpolationContext.inputNames, interpolationContext.inputsIdentifier, fallbackLabel, [
55
+ interpolationContext.cloneCacheIdentifier,
56
+ interpolationContext.contextIdentifier,
57
+ interpolationContext.graphInputsIdentifier,
58
+ interpolationContext.interpolationHelperIdentifier,
59
+ ]);
54
60
  }
55
61
  export function buildJSFilterWrapper(callbackBody) {
56
62
  const interpolationContext = getJSListInterpolationContext(callbackBody);
57
- const { inputsIdentifier } = interpolationContext;
58
- const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody, inputsIdentifier);
63
+ const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody, interpolationContext);
59
64
  return dedent `
60
65
  ${buildJSListRuntimePreamble(interpolationContext)}
61
66
 
@@ -91,8 +96,7 @@ export function buildJSFilterWrapper(callbackBody) {
91
96
  }
92
97
  export function buildJSMapWrapper(callbackBody) {
93
98
  const interpolationContext = getJSListInterpolationContext(callbackBody);
94
- const { inputsIdentifier } = interpolationContext;
95
- const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody, inputsIdentifier);
99
+ const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody, interpolationContext);
96
100
  return dedent `
97
101
  ${buildJSListRuntimePreamble(interpolationContext)}
98
102
 
@@ -145,7 +149,7 @@ export function getJSListEditors() {
145
149
  type: 'code',
146
150
  label: 'Callback Body',
147
151
  helperMessage: '(item, index, array) => {',
148
- postEditorHelperMessage: '};\n\n//Use {{var}} to create input ports that evaluate as connected values.',
152
+ postEditorHelperMessage: '};\n\n//Use {{var}} to create input ports. {{config.limit.max}} creates only config; {{item.name}} and {{array[0]}} use callback locals.',
149
153
  dataKey: 'callbackBody',
150
154
  language: 'javascript',
151
155
  interpolationSyntax: 'js-value',
@@ -182,7 +186,7 @@ export function assertJSListNodeOutputs(outputs, outputId, nodeName) {
182
186
  }
183
187
  export async function runJSListNodeCode({ buildWrapper, callbackBody, context, inputs, nodeName, outputId, }) {
184
188
  try {
185
- const outputs = await context.codeRunner.runCode(buildWrapper(callbackBody), inputs, JS_LIST_CODE_RUNNER_OPTIONS, context.graphInputNodeValues, context.contextValues);
189
+ const outputs = await context.codeRunner.runCode(buildWrapper(callbackBody), inputs, getJsValueInterpolationCodeRunnerOptions(JS_LIST_CODE_RUNNER_OPTIONS, getJSListInterpolationContext(callbackBody)), context.graphInputNodeValues, context.contextValues);
186
190
  assertJSListNodeOutputs(outputs, outputId, nodeName);
187
191
  return outputs;
188
192
  }
@@ -1,7 +1,8 @@
1
1
  import { dedent } from 'ts-dedent';
2
2
  import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
3
3
  import { getError } from '../../utils/errors.js';
4
- import { extractInterpolationVariables, replaceInterpolationTokens } from '../../utils/interpolation.js';
4
+ import { extractInterpolationVariables, parseInterpolationTemplate, replaceInterpolationTokens, resolveInterpolationExpressionRawValue, } from '../../utils/interpolation.js';
5
+ const MISSING_INTERPOLATION_HELPER_MESSAGE = 'This CodeRunner must honor CodeRunnerOptions.interpolationHelperIdentifier to resolve JSONPath or @graphInputs/@context interpolation.';
5
6
  function escapeRegExp(value) {
6
7
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
7
8
  }
@@ -20,32 +21,39 @@ export function getSafeJsValueInterpolationIdentifier(source, baseIdentifier) {
20
21
  export function buildJsValuePreview(source, maxLines) {
21
22
  return source.split('\n').slice(0, maxLines).join('\n').trim();
22
23
  }
23
- function isSpecialReference(inputName) {
24
- return inputName.startsWith('@graphInputs.') || inputName.startsWith('@context.');
25
- }
26
24
  function isSimpleIdentifier(value) {
27
25
  return /^[A-Za-z_$][\w$]*$/.test(value);
28
26
  }
29
27
  function getUserFacingInputName(inputName) {
30
28
  return isSimpleIdentifier(inputName) ? inputName : `{{${inputName}}}`;
31
29
  }
32
- function buildJsValueReference(inputName, targetIdentifier, options) {
33
- if (!inputName || isSpecialReference(inputName)) {
30
+ function buildJsValueReference(token, interpolationContext, options) {
31
+ if (!token.tokenName || !token.reference) {
34
32
  return 'undefined';
35
33
  }
36
- if (options.localIdentifiers?.has(inputName)) {
37
- return inputName;
34
+ const isBareVariableReference = token.reference.source === 'variable' && token.reference.jsonPath === undefined;
35
+ if (isBareVariableReference) {
36
+ return options.localIdentifiers?.has(token.reference.baseName)
37
+ ? token.reference.baseName
38
+ : `${interpolationContext.inputsIdentifier}[${JSON.stringify(token.reference.baseName)}].value`;
38
39
  }
39
- return `${targetIdentifier}[${JSON.stringify(inputName)}]`;
40
+ const isLocalReference = token.reference.source === 'variable' && options.localIdentifiers?.has(token.reference.baseName);
41
+ const sourceInputs = isLocalReference
42
+ ? `{ ${JSON.stringify(token.reference.baseName)}: { type: 'any', value: ${token.reference.baseName} } }`
43
+ : interpolationContext.inputsIdentifier;
44
+ const resolveExpression = `${interpolationContext.interpolationHelperIdentifier}(${sourceInputs}, ${JSON.stringify(token.tokenName)}, ${interpolationContext.graphInputsIdentifier}, ${interpolationContext.contextIdentifier})`;
45
+ return `(typeof ${interpolationContext.interpolationHelperIdentifier} === 'function'
46
+ ? ${resolveExpression}
47
+ : (() => { throw new Error(${JSON.stringify(MISSING_INTERPOLATION_HELPER_MESSAGE)}); })())`;
40
48
  }
41
- function formatJsValuePreviewValue(inputName, inputs, options) {
42
- if (!inputName || isSpecialReference(inputName)) {
49
+ function formatJsValuePreviewValue(token, inputs, options) {
50
+ if (!token.tokenName || !token.reference || token.reference.source !== 'variable') {
43
51
  return 'undefined';
44
52
  }
45
- if (options.localIdentifiers?.has(inputName)) {
46
- return inputName;
53
+ if (options.localIdentifiers?.has(token.reference.baseName)) {
54
+ return token.reference.jsonPath ? `{{${token.tokenName}}}` : token.reference.baseName;
47
55
  }
48
- const value = inputs[inputName]?.value;
56
+ const value = resolveInterpolationExpressionRawValue(token.tokenName, { variables: inputs });
49
57
  if (value === undefined) {
50
58
  return 'undefined';
51
59
  }
@@ -58,7 +66,7 @@ function formatJsValuePreviewValue(inputName, inputs, options) {
58
66
  if (typeof value === 'number' || typeof value === 'boolean') {
59
67
  return String(value);
60
68
  }
61
- return getUserFacingInputName(inputName);
69
+ return getUserFacingInputName(token.tokenName);
62
70
  }
63
71
  export function getJsValueInterpolationInputNames(template, options = {}) {
64
72
  return extractInterpolationVariables(template).filter((inputName) => !options.localIdentifiers?.has(inputName));
@@ -71,18 +79,30 @@ export function getJsValueInterpolationInputDefinitions(template, options = {})
71
79
  }));
72
80
  }
73
81
  export function getJsValueInterpolationRuntimeContext(template, baseInputsIdentifier, options = {}) {
82
+ const inputsIdentifier = getSafeJsValueInterpolationIdentifier(template, baseInputsIdentifier);
83
+ const interpolationHelperIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}`, `${baseInputsIdentifier}ResolveInterpolation`);
84
+ const cloneCacheIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}`, `${baseInputsIdentifier}CloneCache`);
85
+ const graphInputsIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}\n${cloneCacheIdentifier}`, `${baseInputsIdentifier}GraphInputs`);
86
+ const contextIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}\n${cloneCacheIdentifier}\n${graphInputsIdentifier}`, `${baseInputsIdentifier}Context`);
87
+ const parsedTemplate = parseInterpolationTemplate(template);
74
88
  return {
75
89
  inputNames: getJsValueInterpolationInputNames(template, options),
76
- inputsIdentifier: getSafeJsValueInterpolationIdentifier(template, baseInputsIdentifier),
90
+ inputsIdentifier,
91
+ interpolationHelperIdentifier,
92
+ cloneCacheIdentifier,
93
+ graphInputsIdentifier,
94
+ contextIdentifier,
95
+ requiresInterpolationHelper: parsedTemplate.tokens.some((token) => token.reference !== undefined &&
96
+ (token.reference.source !== 'variable' || token.reference.jsonPath !== undefined)),
77
97
  };
78
98
  }
79
- export function buildJsValueInterpolatedSource(template, targetIdentifier, options = {}) {
80
- return replaceInterpolationTokens(template, (token) => buildJsValueReference(token.tokenName, targetIdentifier, options), {
99
+ export function buildJsValueInterpolatedSource(template, interpolationContext, options = {}) {
100
+ return replaceInterpolationTokens(template, (token) => buildJsValueReference(token, interpolationContext, options), {
81
101
  trim: options.trim ?? true,
82
102
  });
83
103
  }
84
104
  export function interpolateJsValuePreviewSource(template, inputs, options = {}) {
85
- return replaceInterpolationTokens(template, (token) => formatJsValuePreviewValue(token.tokenName, inputs, options), {
105
+ return replaceInterpolationTokens(template, (token) => formatJsValuePreviewValue(token, inputs, options), {
86
106
  trim: options.trim ?? true,
87
107
  });
88
108
  }
@@ -178,40 +198,73 @@ export function buildCloneJsInputValueFunction() {
178
198
  }
179
199
  export function buildClonedInputValueAssignments(inputNames, targetIdentifier, cacheIdentifier) {
180
200
  return inputNames
181
- .map((inputName) => `${targetIdentifier}[${JSON.stringify(inputName)}] = cloneJsInputValue(inputs[${JSON.stringify(inputName)}]?.value, ${cacheIdentifier});`)
201
+ .map((inputName) => `${targetIdentifier}[${JSON.stringify(inputName)}] = (() => {
202
+ const sourceDataValue = inputs[${JSON.stringify(inputName)}];
203
+ return sourceDataValue == null
204
+ ? { type: 'any', value: undefined }
205
+ : { ...sourceDataValue, value: cloneJsInputValue(sourceDataValue.value, ${cacheIdentifier}) };
206
+ })();`)
182
207
  .join('\n');
183
208
  }
184
- export function buildJsValueInputClonePreamble({ cacheIdentifier, inputsIdentifier, }) {
209
+ export function buildJsValueInputClonePreamble({ cacheIdentifier, contextIdentifier, graphInputsIdentifier, inputsIdentifier, }) {
185
210
  return dedent `
186
211
  ${buildCloneJsInputValueFunction()}
187
212
  const ${inputsIdentifier} = Object.create(null);
188
213
  const ${cacheIdentifier} = new WeakMap();
214
+ const ${graphInputsIdentifier} = typeof graphInputs === 'undefined'
215
+ ? Object.create(null)
216
+ : cloneJsInputValue(graphInputs, ${cacheIdentifier});
217
+ const ${contextIdentifier} = typeof context === 'undefined'
218
+ ? Object.create(null)
219
+ : cloneJsInputValue(context, ${cacheIdentifier});
189
220
  `;
190
221
  }
191
- export function buildJsValueInputsInitializer({ cacheIdentifier, inputNames, inputsIdentifier, }) {
222
+ export function buildJsValueInputsInitializer({ interpolationContext, }) {
223
+ const { cloneCacheIdentifier, contextIdentifier, graphInputsIdentifier, inputNames, inputsIdentifier } = interpolationContext;
192
224
  return dedent `
193
- ${buildJsValueInputClonePreamble({ cacheIdentifier, inputsIdentifier })}
194
- ${buildClonedInputValueAssignments(inputNames, inputsIdentifier, cacheIdentifier)}
225
+ ${buildJsValueInputClonePreamble({
226
+ cacheIdentifier: cloneCacheIdentifier,
227
+ contextIdentifier,
228
+ graphInputsIdentifier,
229
+ inputsIdentifier,
230
+ })}
231
+ ${buildClonedInputValueAssignments(inputNames, inputsIdentifier, cloneCacheIdentifier)}
195
232
  `;
196
233
  }
197
- export function sanitizeGeneratedJsValueText(text, inputNames, targetIdentifier, fallbackLabel) {
234
+ export function getJsValueInterpolationCodeRunnerOptions(options, interpolationContext) {
235
+ if (!interpolationContext.requiresInterpolationHelper) {
236
+ return options;
237
+ }
238
+ return {
239
+ ...options,
240
+ interpolationHelperIdentifier: interpolationContext.interpolationHelperIdentifier,
241
+ };
242
+ }
243
+ export function sanitizeGeneratedJsValueText(text, inputNames, targetIdentifier, fallbackLabel, generatedIdentifiers = []) {
198
244
  if (!text) {
199
245
  return text;
200
246
  }
201
247
  let sanitized = text;
248
+ const generatedFallbackLabel = inputNames.length === 1 ? `${fallbackLabel} ${getUserFacingInputName(inputNames[0])}` : fallbackLabel;
202
249
  for (const inputName of inputNames) {
203
250
  const userFacingInputName = getUserFacingInputName(inputName);
204
251
  sanitized = sanitized
205
252
  .replaceAll(`${targetIdentifier}[${JSON.stringify(inputName)}]`, userFacingInputName)
206
253
  .replaceAll(`${targetIdentifier}.${inputName}`, userFacingInputName);
207
254
  }
208
- return sanitized.replaceAll(targetIdentifier, fallbackLabel);
255
+ // Several generated identifiers intentionally share the input identifier as
256
+ // a prefix. Replace the longer names first so errors never leak fragments
257
+ // such as "code inputResolveInterpolation".
258
+ for (const identifier of [...generatedIdentifiers].sort((left, right) => right.length - left.length)) {
259
+ sanitized = sanitized.replaceAll(identifier, generatedFallbackLabel);
260
+ }
261
+ sanitized = sanitized.replaceAll(targetIdentifier, fallbackLabel);
262
+ return sanitized;
209
263
  }
210
- export function sanitizeGeneratedJsValueError(error, inputNames, targetIdentifier, fallbackLabel) {
264
+ export function sanitizeGeneratedJsValueError(error, inputNames, targetIdentifier, fallbackLabel, generatedIdentifiers = []) {
211
265
  const jsValueError = getError(error);
212
266
  jsValueError.message =
213
- sanitizeGeneratedJsValueText(jsValueError.message, inputNames, targetIdentifier, fallbackLabel) ??
214
- jsValueError.message;
215
- jsValueError.stack = sanitizeGeneratedJsValueText(jsValueError.stack, inputNames, targetIdentifier, fallbackLabel);
267
+ sanitizeGeneratedJsValueText(jsValueError.message, inputNames, targetIdentifier, fallbackLabel, generatedIdentifiers) ?? jsValueError.message;
268
+ jsValueError.stack = sanitizeGeneratedJsValueText(jsValueError.stack, inputNames, targetIdentifier, fallbackLabel, generatedIdentifiers);
216
269
  return jsValueError;
217
270
  }
@@ -0,0 +1,23 @@
1
+ const MAX_BODY_PREVIEW_LINES = 15;
2
+ const MAX_BODY_PREVIEW_LINE_LENGTH = 240;
3
+ const MAX_BODY_PREVIEW_CHARS = 3000;
4
+ /**
5
+ * Bounds node-card previews without changing the full value persisted in node data.
6
+ *
7
+ * The limits are intentionally shared by text-like node bodies so one long field
8
+ * cannot make its canvas card taller than the familiar Text-node preview.
9
+ */
10
+ export function buildNodeBodyPreview(text, maximumLines = MAX_BODY_PREVIEW_LINES) {
11
+ const allLines = text.split('\n');
12
+ const previewLines = allLines.slice(0, maximumLines).map((line) => line.length > MAX_BODY_PREVIEW_LINE_LENGTH ? `${line.slice(0, MAX_BODY_PREVIEW_LINE_LENGTH)}...` : line);
13
+ const omittedLines = allLines.length > maximumLines;
14
+ let previewText = previewLines.join('\n').trim();
15
+ if (previewText.length > MAX_BODY_PREVIEW_CHARS) {
16
+ previewText = previewText.slice(0, MAX_BODY_PREVIEW_CHARS).trimEnd();
17
+ return previewText.length === 0 ? '...' : `${previewText}\n...`;
18
+ }
19
+ if (omittedLines) {
20
+ return previewText.length === 0 ? '...' : `${previewText}\n...`;
21
+ }
22
+ return previewText;
23
+ }