-
Notifications
You must be signed in to change notification settings - Fork 673
Expand file tree
/
Copy pathgraphTraversalUtil.ts
More file actions
879 lines (781 loc) · 26.5 KB
/
Copy pathgraphTraversalUtil.ts
File metadata and controls
879 lines (781 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
import type {
LGraph,
LGraphNode,
Subgraph
} from '@/lib/litegraph/src/litegraph'
import { LGraphEventMode } from '@/lib/litegraph/src/types/globalEnums'
import type { NodeExecutionId, NodeLocatorId } from '@/types/nodeIdentification'
import {
createNodeExecutionId,
createNodeLocatorId,
getParentExecutionIds,
parseNodeLocatorId
} from '@/types/nodeIdentification'
import { parseNodeId } from '@/types/nodeId'
import type { NodeId } from '@/types/nodeId'
import { isSubgraphIoNode } from './typeGuardUtil'
function parseNodeIdPath(path: string[]): NodeId[] | null {
const nodeIds = path.map(parseNodeId)
return nodeIds.every((nodeId): nodeId is NodeId => nodeId !== null)
? nodeIds
: null
}
function createExecutionIdFromPath(
parentPath: string,
nodeId: NodeId
): NodeExecutionId | null {
const parentNodeIds = parseNodeIdPath(parentPath.split(':'))
if (!parentNodeIds) return null
return createNodeExecutionId([...parentNodeIds, nodeId])
}
/**
* Constructs a locator ID from node data with optional subgraph context.
*
* @param nodeData - Node data containing id and optional subgraphId
* @returns The locator ID string
*/
export function getLocatorIdFromNodeData(nodeData: {
id: string | number
subgraphId?: string | null
}): NodeLocatorId | null {
const nodeId = parseNodeId(nodeData.id)
if (!nodeId) return null
return createNodeLocatorId(nodeData.subgraphId ?? null, nodeId)
}
/**
* Parses an execution ID into its component parts.
*
* @param executionId - The execution ID (e.g., "123:456:789" or "789")
* @returns Array of node IDs in the path, or null if invalid
*/
export function parseExecutionId(executionId: string): string[] | null {
if (!executionId || typeof executionId !== 'string') return null
return executionId.split(':').filter((part) => part.length > 0)
}
/**
* Extracts the local node ID from an execution ID.
*
* @param executionId - The execution ID (e.g., "123:456:789" or "789")
* @returns The local node ID or null if invalid
*/
export function getLocalNodeIdFromExecutionId(
executionId: string
): string | null {
const parts = parseExecutionId(executionId)
return parts ? parts[parts.length - 1] : null
}
/**
* Extracts the subgraph path from an execution ID.
*
* @param executionId - The execution ID (e.g., "123:456:789" or "789")
* @returns Array of subgraph node IDs (excluding the final node ID), or empty array
*/
export function getSubgraphPathFromExecutionId(executionId: string): string[] {
const parts = parseExecutionId(executionId)
return parts ? parts.slice(0, -1) : []
}
/**
* Visits each node in a graph (non-recursive, single level).
*
* @param graph - The graph to visit nodes from
* @param visitor - Function called for each node
*/
export function visitGraphNodes(
graph: LGraph | Subgraph,
visitor: (node: LGraphNode) => void
): void {
for (const node of graph.nodes) {
visitor(node)
}
}
/**
* Traverses a path of subgraphs to reach a target graph.
*
* @param startGraph - The graph to start from
* @param path - Array of subgraph node IDs to traverse
* @returns The target graph or null if path is invalid
*/
export function traverseSubgraphPath(
startGraph: LGraph | Subgraph,
path: string[]
): LGraph | Subgraph | null {
let currentGraph: LGraph | Subgraph = startGraph
for (const nodeId of path) {
const localNodeId = parseNodeId(nodeId)
if (!localNodeId) return null
const node = currentGraph.getNodeById(localNodeId)
if (!node?.isSubgraphNode?.() || !node.subgraph) return null
currentGraph = node.subgraph
}
return currentGraph
}
/**
* Traverses all nodes in a graph hierarchy (including subgraphs) and invokes
* a callback on each node that has the specified property.
*
* @param graph - The root graph to start traversal from
* @param callbackProperty - The name of the callback property to invoke on each node
*/
export function triggerCallbackOnAllNodes(
graph: LGraph | Subgraph,
callbackProperty: keyof LGraphNode
): void {
forEachNode(graph, (node) => {
const callback = node[callbackProperty]
if (typeof callback === 'function') {
callback.call(node)
}
})
}
/**
* Maps a function over all nodes in a graph hierarchy (including subgraphs).
* This is a pure functional traversal that doesn't mutate the graph.
*
* @param graph - The root graph to traverse
* @param mapFn - Function to apply to each node
* @returns Array of mapped results (excluding undefined values)
*/
export function mapAllNodes<T>(
graph: LGraph | Subgraph,
mapFn: (node: LGraphNode) => T | undefined
): T[] {
const results: T[] = []
visitGraphNodes(graph, (node) => {
// Recursively map over subgraphs first
if (node.isSubgraphNode?.() && node.subgraph) {
results.push(...mapAllNodes(node.subgraph, mapFn))
}
// Apply map function to current node
const result = mapFn(node)
if (result !== undefined) {
results.push(result)
}
})
return results
}
/**
* Executes a side-effect function on all nodes in a graph hierarchy.
* This is for operations that modify nodes or perform side effects.
*
* @param graph - The root graph to traverse
* @param fn - Function to execute on each node
*/
export function forEachNode(
graph: LGraph | Subgraph,
fn: (node: LGraphNode) => void
): void {
visitGraphNodes(graph, (node) => {
// Recursively process subgraphs first
if (node.isSubgraphNode?.() && node.subgraph) {
forEachNode(node.subgraph, fn)
}
// Execute function on current node
fn(node)
})
}
/**
* Collects all nodes in a graph hierarchy (including subgraphs) into a flat array.
*
* @param graph - The root graph to collect nodes from
* @param filter - Optional filter function to include only specific nodes
* @returns Array of all nodes in the graph hierarchy
*/
export function collectAllNodes(
graph: LGraph | Subgraph,
filter?: (node: LGraphNode) => boolean
): LGraphNode[] {
return mapAllNodes(graph, (node) => {
if (!filter || filter(node)) {
return node
}
return undefined
})
}
/**
* Finds a node by ID anywhere in the graph hierarchy.
*
* @param graph - The root graph to search
* @param nodeId - The ID of the node to find
* @returns The node if found, null otherwise
*/
export function findNodeInHierarchy(
graph: LGraph | Subgraph,
nodeId: string | number
): LGraphNode | null {
const localNodeId = parseNodeId(nodeId)
if (!localNodeId) return null
// Check current graph
const node = graph.getNodeById(localNodeId)
if (node) return node
// Search in subgraphs
for (const node of graph.nodes) {
if (node.isSubgraphNode?.() && node.subgraph) {
const found = findNodeInHierarchy(node.subgraph, nodeId)
if (found) return found
}
}
return null
}
/**
* Find a subgraph by its UUID anywhere in the graph hierarchy.
*
* @param graph - The root graph to search
* @param targetUuid - The UUID of the subgraph to find
* @returns The subgraph if found, null otherwise
*/
export function findSubgraphByUuid(
graph: LGraph | Subgraph,
targetUuid: string
): Subgraph | null {
// Fast O(1) lookup via the root graph's centralized subgraph registry.
if ('subgraphs' in graph && graph.subgraphs instanceof Map) {
return graph.subgraphs.get(targetUuid) ?? null
}
// Fallback: recursive traversal for non-root graphs without the registry.
for (const node of graph.nodes) {
if (node.isSubgraphNode?.() && node.subgraph) {
if (node.subgraph.id === targetUuid) {
return node.subgraph
}
const found = findSubgraphByUuid(node.subgraph, targetUuid)
if (found) return found
}
}
return null
}
/**
* Iteratively finds the path of subgraph IDs to a target subgraph.
* @param rootGraph The graph to start searching from.
* @param targetId The ID of the subgraph to find.
* @returns An array of subgraph IDs representing the path, or `null` if not found.
*/
export function findSubgraphPathById(
rootGraph: LGraph,
targetId: string
): string[] | null {
const stack: { graph: LGraph | Subgraph; path: string[] }[] = [
{ graph: rootGraph, path: [] }
]
while (stack.length > 0) {
const { graph, path } = stack.pop()!
// Check if graph exists and has _nodes property
if (!graph || !graph._nodes || !Array.isArray(graph._nodes)) {
continue
}
for (const node of graph._nodes) {
if (node.isSubgraphNode?.() && node.subgraph) {
const newPath = [...path, String(node.subgraph.id)]
if (node.subgraph.id === targetId) {
return newPath
}
stack.push({ graph: node.subgraph, path: newPath })
}
}
}
return null
}
/**
* Gets the root parent node associated with a hierarchical execution ID.
* Both Group Nodes and Subgraph Nodes use hierarchical IDs (e.g. "rootId:childId:...").
* The root parent is always located in the rootGraph.
*
* @param rootGraph - The root graph to search from
* @param executionId - The execution ID (e.g., "123:456")
* @returns The root parent node if found, null otherwise
*/
export function getRootParentNode(
rootGraph: LGraph,
executionId: string
): LGraphNode | null {
const parts = parseExecutionId(executionId)
if (!parts || parts.length < 2) return null
const parentId = parts[0]
if (!rootGraph) return null
const localParentId = parseNodeId(parentId)
if (!localParentId) return null
return rootGraph.getNodeById(localParentId) || null
}
/**
* Get a node by its execution ID from anywhere in the graph hierarchy.
* Execution IDs use hierarchical format like "123:456:789" for nested nodes.
*
* @param rootGraph - The root graph to search from
* @param executionId - The execution ID (e.g., "123:456:789" or "789")
* @returns The node if found, null otherwise
*/
export function getNodeByExecutionId(
rootGraph: LGraph,
executionId: string
): LGraphNode | null {
if (!rootGraph) return null
const localNodeId = getLocalNodeIdFromExecutionId(executionId)
if (!localNodeId) return null
const subgraphPath = getSubgraphPathFromExecutionId(executionId)
// If no subgraph path, it's in the root graph
const parsedLocalNodeId = parseNodeId(localNodeId)
if (!parsedLocalNodeId) return null
if (subgraphPath.length === 0) {
return rootGraph.getNodeById(parsedLocalNodeId) || null
}
// Traverse to the target subgraph
const targetGraph = traverseSubgraphPath(rootGraph, subgraphPath)
if (!targetGraph) return null
// Get the node from the target graph
return targetGraph.getNodeById(parsedLocalNodeId) || null
}
/**
* Returns the execution ID for a node relative to the root graph.
*
* Root-level nodes return their ID directly (e.g. "42").
* Nodes inside subgraphs return a colon-separated chain (e.g. "65:70:63").
*
* @param rootGraph - The root graph to resolve from
* @param node - The node whose execution ID to compute
* @returns The execution ID string, or null if the node has no graph
*/
export function getExecutionIdByNode(
rootGraph: LGraph,
node: LGraphNode
): NodeExecutionId | null {
if (!node.graph) return null
if (node.graph === rootGraph || node.graph.isRootGraph) {
return createNodeExecutionId([node.id])
}
const parentPath = findPartialExecutionPathToGraph(
node.graph as LGraph,
rootGraph
)
if (parentPath === undefined) return null
return createExecutionIdFromPath(parentPath, node.id)
}
/**
* True when every ancestor container in the execution path is active
* (not muted, not bypassed). Self is not checked — caller is expected to
* have already verified the target node's own mode.
*
* For root-level nodes (single-segment execution ID) there are no
* ancestors and the result is always true.
*
* Use after an initial full-graph scan to suppress missing-asset entries
* whose enclosing subgraph is muted/bypassed. At scan time only each
* node's own mode is checked; ancestor context is applied here so the
* effect cascades to interior nodes without requiring every scanner to
* carry the ancestor flag.
*/
export function isAncestorPathActive(
rootGraph: LGraph | null | undefined,
executionId: string
): boolean {
if (!rootGraph) return true
for (const ancestorId of getParentExecutionIds(executionId)) {
const ancestor = getNodeByExecutionId(rootGraph, ancestorId)
if (!ancestor) continue
if (
ancestor.mode === LGraphEventMode.NEVER ||
ancestor.mode === LGraphEventMode.BYPASS
) {
return false
}
}
return true
}
export function isExecutionPathActive(
rootGraph: LGraph | null | undefined,
executionId: string
): boolean {
if (!rootGraph) return true
const node = getNodeByExecutionId(rootGraph, executionId)
if (!node) return false
if (
node.mode === LGraphEventMode.NEVER ||
node.mode === LGraphEventMode.BYPASS
) {
return false
}
return isAncestorPathActive(rootGraph, executionId)
}
function getCandidateActivityExecutionId(candidate: {
nodeId?: string | number | null | undefined
sourceExecutionId?: string | number | null | undefined
}): string | null {
const executionId = candidate.sourceExecutionId ?? candidate.nodeId
return executionId == null ? null : String(executionId)
}
export function isCandidateScopeActive(
rootGraph: LGraph | null | undefined,
candidate: {
nodeId?: string | number | null | undefined
sourceExecutionId?: string | number | null | undefined
}
): boolean {
const executionId = getCandidateActivityExecutionId(candidate)
return executionId == null || isExecutionPathActive(rootGraph, executionId)
}
/**
* Predicate used after async verification resolves: a missing-asset
* candidate is surfaceable when it is confirmed missing and its
* enclosing subgraph is still active. Null `nodeId` (workflow-level
* models) bypasses the ancestor check since it has no scope to
* validate. Shared by the missing-model pipeline post-filter and its
* async-resolution call site; missing media resolves scope through the
* promoted-widget-aware `isMissingMediaCandidateActive` instead.
*/
export function isMissingCandidateActive(
rootGraph: LGraph | null | undefined,
candidate: {
nodeId?: string | number | null | undefined
sourceExecutionId?: string | number | null | undefined
isMissing?: boolean | undefined
}
): boolean {
if (candidate.isMissing !== true) return false
return isCandidateScopeActive(rootGraph, candidate)
}
/**
* Returns the execution ID for a node identified by its (graph, nodeId) pair.
*
* Unlike {@link getExecutionIdByNode}, this does not rely on `node.graph`.
* Use this when the node reference may be detached (e.g. inside
* `onNodeRemoved`, which LiteGraph fires after clearing `node.graph`).
*
* @param rootGraph - The root graph to resolve from
* @param graph - The graph the node currently lives in (or lived in)
* @param nodeId - The local node ID within `graph`
*/
export function getExecutionIdForNodeInGraph(
rootGraph: LGraph,
graph: LGraph | Subgraph,
nodeId: string | number
): NodeExecutionId | null {
const localNodeId = parseNodeId(nodeId)
if (!localNodeId) return null
const localExecutionId = createNodeExecutionId([localNodeId])
if (graph === rootGraph || graph.isRootGraph) return localExecutionId
const parentPath = findPartialExecutionPathToGraph(graph as LGraph, rootGraph)
if (parentPath === undefined) return localExecutionId
return createExecutionIdFromPath(parentPath, localNodeId) ?? localExecutionId
}
/**
* Returns the execution ID for a node described by plain data (id + subgraphId),
* without requiring a pre-existing {@link LGraphNode} reference.
* Subgraph nodes return the full colon-separated path (e.g. `"65:70:63"`).
* Falls back to `String(nodeData.id)` if the node cannot be resolved.
*
* @param rootGraph - The root graph to resolve from
* @param nodeData - Object with `id` (local node ID) and optional `subgraphId` (UUID)
*/
export function getExecutionIdFromNodeData(
rootGraph: LGraph,
nodeData: { id: string | number; subgraphId?: string | null }
): NodeExecutionId | null {
const localNodeId = parseNodeId(nodeData.id)
if (!localNodeId) return null
const locatorId = getLocatorIdFromNodeData(nodeData)
if (!locatorId) return createNodeExecutionId([localNodeId])
const node = getNodeByLocatorId(rootGraph, locatorId)
if (!node) return createNodeExecutionId([localNodeId])
return (
getExecutionIdByNode(rootGraph, node) ??
createNodeExecutionId([localNodeId])
)
}
/**
* Get a node by its locator ID from anywhere in the graph hierarchy.
* For subgraph nodes, the format is `<subgraph-definition-uuid>:<node-id>` where
* the node ID is a sequential integer, not a UUID.
*
* @param rootGraph - The root graph to search from
* @param locatorId - The locator ID (e.g., "a1b2c3d4-e5f6-7890-abcd-ef1234567890:123" or "123")
* @returns The node if found, null otherwise
*/
export function getNodeByLocatorId(
rootGraph: LGraph,
locatorId: string
): LGraphNode | null {
if (!rootGraph) return null
const parsedIds = parseNodeLocatorId(locatorId)
if (!parsedIds) return null
const { subgraphUuid, localNodeId } = parsedIds
// If no subgraph UUID, it's in the root graph
if (!subgraphUuid) {
return rootGraph.getNodeById(localNodeId) || null
}
// Find the subgraph with the matching UUID
const targetSubgraph = findSubgraphByUuid(rootGraph, subgraphUuid)
if (!targetSubgraph) return null
return targetSubgraph.getNodeById(localNodeId) || null
}
/**
* Convert execution context node IDs to NodeLocatorIds.
* Uses traverseSubgraphPath to resolve the subgraph chain.
*
* @param rootGraph - The root graph to resolve against
* @param nodeId - The node ID from execution context (could be execution ID like "123:456:789")
* @returns The NodeLocatorId, or undefined if resolution fails
*/
export function executionIdToNodeLocatorId(
rootGraph: LGraph,
nodeId: string | number
): NodeLocatorId | undefined {
const nodeIdStr = String(nodeId)
if (!nodeIdStr.includes(':')) {
// It's a top-level node ID
const localNodeId = parseNodeId(nodeIdStr)
if (!localNodeId) return undefined
return createNodeLocatorId(null, localNodeId) ?? undefined
}
// It's an execution node ID — resolve subgraph path
const parts = nodeIdStr.split(':')
const localNodeId = parts.at(-1)!
const subgraphPath = parts.slice(0, -1)
const targetGraph = traverseSubgraphPath(rootGraph, subgraphPath)
if (!targetGraph) return undefined
const parsedLocalNodeId = parseNodeId(localNodeId)
if (!parsedLocalNodeId) return undefined
return createNodeLocatorId(targetGraph.id, parsedLocalNodeId) ?? undefined
}
/**
* Finds the root graph from any graph in the hierarchy.
*
* @param graph - Any graph or subgraph in the hierarchy
* @returns The root graph
*/
export function getRootGraph(graph: LGraph | Subgraph): LGraph | Subgraph {
let current: LGraph | Subgraph = graph
while ('rootGraph' in current && current.rootGraph) {
current = current.rootGraph
}
return current
}
/**
* Applies a function to all nodes whose type matches a subgraph ID.
* Operates on the entire graph hierarchy starting from the root.
*
* @param rootGraph - The root graph to search in
* @param subgraphId - The ID/type of the subgraph to match nodes against
* @param fn - Function to apply to each matching node
*/
export function forEachSubgraphNode(
rootGraph: LGraph | Subgraph | null | undefined,
subgraphId: string | null | undefined,
fn: (node: LGraphNode) => void
): void {
if (!rootGraph || !subgraphId) return
forEachNode(rootGraph, (node) => {
if (node.type === subgraphId) {
fn(node)
}
})
}
/**
* Maps a function over all nodes whose type matches a subgraph ID.
* Operates on the entire graph hierarchy starting from the root.
*
* @param rootGraph - The root graph to search in
* @param subgraphId - The ID/type of the subgraph to match nodes against
* @param mapFn - Function to apply to each matching node
* @returns Array of mapped results
*/
export function mapSubgraphNodes<T>(
rootGraph: LGraph | Subgraph | null | undefined,
subgraphId: string | null | undefined,
mapFn: (node: LGraphNode) => T
): T[] {
if (!rootGraph || !subgraphId) return []
return mapAllNodes(rootGraph, (node) => {
if (node.type === subgraphId) {
return mapFn(node)
}
return undefined
})
}
/**
* Gets all non-IO nodes from a subgraph (excludes SubgraphInputNode and SubgraphOutputNode).
* These are the user-created nodes that can be safely removed when clearing a subgraph.
*
* @param subgraph - The subgraph to get non-IO nodes from
* @returns Array of non-IO nodes (user-created nodes)
*/
export function getAllNonIoNodesInSubgraph(subgraph: Subgraph): LGraphNode[] {
return subgraph.nodes.filter((node) => !isSubgraphIoNode(node))
}
/**
* Options for traverseNodesDepthFirst function
*/
interface TraverseNodesOptions<T> {
/** Function called for each node during traversal */
visitor?: (node: LGraphNode, context: T) => T
/** Initial context value */
initialContext?: T
/** Whether to traverse into subgraph nodes (default: true) */
expandSubgraphs?: boolean
}
/**
* Performs depth-first traversal of nodes and their subgraphs.
* Generic visitor pattern that can be used for various node processing tasks.
*
* @param nodes - Starting nodes for traversal
* @param options - Optional traversal configuration
*/
export function traverseNodesDepthFirst<T = void>(
nodes: LGraphNode[],
options?: TraverseNodesOptions<T>
): void {
const {
visitor = () => undefined as T,
initialContext = undefined as T,
expandSubgraphs = true
} = options || {}
type StackItem = { node: LGraphNode; context: T }
const stack: StackItem[] = []
// Initialize stack with starting nodes
for (const node of nodes) {
stack.push({ node, context: initialContext })
}
// Process stack iteratively (DFS)
while (stack.length > 0) {
const { node, context } = stack.pop()!
// Visit node and get updated context for children
const childContext = visitor(node, context)
// If it's a subgraph and we should expand, add children to stack
if (expandSubgraphs && node.isSubgraphNode?.() && node.subgraph) {
// Process children in reverse order to maintain left-to-right DFS processing
// when popping from stack (LIFO). Iterate backwards to avoid array reversal.
const children = node.subgraph.nodes
for (let i = children.length - 1; i >= 0; i--) {
stack.push({ node: children[i], context: childContext })
}
}
}
}
/**
* Reduces all nodes in a graph hierarchy to a single value using a reducer function.
* Single-pass traversal for efficient aggregation.
*
* @param graph - The root graph to traverse
* @param reducer - Function that reduces each node into the accumulator
* @param initialValue - The initial accumulator value
* @returns The final reduced value
*/
export function reduceAllNodes<T>(
graph: LGraph | Subgraph,
reducer: (accumulator: T, node: LGraphNode) => T,
initialValue: T
): T {
let result = initialValue
forEachNode(graph, (node) => {
result = reducer(result, node)
})
return result
}
/**
* Options for collectFromNodes function
*/
interface CollectFromNodesOptions<T, C> {
/** Function that returns data to collect for each node */
collector?: (node: LGraphNode, context: C) => T | null
/** Function that builds context for child nodes */
contextBuilder?: (node: LGraphNode, parentContext: C) => C
/** Initial context value */
initialContext?: C
/** Whether to traverse into subgraph nodes (default: true) */
expandSubgraphs?: boolean
}
/**
* Collects nodes with custom data during depth-first traversal.
* Generic collector that can gather any type of data per node.
*
* @param nodes - Starting nodes for traversal
* @param options - Optional collection configuration
* @returns Array of collected data
*/
export function collectFromNodes<T = LGraphNode, C = void>(
nodes: LGraphNode[],
options?: CollectFromNodesOptions<T, C>
): T[] {
const {
collector = (node: LGraphNode) => node as T,
contextBuilder = () => undefined as C,
initialContext = undefined as C,
expandSubgraphs = true
} = options || {}
const results: T[] = []
traverseNodesDepthFirst(nodes, {
visitor: (node, context) => {
const data = collector(node, context)
if (data !== null) {
results.push(data)
}
return contextBuilder(node, context)
},
initialContext,
expandSubgraphs
})
return results
}
/**
* Collects execution IDs for selected nodes and all their descendants.
* Uses the generic DFS traversal with optimized string building.
*
* @param selectedNodes - The selected nodes to process
* @returns Array of execution IDs for selected nodes and all nodes within selected subgraphs
*/
export function getExecutionIdsForSelectedNodes(
selectedNodes: LGraphNode[],
startGraph = selectedNodes[0]?.graph
): NodeExecutionId[] {
if (!startGraph) return []
const rootGraph = startGraph.rootGraph
const parentPath = startGraph.isRootGraph
? ''
: findPartialExecutionPathToGraph(startGraph, rootGraph)
if (parentPath === undefined) return []
function buildExecId(
node: LGraphNode,
parentExecutionId: string | null
): NodeExecutionId | null {
if (!parentExecutionId) return createNodeExecutionId([node.id])
return createExecutionIdFromPath(parentExecutionId, node.id)
}
return collectFromNodes<NodeExecutionId, string | null>(selectedNodes, {
collector: buildExecId,
contextBuilder: buildExecId,
initialContext: parentPath,
expandSubgraphs: true
})
}
/**
* Returns the set of local graph node IDs (as strings) for nodes that live in
* `activeGraph` and whose execution ID appears in `executionIds`.
*
* @param rootGraph - The root graph used to resolve execution IDs
* @param activeGraph - The currently-visible graph scope
* @param executionIds - Set of execution IDs to look up
* @returns Set of stringified local node IDs belonging to activeGraph
*/
export function getActiveGraphNodeIds(
rootGraph: LGraph,
activeGraph: LGraph | Subgraph,
executionIds: Set<NodeExecutionId>
): Set<string> {
const ids = new Set<string>()
for (const executionId of executionIds) {
const graphNode = getNodeByExecutionId(rootGraph, executionId)
if (graphNode?.graph === activeGraph) {
ids.add(String(graphNode.id))
}
}
return ids
}
function findPartialExecutionPathToGraph(
target: LGraph,
root: LGraph
): string | undefined {
for (const node of root.nodes) {
if (!node.isSubgraphNode()) continue
if (node.subgraph === target) return `${node.id}`
const subpath = findPartialExecutionPathToGraph(target, node.subgraph)
if (subpath !== undefined) return node.id + ':' + subpath
}
return undefined
}