Line data Source code
1 : import { zUploadImageResponse } from '@comfyorg/ingest-types/zod'
2 : import { z } from 'zod'
3 :
4 : import { combineAbortSignals } from '@comfyorg/api-client/abortSignal'
5 : import type {
6 : ComfyNode,
7 : ComfyWorkflowJSON
8 : } from '@comfyorg/graph-model/workflowSchema'
9 : import { isWidgetValue } from '@comfyorg/graph-model/widgets'
10 : import type { TWidgetValue } from '@comfyorg/graph-model/widgets'
11 : import { api } from '@/scripts/api'
12 :
13 : import { zTemplateInput } from '@comfyorg/api-client/templateSchema'
14 :
15 2355 : const INPUT_BASE =
16 : 'https://raw.githubusercontent.com/Comfy-Org/workflow_templates/'
17 2355 : const INPUT_WIDGETS: Readonly<Record<string, string>> = {
18 : LoadImage: 'image',
19 : LoadImageMask: 'image',
20 : LoadVideo: 'file',
21 : LoadAudio: 'audio'
22 : }
23 2355 : const zWidgetValue = z.custom<TWidgetValue>(isWidgetValue)
24 2355 : const zValues = z.union([
25 : z.array(zWidgetValue),
26 : z.record(z.string(), zWidgetValue)
27 : ])
28 2355 : const zNamedValues = z.record(z.string(), zWidgetValue)
29 :
30 : type PreparationResult = {
31 : workflow: ComfyWorkflowJSON
32 : uploadedCount: number
33 : errors: unknown[]
34 : }
35 :
36 27 : function getInputBinding(node: ComfyNode, restoreNamed: boolean) {
37 27 : const widget = INPUT_WIDGETS[node.type]
38 27 : if (!widget) return
39 27 : const values = zValues.parse(node.widgets_values ?? [])
40 27 : const named = zNamedValues.optional().parse(node.widgets_values_named)
41 27 : const file =
42 : restoreNamed && named
43 : ? named[widget]
44 : : Array.isArray(values)
45 : ? values[0]
46 : : values[widget]
47 27 : if (typeof file !== 'string') return
48 3 : return { node, widget, file, values, named }
49 : }
50 :
51 3 : function isSampleFilename(file: string): boolean {
52 3 : return file === file.trim() && !file.includes('..') && !/[\\/:%?#]/.test(file)
53 : }
54 :
55 3 : async function uploadTemplateInput(
56 : file: string,
57 : sourceRevision: string,
58 : signal: AbortSignal
59 : ): Promise<{ ok: true; path: string } | { ok: false; error: Error }> {
60 3 : const requestSignal = combineAbortSignals([
61 : signal,
62 : AbortSignal.timeout(120_000)
63 : ])
64 3 : let operation = 'download'
65 0 : function failure(cause: unknown): { ok: false; error: Error } {
66 0 : return {
67 : ok: false,
68 : error: new Error(
69 : `Template sample ${operation} failed: ${file} (${sourceRevision})`,
70 : { cause }
71 : )
72 : }
73 : }
74 :
75 3 : try {
76 3 : const response = await fetch(
77 : `${INPUT_BASE}${sourceRevision}/input/${encodeURIComponent(file)}`,
78 : { signal: requestSignal }
79 : )
80 3 : if (!response.ok) return failure(new Error(`HTTP ${response.status}`))
81 3 : const bytes = await response.arrayBuffer()
82 3 : requestSignal.throwIfAborted()
83 3 : const body = new FormData()
84 3 : body.append('image', new File([bytes], file))
85 3 : body.append('type', 'input')
86 3 : operation = 'upload'
87 3 : const uploaded = await api.fetchApi('/upload/image', {
88 : method: 'POST',
89 : body,
90 : signal: requestSignal
91 : })
92 3 : if (!uploaded.ok) return failure(new Error(`HTTP ${uploaded.status}`))
93 3 : const result = zUploadImageResponse.parse(await uploaded.json())
94 3 : if (!result.name)
95 0 : return failure(new Error('No saved filename in upload response'))
96 3 : return {
97 : ok: true,
98 : path: result.subfolder
99 : ? `${result.subfolder}/${result.name}`
100 : : result.name
101 : }
102 : } catch (cause) {
103 0 : signal.throwIfAborted()
104 0 : return failure(cause)
105 : }
106 : }
107 :
108 3 : function getDeclaredInputFiles(
109 : inputs: unknown,
110 : bindings: NonNullable<ReturnType<typeof getInputBinding>>[]
111 : ) {
112 3 : const files = new Map<string, string>()
113 3 : const errors: unknown[] = []
114 3 : const entries = z.array(z.unknown()).safeParse(inputs)
115 3 : if (!entries.success) {
116 0 : errors.push(entries.error)
117 0 : return { files, errors }
118 : }
119 3 : for (const entry of entries.data) {
120 3 : const parsed = zTemplateInput.safeParse(entry)
121 3 : if (!parsed.success) {
122 0 : errors.push(parsed.error)
123 0 : continue
124 : }
125 3 : const input = parsed.data
126 3 : if (!input.sourceRevision) continue
127 3 : if (
128 : !bindings.some(
129 : ({ node, file }) =>
130 : node.id === input.nodeId &&
131 : node.type === input.nodeType &&
132 : file === input.file
133 : )
134 : )
135 0 : continue
136 3 : if (!isSampleFilename(input.file)) {
137 0 : errors.push(
138 : new Error(`Unsupported template input filename: ${input.file}`)
139 : )
140 0 : continue
141 : }
142 3 : files.set(input.file, input.sourceRevision)
143 : }
144 3 : return { files, errors }
145 : }
146 :
147 3 : export function getTemplateInputPlan(
148 : workflow: ComfyWorkflowJSON,
149 : inputs: unknown,
150 : { restoreNamed }: { restoreNamed: boolean }
151 : ) {
152 3 : const errors: unknown[] = []
153 3 : const bindings = workflow.nodes.flatMap((node) => {
154 27 : try {
155 27 : const binding = getInputBinding(node, restoreNamed)
156 27 : return binding ? [binding] : []
157 : } catch (error) {
158 0 : errors.push(error)
159 0 : return []
160 : }
161 : })
162 3 : const { files, errors: declarationErrors } = getDeclaredInputFiles(
163 : inputs,
164 : bindings
165 : )
166 3 : errors.push(...declarationErrors)
167 3 : return { bindings, files, errors }
168 : }
169 :
170 3 : export async function prepareTemplateInputs(
171 : workflow: ComfyWorkflowJSON,
172 : inputs: unknown,
173 : signal: AbortSignal,
174 : { restoreNamed, onStart }: { restoreNamed: boolean; onStart?: () => void }
175 : ): Promise<PreparationResult> {
176 3 : const prepared = structuredClone(workflow)
177 3 : const { bindings, files, errors } = getTemplateInputPlan(prepared, inputs, {
178 : restoreNamed
179 : })
180 3 : signal.throwIfAborted()
181 3 : if (!files.size) return { workflow, uploadedCount: 0, errors }
182 3 : onStart?.()
183 3 : let uploadedCount = 0
184 3 : for (const [file, sourceRevision] of files) {
185 3 : signal.throwIfAborted()
186 3 : try {
187 3 : const uploaded = await uploadTemplateInput(file, sourceRevision, signal)
188 3 : signal.throwIfAborted()
189 3 : if (!uploaded.ok) {
190 0 : errors.push(uploaded.error)
191 0 : continue
192 : }
193 3 : const path = uploaded.path
194 3 : for (const { node, widget, values, named } of bindings.filter(
195 : (binding) => binding.file === file
196 : )) {
197 3 : node.widgets_values = Array.isArray(values)
198 : ? [path, ...values.slice(1)]
199 : : { ...values, [widget]: path }
200 3 : if (named) node.widgets_values_named = { ...named, [widget]: path }
201 : }
202 3 : uploadedCount++
203 : } catch (error) {
204 0 : signal.throwIfAborted()
205 0 : errors.push(error)
206 : }
207 : }
208 3 : return {
209 : workflow: uploadedCount > 0 ? prepared : workflow,
210 : uploadedCount,
211 : errors
212 : }
213 : }
|