Line data Source code
1 : import { cloneDeep, keyBy, omit } from 'es-toolkit/compat'
2 :
3 : import type {
4 : ComfyLinkObject,
5 : ComfyNode,
6 : Reroute,
7 : WorkflowJSON04
8 : } from '@comfyorg/graph-model/workflowSchema'
9 : import type { SerializedNodeId } from '@comfyorg/graph-model/nodeId'
10 :
11 : type RerouteNode = ComfyNode & {
12 : type: 'Reroute'
13 : }
14 :
15 : type LinkExtension = {
16 : id: number
17 : parentId: number
18 : }
19 :
20 : /**
21 : * Identifies all legacy Reroute nodes in a workflow
22 : */
23 0 : export function findLegacyRerouteNodes(
24 : workflow: WorkflowJSON04
25 : ): RerouteNode[] {
26 0 : return workflow.nodes.filter(
27 : (node) => node.type === 'Reroute'
28 : ) as RerouteNode[]
29 : }
30 :
31 : /**
32 : * Checks if the workflow has no native reroutes
33 : */
34 0 : export function noNativeReroutes(workflow: WorkflowJSON04): boolean {
35 0 : return (
36 : !workflow.extra?.reroutes?.length && !workflow.extra?.linkExtensions?.length
37 : )
38 : }
39 :
40 : /**
41 : * Gets the center position of a node
42 : */
43 0 : function getNodeCenter(node: ComfyNode): [number, number] {
44 0 : return [node.pos[0] + node.size[0] / 2, node.pos[1] + node.size[1] / 2]
45 : }
46 :
47 2356 : class ConversionContext {
48 : nodeById: Record<SerializedNodeId, ComfyNode>
49 : linkById: Record<number, ComfyLinkObject>
50 : rerouteById: Record<number, Reroute>
51 : rerouteByNodeId: Record<SerializedNodeId, Reroute>
52 : linkExtensions: LinkExtension[]
53 :
54 : /** Reroutes that has at least a valid link pass through it */
55 : validReroutes: Set<Reroute>
56 :
57 : private _rerouteIdCounter = 0
58 :
59 0 : constructor(public workflow: WorkflowJSON04) {
60 0 : this.nodeById = keyBy(workflow.nodes.map(cloneDeep), 'id')
61 0 : this.linkById = keyBy(
62 : workflow.links.map((l) => ({
63 : id: l[0],
64 : origin_id: l[1],
65 : origin_slot: l[2],
66 : target_id: l[3],
67 : target_slot: l[4],
68 : type: l[5]
69 : })),
70 : 'id'
71 : )
72 :
73 0 : const reroutes = findLegacyRerouteNodes(workflow).map((node, index) => ({
74 : nodeId: node.id,
75 : id: index + 1,
76 : pos: getNodeCenter(node),
77 : linkIds: []
78 : }))
79 0 : this._rerouteIdCounter = reroutes.length + 1
80 :
81 0 : this.rerouteByNodeId = keyBy(reroutes, 'nodeId')
82 0 : this.rerouteById = keyBy(reroutes, 'id')
83 :
84 0 : this.linkExtensions = []
85 0 : this.validReroutes = new Set()
86 : }
87 :
88 : /**
89 : * Gets the chain of reroute nodes leading to the given node
90 : */
91 : private _getRerouteChain(node: RerouteNode): RerouteNode[] {
92 0 : const nodes: RerouteNode[] = []
93 0 : let currentNode: RerouteNode | undefined = node
94 0 : while (currentNode?.type === 'Reroute') {
95 0 : nodes.push(currentNode)
96 0 : const linkId = currentNode.inputs?.[0]?.link ?? 0
97 0 : const inputLink = Object.hasOwn(this.linkById, linkId)
98 : ? this.linkById[linkId]
99 : : undefined
100 0 : if (!inputLink) break
101 :
102 0 : currentNode = this.nodeById[inputLink.origin_id] as
103 : | RerouteNode
104 : | undefined
105 : }
106 :
107 0 : return nodes
108 : }
109 :
110 : private _connectRerouteChain(rerouteNodes: RerouteNode[]): Reroute[] {
111 0 : const reroutes = rerouteNodes.map((node) => this.rerouteByNodeId[node.id])
112 0 : for (const reroute of reroutes) {
113 0 : this.validReroutes.add(reroute)
114 : }
115 :
116 0 : for (let i = 0; i < rerouteNodes.length - 1; i++) {
117 0 : const to = reroutes[i]
118 : const from = reroutes[i + 1]
119 0 : to.parentId = from.id
120 : }
121 :
122 0 : return reroutes
123 : }
124 :
125 : private _createNewLink(
126 : startingLink: ComfyLinkObject,
127 : endingLink: ComfyLinkObject,
128 : rerouteNodes: RerouteNode[]
129 : ): ComfyLinkObject {
130 0 : if (rerouteNodes.length === 0) {
131 0 : throw new Error('No reroute nodes found')
132 : }
133 :
134 0 : const reroute = this.rerouteByNodeId[rerouteNodes[0].id]
135 0 : this.linkExtensions.push({
136 : id: endingLink.id,
137 : parentId: reroute.id
138 : })
139 :
140 0 : const reroutes = this._connectRerouteChain(rerouteNodes)
141 0 : for (const reroute of reroutes) {
142 0 : reroute.linkIds ??= []
143 0 : reroute.linkIds.push(endingLink.id)
144 0 : delete reroute.floating
145 : }
146 :
147 0 : return {
148 : id: endingLink.id,
149 : origin_id: startingLink.origin_id,
150 : origin_slot: startingLink.origin_slot,
151 : target_id: endingLink.target_id,
152 : target_slot: endingLink.target_slot,
153 : type: endingLink.type
154 : }
155 : }
156 :
157 : private _createNewInputFloatingLink(
158 : endingLink: ComfyLinkObject,
159 : rerouteNodes: RerouteNode[]
160 : ): ComfyLinkObject {
161 0 : const reroutes = this._connectRerouteChain(rerouteNodes)
162 0 : for (const reroute of reroutes) {
163 0 : if (!reroute.linkIds?.length) {
164 0 : reroute.floating = {
165 : slotType: 'input'
166 : }
167 : }
168 : }
169 0 : return {
170 : id: this._rerouteIdCounter++,
171 : origin_id: -1,
172 : origin_slot: -1,
173 : target_id: endingLink.target_id,
174 : target_slot: endingLink.target_slot,
175 : type: endingLink.type,
176 : parentId: reroutes[0].id
177 : }
178 : }
179 :
180 : private _createNewOutputFloatingLink(
181 : startingLink: ComfyLinkObject,
182 : rerouteNodes: RerouteNode[]
183 : ): ComfyLinkObject {
184 0 : const reroutes = this._connectRerouteChain(rerouteNodes)
185 0 : for (const reroute of reroutes) {
186 0 : if (!reroute.linkIds?.length) {
187 0 : reroute.floating = {
188 : slotType: 'output'
189 : }
190 : }
191 : }
192 :
193 0 : return {
194 : id: this._rerouteIdCounter++,
195 : origin_id: startingLink.origin_id,
196 : origin_slot: startingLink.origin_slot,
197 : target_id: -1,
198 : target_slot: -1,
199 : type: startingLink.type,
200 : parentId: reroutes[0].id
201 : }
202 : }
203 :
204 : private _reconnectLinks(nodes: ComfyNode[], links: ComfyLinkObject[]): void {
205 : // Remove all existing links on sockets
206 0 : for (const node of nodes) {
207 0 : for (const input of node.inputs ?? []) {
208 0 : input.link = null
209 : }
210 0 : for (const output of node.outputs ?? []) {
211 0 : output.links = []
212 : }
213 : }
214 :
215 0 : const nodesById = keyBy(nodes, 'id')
216 :
217 : // Reconnect the links
218 0 : for (const link of links) {
219 : const sourceNode = nodesById[link.origin_id]
220 0 : sourceNode.outputs![link.origin_slot].links!.push(link.id)
221 :
222 0 : const targetNode = nodesById[link.target_id]
223 0 : targetNode.inputs![link.target_slot].link = link.id
224 : }
225 : }
226 :
227 : migrateReroutes(): WorkflowJSON04 {
228 0 : const links: ComfyLinkObject[] = []
229 0 : const floatingLinks: ComfyLinkObject[] = []
230 :
231 0 : const endingLinks: ComfyLinkObject[] = []
232 :
233 0 : for (const link of Object.values(this.linkById)) {
234 0 : const sourceIsReroute = Boolean(this.rerouteByNodeId[link.origin_id])
235 0 : const targetIsReroute = Boolean(this.rerouteByNodeId[link.target_id])
236 :
237 : // Process links that are not connected to reroute nodes
238 0 : if (!sourceIsReroute && !targetIsReroute) {
239 0 : links.push(link)
240 0 : } else if (sourceIsReroute && !targetIsReroute) {
241 0 : endingLinks.push(link)
242 : }
243 : }
244 :
245 0 : for (const endingLink of endingLinks) {
246 0 : const endingRerouteNode = this.nodeById[
247 : endingLink.origin_id
248 : ] as RerouteNode
249 0 : const rerouteNodes = this._getRerouteChain(endingRerouteNode)
250 0 : const startingLinkId =
251 : rerouteNodes[rerouteNodes.length - 1]?.inputs?.[0]?.link ?? -1
252 0 : if (Object.hasOwn(this.linkById, startingLinkId)) {
253 0 : const startingLink = this.linkById[startingLinkId]
254 : // Valid link found, create a new link
255 0 : links.push(this._createNewLink(startingLink, endingLink, rerouteNodes))
256 : } else {
257 : // Floating link found, create a new floating link
258 0 : floatingLinks.push(
259 : this._createNewInputFloatingLink(endingLink, rerouteNodes)
260 : )
261 : }
262 : }
263 :
264 0 : const floatingEndingRerouteNodes = Object.keys(this.rerouteByNodeId)
265 : .map((nodeId) => this.nodeById[nodeId] as RerouteNode)
266 : .filter((rerouteNode) => {
267 0 : const output = rerouteNode.outputs?.[0]
268 0 : if (!output) return false
269 0 : return !output.links?.length
270 : })
271 :
272 0 : for (const rerouteNode of floatingEndingRerouteNodes) {
273 0 : const rerouteNodes = this._getRerouteChain(rerouteNode)
274 0 : const startingLinkId =
275 : rerouteNodes[rerouteNodes.length - 1]?.inputs?.[0]?.link ?? -1
276 0 : if (Object.hasOwn(this.linkById, startingLinkId)) {
277 0 : const startingLink = this.linkById[startingLinkId]
278 0 : floatingLinks.push(
279 : this._createNewOutputFloatingLink(startingLink, rerouteNodes)
280 : )
281 : }
282 : }
283 :
284 0 : const nodes = Object.values(this.nodeById).filter(
285 : (node) => node.type !== 'Reroute'
286 : )
287 0 : this._reconnectLinks(nodes, links)
288 :
289 0 : return {
290 : ...this.workflow,
291 : nodes,
292 : links: links.map((link) => [
293 : link.id,
294 : link.origin_id,
295 : link.origin_slot,
296 : link.target_id,
297 : link.target_slot,
298 : link.type
299 : ]),
300 : floatingLinks: floatingLinks.length > 0 ? floatingLinks : undefined,
301 : extra: {
302 : ...this.workflow.extra,
303 : reroutes: Array.from(this.validReroutes).map(
304 : (reroute) => omit(reroute, 'nodeId') as Reroute
305 : ),
306 : linkExtensions: this.linkExtensions
307 : }
308 : }
309 : }
310 : }
311 :
312 : /**
313 : * Main function to migrate legacy reroute nodes to native reroute points
314 : */
315 2356 : export const migrateLegacyRerouteNodes = (
316 : workflow: WorkflowJSON04
317 : ): WorkflowJSON04 => {
318 : // Find all legacy Reroute nodes
319 : const legacyRerouteNodes = findLegacyRerouteNodes(workflow)
320 :
321 : // If no reroute nodes, return the workflow unchanged
322 0 : if (legacyRerouteNodes.length === 0) {
323 0 : return workflow
324 : }
325 :
326 : // Create a deep copy of the workflow to avoid mutating the original
327 0 : const newWorkflow = JSON.parse(JSON.stringify(workflow)) as WorkflowJSON04
328 :
329 : // Initialize extra structure if needed
330 0 : if (!newWorkflow.extra) {
331 0 : newWorkflow.extra = {}
332 : }
333 :
334 : const context = new ConversionContext(newWorkflow)
335 0 : return context.migrateReroutes()
336 : }
|