@valerypopoff/rivet2-core 2.0.8 → 2.0.10

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 (53) hide show
  1. package/dist/cjs/bundle.cjs +1187 -589
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +1 -0
  4. package/dist/esm/api/streaming.js +1 -0
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/DebuggerTransportSentinel.js +78 -0
  7. package/dist/esm/model/GraphAbortReasons.js +69 -0
  8. package/dist/esm/model/GraphBoundaryCache.js +92 -0
  9. package/dist/esm/model/GraphPreprocessor.js +88 -30
  10. package/dist/esm/model/GraphProcessor.js +295 -96
  11. package/dist/esm/model/NodeImpl.js +6 -4
  12. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  13. package/dist/esm/model/RecordingPlayer.js +27 -7
  14. package/dist/esm/model/SplitRunProcessor.js +48 -9
  15. package/dist/esm/model/SubprocessorBridge.js +30 -23
  16. package/dist/esm/model/nodes/DidRunNode.js +12 -7
  17. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  18. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  19. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  20. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  21. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  22. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  23. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  24. package/dist/esm/utils/emitDetached.js +2 -2
  25. package/dist/esm/utils/interpolation.js +41 -1
  26. package/dist/esm/utils/serialization/serialization.js +6 -5
  27. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  28. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  29. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  30. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  31. package/dist/types/api/createProcessor.d.ts +1 -0
  32. package/dist/types/api/streaming.d.ts +1 -0
  33. package/dist/types/exports.d.ts +1 -0
  34. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  35. package/dist/types/model/EditorDefinition.d.ts +7 -1
  36. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  37. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  38. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  39. package/dist/types/model/GraphPreprocessor.d.ts +3 -1
  40. package/dist/types/model/GraphProcessor.d.ts +8 -0
  41. package/dist/types/model/NodeImpl.d.ts +10 -5
  42. package/dist/types/model/Nodes.d.ts +2 -2
  43. package/dist/types/model/ProcessContext.d.ts +3 -0
  44. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  45. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  46. package/dist/types/model/nodes/DidRunNode.d.ts +2 -1
  47. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  48. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  49. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  50. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  51. package/dist/types/utils/emitDetached.d.ts +2 -2
  52. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  53. package/package.json +1 -1
@@ -5,12 +5,11 @@ import {} from '../GraphProcessor.js';
5
5
  import {} from '../NodeGraph.js';
6
6
  import { nanoid } from 'nanoid/non-secure';
7
7
  import {} from '../Project.js';
8
- import {} from './GraphInputNode.js';
9
- import {} from './GraphOutputNode.js';
10
8
  import {} from '../DataValue.js';
11
9
  import {} from '../ProcessContext.js';
12
10
  import { dedent } from 'ts-dedent';
13
11
  import { getError } from '../../utils/errors.js';
12
+ import { buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, } from '../GraphBoundaryCache.js';
14
13
  export class ReferencedGraphAliasNodeImpl extends NodeImpl {
15
14
  static create() {
16
15
  const chartNode = {
@@ -30,44 +29,25 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
30
29
  };
31
30
  return chartNode;
32
31
  }
33
- getInputDefinitions(_connections, _nodes, _project, referencedProjects) {
32
+ getInputDefinitions(_connections, _nodes, _project, referencedProjects, definitionContext) {
34
33
  const referencedProject = referencedProjects[this.data.projectId];
35
34
  if (!referencedProject) {
36
35
  return [];
37
36
  }
38
- const graph = referencedProject.graphs[this.data.graphId];
39
- if (!graph) {
40
- return [];
41
- }
42
- const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput');
43
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
44
- return inputIds.map((id) => ({
45
- id: id,
46
- title: id,
47
- dataType: inputNodes.find((node) => node.data.id === id).data.dataType,
48
- }));
37
+ const boundary = this.getBoundary(referencedProject, definitionContext);
38
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
49
39
  }
50
- getGraphOutputs(referencedProject) {
51
- const graph = referencedProject.graphs[this.data.graphId];
52
- if (!graph) {
53
- return [];
54
- }
55
- const outputNodes = graph.nodes.filter((node) => node.type === 'graphOutput');
56
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
57
- const outputs = outputIds.map((id) => ({
58
- id: id,
59
- title: id,
60
- dataType: outputNodes.find((node) => node.data.id === id).data.dataType,
61
- }));
62
- return outputs;
40
+ getGraphOutputs(referencedProject, definitionContext) {
41
+ const boundary = this.getBoundary(referencedProject, definitionContext);
42
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
63
43
  }
64
- getOutputDefinitions(_connections, _nodes, _project, referencedProjects) {
44
+ getOutputDefinitions(_connections, _nodes, _project, referencedProjects, definitionContext) {
65
45
  const outputs = [];
66
46
  const referencedProject = referencedProjects[this.data.projectId];
67
47
  if (!referencedProject) {
68
48
  return outputs;
69
49
  }
70
- outputs.push(...this.getGraphOutputs(referencedProject));
50
+ outputs.push(...this.getGraphOutputs(referencedProject, definitionContext));
71
51
  if (this.data.useErrorOutput) {
72
52
  outputs.push({
73
53
  id: 'error',
@@ -77,6 +57,10 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
77
57
  }
78
58
  return outputs;
79
59
  }
60
+ getBoundary(referencedProject, definitionContext) {
61
+ return (definitionContext?.getGraphBoundary(referencedProject, this.data.graphId) ??
62
+ getGraphBoundary(referencedProject, this.data.graphId));
63
+ }
80
64
  getEditors(context) {
81
65
  const definitions = [
82
66
  {
@@ -92,19 +76,16 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
92
76
  ];
93
77
  const referencedProject = context.referencedProjects[this.data.projectId];
94
78
  if (referencedProject) {
95
- const graph = referencedProject.graphs[this.data.graphId];
96
- if (graph) {
97
- const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput');
98
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
99
- for (const inputId of inputIds) {
100
- const inputNode = inputNodes.find((node) => node.data.id === inputId);
79
+ const boundary = getGraphBoundary(referencedProject, this.data.graphId);
80
+ if (boundary) {
81
+ for (const input of boundary.inputs) {
101
82
  definitions.push({
102
83
  type: 'dynamic',
103
84
  dataKey: 'inputData',
104
- dynamicDataKey: inputNode.data.id,
105
- dataType: inputNode.data.dataType,
106
- label: inputNode.data.id,
107
- editor: inputNode.data.editor ?? 'auto',
85
+ dynamicDataKey: input.id,
86
+ dataType: input.dataType,
87
+ label: input.id,
88
+ editor: input.editor ?? 'auto',
108
89
  });
109
90
  }
110
91
  }
@@ -133,23 +114,9 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
133
114
  if (!graph) {
134
115
  throw new Error(`ReferencedGraphAliasNode requires a graph with id ${this.data.graphId} to be present in the referenced project.`);
135
116
  }
136
- const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput');
137
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
138
- const inputData = inputIds.reduce((obj, id) => {
139
- if (inputs[id] != null) {
140
- return {
141
- ...obj,
142
- [id]: inputs[id],
143
- };
144
- }
145
- if (this.data.inputData?.[id] != null) {
146
- return {
147
- ...obj,
148
- [id]: this.data.inputData[id],
149
- };
150
- }
151
- return obj;
152
- }, {});
117
+ const boundary = context.getGraphBoundary?.(referencedProject, this.data.graphId) ??
118
+ getGraphBoundary(referencedProject, this.data.graphId);
119
+ const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
153
120
  // Create a subprocessor using the referenced project's graph
154
121
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, {
155
122
  signal: context.signal,
@@ -181,13 +148,7 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
181
148
  if (!this.data.useErrorOutput) {
182
149
  throw err;
183
150
  }
184
- const outputs = this.getGraphOutputs(referencedProject).reduce((obj, output) => ({
185
- ...obj,
186
- [output.id]: {
187
- type: 'control-flow-excluded',
188
- value: undefined,
189
- },
190
- }), {});
151
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
191
152
  outputs['error'] = {
192
153
  type: 'string',
193
154
  value: getError(err).message,
@@ -71,6 +71,7 @@ export class SetGlobalNodeImpl extends NodeImpl {
71
71
  dataKey: 'id',
72
72
  useInputToggleDataKey: 'useIdInput',
73
73
  label: 'ID',
74
+ includeInGraphSearch: true,
74
75
  },
75
76
  {
76
77
  type: 'dataTypeSelector',
@@ -105,7 +106,7 @@ export class SetGlobalNodeImpl extends NodeImpl {
105
106
  if (!id) {
106
107
  throw new Error('Missing variable ID');
107
108
  }
108
- let previousValue = context.getGlobal(this.data.id);
109
+ let previousValue = context.getGlobal(id);
109
110
  if (!previousValue && isArrayDataType(this.data.dataType)) {
110
111
  previousValue = { type: this.data.dataType, value: [] };
111
112
  }
@@ -5,13 +5,12 @@ import {} from '../GraphProcessor.js';
5
5
  import {} from '../NodeGraph.js';
6
6
  import { nanoid } from 'nanoid/non-secure';
7
7
  import {} from '../Project.js';
8
- import {} from './GraphInputNode.js';
9
- import {} from './GraphOutputNode.js';
10
8
  import {} from '../DataValue.js';
11
9
  import {} from '../ProcessContext.js';
12
10
  import {} from '../../index.js';
13
11
  import { dedent } from 'ts-dedent';
14
12
  import { getError } from '../../utils/errors.js';
13
+ import { buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, } from '../GraphBoundaryCache.js';
15
14
  export class SubGraphNodeImpl extends NodeImpl {
16
15
  static create() {
17
16
  const chartNode = {
@@ -31,36 +30,17 @@ export class SubGraphNodeImpl extends NodeImpl {
31
30
  };
32
31
  return chartNode;
33
32
  }
34
- getInputDefinitions(_connections, _nodes, project) {
35
- const graph = project.graphs[this.data.graphId];
36
- if (!graph) {
37
- return [];
38
- }
39
- const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput');
40
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
41
- return inputIds.map((id) => ({
42
- id: id,
43
- title: id,
44
- dataType: inputNodes.find((node) => node.data.id === id).data.dataType,
45
- }));
33
+ getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
34
+ const boundary = this.getBoundary(project, definitionContext);
35
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
46
36
  }
47
- getGraphOutputs(project) {
48
- const graph = project.graphs[this.data.graphId];
49
- if (!graph) {
50
- return [];
51
- }
52
- const outputNodes = graph.nodes.filter((node) => node.type === 'graphOutput');
53
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
54
- const outputs = outputIds.map((id) => ({
55
- id: id,
56
- title: id,
57
- dataType: outputNodes.find((node) => node.data.id === id).data.dataType,
58
- }));
59
- return outputs;
37
+ getGraphOutputs(project, definitionContext) {
38
+ const boundary = this.getBoundary(project, definitionContext);
39
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
60
40
  }
61
- getOutputDefinitions(_connections, _nodes, project) {
41
+ getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
62
42
  const outputs = [];
63
- outputs.push(...this.getGraphOutputs(project));
43
+ outputs.push(...this.getGraphOutputs(project, definitionContext));
64
44
  if (this.data.useErrorOutput) {
65
45
  outputs.push({
66
46
  id: 'error',
@@ -70,6 +50,9 @@ export class SubGraphNodeImpl extends NodeImpl {
70
50
  }
71
51
  return outputs;
72
52
  }
53
+ getBoundary(project, definitionContext) {
54
+ return (definitionContext?.getGraphBoundary(project, this.data.graphId) ?? getGraphBoundary(project, this.data.graphId));
55
+ }
73
56
  getEditors(context) {
74
57
  const definitions = [
75
58
  {
@@ -84,19 +67,16 @@ export class SubGraphNodeImpl extends NodeImpl {
84
67
  },
85
68
  ];
86
69
  if (this.data.graphId) {
87
- const graph = context.project.graphs[this.data.graphId];
88
- if (graph) {
89
- const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput');
90
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
91
- for (const inputId of inputIds) {
92
- const inputNode = inputNodes.find((node) => node.data.id === inputId);
70
+ const boundary = getGraphBoundary(context.project, this.data.graphId);
71
+ if (boundary) {
72
+ for (const input of boundary.inputs) {
93
73
  definitions.push({
94
74
  type: 'dynamic',
95
75
  dataKey: 'inputData',
96
- dynamicDataKey: inputNode.data.id,
97
- dataType: inputNode.data.dataType,
98
- label: inputNode.data.id,
99
- editor: inputNode.data.editor ?? 'auto',
76
+ dynamicDataKey: input.id,
77
+ dataType: input.dataType,
78
+ label: input.id,
79
+ editor: input.editor ?? 'auto',
100
80
  });
101
81
  }
102
82
  }
@@ -122,23 +102,8 @@ export class SubGraphNodeImpl extends NodeImpl {
122
102
  if (!graph) {
123
103
  throw new Error(`SubGraphNode requires a graph with id ${this.data.graphId} to be present in the project.`);
124
104
  }
125
- const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput');
126
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
127
- const inputData = inputIds.reduce((obj, id) => {
128
- if (inputs[id] != null) {
129
- return {
130
- ...obj,
131
- [id]: inputs[id],
132
- };
133
- }
134
- if (this.data.inputData?.[id] != null) {
135
- return {
136
- ...obj,
137
- [id]: this.data.inputData[id],
138
- };
139
- }
140
- return obj;
141
- }, {});
105
+ const boundary = context.getGraphBoundary?.(project, this.data.graphId) ?? getGraphBoundary(project, this.data.graphId);
106
+ const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
142
107
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });
143
108
  try {
144
109
  const startTime = Date.now();
@@ -162,13 +127,7 @@ export class SubGraphNodeImpl extends NodeImpl {
162
127
  if (!this.data.useErrorOutput) {
163
128
  throw err;
164
129
  }
165
- const outputs = this.getGraphOutputs(context.project).reduce((obj, output) => ({
166
- ...obj,
167
- [output.id]: {
168
- type: 'control-flow-excluded',
169
- value: undefined,
170
- },
171
- }), {});
130
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
172
131
  outputs['error'] = {
173
132
  type: 'string',
174
133
  value: getError(err).message,
@@ -9,6 +9,13 @@ import { emitDetached } from '../utils/emitDetached.js';
9
9
  function withExecution(base, execution) {
10
10
  return (execution == null ? base : { ...base, execution });
11
11
  }
12
+ function withDuration(base, durationMs, splitRunDurationMs) {
13
+ return {
14
+ ...base,
15
+ ...(durationMs === undefined ? {} : { durationMs }),
16
+ ...(splitRunDurationMs === undefined ? {} : { splitRunDurationMs }),
17
+ };
18
+ }
12
19
  const toRecordedEventMap = {
13
20
  graphStart: ({ graph, inputs, execution }) => withExecution({ graphId: graph.metadata.id, inputs }, execution),
14
21
  graphFinish: ({ graph, outputs, execution }) => withExecution({ graphId: graph.metadata.id, outputs }, execution),
@@ -21,16 +28,16 @@ const toRecordedEventMap = {
21
28
  inputs,
22
29
  processId,
23
30
  }, execution),
24
- nodeFinish: ({ node, outputs, processId, execution }) => withExecution({
31
+ nodeFinish: ({ node, outputs, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
25
32
  nodeId: node.id,
26
33
  outputs,
27
34
  processId,
28
- }, execution),
29
- nodeError: ({ node, error, processId, execution }) => withExecution({
35
+ }, durationMs, splitRunDurationMs), execution),
36
+ nodeError: ({ node, error, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
30
37
  nodeId: node.id,
31
38
  error: typeof error === 'string' ? error : error.stack,
32
39
  processId,
33
- }, execution),
40
+ }, durationMs, splitRunDurationMs), execution),
34
41
  abort: ({ successful, error }) => ({ successful, error: typeof error === 'string' ? error : error?.stack }),
35
42
  graphAbort: ({ successful, error, graph, execution }) => withExecution({
36
43
  successful,
@@ -206,7 +213,7 @@ export class ExecutionRecorder {
206
213
  return;
207
214
  }
208
215
  this.#events.push(toRecordedEvent(message, data));
209
- if (message === 'done' || message === 'abort' || message === 'error') {
216
+ if (isRecordingTerminalEvent(message, data)) {
210
217
  emitDetached(this.#emitter, 'finish', {
211
218
  recording: this.getRecording(),
212
219
  });
@@ -227,7 +234,7 @@ export class ExecutionRecorder {
227
234
  return;
228
235
  }
229
236
  this.#events.push(toRecordedEvent(event, data));
230
- if (event === 'done' || event === 'abort' || event === 'error') {
237
+ if (isRecordingTerminalEvent(event, data)) {
231
238
  emitDetached(this.#emitter, 'finish', {
232
239
  recording: this.getRecording(),
233
240
  });
@@ -271,3 +278,9 @@ export class ExecutionRecorder {
271
278
  return stringifyJsonStream(serializeToObject(this.getRecording()));
272
279
  }
273
280
  }
281
+ function isRecordingTerminalEvent(event, data) {
282
+ if (event === 'done' || event === 'error') {
283
+ return true;
284
+ }
285
+ return event === 'abort' && data.successful !== true;
286
+ }
@@ -4,8 +4,8 @@
4
4
  * Use this instead of inline `// eslint-disable-next-line @typescript-eslint/no-floating-promises`
5
5
  * to make the "detached async" intent explicit and auditable.
6
6
  *
7
- * The returned promise is intentionally discarded. Listener errors are swallowed
8
- * by Emittery's default behavior (logged to console).
7
+ * The returned promise is intentionally discarded. Call this only for events
8
+ * where listener completion does not affect processor ordering.
9
9
  */
10
10
  export function emitDetached(emitter, event, data) {
11
11
  void emitter.emit(event, data);
@@ -2,6 +2,12 @@ import { dedent } from './misc.js';
2
2
  import { get as lodashGet } from 'lodash-es';
3
3
  export const ESCAPED_TOKEN_REGEX = /\{\{\{([^}]+?)\}\}\}/g;
4
4
  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;
5
11
  const processingFunctions = {
6
12
  indent: (input, spaces = 0) => {
7
13
  const indent = ' '.repeat(spaces);
@@ -274,6 +280,13 @@ export function interpolate(template, variables, graphInputValues, contextValues
274
280
  // Extract all unique variable names from a template string
275
281
  // Ignores variables starting with @graphInputs. or @context., as they are treated as special references.
276
282
  export function extractInterpolationVariables(template) {
283
+ if (!template.includes('{{')) {
284
+ return [];
285
+ }
286
+ const cachedVariables = getCachedInterpolationVariables(template);
287
+ if (cachedVariables) {
288
+ return [...cachedVariables];
289
+ }
277
290
  const protectedTemplate = protectEscapedInterpolationTokens(template);
278
291
  const variables = new Set();
279
292
  for (const match of findInterpolationTokenSpans(protectedTemplate)) {
@@ -282,5 +295,32 @@ export function extractInterpolationVariables(template) {
282
295
  variables.add(token);
283
296
  }
284
297
  }
285
- return Array.from(variables);
298
+ const extractedVariables = Array.from(variables);
299
+ cacheInterpolationVariables(template, extractedVariables);
300
+ return extractedVariables;
301
+ }
302
+ function getCachedInterpolationVariables(template) {
303
+ return extractedInterpolationVariablesCache.get(template)?.variables;
304
+ }
305
+ function cacheInterpolationVariables(template, variables) {
306
+ if (template.length > EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_LENGTH) {
307
+ return;
308
+ }
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;
316
+ }
317
+ extractedInterpolationVariablesCache.clear();
318
+ extractedInterpolationVariablesCacheTemplateChars = 0;
319
+ }
320
+ lastUncachedInterpolationVariableTemplate = undefined;
321
+ extractedInterpolationVariablesCache.set(template, {
322
+ templateLength: template.length,
323
+ variables: Object.freeze([...variables]),
324
+ });
325
+ extractedInterpolationVariablesCacheTemplateChars += template.length;
286
326
  }
@@ -2,7 +2,8 @@
2
2
  import * as yaml from 'yaml';
3
3
  import { graphV3Deserializer, projectV3Deserializer } from './serialization_v3.js';
4
4
  import { getError } from '../errors.js';
5
- import { detectSerializationVersion, yamlProblem } from './serializationUtils.js';
5
+ import { yamlProblem } from './serializationUtils.js';
6
+ import { prepareSerializedInput } from './serializationInput.js';
6
7
  import { datasetV4Deserializer, datasetV4Serializer, graphV4Deserializer, graphV4Serializer, projectV4Deserializer, projectV4Serializer, } from './serialization_v4.js';
7
8
  import { graphV2Deserializer, projectV2Deserializer } from './serialization_v2.js';
8
9
  import { graphV1Deserializer, projectV1Deserializer } from './serialization_v1.js';
@@ -11,9 +12,9 @@ export function serializeProject(project, attachedData) {
11
12
  }
12
13
  const errMessage = (err) => `${getError(err).message}\n${getError(err).stack}`;
13
14
  export function deserializeProject(serializedProject, path = null) {
14
- const version = detectSerializationVersion(serializedProject);
15
+ const { deserializerInput, version } = prepareSerializedInput(serializedProject);
15
16
  try {
16
- const result = deserializeProjectByVersion(serializedProject, version);
17
+ const result = deserializeProjectByVersion(deserializerInput, version);
17
18
  normalizeProjectDefaultNodeTitles(result[0]);
18
19
  if (path !== null) {
19
20
  result[0].metadata.path = path;
@@ -32,9 +33,9 @@ export function serializeGraph(graph) {
32
33
  return graphV4Serializer(graph);
33
34
  }
34
35
  export function deserializeGraph(serializedGraph) {
35
- const version = detectSerializationVersion(serializedGraph);
36
+ const { deserializerInput, version } = prepareSerializedInput(serializedGraph);
36
37
  try {
37
- const graph = deserializeGraphByVersion(serializedGraph, version);
38
+ const graph = deserializeGraphByVersion(deserializerInput, version);
38
39
  normalizeGraphDefaultNodeTitles(graph);
39
40
  return graph;
40
41
  }
@@ -52,10 +52,10 @@ export function wrapInYamlEnvelope(version, data) {
52
52
  return yaml.stringify({ version, data: stabilized }, null, { indent: 2 });
53
53
  }
54
54
  export function unwrapYamlEnvelope(raw, expectedVersion, label) {
55
- if (typeof raw !== 'string') {
55
+ if (typeof raw !== 'string' && (!raw || typeof raw !== 'object' || Array.isArray(raw))) {
56
56
  throw new Error(`${label} deserializer requires a string`);
57
57
  }
58
- const parsed = yaml.parse(raw);
58
+ const parsed = (typeof raw === 'string' ? yaml.parse(raw) : raw);
59
59
  if (parsed.version !== expectedVersion) {
60
60
  throw new Error(`${label} deserializer requires a version ${expectedVersion} ${label.toLowerCase()}`);
61
61
  }
@@ -0,0 +1,48 @@
1
+ import * as YAML from 'yaml';
2
+ export function prepareSerializedInput(data) {
3
+ if (typeof data !== 'string') {
4
+ return {
5
+ deserializerInput: data,
6
+ version: 1,
7
+ };
8
+ }
9
+ const trimmed = data.trim();
10
+ if (!trimmed) {
11
+ return {
12
+ deserializerInput: data,
13
+ version: 1,
14
+ };
15
+ }
16
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
17
+ try {
18
+ const parsed = JSON.parse(trimmed);
19
+ const version = getParsedSerializationVersion(parsed);
20
+ return {
21
+ deserializerInput: version === 1 ? data : parsed,
22
+ version,
23
+ };
24
+ }
25
+ catch {
26
+ return {
27
+ deserializerInput: data,
28
+ version: 1,
29
+ };
30
+ }
31
+ }
32
+ const parsed = YAML.parse(trimmed);
33
+ const version = getParsedSerializationVersion(parsed);
34
+ return {
35
+ deserializerInput: version === 1 ? data : parsed,
36
+ version,
37
+ };
38
+ }
39
+ function getParsedSerializationVersion(parsed) {
40
+ if (!parsed || typeof parsed !== 'object') {
41
+ return 1;
42
+ }
43
+ const version = parsed.version;
44
+ if (version === 2 || version === 3 || version === 4) {
45
+ return version;
46
+ }
47
+ return 1;
48
+ }
@@ -1,4 +1,4 @@
1
- import * as YAML from 'yaml';
1
+ import { prepareSerializedInput } from './serializationInput.js';
2
2
  /** Validates a deserialized project structure. Returns errors for structural problems. */
3
3
  export function validateProject(project) {
4
4
  const errors = [];
@@ -77,36 +77,5 @@ export function yamlProblem(err) {
77
77
  throw new Error(`YAML error: ${code} ${message} at ${pos} ${linePos}`);
78
78
  }
79
79
  export function detectSerializationVersion(data) {
80
- if (typeof data !== 'string') {
81
- return 1;
82
- }
83
- const trimmed = data.trim();
84
- if (!trimmed) {
85
- return 1;
86
- }
87
- if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
88
- try {
89
- const parsed = JSON.parse(trimmed);
90
- if (typeof parsed === 'object' &&
91
- parsed != null &&
92
- typeof parsed.version === 'number' &&
93
- parsed.version >= 2 &&
94
- parsed.version <= 4) {
95
- return parsed.version;
96
- }
97
- return 1;
98
- }
99
- catch {
100
- return 1;
101
- }
102
- }
103
- const parsed = YAML.parse(trimmed);
104
- if (parsed &&
105
- typeof parsed === 'object' &&
106
- typeof parsed.version === 'number' &&
107
- parsed.version >= 2 &&
108
- parsed.version <= 4) {
109
- return parsed.version;
110
- }
111
- return 1;
80
+ return prepareSerializedInput(data).version;
112
81
  }
@@ -2,10 +2,7 @@ import { doubleCheckProject } from './serializationUtils.js';
2
2
  // @ts-ignore
3
3
  import * as yaml from 'yaml';
4
4
  export function projectV2Deserializer(data) {
5
- if (typeof data !== 'string') {
6
- throw new Error('Project v2 deserializer requires a string');
7
- }
8
- const project = yaml.parse(data);
5
+ const project = unwrapV2Envelope(data, 'Project v2');
9
6
  if (project.version !== 2) {
10
7
  throw new Error('Project v2 deserializer requires a version 2 project');
11
8
  }
@@ -13,12 +10,15 @@ export function projectV2Deserializer(data) {
13
10
  return project.data;
14
11
  }
15
12
  export function graphV2Deserializer(data) {
16
- if (typeof data !== 'string') {
17
- throw new Error('Graph v2 deserializer requires a string');
18
- }
19
- const graph = yaml.parse(data);
13
+ const graph = unwrapV2Envelope(data, 'Graph v2');
20
14
  if (graph.version !== 2) {
21
15
  throw new Error('Graph v2 deserializer requires a version 2 graph');
22
16
  }
23
17
  return graph.data;
24
18
  }
19
+ function unwrapV2Envelope(data, label) {
20
+ if (typeof data !== 'string' && (!data || typeof data !== 'object' || Array.isArray(data))) {
21
+ throw new Error(`${label} deserializer requires a string`);
22
+ }
23
+ return (typeof data === 'string' ? yaml.parse(data) : data);
24
+ }
@@ -30,6 +30,7 @@ export type RunGraphOptions = {
30
30
  [key: string]: (data: DataValue | undefined) => void;
31
31
  };
32
32
  abortSignal?: AbortSignal;
33
+ captureNodeTimings?: boolean;
33
34
  registry?: NodeRegistration<any, any>;
34
35
  includeTrace?: boolean;
35
36
  concurrency?: GraphProcessorConcurrency;
@@ -28,6 +28,7 @@ export type RivetEventStreamEvent = {
28
28
  nodeId: NodeId;
29
29
  nodeTitle: string;
30
30
  outputs: Outputs;
31
+ durationMs?: number;
31
32
  };
32
33
  done: {
33
34
  graphOutput: GraphOutputs;
@@ -11,6 +11,7 @@ export * from './native/BaseDir.js';
11
11
  export * from './native/NativeApi.js';
12
12
  export * from './native/BrowserNativeApi.js';
13
13
  export * from './model/ProcessContext.js';
14
+ export * from './model/DebuggerTransportSentinel.js';
14
15
  export * from './model/ProjectReferenceLoader.js';
15
16
  export * from './model/RivetUIContext.js';
16
17
  export * from './model/chat-v2/index.js';
@@ -0,0 +1,21 @@
1
+ declare const DEBUGGER_TRANSPORT_SENTINEL_KEY = "__rivetDebuggerTransportSentinel";
2
+ declare const DEBUGGER_TRANSPORT_SENTINEL_VERSION = 1;
3
+ type DebuggerTransportUndefinedSentinel = {
4
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: {
5
+ type: 'undefined';
6
+ version: typeof DEBUGGER_TRANSPORT_SENTINEL_VERSION;
7
+ };
8
+ };
9
+ type DebuggerTransportEscapedSentinel = {
10
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: {
11
+ type: 'escaped-sentinel';
12
+ version: typeof DEBUGGER_TRANSPORT_SENTINEL_VERSION;
13
+ value: unknown;
14
+ };
15
+ };
16
+ export declare function createDebuggerTransportUndefinedSentinel(): DebuggerTransportUndefinedSentinel;
17
+ export declare function createDebuggerTransportEscapedSentinel(value: unknown): DebuggerTransportEscapedSentinel;
18
+ export declare function createDebuggerTransportEscapedSentinelEnvelope(value: unknown): DebuggerTransportEscapedSentinel;
19
+ export declare function isDebuggerTransportSentinelEnvelope(value: unknown): boolean;
20
+ export declare function decodeDebuggerTransportSentinels<T>(value: T): T;
21
+ export {};