@valerypopoff/rivet2-core 2.0.11 → 2.1.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 (66) hide show
  1. package/dist/cjs/bundle.cjs +1555 -172
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/exports.js +4 -0
  4. package/dist/esm/model/GraphBoundaryCache.js +36 -4
  5. package/dist/esm/model/GraphBoundaryEffects.js +32 -0
  6. package/dist/esm/model/GraphPreprocessor.js +6 -4
  7. package/dist/esm/model/GraphProcessor.js +129 -17
  8. package/dist/esm/model/NodeGraph.js +1 -1
  9. package/dist/esm/model/NodePrefabResolver.js +57 -0
  10. package/dist/esm/model/Nodes.js +4 -1
  11. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  12. package/dist/esm/model/UiGraph.js +113 -0
  13. package/dist/esm/model/UiGraphRendererStyles.js +208 -0
  14. package/dist/esm/model/chat/openAIChatRuntime.js +0 -1
  15. package/dist/esm/model/chat-v2/aiSdkBridge.js +100 -2
  16. package/dist/esm/model/chat-v2/chatV2Pipeline.js +35 -31
  17. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  18. package/dist/esm/model/chat-v2/providerOptions.js +5 -1
  19. package/dist/esm/model/nodes/CoalesceNode.js +1 -1
  20. package/dist/esm/model/nodes/CompareNode.js +15 -14
  21. package/dist/esm/model/nodes/GraphOutputNode.js +1 -0
  22. package/dist/esm/model/nodes/LLMChatV2Node.js +62 -17
  23. package/dist/esm/model/nodes/NodePrefabInstanceNode.js +39 -0
  24. package/dist/esm/model/nodes/PromptNode.js +2 -1
  25. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +49 -7
  26. package/dist/esm/model/nodes/SubGraphNode.js +42 -5
  27. package/dist/esm/utils/index.js +2 -0
  28. package/dist/esm/utils/jsonValueToDataValue.js +48 -0
  29. package/dist/esm/utils/projectComparison/connections.js +57 -0
  30. package/dist/esm/utils/projectComparison/graphs.js +60 -0
  31. package/dist/esm/utils/projectComparison/nodes.js +53 -0
  32. package/dist/esm/utils/projectComparison/summaries.js +60 -0
  33. package/dist/esm/utils/projectComparison/values.js +40 -0
  34. package/dist/esm/utils/projectComparison.js +73 -0
  35. package/dist/esm/utils/serialization/serializationHelpers.js +24 -3
  36. package/dist/esm/utils/serialization/serialization_v4.js +30 -0
  37. package/dist/types/exports.d.ts +5 -0
  38. package/dist/types/model/EditorDefinition.d.ts +1 -0
  39. package/dist/types/model/ExecutorProtocol.d.ts +13 -3
  40. package/dist/types/model/GraphBoundaryCache.d.ts +9 -3
  41. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -0
  42. package/dist/types/model/GraphProcessor.d.ts +15 -0
  43. package/dist/types/model/NodeBase.d.ts +5 -0
  44. package/dist/types/model/NodeBodySpec.d.ts +1 -0
  45. package/dist/types/model/NodePrefabResolver.d.ts +13 -0
  46. package/dist/types/model/Nodes.d.ts +5 -4
  47. package/dist/types/model/ProcessContext.d.ts +5 -1
  48. package/dist/types/model/ProcessContextBuilder.d.ts +4 -2
  49. package/dist/types/model/Project.d.ts +9 -0
  50. package/dist/types/model/UiGraph.d.ts +84 -0
  51. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -0
  52. package/dist/types/model/chat-v2/aiSdkBridge.d.ts +1 -0
  53. package/dist/types/model/chat-v2/chatV2Types.d.ts +23 -1
  54. package/dist/types/model/nodes/CompareNode.d.ts +4 -0
  55. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  56. package/dist/types/model/nodes/NodePrefabInstanceNode.d.ts +13 -0
  57. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  58. package/dist/types/utils/index.d.ts +2 -0
  59. package/dist/types/utils/jsonValueToDataValue.d.ts +2 -0
  60. package/dist/types/utils/projectComparison/connections.d.ts +5 -0
  61. package/dist/types/utils/projectComparison/graphs.d.ts +3 -0
  62. package/dist/types/utils/projectComparison/nodes.d.ts +5 -0
  63. package/dist/types/utils/projectComparison/summaries.d.ts +4 -0
  64. package/dist/types/utils/projectComparison/values.d.ts +5 -0
  65. package/dist/types/utils/projectComparison.d.ts +77 -0
  66. package/package.json +1 -1
@@ -16,31 +16,62 @@ export { buildLLMChatV2EditorCacheKey, resolveLLMChatV2RuntimeProviderOptions };
16
16
  function usesBaseURLInput(data) {
17
17
  return data.provider === 'custom' ? data.useCustomProviderBaseURLInput : data.useBaseURLInput;
18
18
  }
19
- function getCustomProviderBaseURLBodyLine(data) {
19
+ function getCustomProviderBaseURLBodyValue(data) {
20
20
  if (data.provider !== 'custom') {
21
21
  return undefined;
22
22
  }
23
23
  if (data.useCustomProviderBaseURLInput) {
24
- return 'Provider base URL: (Using Input)';
24
+ return '(Using Input)';
25
25
  }
26
26
  const baseURL = data.customProviderBaseURL.trim();
27
- return baseURL ? `Provider base URL: ${baseURL}` : undefined;
27
+ return baseURL || undefined;
28
28
  }
29
29
  function getOptionLabel(options, value) {
30
30
  return options.find((option) => option.value === (value ?? ''))?.label ?? value ?? 'Default';
31
31
  }
32
- function getReasoningEffortBodyLine(data) {
32
+ function getProviderBodyLabel(data) {
33
+ return data.provider === 'custom' ? 'Custom' : getChatV2ProviderLabel(data.provider);
34
+ }
35
+ function getReasoningEffortBodyValue(data) {
33
36
  switch (data.provider) {
34
37
  case 'openai':
35
- return `Reasoning effort: ${getOptionLabel(openAIReasoningEffortOptions, data.openAIReasoningEffort)}`;
38
+ return getOptionLabel(openAIReasoningEffortOptions, data.openAIReasoningEffort);
36
39
  case 'anthropic':
37
- return `Reasoning effort: ${getOptionLabel(anthropicEffortOptions, data.anthropicEffort)}`;
40
+ return getOptionLabel(anthropicEffortOptions, data.anthropicEffort);
38
41
  case 'google':
39
- return `Reasoning effort: ${getOptionLabel(googleThinkingLevelOptions, data.googleThinkingLevel)}`;
42
+ return getOptionLabel(googleThinkingLevelOptions, data.googleThinkingLevel);
40
43
  case 'custom':
41
44
  return undefined;
42
45
  }
43
46
  }
47
+ function escapeMarkdownInline(value) {
48
+ return value
49
+ .replace(/\r/g, '\\r')
50
+ .replace(/\n/g, '\\n')
51
+ .replace(/&/g, '&')
52
+ .replace(/</g, '&lt;')
53
+ .replace(/>/g, '&gt;')
54
+ .replace(/"/g, '&quot;')
55
+ .replace(/([\\`*_[\]{}()#+\-.!|])/g, '\\$1');
56
+ }
57
+ function getBodyLine(label, value) {
58
+ return `<span style="opacity: 0.55">${label}:</span> ${escapeMarkdownInline(value)}`;
59
+ }
60
+ function getOptionalNumberBodyLine(label, value, usesInput) {
61
+ if (usesInput) {
62
+ return getBodyLine(label, '(Using Input)');
63
+ }
64
+ return value === undefined ? undefined : getBodyLine(label, `${value}`);
65
+ }
66
+ function getStopSequencesBodyLine(data) {
67
+ if (data.useStopSequencesInput) {
68
+ return getBodyLine('Stop sequences', '(Using Input)');
69
+ }
70
+ const stopSequences = (data.stopSequences ?? []).filter((sequence) => sequence.length > 0);
71
+ return stopSequences.length === 0
72
+ ? undefined
73
+ : getBodyLine('Stop sequences', stopSequences.map((sequence) => JSON.stringify(sequence)).join(', '));
74
+ }
44
75
  export class LLMChatV2NodeImpl extends NodeImpl {
45
76
  static create() {
46
77
  return {
@@ -197,17 +228,31 @@ export class LLMChatV2NodeImpl extends NodeImpl {
197
228
  }
198
229
  getBody() {
199
230
  const modelInfo = getChatV2ModelInfo(this.data.provider, this.data.model);
200
- const providerLabel = getChatV2ProviderLabel(this.data.provider);
201
- const baseURLLine = getCustomProviderBaseURLBodyLine(this.data);
231
+ const providerLabel = getProviderBodyLabel(this.data);
232
+ const baseURLValue = getCustomProviderBaseURLBodyValue(this.data);
202
233
  const modelLine = modelInfo?.displayName ?? this.data.model;
203
- const providerDetails = baseURLLine ? [providerLabel, baseURLLine, modelLine] : [providerLabel, modelLine];
204
- const reasoningEffortLine = getReasoningEffortBodyLine(this.data);
205
- return [
206
- ...providerDetails,
207
- ...(reasoningEffortLine ? [reasoningEffortLine] : []),
208
- `Temperature: ${this.data.useTemperatureInput ? '(Using Input)' : this.data.temperature}`,
209
- `Max output tokens: ${this.data.useMaxTokensInput ? '(Using Input)' : this.data.maxTokens}`,
210
- ].join('\n');
234
+ const providerDetails = [
235
+ getBodyLine('Provider', providerLabel),
236
+ ...(baseURLValue ? [getBodyLine('Base URL', baseURLValue)] : []),
237
+ getBodyLine('Model', modelLine),
238
+ ];
239
+ const reasoningEffortValue = getReasoningEffortBodyValue(this.data);
240
+ return {
241
+ type: 'markdown',
242
+ disableLinks: true,
243
+ text: [
244
+ ...providerDetails,
245
+ ...(reasoningEffortValue ? [getBodyLine('Reasoning effort', reasoningEffortValue)] : []),
246
+ getBodyLine('Temperature', this.data.useTemperatureInput ? '(Using Input)' : `${this.data.temperature}`),
247
+ getBodyLine('Max output tokens', this.data.useMaxTokensInput ? '(Using Input)' : `${this.data.maxTokens}`),
248
+ getOptionalNumberBodyLine('Top P', this.data.topP, this.data.useTopPInput),
249
+ getOptionalNumberBodyLine('Top K', this.data.topK, this.data.useTopKInput),
250
+ getOptionalNumberBodyLine('Presence penalty', this.data.presencePenalty, this.data.usePresencePenaltyInput),
251
+ getOptionalNumberBodyLine('Frequency penalty', this.data.frequencyPenalty, this.data.useFrequencyPenaltyInput),
252
+ getStopSequencesBodyLine(this.data),
253
+ getOptionalNumberBodyLine('Seed', this.data.seed, this.data.useSeedInput),
254
+ ].filter((line) => line !== undefined).join('\n'),
255
+ };
211
256
  }
212
257
  async process(inputs, context) {
213
258
  const runtime = await resolveLLMChatV2RuntimeConfig({
@@ -0,0 +1,39 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import {} from '../GraphProcessor.js';
3
+ import {} from '../NodeBase.js';
4
+ import { nodeDefinition } from '../NodeDefinition.js';
5
+ import { NodeImpl } from '../NodeImpl.js';
6
+ import { NODE_PREFAB_INSTANCE_TYPE, } from '../NodePrefabResolver.js';
7
+ export class NodePrefabInstanceNodeImpl extends NodeImpl {
8
+ static create() {
9
+ return {
10
+ type: NODE_PREFAB_INSTANCE_TYPE,
11
+ title: 'Linked node',
12
+ id: nanoid(),
13
+ visualData: {
14
+ x: 0,
15
+ y: 0,
16
+ width: 240,
17
+ },
18
+ data: {},
19
+ };
20
+ }
21
+ getInputDefinitions() {
22
+ return [];
23
+ }
24
+ getOutputDefinitions() {
25
+ return [];
26
+ }
27
+ async process(_inputData) {
28
+ throw new Error('Library node is missing. Open the Node Library and reconnect this linked node.');
29
+ }
30
+ static getUIData() {
31
+ return {
32
+ contextMenuTitle: 'Linked node',
33
+ infoBoxTitle: 'Linked node',
34
+ infoBoxBody: 'Runs a node from the project Node Library.',
35
+ group: 'Advanced',
36
+ };
37
+ }
38
+ }
39
+ export const nodePrefabInstanceNode = nodeDefinition(NodePrefabInstanceNodeImpl, 'Linked node');
@@ -178,7 +178,8 @@ export class PromptNodeImpl extends NodeImpl {
178
178
  acc[key] = coerceTypeOptional(inputs[key], 'string') ?? '';
179
179
  return acc;
180
180
  }, {});
181
- const outputValue = interpolate(this.chartNode.data.promptText, inputMap, context.graphInputNodeValues, context.contextValues);
181
+ let outputValue = interpolate(this.chartNode.data.promptText, inputMap, context.graphInputNodeValues, context.contextValues);
182
+ outputValue = outputValue.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
182
183
  const type = getInputOrData(this.data, inputs, 'type', 'string');
183
184
  const isCacheBreakpoint = getInputOrData(this.data, inputs, 'isCacheBreakpoint', 'boolean');
184
185
  if (['assistant', 'system', 'user', 'function'].includes(type) === false) {
@@ -9,7 +9,7 @@ import {} from '../DataValue.js';
9
9
  import {} from '../ProcessContext.js';
10
10
  import { dedent } from 'ts-dedent';
11
11
  import { getError } from '../../utils/errors.js';
12
- import { buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, } from '../GraphBoundaryCache.js';
12
+ import { buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, getRequestedGraphOutputNodeIds, } from '../GraphBoundaryCache.js';
13
13
  export class ReferencedGraphAliasNodeImpl extends NodeImpl {
14
14
  static create() {
15
15
  const chartNode = {
@@ -117,14 +117,32 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
117
117
  const boundary = context.getGraphBoundary?.(referencedProject, this.data.graphId) ??
118
118
  getGraphBoundary(referencedProject, this.data.graphId);
119
119
  const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
120
+ const shouldRunWholeGraph = !GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED ||
121
+ context.isDirectRunTarget ||
122
+ (this.data.useErrorOutput === true && context.activeOutputPortIds.has('error'));
123
+ const requestedGraphOutputNodeIds = shouldRunWholeGraph
124
+ ? []
125
+ : getRequestedGraphOutputNodeIds(boundary, context.activeOutputPortIds);
126
+ if (!shouldRunWholeGraph && requestedGraphOutputNodeIds.length === 0) {
127
+ return buildSkippedReferencedGraphOutputs(boundary, this.data.useErrorOutput, this.data.outputCostDuration);
128
+ }
120
129
  // Create a subprocessor using the referenced project's graph
121
130
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, {
122
131
  signal: context.signal,
123
132
  project: referencedProject,
124
133
  });
134
+ if (!shouldRunWholeGraph) {
135
+ subGraphProcessor.runToNodeIds = requestedGraphOutputNodeIds;
136
+ }
125
137
  try {
126
138
  const startTime = Date.now();
127
- const outputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);
139
+ const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);
140
+ const outputs = shouldRunWholeGraph
141
+ ? graphOutputs
142
+ : {
143
+ ...buildExcludedGraphBoundaryOutputs(boundary),
144
+ ...graphOutputs,
145
+ };
128
146
  const duration = Date.now() - startTime;
129
147
  if (this.data.useErrorOutput) {
130
148
  outputs['error'] = {
@@ -138,11 +156,7 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
138
156
  value: duration,
139
157
  };
140
158
  }
141
- if (!this.data.outputCostDuration) {
142
- delete outputs['cost'];
143
- delete outputs['duration'];
144
- }
145
- return outputs;
159
+ return applyMetricOutputSetting(outputs, this.data.outputCostDuration);
146
160
  }
147
161
  catch (err) {
148
162
  if (!this.data.useErrorOutput) {
@@ -158,3 +172,31 @@ export class ReferencedGraphAliasNodeImpl extends NodeImpl {
158
172
  }
159
173
  }
160
174
  export const referencedGraphAliasNode = nodeDefinition(ReferencedGraphAliasNodeImpl, 'Referenced Graph Alias');
175
+ function buildSkippedReferencedGraphOutputs(boundary, useErrorOutput, outputCostDuration) {
176
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
177
+ if (useErrorOutput) {
178
+ outputs['error'] = {
179
+ type: 'control-flow-excluded',
180
+ value: undefined,
181
+ };
182
+ }
183
+ if (outputCostDuration) {
184
+ outputs['cost'] = {
185
+ type: 'number',
186
+ value: 0,
187
+ };
188
+ outputs['duration'] = {
189
+ type: 'number',
190
+ value: 0,
191
+ };
192
+ }
193
+ return applyMetricOutputSetting(outputs, outputCostDuration);
194
+ }
195
+ function applyMetricOutputSetting(outputs, outputCostDuration) {
196
+ if (outputCostDuration) {
197
+ return outputs;
198
+ }
199
+ delete outputs['cost'];
200
+ delete outputs['duration'];
201
+ return outputs;
202
+ }
@@ -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 { buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, } from '../GraphBoundaryCache.js';
13
+ import { applyGraphBoundaryPortOrder, buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, getRequestedGraphOutputNodeIds, } from '../GraphBoundaryCache.js';
14
14
  export class SubGraphNodeImpl extends NodeImpl {
15
15
  static create() {
16
16
  const chartNode = {
@@ -32,11 +32,11 @@ export class SubGraphNodeImpl extends NodeImpl {
32
32
  }
33
33
  getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
34
34
  const boundary = this.getBoundary(project, definitionContext);
35
- return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
35
+ return boundary ? getGraphBoundaryInputDefinitions(boundary, this.data.inputPortOrder) : [];
36
36
  }
37
37
  getGraphOutputs(project, definitionContext) {
38
38
  const boundary = this.getBoundary(project, definitionContext);
39
- return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
39
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary, this.data.outputPortOrder) : [];
40
40
  }
41
41
  getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
42
42
  const outputs = [];
@@ -69,7 +69,7 @@ export class SubGraphNodeImpl extends NodeImpl {
69
69
  if (this.data.graphId) {
70
70
  const boundary = getGraphBoundary(context.project, this.data.graphId);
71
71
  if (boundary) {
72
- for (const input of boundary.inputs) {
72
+ for (const input of applyGraphBoundaryPortOrder(boundary.inputs, this.data.inputPortOrder)) {
73
73
  definitions.push({
74
74
  type: 'dynamic',
75
75
  dataKey: 'inputData',
@@ -104,10 +104,29 @@ export class SubGraphNodeImpl extends NodeImpl {
104
104
  }
105
105
  const boundary = context.getGraphBoundary?.(project, this.data.graphId) ?? getGraphBoundary(project, this.data.graphId);
106
106
  const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
107
+ const shouldRunWholeGraph = !GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED ||
108
+ context.isDirectRunTarget ||
109
+ this.data.useAsGraphPartialOutput === true ||
110
+ (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);
116
+ }
107
117
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });
118
+ if (!shouldRunWholeGraph) {
119
+ subGraphProcessor.runToNodeIds = requestedGraphOutputNodeIds;
120
+ }
108
121
  try {
109
122
  const startTime = Date.now();
110
- const outputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);
123
+ const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);
124
+ const outputs = shouldRunWholeGraph
125
+ ? graphOutputs
126
+ : {
127
+ ...buildExcludedGraphBoundaryOutputs(boundary),
128
+ ...graphOutputs,
129
+ };
111
130
  const duration = Date.now() - startTime;
112
131
  if (this.data.useErrorOutput) {
113
132
  outputs['error'] = {
@@ -137,3 +156,21 @@ export class SubGraphNodeImpl extends NodeImpl {
137
156
  }
138
157
  }
139
158
  export const subGraphNode = nodeDefinition(SubGraphNodeImpl, 'Subgraph');
159
+ function buildSkippedSubgraphOutputs(boundary, useErrorOutput) {
160
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
161
+ if (useErrorOutput) {
162
+ outputs['error'] = {
163
+ type: 'control-flow-excluded',
164
+ value: undefined,
165
+ };
166
+ }
167
+ outputs['cost'] = {
168
+ type: 'number',
169
+ value: 0,
170
+ };
171
+ outputs['duration'] = {
172
+ type: 'number',
173
+ value: 0,
174
+ };
175
+ return outputs;
176
+ }
@@ -15,3 +15,5 @@ export * from './defaults.js';
15
15
  export * from './orderedStringPortIds.js';
16
16
  export * from './runtimeLogging.js';
17
17
  export * from './providerStreamParsing.js';
18
+ export * from './projectComparison.js';
19
+ export * from './jsonValueToDataValue.js';
@@ -0,0 +1,48 @@
1
+ export function jsonValueToDataValue(value) {
2
+ if (isDataValue(value)) {
3
+ return value;
4
+ }
5
+ if (typeof value === 'string') {
6
+ return { type: 'string', value };
7
+ }
8
+ if (typeof value === 'number') {
9
+ return { type: 'number', value };
10
+ }
11
+ if (typeof value === 'boolean') {
12
+ return { type: 'boolean', value };
13
+ }
14
+ if (Array.isArray(value)) {
15
+ return jsonArrayToDataValue(value);
16
+ }
17
+ if (isRecord(value)) {
18
+ return { type: 'object', value };
19
+ }
20
+ return { type: 'any', value };
21
+ }
22
+ function jsonArrayToDataValue(value) {
23
+ if (value.length === 0) {
24
+ return { type: 'any[]', value: [] };
25
+ }
26
+ if (value.every((item) => typeof item === 'string')) {
27
+ return { type: 'string[]', value };
28
+ }
29
+ if (value.every((item) => typeof item === 'number')) {
30
+ return { type: 'number[]', value };
31
+ }
32
+ if (value.every((item) => typeof item === 'boolean')) {
33
+ return { type: 'boolean[]', value };
34
+ }
35
+ if (value.every(isRecord)) {
36
+ return { type: 'object[]', value };
37
+ }
38
+ return { type: 'any[]', value };
39
+ }
40
+ function isDataValue(value) {
41
+ return (value != null &&
42
+ typeof value === 'object' &&
43
+ typeof value.type === 'string' &&
44
+ 'value' in value);
45
+ }
46
+ function isRecord(value) {
47
+ return value != null && typeof value === 'object' && !Array.isArray(value);
48
+ }
@@ -0,0 +1,57 @@
1
+ import stableStringify from 'safe-stable-stringify';
2
+ import { unionKeys } from './values.js';
3
+ export function getProjectConnectionComparisonKey(connection) {
4
+ return stableStringify([
5
+ connection.outputNodeId,
6
+ connection.outputId,
7
+ connection.inputNodeId,
8
+ connection.inputId,
9
+ ]);
10
+ }
11
+ export function getComparableGraphConnections(connections, nodes) {
12
+ const commentNodeIds = new Set(nodes.filter((node) => node.type === 'comment').map((node) => node.id));
13
+ return connections.filter((connection) => !commentNodeIds.has(connection.outputNodeId) && !commentNodeIds.has(connection.inputNodeId));
14
+ }
15
+ export function compareConnections(beforeConnections, afterConnections) {
16
+ const beforeByKey = new Map(beforeConnections.map((connection) => [getProjectConnectionComparisonKey(connection), connection]));
17
+ const afterByKey = new Map(afterConnections.map((connection) => [getProjectConnectionComparisonKey(connection), connection]));
18
+ const removedKeys = beforeConnections.map(getProjectConnectionComparisonKey).filter((key) => !afterByKey.has(key));
19
+ const addedKeys = afterConnections.map(getProjectConnectionComparisonKey).filter((key) => !beforeByKey.has(key));
20
+ const changedRemovedKeys = new Set();
21
+ const changedAddedKeys = new Set();
22
+ for (const addedKey of addedKeys) {
23
+ const addedConnection = afterByKey.get(addedKey);
24
+ const matchingRemovedKey = removedKeys.find((removedKey) => {
25
+ if (changedRemovedKeys.has(removedKey)) {
26
+ return false;
27
+ }
28
+ const removedConnection = beforeByKey.get(removedKey);
29
+ return (removedConnection.outputNodeId === addedConnection.outputNodeId &&
30
+ removedConnection.inputNodeId === addedConnection.inputNodeId);
31
+ });
32
+ if (matchingRemovedKey) {
33
+ changedRemovedKeys.add(matchingRemovedKey);
34
+ changedAddedKeys.add(addedKey);
35
+ }
36
+ }
37
+ return Object.fromEntries(unionKeys(Object.fromEntries(beforeByKey), Object.fromEntries(afterByKey)).map((key) => {
38
+ const before = beforeByKey.get(key);
39
+ const after = afterByKey.get(key);
40
+ const kind = changedAddedKeys.has(key) || changedRemovedKeys.has(key)
41
+ ? 'changed'
42
+ : !before && after
43
+ ? 'added'
44
+ : before && !after
45
+ ? 'removed'
46
+ : 'unchanged';
47
+ return [
48
+ key,
49
+ {
50
+ key,
51
+ kind,
52
+ before,
53
+ after,
54
+ },
55
+ ];
56
+ }));
57
+ }
@@ -0,0 +1,60 @@
1
+ import { compareConnections, getComparableGraphConnections, getProjectConnectionComparisonKey } from './connections.js';
2
+ import { compareNodes, getComparableGraphNodes } from './nodes.js';
3
+ import { summarizeGraphComparison } from './summaries.js';
4
+ import { areComparisonValuesEqual } from './values.js';
5
+ export function compareGraphs(id, before, after) {
6
+ if (!before && after) {
7
+ return createOneSidedGraphComparison(id, after, 'added');
8
+ }
9
+ if (before && !after) {
10
+ return createOneSidedGraphComparison(id, before, 'removed');
11
+ }
12
+ if (!before || !after) {
13
+ throw new Error(`Cannot compare missing graph ${id}`);
14
+ }
15
+ const nodes = compareNodes(getComparableGraphNodes(before.nodes), getComparableGraphNodes(after.nodes));
16
+ const connections = compareConnections(getComparableGraphConnections(before.connections, before.nodes), getComparableGraphConnections(after.connections, after.nodes));
17
+ const summary = summarizeGraphComparison(nodes, connections);
18
+ const metadataChanged = !areComparisonValuesEqual(before.metadata, after.metadata);
19
+ return {
20
+ id,
21
+ kind: metadataChanged || Object.values(summary).some((count) => count > 0) ? 'changed' : 'unchanged',
22
+ before,
23
+ after,
24
+ metadataChanged,
25
+ nodes,
26
+ connections,
27
+ summary,
28
+ };
29
+ }
30
+ function createOneSidedGraphComparison(id, graph, kind) {
31
+ const graphNodes = getComparableGraphNodes(graph.nodes);
32
+ const graphConnections = getComparableGraphConnections(graph.connections, graph.nodes);
33
+ const nodes = Object.fromEntries(graphNodes.map((node) => [
34
+ node.id,
35
+ kind === 'added'
36
+ ? { id: node.id, kind, after: node }
37
+ : { id: node.id, kind, before: node },
38
+ ]));
39
+ const connections = createOneSidedConnectionComparisons(graphConnections, kind);
40
+ return {
41
+ id,
42
+ kind,
43
+ ...(kind === 'added' ? { after: graph } : { before: graph }),
44
+ metadataChanged: true,
45
+ nodes,
46
+ connections,
47
+ summary: summarizeGraphComparison(nodes, connections),
48
+ };
49
+ }
50
+ function createOneSidedConnectionComparisons(connections, kind) {
51
+ return Object.fromEntries(connections.map((connection) => {
52
+ const key = getProjectConnectionComparisonKey(connection);
53
+ return [
54
+ key,
55
+ kind === 'added'
56
+ ? { key, kind, after: connection }
57
+ : { key, kind, before: connection },
58
+ ];
59
+ }));
60
+ }
@@ -0,0 +1,53 @@
1
+ import { areComparisonValuesEqual, getChangedValueComparisons, isComparisonRecord, unionKeys } from './values.js';
2
+ export function getProjectNodeFieldComparisons(comparison) {
3
+ const before = comparison.before;
4
+ const after = comparison.after;
5
+ if (!before || !after) {
6
+ return [];
7
+ }
8
+ return getChangedValueComparisons([], getComparableNodeRecord(before), getComparableNodeRecord(after));
9
+ }
10
+ export function getComparableGraphNodes(nodes) {
11
+ return nodes.filter((node) => node.type !== 'comment');
12
+ }
13
+ export function compareNodes(beforeNodes, afterNodes) {
14
+ const beforeById = new Map(beforeNodes.map((node) => [node.id, node]));
15
+ const afterById = new Map(afterNodes.map((node) => [node.id, node]));
16
+ const nodeIds = unionKeys(Object.fromEntries(beforeById), Object.fromEntries(afterById));
17
+ return Object.fromEntries(nodeIds.map((nodeId) => {
18
+ const before = beforeById.get(nodeId);
19
+ const after = afterById.get(nodeId);
20
+ if (!before && after) {
21
+ return [nodeId, { id: nodeId, kind: 'added', after }];
22
+ }
23
+ if (before && !after) {
24
+ return [nodeId, { id: nodeId, kind: 'removed', before }];
25
+ }
26
+ return [
27
+ nodeId,
28
+ {
29
+ id: nodeId,
30
+ kind: areComparisonNodesEqual(before, after) ? 'unchanged' : 'changed',
31
+ before,
32
+ after,
33
+ },
34
+ ];
35
+ }));
36
+ }
37
+ function areComparisonNodesEqual(left, right) {
38
+ return areComparisonValuesEqual(left ? getComparableNodeRecord(left) : left, right ? getComparableNodeRecord(right) : right);
39
+ }
40
+ function getComparableNodeRecord(node) {
41
+ const { data, visualData: _visualData, ...rest } = node;
42
+ return {
43
+ ...rest,
44
+ data: getComparableNodeData(node, data),
45
+ };
46
+ }
47
+ function getComparableNodeData(node, data) {
48
+ if (node.type !== 'subGraph' || !isComparisonRecord(data)) {
49
+ return data;
50
+ }
51
+ const { inputPortOrder: _inputPortOrder, outputPortOrder: _outputPortOrder, ...semanticData } = data;
52
+ return semanticData;
53
+ }
@@ -0,0 +1,60 @@
1
+ export function summarizeProjectComparison(graphs, nodePrefabs = {}, uiGraphs = {}) {
2
+ const summary = Object.values(graphs).reduce((acc, graph) => {
3
+ if (graph.kind === 'added')
4
+ acc.addedGraphs += 1;
5
+ if (graph.kind === 'removed')
6
+ acc.removedGraphs += 1;
7
+ if (graph.kind === 'changed')
8
+ acc.changedGraphs += 1;
9
+ acc.addedNodes += graph.summary.addedNodes;
10
+ acc.removedNodes += graph.summary.removedNodes;
11
+ acc.changedNodes += graph.summary.changedNodes;
12
+ acc.addedConnections += graph.summary.addedConnections;
13
+ acc.removedConnections += graph.summary.removedConnections;
14
+ acc.changedConnections += graph.summary.changedConnections;
15
+ return acc;
16
+ }, createEmptyProjectSummary());
17
+ for (const prefab of Object.values(nodePrefabs)) {
18
+ if (prefab.kind === 'added')
19
+ summary.addedNodePrefabs = (summary.addedNodePrefabs ?? 0) + 1;
20
+ if (prefab.kind === 'removed')
21
+ summary.removedNodePrefabs = (summary.removedNodePrefabs ?? 0) + 1;
22
+ if (prefab.kind === 'changed')
23
+ summary.changedNodePrefabs = (summary.changedNodePrefabs ?? 0) + 1;
24
+ }
25
+ for (const uiGraph of Object.values(uiGraphs)) {
26
+ if (uiGraph.kind === 'added')
27
+ summary.addedUiGraphs = (summary.addedUiGraphs ?? 0) + 1;
28
+ if (uiGraph.kind === 'removed')
29
+ summary.removedUiGraphs = (summary.removedUiGraphs ?? 0) + 1;
30
+ if (uiGraph.kind === 'changed')
31
+ summary.changedUiGraphs = (summary.changedUiGraphs ?? 0) + 1;
32
+ }
33
+ return summary;
34
+ }
35
+ export function summarizeGraphComparison(nodes, connections) {
36
+ const nodeComparisons = Object.values(nodes);
37
+ const connectionComparisons = Object.values(connections);
38
+ return {
39
+ addedNodes: nodeComparisons.filter((node) => node.kind === 'added').length,
40
+ removedNodes: nodeComparisons.filter((node) => node.kind === 'removed').length,
41
+ changedNodes: nodeComparisons.filter((node) => node.kind === 'changed').length,
42
+ addedConnections: connectionComparisons.filter((connection) => connection.kind === 'added').length,
43
+ removedConnections: connectionComparisons.filter((connection) => connection.kind === 'removed').length,
44
+ changedConnections: connectionComparisons.filter((connection) => connection.kind === 'changed' && connection.after)
45
+ .length,
46
+ };
47
+ }
48
+ function createEmptyProjectSummary() {
49
+ return {
50
+ addedGraphs: 0,
51
+ removedGraphs: 0,
52
+ changedGraphs: 0,
53
+ addedNodes: 0,
54
+ removedNodes: 0,
55
+ changedNodes: 0,
56
+ addedConnections: 0,
57
+ removedConnections: 0,
58
+ changedConnections: 0,
59
+ };
60
+ }
@@ -0,0 +1,40 @@
1
+ import stableStringify from 'safe-stable-stringify';
2
+ export function areComparisonValuesEqual(left, right) {
3
+ return stableStringify(left) === stableStringify(right);
4
+ }
5
+ export function getChangedValueComparisons(path, before, after) {
6
+ if (areComparisonValuesEqual(before, after)) {
7
+ return [];
8
+ }
9
+ if (Array.isArray(before) && Array.isArray(after)) {
10
+ return Array.from({ length: Math.max(before.length, after.length) }).flatMap((_value, index) => getChangedValueComparisons([...path, String(index)], before[index], after[index]));
11
+ }
12
+ if (isComparisonRecord(before) && isComparisonRecord(after)) {
13
+ return unionKeys(before, after).flatMap((key) => getChangedValueComparisons([...path, key], before[key], after[key]));
14
+ }
15
+ return [
16
+ {
17
+ after,
18
+ before,
19
+ field: formatComparisonPath(path),
20
+ path,
21
+ },
22
+ ];
23
+ }
24
+ export function isComparisonRecord(value) {
25
+ return typeof value === 'object' && value != null && !Array.isArray(value);
26
+ }
27
+ export function unionKeys(left, right) {
28
+ return [...new Set([...Object.keys(left), ...Object.keys(right)])].sort();
29
+ }
30
+ function formatComparisonPath(path) {
31
+ return path.reduce((formatted, segment) => {
32
+ if (/^\d+$/.test(segment)) {
33
+ return `${formatted}[${segment}]`;
34
+ }
35
+ if (formatted.length === 0) {
36
+ return segment;
37
+ }
38
+ return /^[A-Za-z_$][\w$]*$/.test(segment) ? `${formatted}.${segment}` : `${formatted}[${JSON.stringify(segment)}]`;
39
+ }, '');
40
+ }