comfy-ts 1.1.0 → 1.2.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.
- package/README.md +21 -8
- package/dist/cli.js +4 -4552
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +53 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +49 -23
- package/dist/index.d.ts +49 -23
- package/dist/index.js +53 -12
- package/dist/index.js.map +1 -1
- package/dist/{run-tui-DZ22HDHI.js → run-tui-BAdizWsO.js} +722 -130
- package/dist/run-tui-BAdizWsO.js.map +1 -0
- package/dist/state-BYbxDgfr.js +5258 -0
- package/dist/state-BYbxDgfr.js.map +1 -0
- package/examples/README.md +6 -4
- package/examples/{01-txt2img.cflow.ts → rvion/01-txt2img.cflow.ts} +1 -1
- package/examples/{02-img2img-upload.cflow.ts → rvion/02-img2img-upload.cflow.ts} +1 -1
- package/examples/{03-export-workflow-json.cflow.ts → rvion/03-export-workflow-json.cflow.ts} +1 -1
- package/examples/{04-krea2-turbo-t2i.cflow.ts → rvion/04-krea2-turbo-t2i.cflow.ts} +2 -2
- package/examples/{05-comfy-cloud.cflow.ts → rvion/05-comfy-cloud.cflow.ts} +2 -2
- package/examples/rvion/06-qwen-image-edit.cflow.ts +89 -0
- package/package.json +4 -1
- package/src/cli/tui/components/CopyOverlay.tsx +25 -0
- package/src/cli/tui/components/Header.tsx +9 -4
- package/src/cli/tui/components/HostPanel.tsx +3 -2
- package/src/cli/tui/components/HostsOverlay.tsx +33 -0
- package/src/cli/tui/components/StatusBar.tsx +28 -9
- package/src/cli/tui/components/TreePanel.tsx +17 -7
- package/src/cli/tui/components/TuiApp.tsx +47 -5
- package/src/cli/tui/imagePicker/fsListing.ts +6 -4
- package/src/cli/tui/run-tui.tsx +47 -7
- package/src/cli/tui/state/DraftsSt.ts +3 -2
- package/src/cli/tui/state/ExecSt.ts +108 -12
- package/src/cli/tui/state/HostSt.ts +94 -10
- package/src/cli/tui/state/PickerSt.ts +8 -2
- package/src/cli/tui/state/QueueSt.ts +2 -2
- package/src/cli/tui/state/SettingsSt.ts +25 -7
- package/src/cli/tui/state/TreeSt.ts +139 -36
- package/src/cli/tui/state/TuiSt.ts +47 -6
- package/src/cli/tui/state/WorkflowsSt.ts +14 -2
- package/src/cli/tui/treeRows.ts +165 -0
- package/src/host/ComfyHost.ts +7 -0
- package/src/runner/ComfyWorkflowLayout.ts +6 -4
- package/src/state.ts +7 -1
- package/src/vars/ComfyVars.ts +25 -4
- package/src/vars/DefinedWorkflow.ts +21 -8
- package/dist/DefinedWorkflow-BYyu5dK9.js +0 -669
- package/dist/DefinedWorkflow-BYyu5dK9.js.map +0 -1
- package/dist/run-tui-DZ22HDHI.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,4557 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { c as readableStringify, d as ComfySchema, t as ComfyTS } from "./state-BYbxDgfr.js";
|
|
3
3
|
import { spawnSync } from "node:child_process";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import crypto from "node:crypto";
|
|
8
|
-
import { scope, type } from "arktype";
|
|
9
|
-
import { nanoid } from "nanoid";
|
|
10
|
-
import sharp from "sharp";
|
|
11
|
-
import { imageMeta } from "image-meta";
|
|
12
|
-
import WebSocket from "ws";
|
|
13
|
-
import https from "node:https";
|
|
14
|
-
import { stdout } from "node:process";
|
|
15
|
-
//#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
|
|
16
|
-
/** having a bunch of sensible default will help slightly */
|
|
17
|
-
function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
|
|
18
|
-
if (enumName === "KSampler.sampler_name") return "E_SamplerName";
|
|
19
|
-
if (enumName === "KSampler.scheduler") return "E_SchedulerName";
|
|
20
|
-
if (enumName === "CheckpointLoaderSimple.ckpt_name") return "E_CkptName";
|
|
21
|
-
if (enumName === "VAELoader.vae_name") return "E_VaeName";
|
|
22
|
-
if (enumName === "LoraLoader.lora_name") return "E_LoraName";
|
|
23
|
-
if (enumName === "LatentUpscale.upscale_method") return "E_LatentUpscaleMethod";
|
|
24
|
-
if (enumName === "ImageScale.upscale_method") return "E_ImageUpscaleMethod";
|
|
25
|
-
if (enumName === "LoadImage.image") return "E_Image";
|
|
26
|
-
if (enumName === "LoadImageMask.channel") return "E_Channel";
|
|
27
|
-
if (enumName === "KSamplerAdvanced.add_noise") return "E_EnableOrDisable";
|
|
28
|
-
if (enumName === "LatentRotate.rotation") return "E_Rotation";
|
|
29
|
-
if (enumName === "LatentFlip.flip_method") return "E_FlipMethod";
|
|
30
|
-
if (enumName === "CLIPLoader.type") return "E_ClipType";
|
|
31
|
-
if (enumName === "UNETLoader.weight_dtype") return "E_WeightDType";
|
|
32
|
-
if (enumName === "DualCLIPLoader.type") return "E_DualClipType";
|
|
33
|
-
if (enumName === "CheckpointLoader.config_name") return "E_CkptConfigName";
|
|
34
|
-
if (enumName === "civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name") return "E_CivitAICkptName";
|
|
35
|
-
if (enumName === "Impact-Pack.SAMDetectorCombined.detection_hint") return "E_ImpactDetectionHint";
|
|
36
|
-
if (hashContent === "false|true") return "E_TrueOrFalse";
|
|
37
|
-
if (hashContent === "CPU|GPU") return "E_CpuOrGpu";
|
|
38
|
-
return "E_" + hash;
|
|
39
|
-
}
|
|
40
|
-
//#endregion
|
|
41
|
-
//#region src/sdk-generator/_pythonModuleToNamespace.ts
|
|
42
|
-
function pythonModuleToPrefix(pythonModule) {
|
|
43
|
-
if (pythonModule === "nodes") return "";
|
|
44
|
-
if (pythonModule.startsWith("comfy_extras.")) return "";
|
|
45
|
-
if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
|
|
46
|
-
if (pythonModule.startsWith("custom_nodes.")) return pythonModule.replace(/^custom_nodes\./i, "").replace(/^comfyui[-_]/i, "").replace(/[-_]comfyui$/i, "").replace(/^comfy[-_]/i, "").replace(/[-_]comfy$/i, "").replace(/^nodes[-_]/i, "").replace(/[-_]node[-_]suite$/i, "") + ".";
|
|
47
|
-
console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
|
|
48
|
-
return `${pythonModule}.`;
|
|
49
|
-
}
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/sdk-generator/_toQualifiedNodeKey.ts
|
|
52
|
-
const toQualifiedNodeKey = (pythonModule, nameInComfy) => {
|
|
53
|
-
return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`;
|
|
54
|
-
};
|
|
55
|
-
//#endregion
|
|
56
|
-
//#region src/utils/CodeBuffer.ts
|
|
57
|
-
/** this class is used to buffer text and then write it to a file */
|
|
58
|
-
var CodeBuffer = class {
|
|
59
|
-
constructor(_indent = 0, lines = []) {
|
|
60
|
-
this._indent = _indent;
|
|
61
|
-
this.tab = " ";
|
|
62
|
-
this.content = "";
|
|
63
|
-
this.newLine = () => this.content += "\n";
|
|
64
|
-
this.line = (...txts) => this.writeLine(txts.join(""));
|
|
65
|
-
this.append = (str) => this.content += str;
|
|
66
|
-
this.writeLine = (txt) => {
|
|
67
|
-
this.content += txt.split("\n").map((line) => repeatStr(this._indent, this.tab) + line).join("\n") + "\n";
|
|
68
|
-
return this;
|
|
69
|
-
};
|
|
70
|
-
this.w = (txt, opts = { if: true }) => {
|
|
71
|
-
if (opts.if) this.writeLine(txt);
|
|
72
|
-
};
|
|
73
|
-
this.indent = () => this._indent++;
|
|
74
|
-
this.deindent = () => this._indent--;
|
|
75
|
-
this.indented = (fn) => {
|
|
76
|
-
this._indent++;
|
|
77
|
-
fn();
|
|
78
|
-
this._indent--;
|
|
79
|
-
};
|
|
80
|
-
this.bar = (text) => this.w(renderBar(text, "// "));
|
|
81
|
-
for (const line of lines) this.writeLine(line);
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
|
-
const repeatStr = (x, str) => {
|
|
85
|
-
let out = "";
|
|
86
|
-
for (let i = 0; i < x; i++) out += str;
|
|
87
|
-
return out;
|
|
88
|
-
};
|
|
89
|
-
const renderBar = (text, prefix = "") => {
|
|
90
|
-
const ___bar___ = "=============================================================================";
|
|
91
|
-
return `${prefix}|${___bar___}|\n${prefix}| ${text} ${repeatStr(77 - text.length - 4, " ")} |\n${prefix}|${___bar___}|`;
|
|
92
|
-
};
|
|
93
|
-
//#endregion
|
|
94
|
-
//#region src/utils/escapeJSKey.ts
|
|
95
|
-
const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
96
|
-
const isValidJSKey = (s) => {
|
|
97
|
-
return regex.test(s);
|
|
98
|
-
};
|
|
99
|
-
const escapeJSKey = (s) => {
|
|
100
|
-
if (typeof s !== "string") return "string";
|
|
101
|
-
if (!isValidJSKey(s)) return `"${s}"`;
|
|
102
|
-
return s;
|
|
103
|
-
};
|
|
104
|
-
//#endregion
|
|
105
|
-
//#region src/sdk-generator/Primitives.ts
|
|
106
|
-
const ComfyPrimitiveMapping = {
|
|
107
|
-
BOOLEAN: "boolean",
|
|
108
|
-
FLOAT: "number",
|
|
109
|
-
INT: "number",
|
|
110
|
-
STRING: "string"
|
|
111
|
-
};
|
|
112
|
-
const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
|
|
113
|
-
/**
|
|
114
|
-
* when a litegraph node has an input entry with a widget marker, the
|
|
115
|
-
* serialized TYPE string decides how many widgets_values it consumed in that era
|
|
116
|
-
*/
|
|
117
|
-
const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
|
|
118
|
-
if (type === "INT") {
|
|
119
|
-
if (nameInComfy === "seed" || nameInComfy === "noise_seed") return 2;
|
|
120
|
-
return 1;
|
|
121
|
-
}
|
|
122
|
-
if (type === "BOOLEAN") return 1;
|
|
123
|
-
if (type === "FLOAT") return 1;
|
|
124
|
-
if (type === "STRING") return 1;
|
|
125
|
-
if (type === "COMBO") return 1;
|
|
126
|
-
if (type === "INT:seed") return 2;
|
|
127
|
-
if (type === "INT:noise_seed") return 2;
|
|
128
|
-
return 0;
|
|
129
|
-
};
|
|
130
|
-
const ComfyDefaultNodeWhenUnknown_Name = "UnknownNodeXX";
|
|
131
|
-
const ComfyDefaultNodeWhenUnknown_Schema = {
|
|
132
|
-
category: "test",
|
|
133
|
-
input: {},
|
|
134
|
-
output: [],
|
|
135
|
-
description: "This is a test node",
|
|
136
|
-
output_name: [],
|
|
137
|
-
display_name: "UnknownNodeXX",
|
|
138
|
-
name: "UnknownNodeXX",
|
|
139
|
-
output_is_list: [],
|
|
140
|
-
output_node: false,
|
|
141
|
-
python_module: "nodes"
|
|
142
|
-
};
|
|
143
|
-
//#endregion
|
|
144
|
-
//#region src/sdk-generator/ComfyNodeSchema.ts
|
|
145
|
-
var ComfyNodeSchema = class {
|
|
146
|
-
get singleOutputs() {
|
|
147
|
-
if (this._singleOutputs != null) return this._singleOutputs;
|
|
148
|
-
const x = {};
|
|
149
|
-
for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1;
|
|
150
|
-
this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1);
|
|
151
|
-
return this._singleOutputs;
|
|
152
|
-
}
|
|
153
|
-
constructor(raw, nameInComfy, nodeKey, category, inputs, outputs, pythonModule) {
|
|
154
|
-
this.raw = raw;
|
|
155
|
-
this.nameInComfy = nameInComfy;
|
|
156
|
-
this.nodeKey = nodeKey;
|
|
157
|
-
this.category = category;
|
|
158
|
-
this.inputs = inputs;
|
|
159
|
-
this.outputs = outputs;
|
|
160
|
-
this.pythonModule = pythonModule;
|
|
161
|
-
this._singleOutputs = null;
|
|
162
|
-
this.category = this.category.replaceAll("/", "_");
|
|
163
|
-
}
|
|
164
|
-
codegenUI() {
|
|
165
|
-
const b = new CodeBuffer();
|
|
166
|
-
const p = b.w;
|
|
167
|
-
p(` ${escapeJSKey(this.nodeKey)}: {`);
|
|
168
|
-
this.inputs.forEach((i, _ix) => {
|
|
169
|
-
if (i.isPrimitive) {
|
|
170
|
-
const tsType = ComfyPrimitiveMapping[i.typeName];
|
|
171
|
-
if (tsType == null) return console.log(`[🔶] invariant violation`);
|
|
172
|
-
p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`);
|
|
173
|
-
} else if (i.isEnum) p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`);
|
|
174
|
-
else p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`);
|
|
175
|
-
});
|
|
176
|
-
p(` }`);
|
|
177
|
-
return b.content;
|
|
178
|
-
}
|
|
179
|
-
renderOpts(opts) {
|
|
180
|
-
if (opts == null) return null;
|
|
181
|
-
if (typeof opts === "string") return null;
|
|
182
|
-
let out = "/**";
|
|
183
|
-
if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`;
|
|
184
|
-
if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`;
|
|
185
|
-
if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`;
|
|
186
|
-
if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`;
|
|
187
|
-
out += " */";
|
|
188
|
-
return out;
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
const wrapQuote = (s) => {
|
|
192
|
-
if (s.includes("'")) return `"${s}"`;
|
|
193
|
-
return `'${s}'`;
|
|
194
|
-
};
|
|
195
|
-
//#endregion
|
|
196
|
-
//#region src/sdk-generator/inputWidgetKind.ts
|
|
197
|
-
const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
|
|
198
|
-
/**
|
|
199
|
-
* seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
|
|
200
|
-
* The frontend creates the control widget on truthiness, and real 2026 hosts
|
|
201
|
-
* spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
|
|
202
|
-
* SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
|
|
203
|
-
* heuristic applies.
|
|
204
|
-
*/
|
|
205
|
-
const controlConsumes = (o, typeName, name) => {
|
|
206
|
-
if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
|
|
207
|
-
if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
|
|
208
|
-
return 1;
|
|
209
|
-
};
|
|
210
|
-
const flattenInputSections = (inputs) => {
|
|
211
|
-
const out = [];
|
|
212
|
-
for (const section of ["required", "optional"]) {
|
|
213
|
-
const sec = inputs[section];
|
|
214
|
-
if (!isRecord(sec)) continue;
|
|
215
|
-
for (const [name, spec] of Object.entries(sec)) {
|
|
216
|
-
if (!Array.isArray(spec) || spec.length === 0) continue;
|
|
217
|
-
const t = spec[0];
|
|
218
|
-
if (typeof t !== "string" && !Array.isArray(t)) continue;
|
|
219
|
-
out.push({
|
|
220
|
-
name,
|
|
221
|
-
type: t,
|
|
222
|
-
opts: spec[1],
|
|
223
|
-
required: section === "required"
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return out;
|
|
228
|
-
};
|
|
229
|
-
/** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
|
|
230
|
-
const parseDynamicOptions = (options) => {
|
|
231
|
-
if (options.length === 0) return null;
|
|
232
|
-
const out = [];
|
|
233
|
-
for (const entry of options) {
|
|
234
|
-
if (!isRecord(entry)) return null;
|
|
235
|
-
const key = entry["key"];
|
|
236
|
-
const inputs = entry["inputs"];
|
|
237
|
-
if (typeof key !== "string" || !isRecord(inputs)) return null;
|
|
238
|
-
out.push({
|
|
239
|
-
key,
|
|
240
|
-
inputs: flattenInputSections(inputs)
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
return out;
|
|
244
|
-
};
|
|
245
|
-
/**
|
|
246
|
-
* autogrow (`template` WITH a nested `input` section): instances are always
|
|
247
|
-
* link slots named `decl.<name_i>` (the backend force-inputs widget
|
|
248
|
-
* templates), the first `min` of them required WHEN the template input
|
|
249
|
-
* section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
|
|
250
|
-
*/
|
|
251
|
-
const parseContainer = (template) => {
|
|
252
|
-
const input = template["input"];
|
|
253
|
-
const min = typeof template["min"] === "number" ? template["min"] : 1;
|
|
254
|
-
const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
|
|
255
|
-
const max = typeof template["max"] === "number" ? template["max"] : 100;
|
|
256
|
-
const rawNames = template["names"];
|
|
257
|
-
const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
|
|
258
|
-
return {
|
|
259
|
-
kind: "dynamic-container",
|
|
260
|
-
instanceNames: names,
|
|
261
|
-
requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
|
|
262
|
-
};
|
|
263
|
-
};
|
|
264
|
-
/**
|
|
265
|
-
* the single template sub-input's slot type of an autogrow container
|
|
266
|
-
* (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
|
|
267
|
-
* autogrow template or the template has several sub-inputs (corpus-absent
|
|
268
|
-
* 2026-07-30, 27/27 single on the cloud catalog) — then codegen emits no
|
|
269
|
-
* typed instance keys and the container stays builderBase territory.
|
|
270
|
-
*/
|
|
271
|
-
const containerInstanceSlotType = (opts) => {
|
|
272
|
-
const template = (isRecord(opts) ? opts : null)?.["template"];
|
|
273
|
-
if (!isRecord(template) || !isRecord(template["input"])) return null;
|
|
274
|
-
const subs = flattenInputSections(template["input"]);
|
|
275
|
-
const first = subs[0];
|
|
276
|
-
if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
|
|
277
|
-
return first.type;
|
|
278
|
-
};
|
|
279
|
-
const classifyWidgetInput = (p) => {
|
|
280
|
-
const o = isRecord(p.opts) ? p.opts : null;
|
|
281
|
-
if (o?.["forceInput"] === true) return { kind: "slot" };
|
|
282
|
-
if (Array.isArray(p.type) || p.isEnumUnion === true) {
|
|
283
|
-
const tn = typeof p.type === "string" ? p.type : "COMBO";
|
|
284
|
-
return {
|
|
285
|
-
kind: "widget",
|
|
286
|
-
consumes: controlConsumes(o, tn, p.name),
|
|
287
|
-
strictValues: true
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
if (typeof p.type !== "string") return { kind: "slot" };
|
|
291
|
-
const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
|
|
292
|
-
if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
|
|
293
|
-
kind: "widget",
|
|
294
|
-
consumes: controlConsumes(o, widgetTypeName, p.name),
|
|
295
|
-
strictValues: true
|
|
296
|
-
};
|
|
297
|
-
const options = o?.["options"];
|
|
298
|
-
if (Array.isArray(options)) {
|
|
299
|
-
const dynOptions = parseDynamicOptions(options);
|
|
300
|
-
if (dynOptions != null) {
|
|
301
|
-
const first = dynOptions[0];
|
|
302
|
-
if (first == null) return { kind: "slot" };
|
|
303
|
-
return {
|
|
304
|
-
kind: "dynamic-combo",
|
|
305
|
-
options: dynOptions,
|
|
306
|
-
defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
return {
|
|
310
|
-
kind: "widget",
|
|
311
|
-
consumes: controlConsumes(o, p.type, p.name),
|
|
312
|
-
strictValues: true
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
const template = o?.["template"];
|
|
316
|
-
if (isRecord(template)) {
|
|
317
|
-
if (isRecord(template["input"])) return parseContainer(template);
|
|
318
|
-
return { kind: "slot" };
|
|
319
|
-
}
|
|
320
|
-
if (o?.["socketless"] === true) return {
|
|
321
|
-
kind: "widget",
|
|
322
|
-
consumes: 1,
|
|
323
|
-
strictValues: false
|
|
324
|
-
};
|
|
325
|
-
return { kind: "slot" };
|
|
326
|
-
};
|
|
327
|
-
const classifySchemaInput = (input) => classifyWidgetInput({
|
|
328
|
-
name: input.nameInComfy,
|
|
329
|
-
type: input.typeName,
|
|
330
|
-
opts: input.opts,
|
|
331
|
-
isEnumUnion: input.isEnum
|
|
332
|
-
});
|
|
333
|
-
/** how many widgets_values entries this schema input consumes (export path + positional walks) */
|
|
334
|
-
const howManyWidgetValuesForThisSchemaType = (input) => {
|
|
335
|
-
const kind = classifySchemaInput(input);
|
|
336
|
-
return kind.kind === "widget" ? kind.consumes : 0;
|
|
337
|
-
};
|
|
338
|
-
/**
|
|
339
|
-
* what ComfyUI's frontend gives a widget created with no serialized value
|
|
340
|
-
* (`getWidgetDefaultValue` semantics), used when a positional array is
|
|
341
|
-
* shorter than the schema's widget list. `null` for custom widgets — the
|
|
342
|
-
* backend accepts an explicit null but errors on an ABSENT required key.
|
|
343
|
-
*/
|
|
344
|
-
const defaultValueForWidget = (p) => {
|
|
345
|
-
const o = isRecord(p.opts) ? p.opts : null;
|
|
346
|
-
if (o != null && o["default"] !== void 0) return o["default"];
|
|
347
|
-
const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
|
|
348
|
-
if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
|
|
349
|
-
if (widgetTypeName === "BOOLEAN") return false;
|
|
350
|
-
if (widgetTypeName === "STRING") return "";
|
|
351
|
-
const options = o?.["options"];
|
|
352
|
-
if (Array.isArray(options) && options.length > 0) {
|
|
353
|
-
const first = options[0];
|
|
354
|
-
if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
|
|
355
|
-
}
|
|
356
|
-
if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
|
|
357
|
-
return null;
|
|
358
|
-
};
|
|
359
|
-
//#endregion
|
|
360
|
-
//#region src/sdk-generator/comfyui-sdk-codegen.ts
|
|
361
|
-
/**
|
|
362
|
-
* convert a host id to the namespace name it gets inside the global `Comfy` namespace
|
|
363
|
-
* e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
|
|
364
|
-
*/
|
|
365
|
-
function hostIdToNamespace(hostId) {
|
|
366
|
-
const ns = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
|
|
367
|
-
if (ns.length === 0) throw new Error(`cannot derive a namespace from host id "${hostId}"`);
|
|
368
|
-
return /^[0-9]/.test(ns) ? `Host${ns}` : ns;
|
|
369
|
-
}
|
|
370
|
-
/**
|
|
371
|
-
* emit the typed SDK for one host:
|
|
372
|
-
*
|
|
373
|
-
* declare global {
|
|
374
|
-
* namespace Comfy {
|
|
375
|
-
* namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }
|
|
376
|
-
* interface Hosts { '<host-id>': <HostNs>.Sdk }
|
|
377
|
-
* }
|
|
378
|
-
* }
|
|
379
|
-
*/
|
|
380
|
-
function codegenSDK(opts) {
|
|
381
|
-
const ns = hostIdToNamespace(opts.hostId);
|
|
382
|
-
const packageName = opts.packageName ?? "comfy-ts";
|
|
383
|
-
const b = new CodeBuffer();
|
|
384
|
-
const p = b.w;
|
|
385
|
-
p(`/** generated by comfy-ts for host "${opts.hostId}" — do not edit */`);
|
|
386
|
-
p(``);
|
|
387
|
-
p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`);
|
|
388
|
-
p(``);
|
|
389
|
-
p(`declare global {`);
|
|
390
|
-
b.indent();
|
|
391
|
-
p(`namespace Comfy {`);
|
|
392
|
-
b.indent();
|
|
393
|
-
p(`namespace ${ns} {`);
|
|
394
|
-
b.indent();
|
|
395
|
-
p(`// #region PythonModules`);
|
|
396
|
-
p(`/** list of all python modules installed on this host */`);
|
|
397
|
-
p(`export type PythonModules =`);
|
|
398
|
-
b.indent();
|
|
399
|
-
const pythonModulesArr = Array.from(this.pythonModules.entries()).toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
400
|
-
for (const [k, v] of pythonModulesArr) {
|
|
401
|
-
p(`/**`);
|
|
402
|
-
p(`* Nodes: ${v.join(", ")}`);
|
|
403
|
-
p(`*/`);
|
|
404
|
-
p(`| ${wrapQuote(k)}`);
|
|
405
|
-
}
|
|
406
|
-
b.deindent();
|
|
407
|
-
p(`// #endregion`);
|
|
408
|
-
const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
|
|
409
|
-
p(`interface IN {`);
|
|
410
|
-
b.indent();
|
|
411
|
-
for (const n of nodes) {
|
|
412
|
-
p(`${escapeJSKey(n.nodeKey)}: {`);
|
|
413
|
-
for (const i of n.inputs) {
|
|
414
|
-
const kind = classifySchemaInput(i);
|
|
415
|
-
if (kind.kind === "dynamic-container") {
|
|
416
|
-
const instType = containerInstanceSlotType(i.opts);
|
|
417
|
-
if (instType != null) kind.instanceNames.forEach((instName, ix) => {
|
|
418
|
-
const opt = ix >= kind.requiredCount ? "?" : "";
|
|
419
|
-
p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
|
|
420
|
-
});
|
|
421
|
-
continue;
|
|
422
|
-
}
|
|
423
|
-
const opts_ = typeof i.opts === "string" ? null : i.opts;
|
|
424
|
-
let type = `Accepts[${JSON.stringify(i.typeName)}]`;
|
|
425
|
-
const comboOptions = i.typeName === "COMBO" && Array.isArray(opts_?.options) ? opts_.options.filter((o) => typeof o === "string" || typeof o === "number" || typeof o === "boolean") : [];
|
|
426
|
-
if (comboOptions.length > 0) type = `${comboOptions.map((o) => JSON.stringify(o)).join(" | ")} | ${type}`;
|
|
427
|
-
else if (opts_ && !i.isPrimitive && !i.isEnum) {
|
|
428
|
-
if (typeof opts_.default === "string" || opts_.placeholder != null || opts_.multiline != null) type = `string | ${type}`;
|
|
429
|
-
else if (typeof opts_.default === "number") type = `number | ${type}`;
|
|
430
|
-
else if (typeof opts_.default === "boolean") type = `boolean | ${type}`;
|
|
431
|
-
}
|
|
432
|
-
if (opts_) {
|
|
433
|
-
const rendered = n.renderOpts(opts_);
|
|
434
|
-
if (rendered) p(` ${rendered}`);
|
|
435
|
-
}
|
|
436
|
-
const canBeOmmited = opts_?.default !== void 0 || !i.required;
|
|
437
|
-
p(` ${i.nameInComfyEscaped}${canBeOmmited ? "?" : ""}: ${type}`);
|
|
438
|
-
}
|
|
439
|
-
p(`},`);
|
|
440
|
-
}
|
|
441
|
-
b.deindent();
|
|
442
|
-
p("}");
|
|
443
|
-
p("");
|
|
444
|
-
p(`interface OUT {`);
|
|
445
|
-
b.indent();
|
|
446
|
-
for (const n of nodes) {
|
|
447
|
-
p(`${escapeJSKey(n.nodeKey)}: {`);
|
|
448
|
-
n.outputs.forEach((i, ix) => {
|
|
449
|
-
p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`);
|
|
450
|
-
});
|
|
451
|
-
p(`}`);
|
|
452
|
-
}
|
|
453
|
-
b.deindent();
|
|
454
|
-
p("}");
|
|
455
|
-
p(`interface Node {`);
|
|
456
|
-
for (const n of nodes) {
|
|
457
|
-
p(` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`);
|
|
458
|
-
for (const hassingle of n.singleOutputs) p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`);
|
|
459
|
-
p(` }`);
|
|
460
|
-
}
|
|
461
|
-
p("}");
|
|
462
|
-
p(`interface Builder {`);
|
|
463
|
-
for (const n of nodes) {
|
|
464
|
-
const baseDescription = `displayName="${n.raw.display_name}" category="${n.category}" name="${n.nameInComfy}" output=[${n.outputs.map((o) => o.outKey).join(", ")}]`;
|
|
465
|
-
if (n.raw.description) {
|
|
466
|
-
p(` /**`);
|
|
467
|
-
p(n.raw.description.split("\n").map((i) => ` * ${i}`).join("\n"));
|
|
468
|
-
p(` * ${baseDescription}`);
|
|
469
|
-
p(` **/`);
|
|
470
|
-
} else p(` /** ${baseDescription} */`);
|
|
471
|
-
p(` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`);
|
|
472
|
-
}
|
|
473
|
-
p(`}`);
|
|
474
|
-
p(`interface Slots {`);
|
|
475
|
-
for (const e of this.knownUnionByHash.values()) {
|
|
476
|
-
p(" // " + e.unionName);
|
|
477
|
-
for (const alias of e.enumNames) p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`);
|
|
478
|
-
}
|
|
479
|
-
p(`}`);
|
|
480
|
-
p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(" | ") || "\"\""}`);
|
|
481
|
-
const slotTypes = [...this.knownSlotTypes.values()].map((comfyType) => ({
|
|
482
|
-
comfyType,
|
|
483
|
-
tsType: this.toTSType(comfyType),
|
|
484
|
-
tsType2: this.toAcceptsType(comfyType)
|
|
485
|
-
})).sort((a, b) => b.tsType.length - a.tsType.length);
|
|
486
|
-
p("");
|
|
487
|
-
p("interface Producer {");
|
|
488
|
-
b.indent();
|
|
489
|
-
for (const tp of slotTypes) {
|
|
490
|
-
const allProducingNodes = this.nodesByProduction[tp.comfyType];
|
|
491
|
-
if (allProducingNodes) p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(" | ")}>`);
|
|
492
|
-
else p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`);
|
|
493
|
-
}
|
|
494
|
-
b.deindent();
|
|
495
|
-
p("}");
|
|
496
|
-
p(`interface Accepts {`);
|
|
497
|
-
b.indent();
|
|
498
|
-
p("// injected bottom type (broken/null input specs land here)");
|
|
499
|
-
p(`INVALID_null: any`);
|
|
500
|
-
p("");
|
|
501
|
-
p("// named slot types: everything an input of that type accepts");
|
|
502
|
-
for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
|
|
503
|
-
p("");
|
|
504
|
-
p("// enum unions: literal values or an output carrying one");
|
|
505
|
-
for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
|
|
506
|
-
b.deindent();
|
|
507
|
-
p(`}\n`);
|
|
508
|
-
p("interface Union {");
|
|
509
|
-
for (const e of this.knownUnionByHash.values()) if (e.values.length > 0) {
|
|
510
|
-
p(` // ${JSON.stringify(e.enumNames)}`);
|
|
511
|
-
p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(" | ")}`);
|
|
512
|
-
} else p(` ${e.unionName}: '🔴' // never`);
|
|
513
|
-
p("}");
|
|
514
|
-
p(`export interface HasSingle {`);
|
|
515
|
-
for (const t of slotTypes) p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`);
|
|
516
|
-
p(`}`);
|
|
517
|
-
for (const t of this.enumsAppearingInOutput.values()) p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`);
|
|
518
|
-
p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`);
|
|
519
|
-
p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(" | ")}`);
|
|
520
|
-
p(``);
|
|
521
|
-
p(`/** everything above, packaged for the Comfy.Hosts registry */`);
|
|
522
|
-
p(`interface Sdk {`);
|
|
523
|
-
p(` IN: IN`);
|
|
524
|
-
p(` OUT: OUT`);
|
|
525
|
-
p(` Node: Node`);
|
|
526
|
-
p(` Builder: Builder`);
|
|
527
|
-
p(` Slots: Slots`);
|
|
528
|
-
p(` Accepts: Accepts`);
|
|
529
|
-
p(` Union: Union`);
|
|
530
|
-
p(` Producer: Producer`);
|
|
531
|
-
p(` Embeddings: Embeddings`);
|
|
532
|
-
p(` Schemas: Schemas`);
|
|
533
|
-
p(` NodeType: NodeType`);
|
|
534
|
-
p(`}`);
|
|
535
|
-
b.deindent();
|
|
536
|
-
p(`}`);
|
|
537
|
-
p(``);
|
|
538
|
-
p(`interface Hosts {`);
|
|
539
|
-
p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`);
|
|
540
|
-
p(`}`);
|
|
541
|
-
b.deindent();
|
|
542
|
-
p("}");
|
|
543
|
-
b.deindent();
|
|
544
|
-
p("}");
|
|
545
|
-
p(``);
|
|
546
|
-
p(`export {}`);
|
|
547
|
-
return b.content;
|
|
548
|
-
}
|
|
549
|
-
//#endregion
|
|
550
|
-
//#region src/sdk-generator/comfyui-types.ts
|
|
551
|
-
const asComfyNodeSlotTypeName = (x) => x;
|
|
552
|
-
const asComfyNodeSlotName = (x) => x;
|
|
553
|
-
//#endregion
|
|
554
|
-
//#region src/sdk-generator/ComfySchema.ts
|
|
555
|
-
/**
|
|
556
|
-
* ONE host's schema: the parsed view of its object_info.json + embeddings.
|
|
557
|
-
* Owns union dedup (by sha1 of values), node indexing, and the per-host
|
|
558
|
-
* sdk codegen (`codegenDTS`).
|
|
559
|
-
*/
|
|
560
|
-
var ComfySchema = class {
|
|
561
|
-
constructor(data) {
|
|
562
|
-
this.data = data;
|
|
563
|
-
this.codegenDTS = codegenSDK.bind(this);
|
|
564
|
-
this.isInvalid = false;
|
|
565
|
-
this.knownSlotTypes = /* @__PURE__ */ new Set();
|
|
566
|
-
this.knownUnionBySlotName = /* @__PURE__ */ new Map();
|
|
567
|
-
this.knownUnionByHash = /* @__PURE__ */ new Map();
|
|
568
|
-
this.knownUnionByName = /* @__PURE__ */ new Map();
|
|
569
|
-
this.nodes = [];
|
|
570
|
-
this.pythonModuleByNodeKey = /* @__PURE__ */ new Map();
|
|
571
|
-
this.pythonModuleByNodeNameInComfy = /* @__PURE__ */ new Map();
|
|
572
|
-
this.nodesByNameInComfy = {};
|
|
573
|
-
this.nodesByKey = {};
|
|
574
|
-
this.nodesByProduction = {};
|
|
575
|
-
this.enumsAppearingInOutput = /* @__PURE__ */ new Set();
|
|
576
|
-
this.pythonModules = /* @__PURE__ */ new Map();
|
|
577
|
-
this.processSlot = (p) => {
|
|
578
|
-
const enumValues = [];
|
|
579
|
-
for (const enumValue of p.comfyUnionDef) if (typeof enumValue === "string") enumValues.push(enumValue);
|
|
580
|
-
else if (typeof enumValue === "boolean") enumValues.push(enumValue);
|
|
581
|
-
else if (typeof enumValue === "number") enumValues.push(enumValue);
|
|
582
|
-
else enumValues.push(enumValue.content);
|
|
583
|
-
const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
|
|
584
|
-
const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
|
|
585
|
-
let unionInfo = this.knownUnionByHash.get(hash);
|
|
586
|
-
if (unionInfo == null) {
|
|
587
|
-
const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
|
|
588
|
-
unionInfo = {
|
|
589
|
-
hash,
|
|
590
|
-
unionName,
|
|
591
|
-
values: enumValues,
|
|
592
|
-
enumNames: []
|
|
593
|
-
};
|
|
594
|
-
this.knownUnionByHash.set(hash, unionInfo);
|
|
595
|
-
this.knownUnionByName.set(unionName, unionInfo);
|
|
596
|
-
}
|
|
597
|
-
unionInfo.enumNames.push(p.slotName);
|
|
598
|
-
this.knownUnionBySlotName.set(p.slotName, unionInfo);
|
|
599
|
-
return unionInfo;
|
|
600
|
-
};
|
|
601
|
-
this.RUN_BASIC_CHECKS = () => {
|
|
602
|
-
const numNodesInSource = Object.keys(this.data.spec).length;
|
|
603
|
-
const numNodesInSchema = this.nodes.length - 1;
|
|
604
|
-
if (numNodesInSource !== numNodesInSchema) console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`);
|
|
605
|
-
};
|
|
606
|
-
this.getLoras = (filter) => {
|
|
607
|
-
const all = this.stringValues("LoraLoader.lora_name");
|
|
608
|
-
return filter == null ? all : all.filter((n) => filter.test(n));
|
|
609
|
-
};
|
|
610
|
-
this.getImages = () => {
|
|
611
|
-
return this.stringValues("LoadImage.image");
|
|
612
|
-
};
|
|
613
|
-
this.unsafely_addImageInSchemaWithoutReloading = (imgName) => {
|
|
614
|
-
const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName("LoadImage.image"));
|
|
615
|
-
if (enumInfo == null) throw new Error(`LoadImage.image not found`);
|
|
616
|
-
enumInfo.values.push(imgName);
|
|
617
|
-
};
|
|
618
|
-
this.getCheckpoints = () => {
|
|
619
|
-
return this.stringValues("CheckpointLoaderSimple.ckpt_name");
|
|
620
|
-
};
|
|
621
|
-
this.parse();
|
|
622
|
-
}
|
|
623
|
-
update(data) {
|
|
624
|
-
const prev = {
|
|
625
|
-
spec: this.data.spec,
|
|
626
|
-
embeddings: this.data.embeddings
|
|
627
|
-
};
|
|
628
|
-
Object.assign(this.data, data);
|
|
629
|
-
try {
|
|
630
|
-
this.parse();
|
|
631
|
-
this.isInvalid = false;
|
|
632
|
-
} catch (error) {
|
|
633
|
-
console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error);
|
|
634
|
-
this.data = prev;
|
|
635
|
-
try {
|
|
636
|
-
this.parse();
|
|
637
|
-
} catch {}
|
|
638
|
-
this.isInvalid = true;
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
/** number of nodes in the current schema (quick way to check your instance infos) */
|
|
642
|
-
get size() {
|
|
643
|
-
return Object.keys(this.data.spec).length;
|
|
644
|
-
}
|
|
645
|
-
parse() {
|
|
646
|
-
this.knownSlotTypes.clear();
|
|
647
|
-
this.knownUnionBySlotName.clear();
|
|
648
|
-
this.knownUnionByHash.clear();
|
|
649
|
-
this.knownUnionByName.clear();
|
|
650
|
-
this.nodes = [];
|
|
651
|
-
this.pythonModuleByNodeKey.clear();
|
|
652
|
-
this.pythonModuleByNodeNameInComfy.clear();
|
|
653
|
-
this.nodesByNameInComfy = {};
|
|
654
|
-
this.nodesByKey = {};
|
|
655
|
-
this.nodesByProduction = {};
|
|
656
|
-
this.enumsAppearingInOutput.clear();
|
|
657
|
-
this.pythonModules.clear();
|
|
658
|
-
if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0) this.log(`parsing ComfyUI object_info.json`);
|
|
659
|
-
const entries = Object.entries(this.data.spec);
|
|
660
|
-
entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema]);
|
|
661
|
-
for (const [KK, VV] of entries) {
|
|
662
|
-
const pythonModule = VV.python_module;
|
|
663
|
-
const prev = this.pythonModules.get(pythonModule);
|
|
664
|
-
if (prev == null) this.pythonModules.set(pythonModule, [KK]);
|
|
665
|
-
else prev.push(KK);
|
|
666
|
-
const nodeNameInComfy = KK;
|
|
667
|
-
const nodeDef = VV;
|
|
668
|
-
const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy);
|
|
669
|
-
if (typeof nodeDef.output === "string") {
|
|
670
|
-
console.log(`[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`);
|
|
671
|
-
nodeDef.output = [];
|
|
672
|
-
}
|
|
673
|
-
this.pythonModuleByNodeKey.set(nodeKey, pythonModule);
|
|
674
|
-
this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule);
|
|
675
|
-
const inputs = [];
|
|
676
|
-
const outputs = [];
|
|
677
|
-
const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule);
|
|
678
|
-
this.nodesByNameInComfy[nodeNameInComfy] = node;
|
|
679
|
-
this.nodesByKey[nodeKey] = node;
|
|
680
|
-
this.nodes.push(node);
|
|
681
|
-
const nameCountDict = {};
|
|
682
|
-
for (const [ix, slotType] of nodeDef.output.entries()) {
|
|
683
|
-
const outputNameInComfy = nodeDef.output_name[ix] || (typeof slotType === "string" ? slotType : `input_${ix}`);
|
|
684
|
-
const at = nameCountDict[outputNameInComfy] ??= 0;
|
|
685
|
-
const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`;
|
|
686
|
-
nameCountDict[outputNameInComfy]++;
|
|
687
|
-
let slotTypeName;
|
|
688
|
-
const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`);
|
|
689
|
-
if (typeof slotType === "string") {
|
|
690
|
-
slotTypeName = asComfyNodeSlotTypeName(slotType);
|
|
691
|
-
this.knownSlotTypes.add(slotTypeName);
|
|
692
|
-
} else if (Array.isArray(slotType)) {
|
|
693
|
-
slotTypeName = asComfyNodeSlotTypeName(this.processSlot({
|
|
694
|
-
pythonModule,
|
|
695
|
-
slotName: outputSlotName,
|
|
696
|
-
comfyUnionDef: slotType
|
|
697
|
-
}).unionName);
|
|
698
|
-
this.enumsAppearingInOutput.add(slotTypeName);
|
|
699
|
-
} else throw new Error(`invalid output ${ix} "${slotType}" in node "${nodeNameInComfy}"`);
|
|
700
|
-
const arr = this.nodesByProduction[slotTypeName];
|
|
701
|
-
if (arr == null) this.nodesByProduction[slotTypeName] = [node];
|
|
702
|
-
else arr.push(node);
|
|
703
|
-
outputs.push({
|
|
704
|
-
slotName: outputSlotName,
|
|
705
|
-
typeName: slotTypeName,
|
|
706
|
-
nameInComfy: outputNameInComfy,
|
|
707
|
-
outKey: outKeyValue,
|
|
708
|
-
isPrimitive: false
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}).map(([name, spec]) => ({
|
|
712
|
-
required: false,
|
|
713
|
-
name,
|
|
714
|
-
spec
|
|
715
|
-
}));
|
|
716
|
-
const allInputs = [...Object.entries(nodeDef.input?.required ?? {}).map(([name, spec]) => ({
|
|
717
|
-
required: true,
|
|
718
|
-
name,
|
|
719
|
-
spec
|
|
720
|
-
})).filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null), ...optionalInputs];
|
|
721
|
-
for (const ipt of allInputs) {
|
|
722
|
-
const inputNameInComfy = ipt.name;
|
|
723
|
-
const typeDef = ipt.spec;
|
|
724
|
-
const slotType = typeDef[0];
|
|
725
|
-
const slotOpts = typeDef[1];
|
|
726
|
-
let inputTypeName;
|
|
727
|
-
const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`);
|
|
728
|
-
if (slotType == null) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
|
|
729
|
-
pythonModule,
|
|
730
|
-
slotName: inputSlotName,
|
|
731
|
-
comfyUnionDef: ["❌"]
|
|
732
|
-
}).unionName);
|
|
733
|
-
else if (typeof slotType === "string") {
|
|
734
|
-
inputTypeName = asComfyNodeSlotTypeName(slotType);
|
|
735
|
-
this.knownSlotTypes.add(inputTypeName);
|
|
736
|
-
} else if (Array.isArray(slotType)) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
|
|
737
|
-
pythonModule,
|
|
738
|
-
slotName: inputSlotName,
|
|
739
|
-
comfyUnionDef: slotType
|
|
740
|
-
}).unionName);
|
|
741
|
-
else throw new Error(`invalid schema (${JSON.stringify(slotType)}) for input "${ipt.name}" in node "${nodeNameInComfy}" (type: ${typeof slotType}; expected: Array | string)`);
|
|
742
|
-
const isAutogrowContainer = typeof slotType === "string" && classifyWidgetInput({
|
|
743
|
-
name: ipt.name,
|
|
744
|
-
type: slotType,
|
|
745
|
-
opts: slotOpts
|
|
746
|
-
}).kind === "dynamic-container";
|
|
747
|
-
if (isAutogrowContainer) {
|
|
748
|
-
const instType = containerInstanceSlotType(slotOpts);
|
|
749
|
-
if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType));
|
|
750
|
-
}
|
|
751
|
-
node.inputs.push({
|
|
752
|
-
slotName: inputSlotName,
|
|
753
|
-
required: ipt.required && !isAutogrowContainer,
|
|
754
|
-
nameInComfy: inputNameInComfy,
|
|
755
|
-
nameInComfyEscaped: escapeJSKey(inputNameInComfy),
|
|
756
|
-
typeName: inputTypeName,
|
|
757
|
-
opts: slotOpts,
|
|
758
|
-
isPrimitive: ComfyPrimitives.includes(inputTypeName),
|
|
759
|
-
isEnum: this.knownUnionByName.has(inputTypeName),
|
|
760
|
-
index: node.inputs.length
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
log(...args) {
|
|
766
|
-
logInfo(`[👅]: ${args.join(" ")}`);
|
|
767
|
-
}
|
|
768
|
-
toTSType(t) {
|
|
769
|
-
if (t === "*") return `string | number | boolean | ComfyNodeOutput<string, number>`;
|
|
770
|
-
return ComfyPrimitiveMapping[t] ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>` : `ComfyNodeOutput<'${t}'>`;
|
|
771
|
-
}
|
|
772
|
-
toAcceptsType(t) {
|
|
773
|
-
return `ComfyNodeOutput<'${t}'>`;
|
|
774
|
-
}
|
|
775
|
-
/**
|
|
776
|
-
* every possible value for a given slot, straight from the live schema.
|
|
777
|
-
* e.g. schema.values('LoraLoader.lora_name') -> all loras on this host
|
|
778
|
-
*/
|
|
779
|
-
values(slotName) {
|
|
780
|
-
return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? [];
|
|
781
|
-
}
|
|
782
|
-
/** string values only (most enums are), for quick discovery */
|
|
783
|
-
stringValues(slotName) {
|
|
784
|
-
return this.values(slotName).filter((v) => typeof v === "string");
|
|
785
|
-
}
|
|
786
|
-
hasEmbedding(embedding) {
|
|
787
|
-
return this.data.embeddings.includes(embedding);
|
|
788
|
-
}
|
|
789
|
-
hasLora(loraName) {
|
|
790
|
-
return this.getLoras().includes(loraName);
|
|
791
|
-
}
|
|
792
|
-
hasImage(imgName) {
|
|
793
|
-
return this.getImages().includes(imgName);
|
|
794
|
-
}
|
|
795
|
-
hasCheckpoint(ckptName) {
|
|
796
|
-
return this.getCheckpoints().includes(ckptName);
|
|
797
|
-
}
|
|
798
|
-
};
|
|
799
|
-
//#endregion
|
|
800
|
-
//#region package.json
|
|
801
|
-
var version = "1.1.0";
|
|
802
|
-
//#endregion
|
|
803
|
-
//#region src/litegraph/LiteGraphLinkID.ts
|
|
804
|
-
const asLiteGraphLinkID = (id) => id;
|
|
805
|
-
const LiteGraphLinkID_ = type.number.atLeast(0).as();
|
|
806
|
-
//#endregion
|
|
807
|
-
//#region src/utils/bang.ts
|
|
808
|
-
/** assertNotNull */
|
|
809
|
-
const bang = (x, msg = "") => {
|
|
810
|
-
if (x == null) {
|
|
811
|
-
console.error(`[🔴] BANG FAILED`, msg);
|
|
812
|
-
throw new Error("bang: " + (msg ?? "no message"));
|
|
813
|
-
}
|
|
814
|
-
return x;
|
|
815
|
-
};
|
|
816
|
-
//#endregion
|
|
817
|
-
//#region src/litegraph/expandSubgraphs.ts
|
|
818
|
-
/** boundary sentinel ids inside definition link tables */
|
|
819
|
-
const SUBGRAPH_INPUT_NODE_ID = -10;
|
|
820
|
-
const SUBGRAPH_OUTPUT_NODE_ID = -20;
|
|
821
|
-
/** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
|
|
822
|
-
const MAX_EXPANSION_PASSES = 32;
|
|
823
|
-
/**
|
|
824
|
-
* widget-kind fallback when a def input slot has no boundary target carrying a
|
|
825
|
-
* widget marker: these litegraph slot types carry widget values. LOCAL copy on
|
|
826
|
-
* purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
|
|
827
|
-
* (the io-widget era serializes exactly one value per exposed widget slot).
|
|
828
|
-
*/
|
|
829
|
-
const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
|
|
830
|
-
"INT",
|
|
831
|
-
"FLOAT",
|
|
832
|
-
"STRING",
|
|
833
|
-
"BOOLEAN",
|
|
834
|
-
"COMBO"
|
|
835
|
-
]);
|
|
836
|
-
/**
|
|
837
|
-
* inline every subgraph instance (node whose `type` is a definition uuid) into
|
|
838
|
-
* the root graph: fresh numeric ids, boundary links rewired, instance widget
|
|
839
|
-
* values promoted into the inner nodes' `named` overrides. Iterative so nested
|
|
840
|
-
* definitions expand on the next pass. Muted instances are dropped (their
|
|
841
|
-
* consumers resolve unconnected); bypassed instances stay for the converter's
|
|
842
|
-
* passthrough walk, which needs no interior.
|
|
843
|
-
*/
|
|
844
|
-
const expandSubgraphs = (wf, defs) => {
|
|
845
|
-
let passes = 0;
|
|
846
|
-
while (true) {
|
|
847
|
-
const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
|
|
848
|
-
if (expandable.length === 0) return wf;
|
|
849
|
-
if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
|
|
850
|
-
for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
|
|
851
|
-
else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
|
|
852
|
-
}
|
|
853
|
-
};
|
|
854
|
-
/** converter mute semantics applied early: after expansion there is no single node left to skip */
|
|
855
|
-
const dropMutedInstance = (wf, instance) => {
|
|
856
|
-
const dead = /* @__PURE__ */ new Set();
|
|
857
|
-
for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
|
|
858
|
-
wf.links = wf.links.filter((l) => !dead.has(l.id));
|
|
859
|
-
wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
|
|
860
|
-
pruneDeadLinkRefs(wf, dead);
|
|
861
|
-
};
|
|
862
|
-
const pruneDeadLinkRefs = (wf, dead) => {
|
|
863
|
-
if (dead.size === 0) return;
|
|
864
|
-
for (const node of wf.nodes) {
|
|
865
|
-
for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
|
|
866
|
-
for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
|
|
867
|
-
}
|
|
868
|
-
};
|
|
869
|
-
const expandOneInstance = (wf, instance, def) => {
|
|
870
|
-
let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
|
|
871
|
-
let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
|
|
872
|
-
const newNodeIds = /* @__PURE__ */ new Map();
|
|
873
|
-
for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
|
|
874
|
-
const remapNodeId = (id) => newNodeIds.get(id) ?? null;
|
|
875
|
-
const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
|
|
876
|
-
for (const [k, input] of instance.inputs.entries()) {
|
|
877
|
-
const defSlot = def.inputs.findIndex((d) => d.name === input.name);
|
|
878
|
-
if (defSlot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): input "${input.name}" (slot ${k}) matches no definition input (defined: ${def.inputs.map((d) => d.name).join(", ")})`);
|
|
879
|
-
defSlotOfInstanceSlot.set(k, defSlot);
|
|
880
|
-
}
|
|
881
|
-
const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
|
|
882
|
-
for (const link of wf.links) {
|
|
883
|
-
if (link.targetId !== instance.id) continue;
|
|
884
|
-
const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
|
|
885
|
-
if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
|
|
886
|
-
outerLinkIntoDefSlot.set(defSlot, link);
|
|
887
|
-
}
|
|
888
|
-
const newLinkIds = /* @__PURE__ */ new Map();
|
|
889
|
-
const splicedLinks = [];
|
|
890
|
-
const producerByOutSlot = /* @__PURE__ */ new Map();
|
|
891
|
-
const passthroughOutSlot = /* @__PURE__ */ new Map();
|
|
892
|
-
const boundaryTargetsByInSlot = /* @__PURE__ */ new Map();
|
|
893
|
-
for (const link of def.links) {
|
|
894
|
-
const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID;
|
|
895
|
-
const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID;
|
|
896
|
-
if (fromInputBoundary && toOutputBoundary) {
|
|
897
|
-
passthroughOutSlot.set(link.targetSlot, link.originSlot);
|
|
898
|
-
continue;
|
|
899
|
-
}
|
|
900
|
-
if (toOutputBoundary) {
|
|
901
|
-
const producerId = remapNodeId(link.originId);
|
|
902
|
-
if (producerId != null && !producerByOutSlot.has(link.targetSlot)) producerByOutSlot.set(link.targetSlot, {
|
|
903
|
-
nodeId: producerId,
|
|
904
|
-
slot: link.originSlot
|
|
905
|
-
});
|
|
906
|
-
continue;
|
|
907
|
-
}
|
|
908
|
-
if (fromInputBoundary) {
|
|
909
|
-
const targetId = remapNodeId(link.targetId);
|
|
910
|
-
if (targetId == null) continue;
|
|
911
|
-
const target = {
|
|
912
|
-
nodeId: targetId,
|
|
913
|
-
slot: link.targetSlot
|
|
914
|
-
};
|
|
915
|
-
const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? [];
|
|
916
|
-
targets.push(target);
|
|
917
|
-
boundaryTargetsByInSlot.set(link.originSlot, targets);
|
|
918
|
-
const outer = outerLinkIntoDefSlot.get(link.originSlot);
|
|
919
|
-
if (outer == null) continue;
|
|
920
|
-
const fresh = asLiteGraphLinkID(++nextLinkId);
|
|
921
|
-
newLinkIds.set(link.id, fresh);
|
|
922
|
-
splicedLinks.push({
|
|
923
|
-
id: fresh,
|
|
924
|
-
originId: outer.originId,
|
|
925
|
-
originSlot: outer.originSlot,
|
|
926
|
-
targetId: target.nodeId,
|
|
927
|
-
targetSlot: target.slot,
|
|
928
|
-
type: link.type
|
|
929
|
-
});
|
|
930
|
-
wf.nodes.find((n) => n.id === outer.originId)?.outputs[outer.originSlot]?.links.push(fresh);
|
|
931
|
-
continue;
|
|
932
|
-
}
|
|
933
|
-
const interiorOrigin = remapNodeId(link.originId);
|
|
934
|
-
const interiorTarget = remapNodeId(link.targetId);
|
|
935
|
-
if (interiorOrigin == null || interiorTarget == null) continue;
|
|
936
|
-
const fresh = asLiteGraphLinkID(++nextLinkId);
|
|
937
|
-
newLinkIds.set(link.id, fresh);
|
|
938
|
-
splicedLinks.push({
|
|
939
|
-
id: fresh,
|
|
940
|
-
originId: interiorOrigin,
|
|
941
|
-
originSlot: link.originSlot,
|
|
942
|
-
targetId: interiorTarget,
|
|
943
|
-
targetSlot: link.targetSlot,
|
|
944
|
-
type: link.type
|
|
945
|
-
});
|
|
946
|
-
}
|
|
947
|
-
const splicedNodes = def.nodes.map((inner) => ({
|
|
948
|
-
id: bang(newNodeIds.get(inner.id)),
|
|
949
|
-
type: inner.type,
|
|
950
|
-
title: inner.title,
|
|
951
|
-
mode: inner.mode,
|
|
952
|
-
isVirtualNode: inner.isVirtualNode,
|
|
953
|
-
inputs: inner.inputs.map((i) => ({
|
|
954
|
-
name: i.name,
|
|
955
|
-
type: i.type,
|
|
956
|
-
link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
|
|
957
|
-
widgetName: i.widgetName
|
|
958
|
-
})),
|
|
959
|
-
outputs: inner.outputs.map((o) => ({
|
|
960
|
-
name: o.name,
|
|
961
|
-
type: o.type,
|
|
962
|
-
links: o.links.map((id) => newLinkIds.get(id)).filter((id) => id != null)
|
|
963
|
-
})),
|
|
964
|
-
widgets: {
|
|
965
|
-
positional: [...inner.widgets.positional],
|
|
966
|
-
named: { ...inner.widgets.named }
|
|
967
|
-
},
|
|
968
|
-
pos: [inner.pos[0], inner.pos[1]],
|
|
969
|
-
size: [inner.size[0], inner.size[1]],
|
|
970
|
-
properties: { ...inner.properties }
|
|
971
|
-
}));
|
|
972
|
-
const dead = /* @__PURE__ */ new Set();
|
|
973
|
-
for (const link of wf.links) {
|
|
974
|
-
if (link.targetId === instance.id) {
|
|
975
|
-
dead.add(link.id);
|
|
976
|
-
continue;
|
|
977
|
-
}
|
|
978
|
-
if (link.originId !== instance.id) continue;
|
|
979
|
-
const producer = producerByOutSlot.get(link.originSlot);
|
|
980
|
-
if (producer != null) {
|
|
981
|
-
link.originId = producer.nodeId;
|
|
982
|
-
link.originSlot = producer.slot;
|
|
983
|
-
splicedNodes.find((n) => n.id === producer.nodeId)?.outputs[producer.slot]?.links.push(link.id);
|
|
984
|
-
continue;
|
|
985
|
-
}
|
|
986
|
-
const passthroughInSlot = passthroughOutSlot.get(link.originSlot);
|
|
987
|
-
const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null;
|
|
988
|
-
if (outer != null) {
|
|
989
|
-
link.originId = outer.originId;
|
|
990
|
-
link.originSlot = outer.originSlot;
|
|
991
|
-
continue;
|
|
992
|
-
}
|
|
993
|
-
dead.add(link.id);
|
|
994
|
-
}
|
|
995
|
-
wf.links = wf.links.filter((l) => !dead.has(l.id));
|
|
996
|
-
pruneDeadLinkRefs(wf, dead);
|
|
997
|
-
promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
|
|
998
|
-
wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
|
|
999
|
-
wf.nodes.push(...splicedNodes);
|
|
1000
|
-
wf.links.push(...splicedLinks);
|
|
1001
|
-
};
|
|
1002
|
-
/**
|
|
1003
|
-
* instance widget values land in inner nodes' `named` overrides. TWO eras for
|
|
1004
|
-
* the POSITIONAL values:
|
|
1005
|
-
* - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]
|
|
1006
|
-
* zip against the instance's positional values (incl. `control_after_generate`
|
|
1007
|
-
* phantom pairs — written to `named` and simply never read, no schema input
|
|
1008
|
-
* has that name).
|
|
1009
|
-
* - io-widget era (no proxyWidgets): positional values zip against the def's
|
|
1010
|
-
* widget-kind input slots in def order, one value per slot (no phantom —
|
|
1011
|
-
* corpus-verified). An outer link into the same slot wins in the converter;
|
|
1012
|
-
* the named override is still written, matching ComfyUI.
|
|
1013
|
-
* PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:
|
|
1014
|
-
* that is how a NESTED instance receives its outer values (the previous pass
|
|
1015
|
-
* wrote them to `named`), so they must forward through THIS expansion too —
|
|
1016
|
-
* named wins over positional, same precedence as the converter.
|
|
1017
|
-
*/
|
|
1018
|
-
const promoteInstanceWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot) => {
|
|
1019
|
-
const promoteToSlotTargets = (slot, value) => {
|
|
1020
|
-
for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {
|
|
1021
|
-
const target = splicedNodes.find((n) => n.id === t.nodeId);
|
|
1022
|
-
const input = innerInputAt(splicedNodes, t);
|
|
1023
|
-
if (target == null || input == null) continue;
|
|
1024
|
-
target.widgets.named[input.name] = value;
|
|
1025
|
-
}
|
|
1026
|
-
};
|
|
1027
|
-
promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets);
|
|
1028
|
-
for (const [slot, io] of def.inputs.entries()) {
|
|
1029
|
-
if (!Object.hasOwn(instance.widgets.named, io.name)) continue;
|
|
1030
|
-
promoteToSlotTargets(slot, instance.widgets.named[io.name]);
|
|
1031
|
-
}
|
|
1032
|
-
};
|
|
1033
|
-
const promotePositionalWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets) => {
|
|
1034
|
-
const values = instance.widgets.positional;
|
|
1035
|
-
if (values.length === 0) return;
|
|
1036
|
-
const proxy = instance.properties["proxyWidgets"];
|
|
1037
|
-
if (Array.isArray(proxy) && proxy.length > 0) {
|
|
1038
|
-
const count = Math.min(values.length, proxy.length);
|
|
1039
|
-
for (let k = 0; k < count; k++) {
|
|
1040
|
-
const pair = proxy[k];
|
|
1041
|
-
if (!Array.isArray(pair) || pair.length !== 2) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): malformed proxyWidgets entry ${JSON.stringify(pair)}`);
|
|
1042
|
-
const innerId = Number(pair[0]);
|
|
1043
|
-
const widgetName = String(pair[1]);
|
|
1044
|
-
if (innerId < 0) {
|
|
1045
|
-
const slot = def.inputs.findIndex((d) => d.name === widgetName);
|
|
1046
|
-
if (slot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names io widget "${widgetName}" but no definition input matches`);
|
|
1047
|
-
promoteToSlotTargets(slot, values[k]);
|
|
1048
|
-
continue;
|
|
1049
|
-
}
|
|
1050
|
-
const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId));
|
|
1051
|
-
if (target == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names unknown inner node ${String(pair[0])}`);
|
|
1052
|
-
target.widgets.named[widgetName] = values[k];
|
|
1053
|
-
}
|
|
1054
|
-
return;
|
|
1055
|
-
}
|
|
1056
|
-
let valueIndex = 0;
|
|
1057
|
-
for (const [slot, io] of def.inputs.entries()) {
|
|
1058
|
-
const targets = boundaryTargetsByInSlot.get(slot) ?? [];
|
|
1059
|
-
if (!(targets.length > 0 ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null) : PRIMITIVE_WIDGET_TYPES.has(io.type))) continue;
|
|
1060
|
-
if (valueIndex >= values.length) break;
|
|
1061
|
-
promoteToSlotTargets(slot, values[valueIndex++]);
|
|
1062
|
-
}
|
|
1063
|
-
};
|
|
1064
|
-
const innerInputAt = (splicedNodes, t) => {
|
|
1065
|
-
return splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot] ?? null;
|
|
1066
|
-
};
|
|
1067
|
-
//#endregion
|
|
1068
|
-
//#region src/litegraph/LiteGraphGroup.ts
|
|
1069
|
-
const LiteGraphGroup_ark = type({
|
|
1070
|
-
"id?": "number",
|
|
1071
|
-
title: "string",
|
|
1072
|
-
bounding: type([
|
|
1073
|
-
"number",
|
|
1074
|
-
"number",
|
|
1075
|
-
"number",
|
|
1076
|
-
"number"
|
|
1077
|
-
]),
|
|
1078
|
-
"color?": "string",
|
|
1079
|
-
"font_size?": "number",
|
|
1080
|
-
"flags?": type.Record("string", "unknown").as()
|
|
1081
|
-
});
|
|
1082
|
-
//#endregion
|
|
1083
|
-
//#region src/litegraph/LiteGraphLink.ts
|
|
1084
|
-
const LiteGraphLinkTuple_ark = type([
|
|
1085
|
-
LiteGraphLinkID_,
|
|
1086
|
-
"number",
|
|
1087
|
-
"number",
|
|
1088
|
-
"number",
|
|
1089
|
-
"number",
|
|
1090
|
-
"string"
|
|
1091
|
-
]);
|
|
1092
|
-
const LiteGraphLinkObject_ark = type({
|
|
1093
|
-
id: LiteGraphLinkID_,
|
|
1094
|
-
origin_id: "number",
|
|
1095
|
-
origin_slot: "number",
|
|
1096
|
-
target_id: "number",
|
|
1097
|
-
target_slot: "number",
|
|
1098
|
-
type: "string",
|
|
1099
|
-
"parentId?": "number"
|
|
1100
|
-
});
|
|
1101
|
-
const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark);
|
|
1102
|
-
//#endregion
|
|
1103
|
-
//#region src/litegraph/LiteGraphNodeInput.ts
|
|
1104
|
-
const LiteGraphNodeInput_ark = type({
|
|
1105
|
-
name: "string",
|
|
1106
|
-
type: "string",
|
|
1107
|
-
"link?": LiteGraphLinkID_.or(type.null),
|
|
1108
|
-
"shape?": "number",
|
|
1109
|
-
"label?": "string",
|
|
1110
|
-
"widget?": type({
|
|
1111
|
-
name: "string",
|
|
1112
|
-
"config?": "unknown"
|
|
1113
|
-
})
|
|
1114
|
-
});
|
|
1115
|
-
//#endregion
|
|
1116
|
-
//#region src/litegraph/LiteGraphSlotIndex.ts
|
|
1117
|
-
const asLiteGraphSlotIndex = (id) => id;
|
|
1118
|
-
const LiteGraphSlotIndex_ = type.number.atLeast(0).as();
|
|
1119
|
-
//#endregion
|
|
1120
|
-
//#region src/litegraph/LiteGraphNodeOutput.ts
|
|
1121
|
-
const LiteGraphNodeOutput_ark = type({
|
|
1122
|
-
name: "string",
|
|
1123
|
-
type: "string",
|
|
1124
|
-
"links?": LiteGraphLinkID_.array().or(type.null),
|
|
1125
|
-
"shape?": "number",
|
|
1126
|
-
"slot_index?": LiteGraphSlotIndex_
|
|
1127
|
-
});
|
|
1128
|
-
//#endregion
|
|
1129
|
-
//#region src/litegraph/LiteGraphNode.ts
|
|
1130
|
-
const LiteGraphNode_ark = type({
|
|
1131
|
-
id: "number",
|
|
1132
|
-
type: "string",
|
|
1133
|
-
"title?": "string",
|
|
1134
|
-
"color?": "string",
|
|
1135
|
-
"bgcolor?": "string",
|
|
1136
|
-
pos: {
|
|
1137
|
-
"0": "number",
|
|
1138
|
-
"1": "number"
|
|
1139
|
-
},
|
|
1140
|
-
size: {
|
|
1141
|
-
"0": "number",
|
|
1142
|
-
"1": "number"
|
|
1143
|
-
},
|
|
1144
|
-
"flags?": type.Record("string", "unknown"),
|
|
1145
|
-
"order?": "number",
|
|
1146
|
-
"mode?": "number",
|
|
1147
|
-
"inputs?": LiteGraphNodeInput_ark.array(),
|
|
1148
|
-
"outputs?": LiteGraphNodeOutput_ark.array(),
|
|
1149
|
-
"isVirtualNode?": "boolean",
|
|
1150
|
-
"properties?": type.Record("string", "unknown"),
|
|
1151
|
-
"widgets_values?": type("unknown[]").or(type.Record("string", "unknown"))
|
|
1152
|
-
});
|
|
1153
|
-
//#endregion
|
|
1154
|
-
//#region src/litegraph/LiteGraphSubgraphDef.ts
|
|
1155
|
-
const LiteGraphSubgraphIO_ark = type({
|
|
1156
|
-
id: "string",
|
|
1157
|
-
name: "string",
|
|
1158
|
-
type: "string",
|
|
1159
|
-
"linkIds?": LiteGraphLinkID_.array(),
|
|
1160
|
-
"label?": "string",
|
|
1161
|
-
"localized_name?": "string",
|
|
1162
|
-
"pos?": {
|
|
1163
|
-
"0": "number",
|
|
1164
|
-
"1": "number"
|
|
1165
|
-
},
|
|
1166
|
-
"shape?": "number"
|
|
1167
|
-
});
|
|
1168
|
-
const LiteGraphSubgraphDef_ark = type({
|
|
1169
|
-
id: "string",
|
|
1170
|
-
name: "string",
|
|
1171
|
-
version: "number",
|
|
1172
|
-
"state?": type.Record("string", "unknown"),
|
|
1173
|
-
"revision?": "number",
|
|
1174
|
-
"config?": type.Record("string", "unknown").as(),
|
|
1175
|
-
"extra?": "unknown",
|
|
1176
|
-
nodes: LiteGraphNode_ark.array(),
|
|
1177
|
-
links: LiteGraphLinkObject_ark.array(),
|
|
1178
|
-
"groups?": LiteGraphGroup_ark.array(),
|
|
1179
|
-
inputNode: {
|
|
1180
|
-
id: "number",
|
|
1181
|
-
bounding: "number[]"
|
|
1182
|
-
},
|
|
1183
|
-
outputNode: {
|
|
1184
|
-
id: "number",
|
|
1185
|
-
bounding: "number[]"
|
|
1186
|
-
},
|
|
1187
|
-
inputs: LiteGraphSubgraphIO_ark.array(),
|
|
1188
|
-
outputs: LiteGraphSubgraphIO_ark.array(),
|
|
1189
|
-
widgets: "unknown[]"
|
|
1190
|
-
});
|
|
1191
|
-
//#endregion
|
|
1192
|
-
//#region src/litegraph/LiteGraphJSON.ts
|
|
1193
|
-
const LiteGraphJSON_ark = type({
|
|
1194
|
-
"id?": "string",
|
|
1195
|
-
"revision?": "number",
|
|
1196
|
-
"last_node_id?": "number",
|
|
1197
|
-
"last_link_id?": "number",
|
|
1198
|
-
"state?": type.Record("string", "unknown"),
|
|
1199
|
-
nodes: LiteGraphNode_ark.array(),
|
|
1200
|
-
links: LiteGraphLink_ark.array(),
|
|
1201
|
-
"groups?": LiteGraphGroup_ark.array(),
|
|
1202
|
-
"config?": type.Record("never", "never"),
|
|
1203
|
-
"extra?": { "ds?": {
|
|
1204
|
-
scale: "number",
|
|
1205
|
-
offset: {
|
|
1206
|
-
"0": "number",
|
|
1207
|
-
"1": "number"
|
|
1208
|
-
}
|
|
1209
|
-
} },
|
|
1210
|
-
"models?": "unknown[]",
|
|
1211
|
-
"definitions?": { subgraphs: LiteGraphSubgraphDef_ark.array() },
|
|
1212
|
-
"reroutes?": "unknown[]",
|
|
1213
|
-
"floatingLinks?": "unknown[]",
|
|
1214
|
-
version: "0.4 | 1"
|
|
1215
|
-
});
|
|
1216
|
-
//#endregion
|
|
1217
|
-
//#region src/litegraph/normalizeWorkflow.ts
|
|
1218
|
-
/** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */
|
|
1219
|
-
var WorkflowNormalizeError = class extends Error {
|
|
1220
|
-
constructor(code, message, detail) {
|
|
1221
|
-
super(`[workflow ${code}] ${message}`);
|
|
1222
|
-
this.code = code;
|
|
1223
|
-
this.detail = detail;
|
|
1224
|
-
this.name = "WorkflowNormalizeError";
|
|
1225
|
-
}
|
|
1226
|
-
};
|
|
1227
|
-
/**
|
|
1228
|
-
* THE one entry for foreign workflow JSON (files, clipboard, imports):
|
|
1229
|
-
* tolerant ark validation, then normalization to the strict canonical shape.
|
|
1230
|
-
*/
|
|
1231
|
-
const parseWorkflowJson = (json) => {
|
|
1232
|
-
const out = LiteGraphJSON_ark(json);
|
|
1233
|
-
if (out instanceof type.errors) throw new WorkflowNormalizeError("schema-reject", out.summary, out);
|
|
1234
|
-
return normalizeWorkflow(out);
|
|
1235
|
-
};
|
|
1236
|
-
/**
|
|
1237
|
-
* loose wire document → strict canonical document. Defaults filled, both link
|
|
1238
|
-
* eras unified, cosmetic fields dropped, subgraph definitions expanded away
|
|
1239
|
-
* (see expandSubgraphs.ts — def interiors go through the SAME per-shape
|
|
1240
|
-
* normalizers, they are v1 bodies).
|
|
1241
|
-
*/
|
|
1242
|
-
const normalizeWorkflow = (raw) => {
|
|
1243
|
-
const wf = {
|
|
1244
|
-
nodes: raw.nodes.map(normalizeNode),
|
|
1245
|
-
links: raw.links.map(normalizeLink),
|
|
1246
|
-
groups: (raw.groups ?? []).map(normalizeGroup)
|
|
1247
|
-
};
|
|
1248
|
-
const rawDefs = raw.definitions?.subgraphs ?? [];
|
|
1249
|
-
if (rawDefs.length === 0) return wf;
|
|
1250
|
-
const defs = /* @__PURE__ */ new Map();
|
|
1251
|
-
for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d));
|
|
1252
|
-
return expandSubgraphs(wf, defs);
|
|
1253
|
-
};
|
|
1254
|
-
const normalizeSubgraphDef = (d) => {
|
|
1255
|
-
return {
|
|
1256
|
-
id: d.id,
|
|
1257
|
-
name: d.name,
|
|
1258
|
-
inputs: d.inputs.map((io) => ({
|
|
1259
|
-
name: io.name,
|
|
1260
|
-
type: io.type
|
|
1261
|
-
})),
|
|
1262
|
-
outputs: d.outputs.map((io) => ({
|
|
1263
|
-
name: io.name,
|
|
1264
|
-
type: io.type
|
|
1265
|
-
})),
|
|
1266
|
-
nodes: d.nodes.map(normalizeNode),
|
|
1267
|
-
links: d.links.map(normalizeLink)
|
|
1268
|
-
};
|
|
1269
|
-
};
|
|
1270
|
-
const normalizeMode = (mode) => {
|
|
1271
|
-
if (mode === 2) return "muted";
|
|
1272
|
-
if (mode === 4) return "bypassed";
|
|
1273
|
-
return "normal";
|
|
1274
|
-
};
|
|
1275
|
-
const normalizeNode = (n) => {
|
|
1276
|
-
return {
|
|
1277
|
-
id: n.id,
|
|
1278
|
-
type: n.type,
|
|
1279
|
-
title: n.title ?? null,
|
|
1280
|
-
mode: normalizeMode(n.mode),
|
|
1281
|
-
isVirtualNode: n.isVirtualNode ?? false,
|
|
1282
|
-
inputs: (n.inputs ?? []).map(normalizeInput),
|
|
1283
|
-
outputs: (n.outputs ?? []).map(normalizeOutput),
|
|
1284
|
-
widgets: normalizeWidgetValues(n.widgets_values),
|
|
1285
|
-
pos: [n.pos[0], n.pos[1]],
|
|
1286
|
-
size: [n.size[0], n.size[1]],
|
|
1287
|
-
properties: { ...n.properties }
|
|
1288
|
-
};
|
|
1289
|
-
};
|
|
1290
|
-
const normalizeInput = (i) => {
|
|
1291
|
-
return {
|
|
1292
|
-
name: i.name,
|
|
1293
|
-
type: i.type,
|
|
1294
|
-
link: i.link ?? null,
|
|
1295
|
-
widgetName: i.widget?.name ?? null
|
|
1296
|
-
};
|
|
1297
|
-
};
|
|
1298
|
-
const normalizeOutput = (o) => {
|
|
1299
|
-
return {
|
|
1300
|
-
name: o.name,
|
|
1301
|
-
type: o.type,
|
|
1302
|
-
links: [...o.links ?? []]
|
|
1303
|
-
};
|
|
1304
|
-
};
|
|
1305
|
-
const normalizeWidgetValues = (wv) => {
|
|
1306
|
-
if (wv == null) return {
|
|
1307
|
-
positional: [],
|
|
1308
|
-
named: {}
|
|
1309
|
-
};
|
|
1310
|
-
if (Array.isArray(wv)) return {
|
|
1311
|
-
positional: [...wv],
|
|
1312
|
-
named: {}
|
|
1313
|
-
};
|
|
1314
|
-
return {
|
|
1315
|
-
positional: [],
|
|
1316
|
-
named: { ...wv }
|
|
1317
|
-
};
|
|
1318
|
-
};
|
|
1319
|
-
const normalizeLink = (l) => {
|
|
1320
|
-
if (Array.isArray(l)) return {
|
|
1321
|
-
id: l[0],
|
|
1322
|
-
originId: l[1],
|
|
1323
|
-
originSlot: l[2],
|
|
1324
|
-
targetId: l[3],
|
|
1325
|
-
targetSlot: l[4],
|
|
1326
|
-
type: l[5]
|
|
1327
|
-
};
|
|
1328
|
-
return {
|
|
1329
|
-
id: l.id,
|
|
1330
|
-
originId: l.origin_id,
|
|
1331
|
-
originSlot: l.origin_slot,
|
|
1332
|
-
targetId: l.target_id,
|
|
1333
|
-
targetSlot: l.target_slot,
|
|
1334
|
-
type: l.type
|
|
1335
|
-
};
|
|
1336
|
-
};
|
|
1337
|
-
const normalizeGroup = (g) => {
|
|
1338
|
-
return {
|
|
1339
|
-
title: g.title,
|
|
1340
|
-
bounding: [
|
|
1341
|
-
g.bounding[0],
|
|
1342
|
-
g.bounding[1],
|
|
1343
|
-
g.bounding[2],
|
|
1344
|
-
g.bounding[3]
|
|
1345
|
-
],
|
|
1346
|
-
color: g.color ?? "#3f789e",
|
|
1347
|
-
fontSize: g.font_size ?? 24
|
|
1348
|
-
};
|
|
1349
|
-
};
|
|
1350
|
-
//#endregion
|
|
1351
|
-
//#region src/runner/wsBinaryFrame.ts
|
|
1352
|
-
function parseBinaryWsFrame(data) {
|
|
1353
|
-
const view = new DataView(data);
|
|
1354
|
-
const eventType = view.getUint32(0);
|
|
1355
|
-
if (eventType === 1) {
|
|
1356
|
-
const imageType = view.getUint32(4);
|
|
1357
|
-
return {
|
|
1358
|
-
kind: "preview",
|
|
1359
|
-
bytes: new Uint8Array(data.slice(8)),
|
|
1360
|
-
mime: imageType === 2 ? "image/png" : "image/jpeg",
|
|
1361
|
-
metadata: null
|
|
1362
|
-
};
|
|
1363
|
-
}
|
|
1364
|
-
if (eventType === 3) {
|
|
1365
|
-
const nodeIdLen = view.getUint32(4);
|
|
1366
|
-
const decoder = new TextDecoder();
|
|
1367
|
-
return {
|
|
1368
|
-
kind: "text",
|
|
1369
|
-
nodeId: decoder.decode(data.slice(8, 8 + nodeIdLen)),
|
|
1370
|
-
text: decoder.decode(data.slice(8 + nodeIdLen))
|
|
1371
|
-
};
|
|
1372
|
-
}
|
|
1373
|
-
if (eventType === 4) {
|
|
1374
|
-
const metadataLen = view.getUint32(4);
|
|
1375
|
-
let metadata = null;
|
|
1376
|
-
try {
|
|
1377
|
-
metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)));
|
|
1378
|
-
} catch {}
|
|
1379
|
-
const bytes = new Uint8Array(data.slice(8 + metadataLen));
|
|
1380
|
-
return {
|
|
1381
|
-
kind: "preview",
|
|
1382
|
-
bytes,
|
|
1383
|
-
mime: bytes[0] === 137 && bytes[1] === 80 ? "image/png" : "image/jpeg",
|
|
1384
|
-
metadata
|
|
1385
|
-
};
|
|
1386
|
-
}
|
|
1387
|
-
return {
|
|
1388
|
-
kind: "unknown",
|
|
1389
|
-
eventType
|
|
1390
|
-
};
|
|
1391
|
-
}
|
|
1392
|
-
//#endregion
|
|
1393
|
-
//#region src/sdk-generator/litegraphToApiRequestPayload.ts
|
|
1394
|
-
/** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
|
|
1395
|
-
var WorkflowConvertError = class extends Error {
|
|
1396
|
-
constructor(code, message, node) {
|
|
1397
|
-
super(`[workflow ${code}] ${message}`);
|
|
1398
|
-
this.code = code;
|
|
1399
|
-
this.node = node;
|
|
1400
|
-
this.name = "WorkflowConvertError";
|
|
1401
|
-
}
|
|
1402
|
-
};
|
|
1403
|
-
/**
|
|
1404
|
-
* closed set: frontend-only node types that NEVER execute. PrimitiveString /
|
|
1405
|
-
* PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.
|
|
1406
|
-
*/
|
|
1407
|
-
const VIRTUAL_NODE_TYPES = /* @__PURE__ */ new Set([
|
|
1408
|
-
"Note",
|
|
1409
|
-
"MarkdownNote",
|
|
1410
|
-
"Reroute",
|
|
1411
|
-
"PrimitiveNode"
|
|
1412
|
-
]);
|
|
1413
|
-
const isNeverExecuted = (node) => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type);
|
|
1414
|
-
/** exact match, or `*` wildcard on either side (Reroute-style slots) */
|
|
1415
|
-
/** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */
|
|
1416
|
-
const linkTypeMatches = (a, b) => {
|
|
1417
|
-
if (a === b || a === "*" || b === "*") return true;
|
|
1418
|
-
if (!a.includes(",") && !b.includes(",")) return false;
|
|
1419
|
-
const as = a.split(",");
|
|
1420
|
-
const bs = b.split(",");
|
|
1421
|
-
return as.some((x) => bs.includes(x));
|
|
1422
|
-
};
|
|
1423
|
-
/** what an inlined PrimitiveNode may contribute: scalar widget values only */
|
|
1424
|
-
const isPromptScalar = (v) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean";
|
|
1425
|
-
/**
|
|
1426
|
-
* convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)
|
|
1427
|
-
* into the api.json (prompt format) ComfyUI's POST /prompt takes.
|
|
1428
|
-
* Handles: muted nodes (skipped, consumers resolve unconnected), bypassed
|
|
1429
|
-
* nodes (mode 4: link resolution walks through to the first type-matching
|
|
1430
|
-
* input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes
|
|
1431
|
-
* unwrapped, primitives inlined into their consumers), widget values both
|
|
1432
|
-
* positional (with the phantom `control_after_generate` offset after seeds)
|
|
1433
|
-
* and named (object-form widgets_values + subgraph promotion overrides —
|
|
1434
|
-
* named wins, but a live link wins over both). Widget-ness is decided from
|
|
1435
|
-
* the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types
|
|
1436
|
-
* (COMBO options, dynamic combos, autogrow containers, socketless customs)
|
|
1437
|
-
* and 2024-era enums go through ONE classifier; a positional array shorter
|
|
1438
|
-
* than the schema's widget list fills schema defaults, never throws
|
|
1439
|
-
* (agent/architecture.md owns both decisions).
|
|
1440
|
-
*/
|
|
1441
|
-
const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
|
|
1442
|
-
const prompt = {};
|
|
1443
|
-
const LOG = opts.verbose ? (...args) => console.log("[🔥] converter:", ...args) : () => {};
|
|
1444
|
-
const PRIMITIVE_VALUES = {};
|
|
1445
|
-
for (const node of workflow.nodes) {
|
|
1446
|
-
if (node.type !== "PrimitiveNode") continue;
|
|
1447
|
-
if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
|
|
1448
|
-
else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
|
|
1449
|
-
}
|
|
1450
|
-
for (const node of workflow.nodes) {
|
|
1451
|
-
if (isNeverExecuted(node)) continue;
|
|
1452
|
-
if (node.mode !== "normal") continue;
|
|
1453
|
-
const inputs = {};
|
|
1454
|
-
const fieldNamesPresent = new Set(node.inputs.map((i) => i.name));
|
|
1455
|
-
const nodeSchema_ = schema.nodesByNameInComfy[node.type];
|
|
1456
|
-
if (nodeSchema_ == null) throw new WorkflowConvertError("unknown-node", `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`, node);
|
|
1457
|
-
const nodeSchema = nodeSchema_;
|
|
1458
|
-
let offset = 0;
|
|
1459
|
-
const positional = node.widgets.positional;
|
|
1460
|
-
const named = node.widgets.named;
|
|
1461
|
-
const widgetFallback = /* @__PURE__ */ new Map();
|
|
1462
|
-
const inputsInNodeJSON = node.inputs;
|
|
1463
|
-
const inputsInNodeSchema = nodeSchema.inputs;
|
|
1464
|
-
/** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */
|
|
1465
|
-
const toPromptValue = (value, p) => {
|
|
1466
|
-
if (value == null) return null;
|
|
1467
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
1468
|
-
if (Array.isArray(value)) return { __value__: value };
|
|
1469
|
-
if (!p.strict && isRecord(value)) return value;
|
|
1470
|
-
throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
|
|
1471
|
-
};
|
|
1472
|
-
/** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
|
|
1473
|
-
const resolveWidgetValue = (p) => {
|
|
1474
|
-
let value;
|
|
1475
|
-
let has = false;
|
|
1476
|
-
if (Object.hasOwn(named, p.promptName)) {
|
|
1477
|
-
value = named[p.promptName];
|
|
1478
|
-
has = true;
|
|
1479
|
-
} else if (offset < positional.length) {
|
|
1480
|
-
value = positional[offset];
|
|
1481
|
-
has = true;
|
|
1482
|
-
}
|
|
1483
|
-
if (positional.length > 0) offset += p.consumes;
|
|
1484
|
-
return {
|
|
1485
|
-
value,
|
|
1486
|
-
filled: !has
|
|
1487
|
-
};
|
|
1488
|
-
};
|
|
1489
|
-
const consumePlainWidget = (p) => {
|
|
1490
|
-
const r = resolveWidgetValue({
|
|
1491
|
-
promptName: p.promptName,
|
|
1492
|
-
consumes: p.consumes
|
|
1493
|
-
});
|
|
1494
|
-
const raw = r.filled ? defaultValueForWidget({
|
|
1495
|
-
type: p.typeName,
|
|
1496
|
-
opts: p.opts,
|
|
1497
|
-
enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values
|
|
1498
|
-
}) : r.value;
|
|
1499
|
-
const value = toPromptValue(raw, {
|
|
1500
|
-
promptName: p.promptName,
|
|
1501
|
-
strict: p.strict
|
|
1502
|
-
});
|
|
1503
|
-
if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`);
|
|
1504
|
-
if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value);
|
|
1505
|
-
else inputs[p.promptName] = value;
|
|
1506
|
-
};
|
|
1507
|
-
/** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
|
|
1508
|
-
const consumeDynamicCombo = (p) => {
|
|
1509
|
-
const r = resolveWidgetValue({
|
|
1510
|
-
promptName: p.path,
|
|
1511
|
-
consumes: 1
|
|
1512
|
-
});
|
|
1513
|
-
const key = r.filled ? p.defaultKey : r.value;
|
|
1514
|
-
if (typeof key !== "string") throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): dynamic combo "${p.path}" key is not a string: ${JSON.stringify(key)}`, node);
|
|
1515
|
-
const opt = p.options.find((o) => o.key === key);
|
|
1516
|
-
if (opt == null) throw new WorkflowConvertError("unknown-dynamic-combo-option", `node ${node.id}(${node.type}): "${key}" is not an option of dynamic combo "${p.path}" (options: ${p.options.map((o) => o.key).join(", ")})`, node);
|
|
1517
|
-
if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`);
|
|
1518
|
-
inputs[p.path] = key;
|
|
1519
|
-
for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
|
|
1520
|
-
};
|
|
1521
|
-
const consumeBranchInput = (subPath, sub) => {
|
|
1522
|
-
const kind = classifyWidgetInput({
|
|
1523
|
-
name: sub.name,
|
|
1524
|
-
type: sub.type,
|
|
1525
|
-
opts: sub.opts
|
|
1526
|
-
});
|
|
1527
|
-
if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
|
|
1528
|
-
if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
|
|
1529
|
-
path: subPath,
|
|
1530
|
-
options: kind.options,
|
|
1531
|
-
defaultKey: kind.defaultKey
|
|
1532
|
-
});
|
|
1533
|
-
const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
|
|
1534
|
-
consumePlainWidget({
|
|
1535
|
-
promptName: subPath,
|
|
1536
|
-
typeName: typeof sub.type === "string" ? sub.type : "COMBO",
|
|
1537
|
-
opts: sub.opts,
|
|
1538
|
-
consumes: kind.consumes,
|
|
1539
|
-
strict: kind.strictValues,
|
|
1540
|
-
enumValues: inlineEnum,
|
|
1541
|
-
linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
|
|
1542
|
-
});
|
|
1543
|
-
};
|
|
1544
|
-
for (const field of inputsInNodeSchema) {
|
|
1545
|
-
const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy);
|
|
1546
|
-
let kind = classifySchemaInput(field);
|
|
1547
|
-
if (kind.kind === "slot" && input?.widgetName != null) kind = {
|
|
1548
|
-
kind: "widget",
|
|
1549
|
-
consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
|
|
1550
|
-
strictValues: true
|
|
1551
|
-
};
|
|
1552
|
-
if (kind.kind === "widget") consumePlainWidget({
|
|
1553
|
-
promptName: field.nameInComfy,
|
|
1554
|
-
typeName: field.typeName,
|
|
1555
|
-
opts: field.opts,
|
|
1556
|
-
consumes: kind.consumes,
|
|
1557
|
-
strict: kind.strictValues,
|
|
1558
|
-
linkedInput: input
|
|
1559
|
-
});
|
|
1560
|
-
else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
|
|
1561
|
-
path: field.nameInComfy,
|
|
1562
|
-
options: kind.options,
|
|
1563
|
-
defaultKey: kind.defaultKey
|
|
1564
|
-
});
|
|
1565
|
-
else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
|
|
1566
|
-
const iname = `${field.nameInComfy}.${instName}`;
|
|
1567
|
-
if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
|
|
1568
|
-
}
|
|
1569
|
-
else if (!fieldNamesPresent.has(field.nameInComfy)) {
|
|
1570
|
-
if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
const getParentNode = (linkId) => {
|
|
1574
|
-
const link = workflow.links.find((link) => link.id === linkId);
|
|
1575
|
-
if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
|
|
1576
|
-
const parentNode = workflow.nodes.find((n) => n.id === link.originId);
|
|
1577
|
-
if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
|
|
1578
|
-
return {
|
|
1579
|
-
node: parentNode,
|
|
1580
|
-
link
|
|
1581
|
-
};
|
|
1582
|
-
};
|
|
1583
|
-
const pickBypassInput = (p) => {
|
|
1584
|
-
const sameSlot = p.inputs[p.outSlot];
|
|
1585
|
-
if (p.consumerType === "*" || p.consumerType === "") return sameSlot ?? p.inputs[0] ?? null;
|
|
1586
|
-
if (sameSlot != null && linkTypeMatches(sameSlot.type, p.outputType) && linkTypeMatches(sameSlot.type, p.consumerType)) return sameSlot;
|
|
1587
|
-
const exact = p.inputs.find((i) => i.type === p.consumerType);
|
|
1588
|
-
if (exact != null) return exact;
|
|
1589
|
-
return p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ?? null;
|
|
1590
|
-
};
|
|
1591
|
-
const resolveThroughParents = (startLink, consumerType) => {
|
|
1592
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1593
|
-
let linkId = startLink;
|
|
1594
|
-
let effectiveType = consumerType;
|
|
1595
|
-
while (true) {
|
|
1596
|
-
const parent = getParentNode(linkId);
|
|
1597
|
-
if (visited.has(parent.node.id)) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`, node);
|
|
1598
|
-
visited.add(parent.node.id);
|
|
1599
|
-
if (parent.node.type === "Reroute") {
|
|
1600
|
-
const rerouteIn = parent.node.inputs[0]?.link;
|
|
1601
|
-
if (rerouteIn == null) return {
|
|
1602
|
-
kind: "unconnected",
|
|
1603
|
-
reason: "reroute chain ends on an empty slot"
|
|
1604
|
-
};
|
|
1605
|
-
linkId = rerouteIn;
|
|
1606
|
-
continue;
|
|
1607
|
-
}
|
|
1608
|
-
if (parent.node.mode === "muted") return {
|
|
1609
|
-
kind: "unconnected",
|
|
1610
|
-
reason: `parent ${parent.node.id}(${parent.node.type}) is muted`
|
|
1611
|
-
};
|
|
1612
|
-
if (parent.node.mode === "bypassed") {
|
|
1613
|
-
const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type;
|
|
1614
|
-
const through = pickBypassInput({
|
|
1615
|
-
inputs: parent.node.inputs,
|
|
1616
|
-
outSlot: parent.link.originSlot,
|
|
1617
|
-
outputType,
|
|
1618
|
-
consumerType: effectiveType
|
|
1619
|
-
});
|
|
1620
|
-
if (through?.link == null) return {
|
|
1621
|
-
kind: "unconnected",
|
|
1622
|
-
reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`
|
|
1623
|
-
};
|
|
1624
|
-
linkId = through.link;
|
|
1625
|
-
effectiveType = through.type;
|
|
1626
|
-
continue;
|
|
1627
|
-
}
|
|
1628
|
-
if (parent.node.type === "PrimitiveNode") {
|
|
1629
|
-
if (!(parent.node.id in PRIMITIVE_VALUES)) return {
|
|
1630
|
-
kind: "unconnected",
|
|
1631
|
-
reason: `PrimitiveNode#${parent.node.id} has no widget value`
|
|
1632
|
-
};
|
|
1633
|
-
return {
|
|
1634
|
-
kind: "primitive",
|
|
1635
|
-
nodeId: parent.node.id
|
|
1636
|
-
};
|
|
1637
|
-
}
|
|
1638
|
-
return {
|
|
1639
|
-
kind: "link",
|
|
1640
|
-
nodeId: parent.node.id,
|
|
1641
|
-
slot: parent.link.originSlot
|
|
1642
|
-
};
|
|
1643
|
-
}
|
|
1644
|
-
};
|
|
1645
|
-
for (const ipt of node.inputs) {
|
|
1646
|
-
if (ipt.link == null) {
|
|
1647
|
-
LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`);
|
|
1648
|
-
continue;
|
|
1649
|
-
}
|
|
1650
|
-
const resolved = resolveThroughParents(ipt.link, ipt.type);
|
|
1651
|
-
if (resolved.kind === "primitive") {
|
|
1652
|
-
const pv = PRIMITIVE_VALUES[resolved.nodeId];
|
|
1653
|
-
if (!isPromptScalar(pv)) throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`, node);
|
|
1654
|
-
inputs[ipt.name] = pv;
|
|
1655
|
-
LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`);
|
|
1656
|
-
continue;
|
|
1657
|
-
}
|
|
1658
|
-
if (resolved.kind === "link") {
|
|
1659
|
-
LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`);
|
|
1660
|
-
inputs[ipt.name] = [String(resolved.nodeId), resolved.slot];
|
|
1661
|
-
continue;
|
|
1662
|
-
}
|
|
1663
|
-
if (widgetFallback.has(ipt.name)) {
|
|
1664
|
-
inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null;
|
|
1665
|
-
LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`);
|
|
1666
|
-
continue;
|
|
1667
|
-
}
|
|
1668
|
-
if (inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)?.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${ipt.name}" resolves unconnected (${resolved.reason}) and no widget value covers it`, node);
|
|
1669
|
-
LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`);
|
|
1670
|
-
}
|
|
1671
|
-
prompt[String(node.id)] = {
|
|
1672
|
-
inputs,
|
|
1673
|
-
class_type: node.type
|
|
1674
|
-
};
|
|
1675
|
-
}
|
|
1676
|
-
return prompt;
|
|
1677
|
-
};
|
|
1678
|
-
//#endregion
|
|
1679
|
-
//#region src/errors/InvalidPromptError.ts
|
|
1680
|
-
var InvalidPromptError = class extends Error {
|
|
1681
|
-
constructor(message, snapshot, details) {
|
|
1682
|
-
super(message);
|
|
1683
|
-
this.message = message;
|
|
1684
|
-
this.snapshot = snapshot;
|
|
1685
|
-
this.details = details;
|
|
1686
|
-
}
|
|
1687
|
-
};
|
|
1688
|
-
//#endregion
|
|
1689
|
-
//#region src/utils/ComfyColors.ts
|
|
1690
|
-
const palette = {
|
|
1691
|
-
primitive: "var(--comfy-primitive)",
|
|
1692
|
-
loader: "var(--comfy-loader)",
|
|
1693
|
-
latent: "var(--comfy-latent)",
|
|
1694
|
-
conditioning: "var(--comfy-conditioning)",
|
|
1695
|
-
sampl: "var(--comfy-sampl)",
|
|
1696
|
-
image: "var(--comfy-image)"
|
|
1697
|
-
};
|
|
1698
|
-
Object.keys(palette);
|
|
1699
|
-
const comfyColors = {
|
|
1700
|
-
loaders: palette.loader,
|
|
1701
|
-
latent: palette.latent,
|
|
1702
|
-
"latent/transform": palette.latent,
|
|
1703
|
-
conditioning: palette.conditioning,
|
|
1704
|
-
"conditioning/style_model": palette.conditioning,
|
|
1705
|
-
sampling: palette.sampl,
|
|
1706
|
-
image: palette.image,
|
|
1707
|
-
primitive: palette.primitive
|
|
1708
|
-
};
|
|
1709
|
-
//#endregion
|
|
1710
|
-
//#region src/graph/autoValue.ts
|
|
1711
|
-
const auto_ = { ___AUTO___: true };
|
|
1712
|
-
//#endregion
|
|
1713
|
-
//#region src/graph/ComfyNodeOutput.ts
|
|
1714
|
-
var ComfyNodeOutput = class {
|
|
1715
|
-
constructor(node, slotIx, type, name) {
|
|
1716
|
-
this.node = node;
|
|
1717
|
-
this.slotIx = slotIx;
|
|
1718
|
-
this.type = type;
|
|
1719
|
-
this.name = name;
|
|
1720
|
-
}
|
|
1721
|
-
};
|
|
1722
|
-
//#endregion
|
|
1723
|
-
//#region src/graph/ComfyNode.ts
|
|
1724
|
-
/** ComfyNode
|
|
1725
|
-
* - correspond to a signal in the graph
|
|
1726
|
-
* - belongs to a script
|
|
1727
|
-
*/
|
|
1728
|
-
var ComfyNode = class ComfyNode {
|
|
1729
|
-
storeAs(storeName) {
|
|
1730
|
-
this.meta.storeAs = storeName;
|
|
1731
|
-
return this;
|
|
1732
|
-
}
|
|
1733
|
-
tag(tagName) {
|
|
1734
|
-
this.addTag(tagName);
|
|
1735
|
-
return this;
|
|
1736
|
-
}
|
|
1737
|
-
addTag(tag) {
|
|
1738
|
-
if (this.meta.tags == null) this.meta.tags = [tag];
|
|
1739
|
-
else this.meta.tags.push(tag);
|
|
1740
|
-
return this;
|
|
1741
|
-
}
|
|
1742
|
-
get progressReport() {
|
|
1743
|
-
return {
|
|
1744
|
-
percent: this.status === "done" ? 100 : this.progressRatio * 100,
|
|
1745
|
-
isDone: this.status === "done",
|
|
1746
|
-
countDone: this.progressRatio * 100,
|
|
1747
|
-
countTotal: 100
|
|
1748
|
-
};
|
|
1749
|
-
}
|
|
1750
|
-
get isExecuting() {
|
|
1751
|
-
return this.status === "executing";
|
|
1752
|
-
}
|
|
1753
|
-
disable() {
|
|
1754
|
-
this.disabled = true;
|
|
1755
|
-
}
|
|
1756
|
-
get inputs() {
|
|
1757
|
-
return this.json.inputs;
|
|
1758
|
-
}
|
|
1759
|
-
/** update a node */
|
|
1760
|
-
set(p) {
|
|
1761
|
-
for (const [key, value] of Object.entries(p)) {
|
|
1762
|
-
const next = this.serializeValue(key, value);
|
|
1763
|
-
if (next === this.json.inputs[key]) continue;
|
|
1764
|
-
this.json.inputs[key] = next;
|
|
1765
|
-
}
|
|
1766
|
-
return this;
|
|
1767
|
-
}
|
|
1768
|
-
get color() {
|
|
1769
|
-
return comfyColors[this.$schema.category] ?? "#aaa";
|
|
1770
|
-
}
|
|
1771
|
-
constructor(graph, uid, jsonExt, meta = {}) {
|
|
1772
|
-
this.graph = graph;
|
|
1773
|
-
this.uid = uid;
|
|
1774
|
-
this.meta = meta;
|
|
1775
|
-
this.status = null;
|
|
1776
|
-
this.progress = null;
|
|
1777
|
-
this.progressRatio = 0;
|
|
1778
|
-
this.updatedAt = Date.now();
|
|
1779
|
-
this.disabled = false;
|
|
1780
|
-
this.$outputs = [];
|
|
1781
|
-
this._visible = true;
|
|
1782
|
-
this._x = 0;
|
|
1783
|
-
this._y = 0;
|
|
1784
|
-
this.isDirty = true;
|
|
1785
|
-
this.col = 0;
|
|
1786
|
-
this.selected = false;
|
|
1787
|
-
const parsedUid = /^\d+$/.test(uid) ? Number(uid) : NaN;
|
|
1788
|
-
this.uidNumber = Number.isNaN(parsedUid) ? this.graph._uidNumber++ : parsedUid;
|
|
1789
|
-
if (this.uidNumber >= this.graph._uidNumber) this.graph._uidNumber = this.uidNumber + 1;
|
|
1790
|
-
if (jsonExt == null) throw new Error("invariant violation: jsonExt is null");
|
|
1791
|
-
const exactSchema = graph.schema.nodesByNameInComfy[jsonExt.class_type];
|
|
1792
|
-
if (exactSchema == null) graph.recordProblem(`unknown node type "${jsonExt.class_type}" — schema fallback to ${ComfyDefaultNodeWhenUnknown_Name}; install the missing custom node on the host`);
|
|
1793
|
-
this.$schema = exactSchema ?? graph.schema.nodesByNameInComfy["UnknownNodeXX"];
|
|
1794
|
-
if (this.$schema == null) {
|
|
1795
|
-
console.log(`❌ available nodes:`, Object.keys(graph.schema.nodesByNameInComfy).join(","));
|
|
1796
|
-
throw new Error(`❌ no schema found for node "${jsonExt.class_type}"`);
|
|
1797
|
-
}
|
|
1798
|
-
this.uidPrefixed = `${this.$schema.nodeKey}_${this.uidNumber}`;
|
|
1799
|
-
let ix = 0;
|
|
1800
|
-
this.json = this._convertPromptExtToPrompt(jsonExt);
|
|
1801
|
-
this.graph.registerNode(this);
|
|
1802
|
-
const outputs = {};
|
|
1803
|
-
for (const x of this.$schema.outputs) {
|
|
1804
|
-
const output = new ComfyNodeOutput(this, ix++, x.typeName, x.nameInComfy);
|
|
1805
|
-
outputs[x.outKey] = output;
|
|
1806
|
-
this.$outputs.push(output);
|
|
1807
|
-
}
|
|
1808
|
-
this.outputs = outputs;
|
|
1809
|
-
const extensions = {};
|
|
1810
|
-
for (const x of this.$schema.singleOutputs) extensions[`_${x.typeName}`] = outputs[x.outKey];
|
|
1811
|
-
Object.assign(this, extensions);
|
|
1812
|
-
}
|
|
1813
|
-
_convertPromptExtToPrompt(promptExt) {
|
|
1814
|
-
const inputs = {};
|
|
1815
|
-
const _done = /* @__PURE__ */ new Set();
|
|
1816
|
-
for (const i of this.$schema.inputs) {
|
|
1817
|
-
_done.add(i.nameInComfy);
|
|
1818
|
-
const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
|
|
1819
|
-
if (value !== void 0) inputs[i.nameInComfy] = value;
|
|
1820
|
-
}
|
|
1821
|
-
for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {
|
|
1822
|
-
if (_done.has(nameInComfy)) continue;
|
|
1823
|
-
inputs[nameInComfy] = this.serializeValue(nameInComfy, rawVal);
|
|
1824
|
-
}
|
|
1825
|
-
return {
|
|
1826
|
-
class_type: this.$schema.nameInComfy,
|
|
1827
|
-
inputs
|
|
1828
|
-
};
|
|
1829
|
-
}
|
|
1830
|
-
/** return the list of nodes piped into this node */
|
|
1831
|
-
_incomingNodes() {
|
|
1832
|
-
const incomingNodes = [];
|
|
1833
|
-
for (const [_name, val] of Object.entries(this.inputs)) if (Array.isArray(val)) {
|
|
1834
|
-
const [from, _slotIx] = val;
|
|
1835
|
-
incomingNodes.push(from);
|
|
1836
|
-
}
|
|
1837
|
-
return incomingNodes;
|
|
1838
|
-
}
|
|
1839
|
-
_primitives() {
|
|
1840
|
-
const primitives = [];
|
|
1841
|
-
for (const [inputName, val] of Object.entries(this.inputs)) {
|
|
1842
|
-
if (Array.isArray(val)) continue;
|
|
1843
|
-
primitives.push({
|
|
1844
|
-
inputName,
|
|
1845
|
-
value: val?.toString()
|
|
1846
|
-
});
|
|
1847
|
-
}
|
|
1848
|
-
return primitives;
|
|
1849
|
-
}
|
|
1850
|
-
/** return true if the given node is plugged into this one */
|
|
1851
|
-
isChildrenOf(node) {
|
|
1852
|
-
return this._incomingNodes().includes(node.uid);
|
|
1853
|
-
}
|
|
1854
|
-
get parents() {
|
|
1855
|
-
return this._incomingNodes().map((id) => this.graph.getNode(id));
|
|
1856
|
-
}
|
|
1857
|
-
set visible(value) {
|
|
1858
|
-
this._visible = value;
|
|
1859
|
-
}
|
|
1860
|
-
get visible() {
|
|
1861
|
-
return this._visible;
|
|
1862
|
-
}
|
|
1863
|
-
get x() {
|
|
1864
|
-
return this._x;
|
|
1865
|
-
}
|
|
1866
|
-
set x(value) {
|
|
1867
|
-
this.isDirty = true;
|
|
1868
|
-
this._x = value;
|
|
1869
|
-
}
|
|
1870
|
-
get y() {
|
|
1871
|
-
return this._y;
|
|
1872
|
-
}
|
|
1873
|
-
set y(value) {
|
|
1874
|
-
this.isDirty = true;
|
|
1875
|
-
this._y = value;
|
|
1876
|
-
}
|
|
1877
|
-
tagDirty(value) {
|
|
1878
|
-
this.isDirty = value;
|
|
1879
|
-
}
|
|
1880
|
-
get outgoingPorts() {
|
|
1881
|
-
return this.$outputs.map((o, ix) => ({
|
|
1882
|
-
id: this.uid + "#" + o.slotIx,
|
|
1883
|
-
label: o.type,
|
|
1884
|
-
width: 10,
|
|
1885
|
-
height: 10,
|
|
1886
|
-
fromNode: this,
|
|
1887
|
-
toNode: o.node ?? void 0,
|
|
1888
|
-
type: o.type,
|
|
1889
|
-
x: this.x + this.width,
|
|
1890
|
-
y: this.y + 20 + ix * 20 + 20 / 2
|
|
1891
|
-
}));
|
|
1892
|
-
}
|
|
1893
|
-
get incomingPorts() {
|
|
1894
|
-
return this._incomingEdges().map((e, ix) => ({
|
|
1895
|
-
id: this.uid + "<-" + e.from + "#" + e.fromSlotIx,
|
|
1896
|
-
width: 10,
|
|
1897
|
-
height: 10,
|
|
1898
|
-
fromNode: this.graph.getNode(e.from) ?? void 0,
|
|
1899
|
-
toNode: this,
|
|
1900
|
-
label: e.inputName,
|
|
1901
|
-
type: e.type,
|
|
1902
|
-
x: this.x,
|
|
1903
|
-
y: this.y + 20 + ix * 20 + 20 / 2
|
|
1904
|
-
}));
|
|
1905
|
-
}
|
|
1906
|
-
_incomingEdges() {
|
|
1907
|
-
const incomingEdges = [];
|
|
1908
|
-
for (const [inputName, val] of Object.entries(this.inputs)) if (Array.isArray(val)) {
|
|
1909
|
-
const [from, _slotIx] = val;
|
|
1910
|
-
const type = this.graph.getNode(from)?.$outputs[_slotIx]?.type ?? "UNKNOWN";
|
|
1911
|
-
incomingEdges.push({
|
|
1912
|
-
from,
|
|
1913
|
-
inputName,
|
|
1914
|
-
fromSlotIx: _slotIx,
|
|
1915
|
-
type
|
|
1916
|
-
});
|
|
1917
|
-
}
|
|
1918
|
-
return incomingEdges;
|
|
1919
|
-
}
|
|
1920
|
-
/** number of primitive fields in this node */
|
|
1921
|
-
primitivesCount() {
|
|
1922
|
-
return Object.values(this.inputs).filter((val) => !Array.isArray(val)).length;
|
|
1923
|
-
}
|
|
1924
|
-
/** width dimensions for autolayout algorithm */
|
|
1925
|
-
get width() {
|
|
1926
|
-
return 200;
|
|
1927
|
-
}
|
|
1928
|
-
/** height dimensions for autolayout algorithm */
|
|
1929
|
-
get height() {
|
|
1930
|
-
const inputLen = this._incomingEdges().length;
|
|
1931
|
-
const outputLen = this.$schema.outputs.length;
|
|
1932
|
-
const headerCount = Math.max(inputLen, outputLen);
|
|
1933
|
-
return (this.primitivesCount() + headerCount + 1) * 20;
|
|
1934
|
-
}
|
|
1935
|
-
serializeValue(field, value) {
|
|
1936
|
-
if (value == null) {
|
|
1937
|
-
const schema = this.$schema.inputs.find((i) => i.nameInComfy === field);
|
|
1938
|
-
if (schema == null) throw new Error(`❌ no schema for field "${field}" (of node ${this.$schema.nodeKey})`);
|
|
1939
|
-
const opts = schema.opts == null || typeof schema.opts !== "object" ? void 0 : schema.opts;
|
|
1940
|
-
if (opts?.default != null) return opts.default;
|
|
1941
|
-
if (!schema.required) return void 0;
|
|
1942
|
-
console.error(field, "is required but value is ", value, this.json);
|
|
1943
|
-
this.graph.recordProblem(`🔴 [serializeValue] field "${field}" (of node ${this.$schema.nodeKey}#${this.uid}) value is null but field is not optional`);
|
|
1944
|
-
return;
|
|
1945
|
-
}
|
|
1946
|
-
if (typeof value === "function") return this.serializeValue(field, value(this.graph.builder, this.graph));
|
|
1947
|
-
if (value === auto_) {
|
|
1948
|
-
const expectedType = this._getExpectedTypeForField(field);
|
|
1949
|
-
console.info(`🔍 looking for type ${expectedType} for field ${field}`);
|
|
1950
|
-
for (const node of this.graph.nodes.slice().reverse()) {
|
|
1951
|
-
const output = node._getOutputForTypeOrNull(expectedType);
|
|
1952
|
-
if (output != null) return [node.uid, output.slotIx];
|
|
1953
|
-
}
|
|
1954
|
-
throw new Error(`🔴 [AUTO failed] field "${field}" (of node ${this.$schema.nodeKey}) value is null`);
|
|
1955
|
-
}
|
|
1956
|
-
if (value instanceof ComfyNodeOutput) return [value.node.uid, value.slotIx];
|
|
1957
|
-
if (value instanceof ComfyNode) {
|
|
1958
|
-
const expectedType = this._getExpectedTypeForField(field);
|
|
1959
|
-
const output = value._getOutputForTypeOrCrash(expectedType);
|
|
1960
|
-
return [value.uid, output.slotIx];
|
|
1961
|
-
}
|
|
1962
|
-
return value;
|
|
1963
|
-
}
|
|
1964
|
-
_getExpectedTypeForField(name) {
|
|
1965
|
-
const input = this.$schema.inputs.find((i) => i.nameInComfy === name);
|
|
1966
|
-
if (input == null) throw new Error("🔴 input not found asdf");
|
|
1967
|
-
return input.typeName;
|
|
1968
|
-
}
|
|
1969
|
-
_getOutputForTypeOrCrash(type) {
|
|
1970
|
-
const i = this.$schema.outputs.find((i) => i.typeName === type);
|
|
1971
|
-
const val = this.outputs[i.outKey];
|
|
1972
|
-
if (val instanceof ComfyNodeOutput) return val;
|
|
1973
|
-
throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
|
|
1974
|
-
}
|
|
1975
|
-
_getOutputForTypeOrNull(type) {
|
|
1976
|
-
const i = this.$schema.outputs.find((i) => i.typeName === type);
|
|
1977
|
-
if (i == null) return null;
|
|
1978
|
-
const val = this.outputs[i.outKey];
|
|
1979
|
-
if (val == null) return null;
|
|
1980
|
-
if (val instanceof ComfyNodeOutput) return val;
|
|
1981
|
-
throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
|
|
1982
|
-
}
|
|
1983
|
-
};
|
|
1984
|
-
//#endregion
|
|
1985
|
-
//#region src/host/ComfyWorkflowBuilder.ts
|
|
1986
|
-
var ComfyWorkflowBuilder = class {
|
|
1987
|
-
constructor(graph) {
|
|
1988
|
-
this.graph = graph;
|
|
1989
|
-
const schema = graph.host.schema;
|
|
1990
|
-
for (const node of schema.nodes) try {
|
|
1991
|
-
Object.defineProperty(this, node.nodeKey, { value: (inputs, meta) => {
|
|
1992
|
-
return new ComfyNode(graph, this.___allocateNodeUID(meta), {
|
|
1993
|
-
class_type: node.nameInComfy,
|
|
1994
|
-
inputs
|
|
1995
|
-
}, meta ?? {});
|
|
1996
|
-
} });
|
|
1997
|
-
} catch (e) {
|
|
1998
|
-
console.log(e);
|
|
1999
|
-
console.error("impossible to create builder for node");
|
|
2000
|
-
console.log(`current:`, JSON.stringify(node.nameInComfy), JSON.stringify(node.nodeKey));
|
|
2001
|
-
const prev = schema.nodes.find((n) => n.nodeKey === node.nodeKey);
|
|
2002
|
-
console.log(`prev`, JSON.stringify(prev?.nameInComfy), JSON.stringify(prev?.nodeKey));
|
|
2003
|
-
throw e;
|
|
2004
|
-
}
|
|
2005
|
-
}
|
|
2006
|
-
/**
|
|
2007
|
-
* helper function to allocate an unique node Id while
|
|
2008
|
-
* while respecting user provided metadata id if present.
|
|
2009
|
-
*/
|
|
2010
|
-
___allocateNodeUID(meta) {
|
|
2011
|
-
let uidString;
|
|
2012
|
-
if (meta?.id != null && meta.id !== "") {
|
|
2013
|
-
const uidNumber = parseInt(meta.id, 10);
|
|
2014
|
-
if (!Number.isNaN(uidNumber) && uidNumber > this.graph._uidNumber) this.graph._uidNumber = Math.round(uidNumber + 1);
|
|
2015
|
-
uidString = meta.id;
|
|
2016
|
-
} else uidString = (this.graph._uidNumber++).toString();
|
|
2017
|
-
return uidString;
|
|
2018
|
-
}
|
|
2019
|
-
};
|
|
2020
|
-
//#endregion
|
|
2021
|
-
//#region src/litegraph/convertFlowToLiteGraphJSON.ts
|
|
2022
|
-
const convertFlowToLiteGraphJSON = (graph) => {
|
|
2023
|
-
const ctx = new LiteGraphCtx(graph);
|
|
2024
|
-
const last_node_id = Math.max(...graph.nodes.map((n) => n.uidNumber));
|
|
2025
|
-
const xxx = graph.nodes.map((comfyNode) => ({
|
|
2026
|
-
liteGraphNode: convertNodeToLiteGraphNode(ctx, comfyNode),
|
|
2027
|
-
comfyNode
|
|
2028
|
-
}));
|
|
2029
|
-
for (const xx of xxx) {
|
|
2030
|
-
const n = xx.liteGraphNode;
|
|
2031
|
-
n.pos[0] = bang(xx.comfyNode.x);
|
|
2032
|
-
n.pos[1] = bang(xx.comfyNode.y);
|
|
2033
|
-
for (const o of n.outputs ?? []) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
|
|
2034
|
-
}
|
|
2035
|
-
return {
|
|
2036
|
-
last_node_id,
|
|
2037
|
-
last_link_id: ctx.nextLinkId,
|
|
2038
|
-
nodes: xxx.map((n) => n.liteGraphNode),
|
|
2039
|
-
links: ctx.links,
|
|
2040
|
-
config: {},
|
|
2041
|
-
extra: {},
|
|
2042
|
-
groups: [],
|
|
2043
|
-
version: .4
|
|
2044
|
-
};
|
|
2045
|
-
};
|
|
2046
|
-
const convertNodeToLiteGraphNode = (ctx, node) => {
|
|
2047
|
-
const inputs = [];
|
|
2048
|
-
const widgets_values = [];
|
|
2049
|
-
for (const ipt of node.$schema.inputs) {
|
|
2050
|
-
const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
|
|
2051
|
-
const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0;
|
|
2052
|
-
if (_isLink(raw)) {
|
|
2053
|
-
const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber, `link target node "${raw[0]}" not found in graph`);
|
|
2054
|
-
inputs.push({
|
|
2055
|
-
name: ipt.nameInComfy,
|
|
2056
|
-
type: ipt.typeName,
|
|
2057
|
-
link: ctx.allocateLink(nodeUidNumber, raw[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), ipt.typeName)
|
|
2058
|
-
});
|
|
2059
|
-
} else if (isWidget) {
|
|
2060
|
-
widgets_values.push(raw);
|
|
2061
|
-
if (ipt.typeName === "INT" && (ipt.nameInComfy === "seed" || ipt.nameInComfy === "noise_seed")) widgets_values.push(false);
|
|
2062
|
-
} else inputs.push({
|
|
2063
|
-
name: ipt.nameInComfy,
|
|
2064
|
-
type: ipt.typeName,
|
|
2065
|
-
link: null
|
|
2066
|
-
});
|
|
2067
|
-
}
|
|
2068
|
-
const outputs = node.$schema.outputs.map((i, ix) => ({
|
|
2069
|
-
type: i.typeName,
|
|
2070
|
-
links: [],
|
|
2071
|
-
slot_index: asLiteGraphSlotIndex(ix),
|
|
2072
|
-
name: i.outKey
|
|
2073
|
-
}));
|
|
2074
|
-
return {
|
|
2075
|
-
type: node.$schema.nameInComfy,
|
|
2076
|
-
id: node.uidNumber,
|
|
2077
|
-
inputs,
|
|
2078
|
-
outputs,
|
|
2079
|
-
pos: [0, 0],
|
|
2080
|
-
size: [node.width, node.height],
|
|
2081
|
-
widgets_values
|
|
2082
|
-
};
|
|
2083
|
-
};
|
|
2084
|
-
const _isLink = (v) => {
|
|
2085
|
-
return Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number";
|
|
2086
|
-
};
|
|
2087
|
-
var LiteGraphCtx = class {
|
|
2088
|
-
constructor(graph) {
|
|
2089
|
-
this.graph = graph;
|
|
2090
|
-
this.nextLinkId = 0;
|
|
2091
|
-
this.links = [];
|
|
2092
|
-
this.allocateLink = (fromNodeId, fromNodeOutputIx, toNodeId, toNodeInputIx, linkType) => {
|
|
2093
|
-
const linkId = asLiteGraphLinkID(++this.nextLinkId);
|
|
2094
|
-
this.links.push([
|
|
2095
|
-
linkId,
|
|
2096
|
-
fromNodeId,
|
|
2097
|
-
fromNodeOutputIx,
|
|
2098
|
-
toNodeId,
|
|
2099
|
-
toNodeInputIx,
|
|
2100
|
-
linkType
|
|
2101
|
-
]);
|
|
2102
|
-
return linkId;
|
|
2103
|
-
};
|
|
2104
|
-
}
|
|
2105
|
-
};
|
|
2106
|
-
//#endregion
|
|
2107
|
-
//#region src/types/index.ts
|
|
2108
|
-
const asAbsolutePath = (path) => path;
|
|
2109
|
-
const resultSuccess = (value) => ({
|
|
2110
|
-
success: true,
|
|
2111
|
-
value
|
|
2112
|
-
});
|
|
2113
|
-
const resultFailure = (value) => ({
|
|
2114
|
-
success: false,
|
|
2115
|
-
value
|
|
2116
|
-
});
|
|
2117
|
-
//#endregion
|
|
2118
|
-
//#region src/image-utils/_getPngMetadata.ts
|
|
2119
|
-
const getPngMetadataFromUint8Array = (pngData) => {
|
|
2120
|
-
const dataView = new DataView(pngData.buffer, pngData.byteOffset, pngData.byteLength);
|
|
2121
|
-
if (dataView.getUint32(0) !== 2303741511) return resultFailure("Not a valid PNG file");
|
|
2122
|
-
let offset = 8;
|
|
2123
|
-
const txt_chunks = {};
|
|
2124
|
-
while (offset < pngData.length) {
|
|
2125
|
-
const length = dataView.getUint32(offset);
|
|
2126
|
-
if (String.fromCharCode(...pngData.slice(offset + 4, offset + 8)) === "tEXt") {
|
|
2127
|
-
let keyword_end = offset + 8;
|
|
2128
|
-
while (pngData[keyword_end] !== 0) keyword_end++;
|
|
2129
|
-
const keyword = String.fromCharCode(...pngData.slice(offset + 8, keyword_end));
|
|
2130
|
-
const contentArraySegment = pngData.slice(keyword_end + 1, offset + 8 + length);
|
|
2131
|
-
txt_chunks[keyword] = Array.from(contentArraySegment).map((s) => String.fromCharCode(s)).join("");
|
|
2132
|
-
}
|
|
2133
|
-
offset += 12 + length;
|
|
2134
|
-
}
|
|
2135
|
-
return resultSuccess(txt_chunks);
|
|
2136
|
-
};
|
|
2137
|
-
//#endregion
|
|
2138
|
-
//#region src/utils/exhaust.ts
|
|
2139
|
-
function exhaust(x) {
|
|
2140
|
-
return x;
|
|
2141
|
-
}
|
|
2142
|
-
//#endregion
|
|
2143
|
-
//#region src/utils/hashArrayBuffer.ts
|
|
2144
|
-
const hashArrayBuffer = (buffer) => {
|
|
2145
|
-
const data = Buffer.from(buffer);
|
|
2146
|
-
return crypto.createHash("sha1").update(data).digest("hex");
|
|
2147
|
-
};
|
|
2148
|
-
//#endregion
|
|
2149
|
-
//#region src/graph/ComfyNodeID.ts
|
|
2150
|
-
const ComfyNodeId_ark = type.string.as();
|
|
2151
|
-
type({
|
|
2152
|
-
"id?": ComfyNodeId_ark,
|
|
2153
|
-
"tag?": "string",
|
|
2154
|
-
"tags?": "string[]",
|
|
2155
|
-
"storeAs?": "string"
|
|
2156
|
-
}).as();
|
|
2157
|
-
const types$1 = scope({
|
|
2158
|
-
PromptID: type.string.as(),
|
|
2159
|
-
ComfyNodeID: ComfyNodeId_ark,
|
|
2160
|
-
Timestamp: "number",
|
|
2161
|
-
ApiPromptInput: {
|
|
2162
|
-
client_id: "string",
|
|
2163
|
-
extra_data: { extra_pnginfo: "unknown" },
|
|
2164
|
-
prompt: "unknown"
|
|
2165
|
-
},
|
|
2166
|
-
NodeProgress: {
|
|
2167
|
-
value: "number",
|
|
2168
|
-
max: "number"
|
|
2169
|
-
},
|
|
2170
|
-
ComfyStatusData: {
|
|
2171
|
-
"sid?": "string",
|
|
2172
|
-
status: {
|
|
2173
|
-
exec_info: { queue_remaining: "number" },
|
|
2174
|
-
"sid?": "string"
|
|
2175
|
-
}
|
|
2176
|
-
},
|
|
2177
|
-
WsMsgStatus: {
|
|
2178
|
-
type: "'status'",
|
|
2179
|
-
data: "ComfyStatusData"
|
|
2180
|
-
},
|
|
2181
|
-
_WsMsgExecutionStartData: { prompt_id: "PromptID" },
|
|
2182
|
-
WsMsgExecutionStart: {
|
|
2183
|
-
type: "'execution_start'",
|
|
2184
|
-
data: "_WsMsgExecutionStartData"
|
|
2185
|
-
},
|
|
2186
|
-
_WsMsgExecutionCachedData: {
|
|
2187
|
-
nodes: "ComfyNodeID[]",
|
|
2188
|
-
prompt_id: "PromptID"
|
|
2189
|
-
},
|
|
2190
|
-
WsMsgExecutionCached: {
|
|
2191
|
-
type: "'execution_cached'",
|
|
2192
|
-
data: "_WsMsgExecutionCachedData"
|
|
2193
|
-
},
|
|
2194
|
-
_WSMsgExecutingData: {
|
|
2195
|
-
prompt_id: "PromptID",
|
|
2196
|
-
"node?": "ComfyNodeID | null"
|
|
2197
|
-
},
|
|
2198
|
-
WsMsgExecuting: {
|
|
2199
|
-
type: "'executing'",
|
|
2200
|
-
data: "_WSMsgExecutingData"
|
|
2201
|
-
},
|
|
2202
|
-
ComfyImageInfo: {
|
|
2203
|
-
filename: "string",
|
|
2204
|
-
subfolder: "string",
|
|
2205
|
-
type: "string"
|
|
2206
|
-
},
|
|
2207
|
-
_WsMsgExecutedData: {
|
|
2208
|
-
node: "ComfyNodeID",
|
|
2209
|
-
output: {
|
|
2210
|
-
"previews?": [{ filepath: "string" }, "[]"],
|
|
2211
|
-
"images?": "ComfyImageInfo[]"
|
|
2212
|
-
},
|
|
2213
|
-
prompt_id: "PromptID"
|
|
2214
|
-
},
|
|
2215
|
-
WsMsgExecuted: {
|
|
2216
|
-
type: "'executed'",
|
|
2217
|
-
data: "_WsMsgExecutedData"
|
|
2218
|
-
},
|
|
2219
|
-
WsMsgExecutionSuccessData: {
|
|
2220
|
-
prompt_id: "PromptID",
|
|
2221
|
-
timestamp: "Timestamp"
|
|
2222
|
-
},
|
|
2223
|
-
WsMsgExecutionSuccess: {
|
|
2224
|
-
type: "'execution_success'",
|
|
2225
|
-
data: "WsMsgExecutionSuccessData"
|
|
2226
|
-
},
|
|
2227
|
-
_WsMsgExecutionErrorData: {
|
|
2228
|
-
prompt_id: "PromptID",
|
|
2229
|
-
node_id: "ComfyNodeID",
|
|
2230
|
-
node_type: "string",
|
|
2231
|
-
executed: "ComfyNodeID[]",
|
|
2232
|
-
exception_message: "string",
|
|
2233
|
-
exception_type: "string",
|
|
2234
|
-
traceback: "string[]",
|
|
2235
|
-
current_inputs: "Record<string, unknown>",
|
|
2236
|
-
current_outputs: "Record<string, unknown>"
|
|
2237
|
-
},
|
|
2238
|
-
WsMsgExecutionError: {
|
|
2239
|
-
type: "'execution_error'",
|
|
2240
|
-
data: "_WsMsgExecutionErrorData"
|
|
2241
|
-
},
|
|
2242
|
-
WSMsgManagerFeedbackData: { data: "string" },
|
|
2243
|
-
WSMsgManagerFeedback: {
|
|
2244
|
-
type: "'manager-terminal-feedback'",
|
|
2245
|
-
data: "WSMsgManagerFeedbackData"
|
|
2246
|
-
},
|
|
2247
|
-
LogEntry: {
|
|
2248
|
-
t: "string",
|
|
2249
|
-
m: "string"
|
|
2250
|
-
},
|
|
2251
|
-
_WsMsgLogsData: {
|
|
2252
|
-
entries: "LogEntry[]",
|
|
2253
|
-
"size?": "unknown"
|
|
2254
|
-
},
|
|
2255
|
-
WsMsgLogs: {
|
|
2256
|
-
type: "'logs'",
|
|
2257
|
-
data: "_WsMsgLogsData"
|
|
2258
|
-
},
|
|
2259
|
-
WsMsgProgress: {
|
|
2260
|
-
type: "'progress'",
|
|
2261
|
-
data: "NodeProgress"
|
|
2262
|
-
},
|
|
2263
|
-
_WsMsgProgressStateData: {
|
|
2264
|
-
prompt_id: "PromptID",
|
|
2265
|
-
nodes: "Record<string, unknown>"
|
|
2266
|
-
},
|
|
2267
|
-
WsMsgProgressState: {
|
|
2268
|
-
type: "'progress_state'",
|
|
2269
|
-
data: "_WsMsgProgressStateData"
|
|
2270
|
-
},
|
|
2271
|
-
PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
|
|
2272
|
-
WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
|
|
2273
|
-
}).export();
|
|
2274
|
-
const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
|
|
2275
|
-
const WsMsg_ark = types$1.WsMsg;
|
|
2276
|
-
const ComfyImageInfo_ark = types$1.ComfyImageInfo;
|
|
2277
|
-
const WsMsgLogsData_ark = types$1._WsMsgLogsData;
|
|
2278
|
-
type({
|
|
2279
|
-
comfyHostHttpURL: "string",
|
|
2280
|
-
comfyImageInfo: ComfyImageInfo_ark
|
|
2281
|
-
});
|
|
2282
|
-
var MediaImage = class MediaImage {
|
|
2283
|
-
/** return the workflow from which this image was generated */
|
|
2284
|
-
get workflow() {
|
|
2285
|
-
return this.execution?.workflow;
|
|
2286
|
-
}
|
|
2287
|
-
constructor(data) {
|
|
2288
|
-
this.tags = [];
|
|
2289
|
-
this.uploadAndReturnEnumName = async (host) => {
|
|
2290
|
-
return await host.uploader.uploadImage(this, {
|
|
2291
|
-
type: "input",
|
|
2292
|
-
override: true
|
|
2293
|
-
});
|
|
2294
|
-
};
|
|
2295
|
-
this.loadInWorkflow_viaLoadImageNode = async (workflow) => {
|
|
2296
|
-
const enumName = await this.uploadAndReturnEnumName(workflow.host);
|
|
2297
|
-
return bang(workflow.builderBase.LoadImage, "host has no LoadImage node")({ image: enumName });
|
|
2298
|
-
};
|
|
2299
|
-
this.loadInWorkflowAsMask_viaLoadImageMask = async (channel, workflow) => {
|
|
2300
|
-
const enumName = await this.uploadAndReturnEnumName(workflow.host);
|
|
2301
|
-
return bang(workflow.builderBase.LoadImageMask, "host has no LoadImageMask node")({
|
|
2302
|
-
image: enumName,
|
|
2303
|
-
channel
|
|
2304
|
-
});
|
|
2305
|
-
};
|
|
2306
|
-
this._buffer = null;
|
|
2307
|
-
this.freeBuffer = () => void (this._buffer = null);
|
|
2308
|
-
this.updateBuffer = (buff) => {
|
|
2309
|
-
this._buffer = buff;
|
|
2310
|
-
this._metadata = null;
|
|
2311
|
-
this._hash = null;
|
|
2312
|
-
};
|
|
2313
|
-
this.reloadBuffer = () => {
|
|
2314
|
-
this._buffer = null;
|
|
2315
|
-
this._metadata = null;
|
|
2316
|
-
this._hash = null;
|
|
2317
|
-
return this.buffer;
|
|
2318
|
-
};
|
|
2319
|
-
this._metadata = null;
|
|
2320
|
-
this._hash = null;
|
|
2321
|
-
this.processWithSharp_inplace = async (fn) => {
|
|
2322
|
-
const buff = await fn(sharp(this.absPath)).toBuffer();
|
|
2323
|
-
writeFileSync(this.absPath, buff);
|
|
2324
|
-
this.updateBuffer(new Uint8Array(buff));
|
|
2325
|
-
return this;
|
|
2326
|
-
};
|
|
2327
|
-
this.processWithSharp = async (fn, path) => {
|
|
2328
|
-
const res = fn(sharp(this.absPath));
|
|
2329
|
-
path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
|
|
2330
|
-
await res.toFile(path);
|
|
2331
|
-
const buffer = await res.toBuffer();
|
|
2332
|
-
return new MediaImage({
|
|
2333
|
-
path,
|
|
2334
|
-
buffer
|
|
2335
|
-
});
|
|
2336
|
-
};
|
|
2337
|
-
this.generatePreview = async (targetPath) => {
|
|
2338
|
-
const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
|
|
2339
|
-
mkdirSync(dirname(targetPath), { recursive: true });
|
|
2340
|
-
await img.toFile(targetPath);
|
|
2341
|
-
};
|
|
2342
|
-
this.generateMiniPreview = async () => {
|
|
2343
|
-
return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
|
|
2344
|
-
};
|
|
2345
|
-
this.absPath = data.path;
|
|
2346
|
-
this.execution = data.execution;
|
|
2347
|
-
this.promptNodeID = data.promptNodeID;
|
|
2348
|
-
if (data.buffer != null) this.updateBuffer(data.buffer);
|
|
2349
|
-
}
|
|
2350
|
-
/** the image as a Blob, e.g. to feed FormData uploads */
|
|
2351
|
-
getAsBlob() {
|
|
2352
|
-
return new Blob([this.buffer], { type: `image/${this.metadata.type ?? "png"}` });
|
|
2353
|
-
}
|
|
2354
|
-
/** return the image filename */
|
|
2355
|
-
get filename() {
|
|
2356
|
-
return basename(this.absPath);
|
|
2357
|
-
}
|
|
2358
|
-
get baseNameWithoutExtension() {
|
|
2359
|
-
const fname = this.filename;
|
|
2360
|
-
return fname.slice(0, fname.lastIndexOf("."));
|
|
2361
|
-
}
|
|
2362
|
-
/**
|
|
2363
|
-
* return file extension including dot
|
|
2364
|
-
* e.g. `.png`, or `.webp`
|
|
2365
|
-
* */
|
|
2366
|
-
get extension() {
|
|
2367
|
-
const fname = this.filename;
|
|
2368
|
-
return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 1);
|
|
2369
|
-
}
|
|
2370
|
-
/** get the expected enum name (hash) */
|
|
2371
|
-
get enumName() {
|
|
2372
|
-
return `${this.hash}${this.extension}`;
|
|
2373
|
-
}
|
|
2374
|
-
/** return the json of the ComfyNode that led to this image */
|
|
2375
|
-
get ComfyNode() {
|
|
2376
|
-
const nodeID = this.promptNodeID;
|
|
2377
|
-
if (nodeID == null) return null;
|
|
2378
|
-
return this.workflow?.apiJson[nodeID];
|
|
2379
|
-
}
|
|
2380
|
-
/**
|
|
2381
|
-
* return the metadata of the ComfyNode that led to this image
|
|
2382
|
-
* null if not generated by comfy through a ComfyTS prompt
|
|
2383
|
-
* null if no metadata associated in the node in ComfyTS
|
|
2384
|
-
*/
|
|
2385
|
-
get ComfyNodeMetadata() {
|
|
2386
|
-
const nodeID = this.promptNodeID;
|
|
2387
|
-
if (nodeID == null) return null;
|
|
2388
|
-
return this.workflow?.data.metadata[nodeID];
|
|
2389
|
-
}
|
|
2390
|
-
get width() {
|
|
2391
|
-
return this.metadata.width;
|
|
2392
|
-
}
|
|
2393
|
-
get height() {
|
|
2394
|
-
return this.metadata.height;
|
|
2395
|
-
}
|
|
2396
|
-
get width_orCrash() {
|
|
2397
|
-
return bang(this.metadata.width);
|
|
2398
|
-
}
|
|
2399
|
-
get height_orCrash() {
|
|
2400
|
-
return bang(this.metadata.height);
|
|
2401
|
-
}
|
|
2402
|
-
/**
|
|
2403
|
-
* return the base64 url for this file, regardless of it's exact representation
|
|
2404
|
-
* includes the prefix `data:image/<type>;base64,`
|
|
2405
|
-
*/
|
|
2406
|
-
getBase64Url() {
|
|
2407
|
-
return `data:image/${this.metadata.type ?? "png"};base64,${this.getBase64Payload()}`;
|
|
2408
|
-
}
|
|
2409
|
-
/**
|
|
2410
|
-
* return the base64 url for this file, regardless of it's exact representation
|
|
2411
|
-
* does not includes the prefix `data:image/png;base64,`
|
|
2412
|
-
*/
|
|
2413
|
-
getBase64Payload() {
|
|
2414
|
-
return Buffer.from(this.buffer).toString("base64");
|
|
2415
|
-
}
|
|
2416
|
-
get buffer() {
|
|
2417
|
-
if (this._buffer != null) return this._buffer;
|
|
2418
|
-
const buff = readFileSync(this.absPath);
|
|
2419
|
-
const uint8arr = new Uint8Array(buff);
|
|
2420
|
-
this._buffer = uint8arr;
|
|
2421
|
-
return this._buffer;
|
|
2422
|
-
}
|
|
2423
|
-
get metadata() {
|
|
2424
|
-
if (this._metadata != null) return this._metadata;
|
|
2425
|
-
const buff = readFileSync(this.absPath);
|
|
2426
|
-
const uint8arr = new Uint8Array(buff);
|
|
2427
|
-
this._metadata = imageMeta(uint8arr);
|
|
2428
|
-
return this._metadata;
|
|
2429
|
-
}
|
|
2430
|
-
get hash() {
|
|
2431
|
-
if (this._hash != null) return this._hash;
|
|
2432
|
-
const buff = readFileSync(this.absPath);
|
|
2433
|
-
this._hash = hashArrayBuffer(new Uint8Array(buff));
|
|
2434
|
-
return this._hash;
|
|
2435
|
-
}
|
|
2436
|
-
};
|
|
2437
|
-
//#endregion
|
|
2438
|
-
//#region src/runner/ComfyExecution.ts
|
|
2439
|
-
var ComfyExecution = class {
|
|
2440
|
-
get host() {
|
|
2441
|
-
return this.workflow.host;
|
|
2442
|
-
}
|
|
2443
|
-
constructor(workflow, data, init = {}) {
|
|
2444
|
-
this.workflow = workflow;
|
|
2445
|
-
this.data = data;
|
|
2446
|
-
this.saveFormat = null;
|
|
2447
|
-
this.snapshot = null;
|
|
2448
|
-
this.onProgress = null;
|
|
2449
|
-
this.logProgress = false;
|
|
2450
|
-
this.startedAt = Date.now();
|
|
2451
|
-
this._lastLoggedLine = "";
|
|
2452
|
-
this.done = new Promise((resolve) => {
|
|
2453
|
-
this._resolve = resolve;
|
|
2454
|
-
});
|
|
2455
|
-
this.onPromptRelatedMessage = (msg) => {
|
|
2456
|
-
const graph = this.workflow;
|
|
2457
|
-
if (msg.type === "execution_start") return;
|
|
2458
|
-
else if (msg.type === "execution_cached") graph.onExecutionCached(msg);
|
|
2459
|
-
else if (msg.type === "executing") this.onExecuting(msg);
|
|
2460
|
-
else if (msg.type === "progress") graph.onProgress(msg);
|
|
2461
|
-
else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
|
|
2462
|
-
else if (msg.type === "execution_error") return void this.onError(msg);
|
|
2463
|
-
else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
|
|
2464
|
-
else {
|
|
2465
|
-
console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
|
|
2466
|
-
return exhaust(msg);
|
|
2467
|
-
}
|
|
2468
|
-
this.emitProgress();
|
|
2469
|
-
};
|
|
2470
|
-
this.onExecuting = (msg) => {
|
|
2471
|
-
this.workflow.onExecuting(msg);
|
|
2472
|
-
};
|
|
2473
|
-
this.onExecutionSuccess = async (_msg) => {
|
|
2474
|
-
await Promise.all(this.pendingPromises);
|
|
2475
|
-
return this._finish({ status: "Success" });
|
|
2476
|
-
};
|
|
2477
|
-
this.onError = async (msg) => {
|
|
2478
|
-
console.error("❌ Execution error:");
|
|
2479
|
-
console.error(msg);
|
|
2480
|
-
return this._finish({
|
|
2481
|
-
status: "Failure",
|
|
2482
|
-
error: msg
|
|
2483
|
-
});
|
|
2484
|
-
};
|
|
2485
|
-
this.onExecuted = (msg) => {
|
|
2486
|
-
const promptNodeID = msg.data.node;
|
|
2487
|
-
const images = msg.data.output?.images;
|
|
2488
|
-
if (images) for (const img of images) this.pendingPromises.push(this.retrieveImage(img, promptNodeID).catch((e) => {
|
|
2489
|
-
console.error(`🔴 failed to retrieve ${img.filename}:`, e);
|
|
2490
|
-
this.imageErrors.push({
|
|
2491
|
-
image: img,
|
|
2492
|
-
error: e
|
|
2493
|
-
});
|
|
2494
|
-
}));
|
|
2495
|
-
};
|
|
2496
|
-
this.pendingPromises = [];
|
|
2497
|
-
this.imageErrors = [];
|
|
2498
|
-
this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
|
|
2499
|
-
const promptNode = this.workflow.data.apiJson?.[promptNodeID];
|
|
2500
|
-
const promptMeta = this.workflow.data.metadata?.[promptNodeID];
|
|
2501
|
-
if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
|
|
2502
|
-
const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
|
|
2503
|
-
const sf = this.saveFormat;
|
|
2504
|
-
let absPath = comfyts.resolveFromOutput(join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
|
|
2505
|
-
if (sf?.format && sf.format !== "raw") {
|
|
2506
|
-
const extension = sf.format.split("/")[1];
|
|
2507
|
-
absPath += "." + extension;
|
|
2508
|
-
}
|
|
2509
|
-
mkdirSync(dirname(absPath), { recursive: true });
|
|
2510
|
-
let img;
|
|
2511
|
-
if (sf && sf.format !== "raw") {
|
|
2512
|
-
const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
|
|
2513
|
-
let textChunk = {};
|
|
2514
|
-
try {
|
|
2515
|
-
const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
|
|
2516
|
-
if (res.success) textChunk = res.value;
|
|
2517
|
-
} catch {}
|
|
2518
|
-
const format = (() => {
|
|
2519
|
-
if (sf.format === "image/jpeg") return "jpeg";
|
|
2520
|
-
if (sf.format === "image/png") return "png";
|
|
2521
|
-
if (sf.format === "image/webp") return "webp";
|
|
2522
|
-
return "png";
|
|
2523
|
-
})();
|
|
2524
|
-
await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
|
|
2525
|
-
img = new MediaImage({
|
|
2526
|
-
path: asAbsolutePath(absPath),
|
|
2527
|
-
execution: this,
|
|
2528
|
-
promptNodeID,
|
|
2529
|
-
comfyUIInfos: {
|
|
2530
|
-
comfyImageInfo,
|
|
2531
|
-
comfyHostHttpURL: this.host.getServerHostHTTP()
|
|
2532
|
-
}
|
|
2533
|
-
});
|
|
2534
|
-
} else {
|
|
2535
|
-
const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
|
|
2536
|
-
const uint8arr = new Uint8Array(buff);
|
|
2537
|
-
writeFileSync(absPath, uint8arr);
|
|
2538
|
-
img = new MediaImage({
|
|
2539
|
-
path: asAbsolutePath(absPath),
|
|
2540
|
-
buffer: uint8arr,
|
|
2541
|
-
execution: this,
|
|
2542
|
-
promptNodeID,
|
|
2543
|
-
comfyUIInfos: {
|
|
2544
|
-
comfyImageInfo,
|
|
2545
|
-
comfyHostHttpURL: this.host.getServerHostHTTP()
|
|
2546
|
-
}
|
|
2547
|
-
});
|
|
2548
|
-
}
|
|
2549
|
-
if (promptMeta?.tag) img.tags.push(promptMeta.tag);
|
|
2550
|
-
if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
|
|
2551
|
-
this.images.push(img);
|
|
2552
|
-
};
|
|
2553
|
-
this.images = [];
|
|
2554
|
-
this.alreadyDone = false;
|
|
2555
|
-
this._finish = async (p) => {
|
|
2556
|
-
if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`);
|
|
2557
|
-
this.alreadyDone = true;
|
|
2558
|
-
this.update({
|
|
2559
|
-
...p,
|
|
2560
|
-
executed: true
|
|
2561
|
-
});
|
|
2562
|
-
await Promise.all(this.pendingPromises);
|
|
2563
|
-
this.host.executions.delete(this.data.id);
|
|
2564
|
-
this.host._pendingMsgs.delete(this.data.id);
|
|
2565
|
-
this.finishProgressLine();
|
|
2566
|
-
this._resolve(this);
|
|
2567
|
-
};
|
|
2568
|
-
this.snapshot = init.snapshot ?? null;
|
|
2569
|
-
this.saveFormat = init.saveFormat ?? null;
|
|
2570
|
-
this.onProgress = init.onProgress ?? null;
|
|
2571
|
-
this.logProgress = init.logProgress ?? false;
|
|
2572
|
-
this.host.executions.set(data.id, this);
|
|
2573
|
-
this.onCreate();
|
|
2574
|
-
}
|
|
2575
|
-
get progress() {
|
|
2576
|
-
return {
|
|
2577
|
-
...this.progressGlobal,
|
|
2578
|
-
promptId: this.data.id,
|
|
2579
|
-
nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,
|
|
2580
|
-
elapsedMs: Date.now() - this.startedAt
|
|
2581
|
-
};
|
|
2582
|
-
}
|
|
2583
|
-
emitProgress() {
|
|
2584
|
-
const p = this.progress;
|
|
2585
|
-
this.onProgress?.(p);
|
|
2586
|
-
if (!this.logProgress) return;
|
|
2587
|
-
const width = 12;
|
|
2588
|
-
const filled = Math.round(p.percent / 100 * width);
|
|
2589
|
-
const bar = "█".repeat(filled) + "░".repeat(width - filled);
|
|
2590
|
-
const node = p.nodeName ? ` · ${p.nodeName}` : "";
|
|
2591
|
-
const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
|
|
2592
|
-
if (line === this._lastLoggedLine) return;
|
|
2593
|
-
this._lastLoggedLine = line;
|
|
2594
|
-
if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
|
|
2595
|
-
else console.log(line);
|
|
2596
|
-
}
|
|
2597
|
-
finishProgressLine() {
|
|
2598
|
-
if (!this.logProgress) return;
|
|
2599
|
-
const p = this.progress;
|
|
2600
|
-
const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
|
|
2601
|
-
if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
|
|
2602
|
-
else console.log(line);
|
|
2603
|
-
}
|
|
2604
|
-
log(...args) {
|
|
2605
|
-
console.log(`[ComfyExecution#${this.data.id}]`, ...args);
|
|
2606
|
-
}
|
|
2607
|
-
onCreate() {
|
|
2608
|
-
const data = this.data;
|
|
2609
|
-
const pending = this.host._pendingMsgs.get(data.id);
|
|
2610
|
-
if (pending == null) return;
|
|
2611
|
-
this.log(`🟢 onCreate: ${pending.length} pending messages`);
|
|
2612
|
-
this.host._pendingMsgs.delete(data.id);
|
|
2613
|
-
for (const msg of pending) this.onPromptRelatedMessage(msg);
|
|
2614
|
-
}
|
|
2615
|
-
get progressGlobal() {
|
|
2616
|
-
if (this.data.status === "Success") return {
|
|
2617
|
-
countDone: 1,
|
|
2618
|
-
countTotal: 1,
|
|
2619
|
-
isDone: true,
|
|
2620
|
-
percent: 100
|
|
2621
|
-
};
|
|
2622
|
-
return this.workflow.progressGlobal;
|
|
2623
|
-
}
|
|
2624
|
-
get status() {
|
|
2625
|
-
return this.data.status ?? "New";
|
|
2626
|
-
}
|
|
2627
|
-
update(data) {
|
|
2628
|
-
Object.assign(this.data, data);
|
|
2629
|
-
}
|
|
2630
|
-
};
|
|
2631
|
-
//#endregion
|
|
2632
|
-
//#region src/utils/deepCopyNaive.ts
|
|
2633
|
-
const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
|
|
2634
|
-
//#endregion
|
|
2635
|
-
//#region src/utils/printArkResultInConsole.ts
|
|
2636
|
-
const MAX_PRINTED_ERRORS = 10;
|
|
2637
|
-
function printArkResultInConsole(res) {
|
|
2638
|
-
if (isQuiet()) return;
|
|
2639
|
-
console.log(ansi.red(" ❌ Ark validation failed:"));
|
|
2640
|
-
for (const error of res.slice(0, MAX_PRINTED_ERRORS)) console.log(ansi.red(` - ${error.path.join(".")} : ${error.message}`));
|
|
2641
|
-
if (res.length > MAX_PRINTED_ERRORS) console.log(ansi.red(` … ${res.length - MAX_PRINTED_ERRORS} more (${res.length} total)`));
|
|
2642
|
-
}
|
|
2643
|
-
//#endregion
|
|
2644
|
-
//#region src/utils/softValidate.ts
|
|
2645
|
-
const softValidate = (schema, stuff) => {
|
|
2646
|
-
const res = schema(stuff);
|
|
2647
|
-
if (res instanceof type.errors) printArkResultInConsole(res);
|
|
2648
|
-
return stuff;
|
|
2649
|
-
};
|
|
2650
|
-
//#endregion
|
|
2651
|
-
//#region src/utils/toposort.ts
|
|
2652
|
-
function toposort(nodes, edges) {
|
|
2653
|
-
return toposortAlgo(nodes, edges);
|
|
2654
|
-
}
|
|
2655
|
-
function toposortAlgo(nodes, edges) {
|
|
2656
|
-
let cursor = nodes.length;
|
|
2657
|
-
const sorted = Array.from({ length: cursor });
|
|
2658
|
-
const visited = {};
|
|
2659
|
-
let k = cursor;
|
|
2660
|
-
while (k--) if (!visited[k]) visit(BONG(nodes[k]), k, []);
|
|
2661
|
-
return sorted;
|
|
2662
|
-
function visit(node, ix, predecessors) {
|
|
2663
|
-
let i = ix;
|
|
2664
|
-
if (predecessors.indexOf(node) >= 0) {
|
|
2665
|
-
console.log(predecessors, node);
|
|
2666
|
-
throw new Error("Cyclic dependency: " + JSON.stringify(node));
|
|
2667
|
-
}
|
|
2668
|
-
if (nodes.indexOf(node) === -1) throw new Error("[toposort] Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node) + "; known nodes are " + JSON.stringify(nodes));
|
|
2669
|
-
if (visited[i]) return;
|
|
2670
|
-
visited[i] = true;
|
|
2671
|
-
const outgoing = edges.filter((edge) => edge[0] === node);
|
|
2672
|
-
i = outgoing.length;
|
|
2673
|
-
if (i) {
|
|
2674
|
-
const preds = predecessors.concat(node);
|
|
2675
|
-
do {
|
|
2676
|
-
const child = BONG(outgoing[--i])[1];
|
|
2677
|
-
visit(child, nodes.indexOf(child), preds);
|
|
2678
|
-
} while (i);
|
|
2679
|
-
}
|
|
2680
|
-
sorted[--cursor] = node;
|
|
2681
|
-
}
|
|
2682
|
-
}
|
|
2683
|
-
function BONG(x) {
|
|
2684
|
-
if (x == null) throw new Error("BONG");
|
|
2685
|
-
return x;
|
|
2686
|
-
}
|
|
2687
|
-
//#endregion
|
|
2688
|
-
//#region src/runner/ComfyWorkflowLayout.ts
|
|
2689
|
-
/**
|
|
2690
|
-
* compute autolayout
|
|
2691
|
-
*
|
|
2692
|
-
* 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive
|
|
2693
|
-
* libraries were pretty bad; ended up writing my own simple algorithm, and I'm
|
|
2694
|
-
* happy with it. Feel free to improve it, but I think it works well enough.
|
|
2695
|
-
* I will accept PRs for new layout algorithms if they don't have massive dependencies.
|
|
2696
|
-
**/
|
|
2697
|
-
function comfyWorkflowAutoLayout(p) {
|
|
2698
|
-
const nodeIds = toposort(this.nodes.map((n) => n.uid), this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid])));
|
|
2699
|
-
const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`));
|
|
2700
|
-
const cols = Array.from({ length: nodeIds.length });
|
|
2701
|
-
const ranges = {};
|
|
2702
|
-
for (const node of nodes) {
|
|
2703
|
-
const parentCols = node.parents.map((p) => ranges[p.uid].minCol);
|
|
2704
|
-
const range = {
|
|
2705
|
-
node,
|
|
2706
|
-
minCol: Math.max(...parentCols, -1) + 1
|
|
2707
|
-
};
|
|
2708
|
-
ranges[node.uid] = range;
|
|
2709
|
-
}
|
|
2710
|
-
if (!p?.forceLeft === true) for (const node of nodes) {
|
|
2711
|
-
const range = ranges[node.uid];
|
|
2712
|
-
for (const p of node.parents) {
|
|
2713
|
-
const parentRange = ranges[p.uid];
|
|
2714
|
-
parentRange.maxCol = parentRange.maxCol != null ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1) : (range.maxCol ?? range.minCol) - 1;
|
|
2715
|
-
}
|
|
2716
|
-
}
|
|
2717
|
-
for (const node of nodes) {
|
|
2718
|
-
const range = ranges[node.uid];
|
|
2719
|
-
const at = range.maxCol ?? range.minCol;
|
|
2720
|
-
if (cols[at]) cols[at].push(node);
|
|
2721
|
-
else cols[at] = [node];
|
|
2722
|
-
}
|
|
2723
|
-
const HSEP = p?.node_hsep ?? 20;
|
|
2724
|
-
const VSEP = p?.node_vsep ?? 20;
|
|
2725
|
-
let colX = 0;
|
|
2726
|
-
let maxY = 0;
|
|
2727
|
-
for (const col of cols) {
|
|
2728
|
-
if (col == null) continue;
|
|
2729
|
-
let colWidth = 0;
|
|
2730
|
-
let currNodeY = 32;
|
|
2731
|
-
const nodesSorted = col.toSorted((a, b) => b.height - a.height);
|
|
2732
|
-
for (const node of nodesSorted) {
|
|
2733
|
-
colWidth = Math.max(colWidth, node.width);
|
|
2734
|
-
node.x = colX;
|
|
2735
|
-
node.y = currNodeY;
|
|
2736
|
-
currNodeY += node.height + VSEP;
|
|
2737
|
-
}
|
|
2738
|
-
maxY = Math.max(maxY, currNodeY);
|
|
2739
|
-
colX += colWidth + HSEP;
|
|
2740
|
-
}
|
|
2741
|
-
this.height = maxY;
|
|
2742
|
-
this.width = colX;
|
|
2743
|
-
return this;
|
|
2744
|
-
}
|
|
2745
|
-
//#endregion
|
|
2746
|
-
//#region src/runner/ComfyWorkflow.ts
|
|
2747
|
-
const asComfyWorkflowID = (x) => x;
|
|
2748
|
-
var ComfyWorkflow = class {
|
|
2749
|
-
constructor(host, data) {
|
|
2750
|
-
this.host = host;
|
|
2751
|
-
this.data = data;
|
|
2752
|
-
this.nodes = [];
|
|
2753
|
-
this.registerNode = (node) => {
|
|
2754
|
-
if (this.data.apiJson == null) throw new Error("graph not hydrated");
|
|
2755
|
-
this.data.apiJson[node.uid] = node.json;
|
|
2756
|
-
this.data.metadata[node.uid] = node.meta;
|
|
2757
|
-
this.nodesIndex.set(node.uid, node);
|
|
2758
|
-
this.nodes.push(node);
|
|
2759
|
-
};
|
|
2760
|
-
this.setMetadata = (nodeID, meta) => {
|
|
2761
|
-
this.data.metadata[nodeID] = meta;
|
|
2762
|
-
};
|
|
2763
|
-
this.getMetadata = (nodeID) => {
|
|
2764
|
-
return this.data.metadata[nodeID] ?? null;
|
|
2765
|
-
};
|
|
2766
|
-
this.problems = [];
|
|
2767
|
-
this.recordProblem = (title, data) => {
|
|
2768
|
-
this.problems.push({
|
|
2769
|
-
title,
|
|
2770
|
-
data
|
|
2771
|
-
});
|
|
2772
|
-
};
|
|
2773
|
-
this._builder = null;
|
|
2774
|
-
this.onUpdate = (prev, next) => {
|
|
2775
|
-
if (prev != null) {
|
|
2776
|
-
this.nodes = [];
|
|
2777
|
-
this.nodesIndex.clear();
|
|
2778
|
-
this.currentExecutingNode = null;
|
|
2779
|
-
}
|
|
2780
|
-
for (const [uid, node] of Object.entries(bang(next.apiJson))) {
|
|
2781
|
-
const meta = next.metadata?.[uid];
|
|
2782
|
-
new ComfyNode(this, uid, node, meta);
|
|
2783
|
-
}
|
|
2784
|
-
};
|
|
2785
|
-
this.nodesIndex = /* @__PURE__ */ new Map();
|
|
2786
|
-
this.toMermaid = (DIR = "LR") => {
|
|
2787
|
-
return [
|
|
2788
|
-
`graph ${DIR}`,
|
|
2789
|
-
this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join("\n"),
|
|
2790
|
-
this.nodes.map((n) => n._incomingEdges().map((i) => {
|
|
2791
|
-
const from = this.nodesIndex.get(i.from);
|
|
2792
|
-
return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${n.$schema.nodeKey}]`;
|
|
2793
|
-
}).join("\n")).join("\n")
|
|
2794
|
-
].join("\n");
|
|
2795
|
-
};
|
|
2796
|
-
this.toWorkflowJson = async (p = {}) => {
|
|
2797
|
-
if (p.layout !== false) this.autoLayout();
|
|
2798
|
-
return convertFlowToLiteGraphJSON(this);
|
|
2799
|
-
};
|
|
2800
|
-
this.toApiJson = (ns = "use_stringified_numbers_only") => {
|
|
2801
|
-
const json = {};
|
|
2802
|
-
const keyOf = (uid) => ns === "use_stringified_numbers_only" ? uid : this.nodesIndex.get(uid)?.uidPrefixed ?? uid;
|
|
2803
|
-
for (const node of this.nodes) {
|
|
2804
|
-
if (node.disabled) continue;
|
|
2805
|
-
const key = ns === "use_stringified_numbers_only" ? node.uid : node.uidPrefixed;
|
|
2806
|
-
const inputs = {};
|
|
2807
|
-
for (const [name, value] of Object.entries(node.json.inputs)) inputs[name] = Array.isArray(value) && typeof value[0] === "string" && typeof value[1] === "number" ? [keyOf(value[0]), value[1]] : value;
|
|
2808
|
-
json[key] = {
|
|
2809
|
-
class_type: node.json.class_type,
|
|
2810
|
-
inputs
|
|
2811
|
-
};
|
|
2812
|
-
}
|
|
2813
|
-
return json;
|
|
2814
|
-
};
|
|
2815
|
-
this.currentExecutingNode = null;
|
|
2816
|
-
this.onProgress = (msg) => {
|
|
2817
|
-
if (this.currentExecutingNode == null) return void console.log("❌ no current executing node", msg);
|
|
2818
|
-
this.currentExecutingNode.progress = msg.data;
|
|
2819
|
-
this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1);
|
|
2820
|
-
};
|
|
2821
|
-
this.getTargetWorkflowFilePath = () => {
|
|
2822
|
-
return join(this.cacheFolderPath, "workflow.json");
|
|
2823
|
-
};
|
|
2824
|
-
this.getTargetPromptFilePath = () => {
|
|
2825
|
-
return join(this.cacheFolderPath, "prompt.json");
|
|
2826
|
-
};
|
|
2827
|
-
this.done = false;
|
|
2828
|
-
this.onExecuting = (msg) => {
|
|
2829
|
-
if (this.currentExecutingNode) this.currentExecutingNode.status = "done";
|
|
2830
|
-
if (msg.data.node == null) {
|
|
2831
|
-
this.currentExecutingNode = null;
|
|
2832
|
-
this.done = true;
|
|
2833
|
-
return;
|
|
2834
|
-
}
|
|
2835
|
-
this.done = false;
|
|
2836
|
-
const node = this.getNodeOrCrash(msg.data.node);
|
|
2837
|
-
this.currentExecutingNode = node;
|
|
2838
|
-
node.status = "executing";
|
|
2839
|
-
node.updatedAt = Date.now();
|
|
2840
|
-
};
|
|
2841
|
-
this.onExecutionCached = (msg) => {
|
|
2842
|
-
for (const x of msg.data.nodes) {
|
|
2843
|
-
const node = this.getNodeOrCrash(x);
|
|
2844
|
-
node.status = "cached";
|
|
2845
|
-
}
|
|
2846
|
-
};
|
|
2847
|
-
this._uidNumber = 0;
|
|
2848
|
-
this.getNodeOrCrash = (nodeID) => {
|
|
2849
|
-
const node = this.nodesIndex.get(nodeID);
|
|
2850
|
-
if (node == null) throw new Error("Node not found:" + nodeID);
|
|
2851
|
-
return node;
|
|
2852
|
-
};
|
|
2853
|
-
this.getNode = (nodeID) => {
|
|
2854
|
-
return this.nodesIndex.get(nodeID);
|
|
2855
|
-
};
|
|
2856
|
-
this.width = 100;
|
|
2857
|
-
this.height = 100;
|
|
2858
|
-
this.autoLayout = comfyWorkflowAutoLayout.bind(this);
|
|
2859
|
-
this.run = async (p = {}) => {
|
|
2860
|
-
const execution = await this.start(p);
|
|
2861
|
-
await execution.done;
|
|
2862
|
-
return execution;
|
|
2863
|
-
};
|
|
2864
|
-
this.start = async (p = {}) => {
|
|
2865
|
-
this.resetRunState();
|
|
2866
|
-
const snapshot = {
|
|
2867
|
-
apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
|
|
2868
|
-
workflowJson: await this.toWorkflowJson()
|
|
2869
|
-
};
|
|
2870
|
-
const out = {
|
|
2871
|
-
client_id: this.host.comfySessionId,
|
|
2872
|
-
prompt: snapshot.apiJson,
|
|
2873
|
-
extra_data: { extra_pnginfo: {
|
|
2874
|
-
workflow: snapshot.workflowJson,
|
|
2875
|
-
comfy_ts_workflow_id: this.id,
|
|
2876
|
-
comfy_ts_version: comfyts.version
|
|
2877
|
-
} }
|
|
2878
|
-
};
|
|
2879
|
-
const res = await this.host.fetch("/prompt", {
|
|
2880
|
-
method: "POST",
|
|
2881
|
-
headers: { "Content-Type": "application/json" },
|
|
2882
|
-
body: JSON.stringify(out)
|
|
2883
|
-
});
|
|
2884
|
-
const promptInfo = softValidate(PromptInfo_ark, await res.json());
|
|
2885
|
-
if (res.status !== 200) throw new InvalidPromptError("ComfyUI /prompt request failed", snapshot, promptInfo);
|
|
2886
|
-
return new ComfyExecution(this, {
|
|
2887
|
-
id: promptInfo.prompt_id,
|
|
2888
|
-
executed: false,
|
|
2889
|
-
graphID: this.id
|
|
2890
|
-
}, {
|
|
2891
|
-
snapshot,
|
|
2892
|
-
saveFormat: p.saveFormat,
|
|
2893
|
-
onProgress: p.onProgress,
|
|
2894
|
-
logProgress: p.log ?? false
|
|
2895
|
-
});
|
|
2896
|
-
};
|
|
2897
|
-
this.id = data.id ?? nanoid(8);
|
|
2898
|
-
this.apiJson = data.apiJson ?? {};
|
|
2899
|
-
data.apiJson = this.apiJson;
|
|
2900
|
-
this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`);
|
|
2901
|
-
}
|
|
2902
|
-
/** number of node in the graph */
|
|
2903
|
-
get size() {
|
|
2904
|
-
return this.nodes.length;
|
|
2905
|
-
}
|
|
2906
|
-
get builder() {
|
|
2907
|
-
if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this);
|
|
2908
|
-
return this._builder;
|
|
2909
|
-
}
|
|
2910
|
-
/** base (untyped) view of the same builder, for generic library code */
|
|
2911
|
-
get builderBase() {
|
|
2912
|
-
if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this);
|
|
2913
|
-
return this._builder;
|
|
2914
|
-
}
|
|
2915
|
-
/** proxy to this.db.schema */
|
|
2916
|
-
get schema() {
|
|
2917
|
-
return this.host.schema;
|
|
2918
|
-
}
|
|
2919
|
-
/** nodes that are still pending execution */
|
|
2920
|
-
get pendingNodes() {
|
|
2921
|
-
return this.nodes.filter((n) => n.status == null || n.status === "waiting");
|
|
2922
|
-
}
|
|
2923
|
-
get nodesByUpdatedAt() {
|
|
2924
|
-
return this.nodes.filter((n) => n.status != null && n.status !== "waiting").sort((a, b) => b.updatedAt - a.updatedAt);
|
|
2925
|
-
}
|
|
2926
|
-
get progressCurrentNode() {
|
|
2927
|
-
return this.currentExecutingNode?.progressReport;
|
|
2928
|
-
}
|
|
2929
|
-
get progressGlobal() {
|
|
2930
|
-
const totalNode = this.nodes.length;
|
|
2931
|
-
const doneNodes = this.nodes.filter((n) => n.status === "done" || n.status === "cached").length;
|
|
2932
|
-
const bonus = this.currentExecutingNode?.progressRatio ?? 0;
|
|
2933
|
-
const score = (doneNodes + bonus) / totalNode;
|
|
2934
|
-
return {
|
|
2935
|
-
percent: this.done ? 100 : score * 100,
|
|
2936
|
-
isDone: this.done,
|
|
2937
|
-
countDone: doneNodes + bonus,
|
|
2938
|
-
countTotal: totalNode
|
|
2939
|
-
};
|
|
2940
|
-
}
|
|
2941
|
-
get cacheFolderPath() {
|
|
2942
|
-
return comfyts.resolveFromOutput(`workflows/${this.id}`);
|
|
2943
|
-
}
|
|
2944
|
-
/** reset per-run node state so the same workflow can run again cleanly */
|
|
2945
|
-
resetRunState() {
|
|
2946
|
-
this.done = false;
|
|
2947
|
-
this.currentExecutingNode = null;
|
|
2948
|
-
for (const node of this.nodes) {
|
|
2949
|
-
node.status = null;
|
|
2950
|
-
node.progress = null;
|
|
2951
|
-
node.progressRatio = 0;
|
|
2952
|
-
}
|
|
2953
|
-
}
|
|
2954
|
-
};
|
|
2955
|
-
const types = scope({
|
|
2956
|
-
ComfySchemaJSON: { "[string]": "ComfyNodeSchemaJSON" },
|
|
2957
|
-
ComfyNodeSchemaJSON: {
|
|
2958
|
-
input: {
|
|
2959
|
-
"required?": { "[string]": "ComfyInputSpec" },
|
|
2960
|
-
"optional?": { "[string]": "ComfyInputSpec" },
|
|
2961
|
-
"hidden?": { "[string]": "ComfyInputHiddenEntry" }
|
|
2962
|
-
},
|
|
2963
|
-
"input_order?": {
|
|
2964
|
-
"required?": "string[]",
|
|
2965
|
-
"optional?": "string[]",
|
|
2966
|
-
"hidden?": "string[]"
|
|
2967
|
-
},
|
|
2968
|
-
output: "ComfyInputType[]",
|
|
2969
|
-
output_is_list: "boolean[]",
|
|
2970
|
-
output_name: "string[]",
|
|
2971
|
-
name: "string",
|
|
2972
|
-
display_name: "string",
|
|
2973
|
-
description: "string",
|
|
2974
|
-
/** */
|
|
2975
|
-
python_module: "string",
|
|
2976
|
-
category: "string",
|
|
2977
|
-
output_node: "boolean",
|
|
2978
|
-
"output_tooltips?": "string[]",
|
|
2979
|
-
"deprecated?": "boolean",
|
|
2980
|
-
"experimental?": "boolean"
|
|
2981
|
-
},
|
|
2982
|
-
ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
|
|
2983
|
-
ComfyInputSpecAlt2: ["ComfyInputType"],
|
|
2984
|
-
ComfyInputSpecAlt3: type([type.null]),
|
|
2985
|
-
ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
|
|
2986
|
-
ComfyInputType: `string | ComfyEnumDef`,
|
|
2987
|
-
ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
|
|
2988
|
-
ComfyInputHiddenEntry_broken2: type.Record("string", type.unknown),
|
|
2989
|
-
ComfyInputHiddenEntry: "string | ComfyInputHiddenEntry_broken1 | ComfyInputHiddenEntry_broken2 ",
|
|
2990
|
-
ComfyInputOpts_simple: "string",
|
|
2991
|
-
ComfyInputOpts_advanced: {
|
|
2992
|
-
"tooltip?": "string | null | ComfyInputOpts_advanced",
|
|
2993
|
-
"multiline?": "boolean | null",
|
|
2994
|
-
"default?": "boolean | number | string | null | number[]",
|
|
2995
|
-
"forceInput?": "boolean | null",
|
|
2996
|
-
"min?": "number | null",
|
|
2997
|
-
"round?": "boolean | number | null",
|
|
2998
|
-
"max?": "number | null",
|
|
2999
|
-
"step?": "number | null",
|
|
3000
|
-
/** Observed on 2024-11-01; 171 occurrences */
|
|
3001
|
-
"dynamicPrompts?": "boolean",
|
|
3002
|
-
/** text widgets (e.g. LoraManager autocomplete fields) */
|
|
3003
|
-
"placeholder?": "string | null",
|
|
3004
|
-
/** COMBO-typed inputs (ComfyUI ≥ 0.3.x) carry their choices here */
|
|
3005
|
-
"options?": "unknown[] | null",
|
|
3006
|
-
"multiselect?": "boolean | null",
|
|
3007
|
-
"padding?": "boolean | 0"
|
|
3008
|
-
},
|
|
3009
|
-
ComfyInputOpts: "ComfyInputOpts_simple | ComfyInputOpts_advanced",
|
|
3010
|
-
ComfyEnumIllustratedItem: {
|
|
3011
|
-
content: "string",
|
|
3012
|
-
"image?": "string | null"
|
|
3013
|
-
},
|
|
3014
|
-
ComfyEnumItem: "string | number | boolean | ComfyEnumIllustratedItem",
|
|
3015
|
-
ComfyEnumDef: `ComfyEnumItem[]`
|
|
3016
|
-
}).export();
|
|
3017
|
-
const ComfySchemaJSON_ark = types.ComfySchemaJSON;
|
|
3018
|
-
types.ComfyNodeSchemaJSON;
|
|
3019
|
-
types.ComfyInputSpec;
|
|
3020
|
-
types.ComfyInputType;
|
|
3021
|
-
types.ComfyEnumDef;
|
|
3022
|
-
types.ComfyInputOpts;
|
|
3023
|
-
//#endregion
|
|
3024
|
-
//#region src/utils/stringifyReadable.ts
|
|
3025
|
-
const tab = " ";
|
|
3026
|
-
function readableStringify(obj, maxLevel = 3, level = 0) {
|
|
3027
|
-
if (level > maxLevel) return JSON.stringify(obj);
|
|
3028
|
-
if (typeof obj !== "object" || obj === null) return JSON.stringify(obj);
|
|
3029
|
-
const indent = " ".repeat(level + 1);
|
|
3030
|
-
let result = "{\n";
|
|
3031
|
-
const keys = Object.keys(obj);
|
|
3032
|
-
for (let i = 0; i < keys.length; i++) {
|
|
3033
|
-
const key = keys[i];
|
|
3034
|
-
const value = obj[key];
|
|
3035
|
-
if (value === void 0) continue;
|
|
3036
|
-
const valueType = typeof value;
|
|
3037
|
-
if (i > 0) result += ",";
|
|
3038
|
-
const thisIndent = i > 0 ? indent.slice(1) : indent;
|
|
3039
|
-
if (Array.isArray(value)) result += `${thisIndent}${JSON.stringify(key)}: ${JSON.stringify(value)}`;
|
|
3040
|
-
else if (valueType === "object" && value !== null) result += `${thisIndent}${JSON.stringify(key)}: ${readableStringify(value, maxLevel, level + 1)}`;
|
|
3041
|
-
else {
|
|
3042
|
-
const formattedValue = valueType === "string" ? JSON.stringify(value) : value;
|
|
3043
|
-
result += `${thisIndent}${JSON.stringify(key)}: ${formattedValue}`;
|
|
3044
|
-
}
|
|
3045
|
-
result += "\n";
|
|
3046
|
-
}
|
|
3047
|
-
result += `${tab.repeat(Math.max(0, level))}}`;
|
|
3048
|
-
return result;
|
|
3049
|
-
}
|
|
3050
|
-
//#endregion
|
|
3051
|
-
//#region src/utils/writeFile.ts
|
|
3052
|
-
const writeFileAsync = async (path, data, fmt) => {
|
|
3053
|
-
return new Promise((resolve, reject) => {
|
|
3054
|
-
logInfo(`writing file: ${ansi.blue(path)}`);
|
|
3055
|
-
writeFile(path, data, fmt, (err) => {
|
|
3056
|
-
if (err) reject(err);
|
|
3057
|
-
else resolve();
|
|
3058
|
-
});
|
|
3059
|
-
});
|
|
3060
|
-
};
|
|
3061
|
-
//#endregion
|
|
3062
|
-
//#region src/manager/types/ComfyManagerAPIModelList.ts
|
|
3063
|
-
const ComfyManagerAPIModelList_ark = type({ models: type({
|
|
3064
|
-
name: type.string.as(),
|
|
3065
|
-
installed: `'False' | 'True' | 'Update'`
|
|
3066
|
-
}).array() });
|
|
3067
|
-
//#endregion
|
|
3068
|
-
//#region src/manager/types/ComfyManagerAPIPluginList.ts
|
|
3069
|
-
const ComfyManagerAPIPluginList_ark = type({
|
|
3070
|
-
custom_nodes: type({
|
|
3071
|
-
title: type.string.as(),
|
|
3072
|
-
installed: `'False' | 'True' | 'Update'`
|
|
3073
|
-
}).array(),
|
|
3074
|
-
chanel: "string"
|
|
3075
|
-
});
|
|
3076
|
-
//#endregion
|
|
3077
|
-
//#region src/host/ComfyManager.ts
|
|
3078
|
-
var ComfyManager = class {
|
|
3079
|
-
constructor(host) {
|
|
3080
|
-
this.host = host;
|
|
3081
|
-
this.fetchPluginsAndModels = async () => {
|
|
3082
|
-
const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
|
|
3083
|
-
this.pluginList = _pluginList;
|
|
3084
|
-
this.modelList = _modelList;
|
|
3085
|
-
};
|
|
3086
|
-
this.configureLogging = (mi) => {
|
|
3087
|
-
return this.fetchGetText(`/manager/terminal?mode=${mi}`);
|
|
3088
|
-
};
|
|
3089
|
-
this.getModelInfoFinalFilePath = (mi) => {
|
|
3090
|
-
return comfyts.registry.getModelInfoFinalFilePath(mi);
|
|
3091
|
-
};
|
|
3092
|
-
this.restartComfyUI = async () => {
|
|
3093
|
-
return this.fetchGetJSON("/manager/reboot");
|
|
3094
|
-
};
|
|
3095
|
-
this.modelList = null;
|
|
3096
|
-
this.fetchModels = () => {
|
|
3097
|
-
return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
|
|
3098
|
-
};
|
|
3099
|
-
this.fetchLogs = () => {
|
|
3100
|
-
return this.fetchGetJSON("/internal/logs");
|
|
3101
|
-
};
|
|
3102
|
-
this.isModelInstalled = (name) => {
|
|
3103
|
-
return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
|
|
3104
|
-
};
|
|
3105
|
-
this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
|
|
3106
|
-
this.installModel = async (model) => {
|
|
3107
|
-
try {
|
|
3108
|
-
this.modelsBeeingInstalled.add(model.name);
|
|
3109
|
-
await this.fetchPost("/model/install", model);
|
|
3110
|
-
this.modelsBeeingInstalled.delete(model.name);
|
|
3111
|
-
logSuccess("Model installed");
|
|
3112
|
-
return true;
|
|
3113
|
-
} catch (exception) {
|
|
3114
|
-
console.error(`Install failed: / ${exception}`);
|
|
3115
|
-
logError("Model Installation Failed");
|
|
3116
|
-
this.modelsBeeingInstalled.delete(model.name);
|
|
3117
|
-
return false;
|
|
3118
|
-
}
|
|
3119
|
-
};
|
|
3120
|
-
this.getModelStatus = (modelName) => {
|
|
3121
|
-
if (this.modelList == null) return "unknown";
|
|
3122
|
-
const entry = this.modelList?.models.find((x) => x.name === modelName);
|
|
3123
|
-
return (() => {
|
|
3124
|
-
if (!entry) return "unknown";
|
|
3125
|
-
if (entry?.installed === "False") return "not-installed";
|
|
3126
|
-
if (entry?.installed === "True") return "installed";
|
|
3127
|
-
if (entry?.installed === "Update") return "update-available";
|
|
3128
|
-
return "error";
|
|
3129
|
-
})();
|
|
3130
|
-
};
|
|
3131
|
-
this.pluginList = null;
|
|
3132
|
-
this.isPluginInstalled = (title) => {
|
|
3133
|
-
if (!this.pluginList || !this.pluginList.custom_nodes) return false;
|
|
3134
|
-
return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === "True") ?? false;
|
|
3135
|
-
};
|
|
3136
|
-
this.getPluginStatus = (title) => {
|
|
3137
|
-
if (this.pluginList == null) return "unknown";
|
|
3138
|
-
const entry = this.pluginList?.custom_nodes.find((x) => x.title === title);
|
|
3139
|
-
return (() => {
|
|
3140
|
-
if (!entry) return "unknown";
|
|
3141
|
-
if (entry?.installed === "False") return "not-installed";
|
|
3142
|
-
if (entry?.installed === "True") return "installed";
|
|
3143
|
-
if (entry?.installed === "Update") return "update-available";
|
|
3144
|
-
return "error";
|
|
3145
|
-
})();
|
|
3146
|
-
};
|
|
3147
|
-
this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
|
|
3148
|
-
try {
|
|
3149
|
-
const skip_update = skipUpdate ? "&skip_update=true" : "";
|
|
3150
|
-
return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
|
|
3151
|
-
} catch (exception) {
|
|
3152
|
-
console.error(`node list retrieval failed: ${exception}`);
|
|
3153
|
-
logError("node list retrieveal failed");
|
|
3154
|
-
throw exception;
|
|
3155
|
-
}
|
|
3156
|
-
};
|
|
3157
|
-
this.installPlugin = async (model) => {
|
|
3158
|
-
try {
|
|
3159
|
-
await this.fetchPost("/customnode/install", model);
|
|
3160
|
-
console.log("✅ Custom Node installed");
|
|
3161
|
-
logSuccess("Custom Node installed");
|
|
3162
|
-
return true;
|
|
3163
|
-
} catch (exception) {
|
|
3164
|
-
console.error(`Install failed: / ${exception}`);
|
|
3165
|
-
logError("Custom Node Installation Failed");
|
|
3166
|
-
return false;
|
|
3167
|
-
}
|
|
3168
|
-
};
|
|
3169
|
-
this.fetchPost = async (endpoint, body, validator) => {
|
|
3170
|
-
const response = await this.host.fetch(endpoint, {
|
|
3171
|
-
method: "POST",
|
|
3172
|
-
headers: { "Content-Type": "application/json" },
|
|
3173
|
-
body: JSON.stringify(body)
|
|
3174
|
-
});
|
|
3175
|
-
if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
|
|
3176
|
-
const status = await response.json();
|
|
3177
|
-
if (validator) return softValidate(validator, status);
|
|
3178
|
-
return status;
|
|
3179
|
-
};
|
|
3180
|
-
this.fetchGetJSON = async (endpoint, validator) => {
|
|
3181
|
-
const response = await this.host.fetch(endpoint);
|
|
3182
|
-
if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
|
|
3183
|
-
const jsonResult = await response.json();
|
|
3184
|
-
if (validator) return softValidate(validator, jsonResult);
|
|
3185
|
-
return jsonResult;
|
|
3186
|
-
};
|
|
3187
|
-
this.fetchGetText = async (endopint) => {
|
|
3188
|
-
return await (await this.host.fetch(endopint)).text();
|
|
3189
|
-
};
|
|
3190
|
-
}
|
|
3191
|
-
get registry() {
|
|
3192
|
-
return comfyts.registry;
|
|
3193
|
-
}
|
|
3194
|
-
waitForHostToBeBackOnline(maxAttempt) {
|
|
3195
|
-
return new Promise((yes, no) => {
|
|
3196
|
-
let attempt = 0;
|
|
3197
|
-
let abortCtrl;
|
|
3198
|
-
const interval = setInterval(async () => {
|
|
3199
|
-
attempt++;
|
|
3200
|
-
if (attempt > maxAttempt) {
|
|
3201
|
-
console.log(` - failure`);
|
|
3202
|
-
clearInterval(interval);
|
|
3203
|
-
no();
|
|
3204
|
-
}
|
|
3205
|
-
if (abortCtrl) abortCtrl.abort();
|
|
3206
|
-
abortCtrl = new AbortController();
|
|
3207
|
-
try {
|
|
3208
|
-
console.log(` - trying...`);
|
|
3209
|
-
await this.host.fetch("/", { signal: abortCtrl.signal }, { apiPrefix: false });
|
|
3210
|
-
clearInterval(interval);
|
|
3211
|
-
yes(true);
|
|
3212
|
-
} catch {}
|
|
3213
|
-
}, 1e3);
|
|
3214
|
-
});
|
|
3215
|
-
}
|
|
3216
|
-
rebootComfyUIAndUpdateHostPluginsAndModelsAfter10Seconds() {
|
|
3217
|
-
setTimeout(() => void this.fetchPluginsAndModels(), 1e4);
|
|
3218
|
-
return this.fetchGetJSON("/manager/reboot");
|
|
3219
|
-
}
|
|
3220
|
-
get titlesOfAllInstalledPlugins() {
|
|
3221
|
-
return this.pluginList?.custom_nodes.filter((x) => x.installed === "True").map((x) => x.title) ?? [];
|
|
3222
|
-
}
|
|
3223
|
-
};
|
|
3224
|
-
//#endregion
|
|
3225
|
-
//#region src/host/ComfyUploader.ts
|
|
3226
|
-
const ComfyUploadImageResult_ark = type({
|
|
3227
|
-
name: type.string.as(),
|
|
3228
|
-
subfolder: "string",
|
|
3229
|
-
type: "string"
|
|
3230
|
-
});
|
|
3231
|
-
/** all those functions are kinda legacy */
|
|
3232
|
-
var ComfyUploader = class {
|
|
3233
|
-
constructor(host) {
|
|
3234
|
-
this.host = host;
|
|
3235
|
-
this.uploadImage = async (img, p) => {
|
|
3236
|
-
const uniqFileName = img.enumName;
|
|
3237
|
-
const expectedFinalName = p.subfolder ? `${p.subfolder}/${uniqFileName}` : uniqFileName;
|
|
3238
|
-
if (this.host.schema.hasImage(expectedFinalName)) {
|
|
3239
|
-
console.log(`[🌁] UPLOAD: 🩶 "${img.absPath}" already exists on current ComfyUI instance`);
|
|
3240
|
-
return expectedFinalName;
|
|
3241
|
-
}
|
|
3242
|
-
const form = new FormData();
|
|
3243
|
-
form.set("image", img.getAsBlob(), uniqFileName);
|
|
3244
|
-
if (p.type) form.set("type", p.type);
|
|
3245
|
-
if (p.override ?? true) form.set("override", "true");
|
|
3246
|
-
if (p.subfolder) form.set("subfolder", p.subfolder);
|
|
3247
|
-
const resp = await this.host.fetch("/upload/image", {
|
|
3248
|
-
method: "POST",
|
|
3249
|
-
body: form
|
|
3250
|
-
});
|
|
3251
|
-
const result = softValidate(ComfyUploadImageResult_ark, await resp.json());
|
|
3252
|
-
console.log("[🌁] UPLOAD: ✅ got", result);
|
|
3253
|
-
if (result.name == null) throw new Error("upload failed");
|
|
3254
|
-
const finalName = result.subfolder ? `${result.subfolder}/${result.name}` : result.name;
|
|
3255
|
-
if (finalName !== expectedFinalName) console.warn(`[🌁] UPLOAD: ⚠️ expected "${expectedFinalName}" but got "${finalName}"`);
|
|
3256
|
-
else console.log(`[🌁] UPLOAD: ✅ finalName is "${finalName}"`);
|
|
3257
|
-
this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName);
|
|
3258
|
-
return finalName;
|
|
3259
|
-
};
|
|
3260
|
-
}
|
|
3261
|
-
};
|
|
3262
|
-
//#endregion
|
|
3263
|
-
//#region src/host/hostUrl.ts
|
|
3264
|
-
/** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
|
|
3265
|
-
function parseHostBase(p) {
|
|
3266
|
-
const hasLegacy = p.host != null || p.port != null || p.https != null;
|
|
3267
|
-
if (p.url != null && hasLegacy) throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`);
|
|
3268
|
-
if (p.url == null) {
|
|
3269
|
-
if (p.host == null || p.port == null) throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`);
|
|
3270
|
-
return {
|
|
3271
|
-
scheme: p.https ? "https" : "http",
|
|
3272
|
-
host: p.host,
|
|
3273
|
-
port: p.port,
|
|
3274
|
-
basePath: ""
|
|
3275
|
-
};
|
|
3276
|
-
}
|
|
3277
|
-
let parsed;
|
|
3278
|
-
try {
|
|
3279
|
-
parsed = new URL(p.url);
|
|
3280
|
-
} catch {
|
|
3281
|
-
throw new Error(`host '${p.id}': unparseable url '${p.url}'`);
|
|
3282
|
-
}
|
|
3283
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`);
|
|
3284
|
-
if (parsed.search !== "" || parsed.hash !== "") throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`);
|
|
3285
|
-
const scheme = parsed.protocol === "https:" ? "https" : "http";
|
|
3286
|
-
const port = parsed.port !== "" ? Number(parsed.port) : scheme === "https" ? 443 : 80;
|
|
3287
|
-
const basePath = parsed.pathname.replace(/\/+$/, "");
|
|
3288
|
-
return {
|
|
3289
|
-
scheme,
|
|
3290
|
-
host: parsed.hostname,
|
|
3291
|
-
port,
|
|
3292
|
-
basePath
|
|
3293
|
-
};
|
|
3294
|
-
}
|
|
3295
|
-
/** http(s) base, port omitted when it is the scheme default */
|
|
3296
|
-
function renderHttpBase(p) {
|
|
3297
|
-
return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
|
|
3298
|
-
}
|
|
3299
|
-
/** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
|
|
3300
|
-
function renderWsUrl(p) {
|
|
3301
|
-
return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
|
|
3302
|
-
}
|
|
3303
|
-
function renderPort(p) {
|
|
3304
|
-
const schemeDefault = p.scheme === "https" ? 443 : 80;
|
|
3305
|
-
return p.port === schemeDefault ? "" : `:${p.port}`;
|
|
3306
|
-
}
|
|
3307
|
-
//#endregion
|
|
3308
|
-
//#region src/host/ResilientWebsocket.ts
|
|
3309
|
-
var ResilientWebSocketClient = class {
|
|
3310
|
-
addInfo(msg) {
|
|
3311
|
-
this.debugMessages.push({
|
|
3312
|
-
type: "info",
|
|
3313
|
-
timestamp: Date.now(),
|
|
3314
|
-
message: msg
|
|
3315
|
-
});
|
|
3316
|
-
logInfo(`[🧦] WS: ${msg}`);
|
|
3317
|
-
}
|
|
3318
|
-
addError(err) {
|
|
3319
|
-
this.debugMessages.push({
|
|
3320
|
-
type: "error",
|
|
3321
|
-
timestamp: Date.now(),
|
|
3322
|
-
message: err
|
|
3323
|
-
});
|
|
3324
|
-
console.error("[🧦] WS:", err);
|
|
3325
|
-
}
|
|
3326
|
-
constructor(options) {
|
|
3327
|
-
this.options = options;
|
|
3328
|
-
this.messageBuffer = [];
|
|
3329
|
-
this.isOpen = false;
|
|
3330
|
-
this.debugMessages = [];
|
|
3331
|
-
this.permanentlyClosed = false;
|
|
3332
|
-
this.url = options.url();
|
|
3333
|
-
this.connect();
|
|
3334
|
-
}
|
|
3335
|
-
/** close and stop reconnecting (lets a script exit cleanly) */
|
|
3336
|
-
disconnectPermanently() {
|
|
3337
|
-
this.permanentlyClosed = true;
|
|
3338
|
-
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
|
|
3339
|
-
this.currentWS?.close();
|
|
3340
|
-
this.currentWS = null;
|
|
3341
|
-
this.isOpen = false;
|
|
3342
|
-
}
|
|
3343
|
-
connect() {
|
|
3344
|
-
this.isOpen = false;
|
|
3345
|
-
const prevWS = this.currentWS;
|
|
3346
|
-
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
|
|
3347
|
-
this.currentWS = null;
|
|
3348
|
-
if (prevWS) {
|
|
3349
|
-
this.addInfo("Previous WebSocket discarded");
|
|
3350
|
-
prevWS.close();
|
|
3351
|
-
}
|
|
3352
|
-
const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
|
|
3353
|
-
ws.binaryType = "arraybuffer";
|
|
3354
|
-
this.currentWS = ws;
|
|
3355
|
-
if (this.options.onMessage) ws.onmessage = (event) => {
|
|
3356
|
-
this.options.onMessage(event);
|
|
3357
|
-
};
|
|
3358
|
-
ws.onopen = (_event) => {
|
|
3359
|
-
if (ws !== this.currentWS) return;
|
|
3360
|
-
this.addInfo("✅ WebSocket connected to " + this.url);
|
|
3361
|
-
this.isOpen = true;
|
|
3362
|
-
this.options.onConnectOrReconnect();
|
|
3363
|
-
this.flushMessageBuffer();
|
|
3364
|
-
};
|
|
3365
|
-
ws.onclose = (event) => {
|
|
3366
|
-
if (ws !== this.currentWS) return;
|
|
3367
|
-
this.isOpen = false;
|
|
3368
|
-
this.options.onClose();
|
|
3369
|
-
if (this.permanentlyClosed) return;
|
|
3370
|
-
this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
|
|
3371
|
-
this.addInfo("⏱️ reconnecting in 2 seconds...");
|
|
3372
|
-
this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
|
|
3373
|
-
};
|
|
3374
|
-
ws.onerror = (event) => {
|
|
3375
|
-
if (ws !== this.currentWS) return;
|
|
3376
|
-
this.addError(`WebSocket ERROR` + JSON.stringify(event));
|
|
3377
|
-
console.error({ event });
|
|
3378
|
-
};
|
|
3379
|
-
}
|
|
3380
|
-
send(message) {
|
|
3381
|
-
if (this.isOpen) this.currentWS?.send(message);
|
|
3382
|
-
else this.messageBuffer.push(message);
|
|
3383
|
-
}
|
|
3384
|
-
flushMessageBuffer() {
|
|
3385
|
-
while (this.messageBuffer.length > 0) {
|
|
3386
|
-
const message = bang(this.messageBuffer.shift());
|
|
3387
|
-
this.currentWS?.send(message);
|
|
3388
|
-
}
|
|
3389
|
-
}
|
|
3390
|
-
/** forward WebSocket add event listeners to the current WebSocket instance */
|
|
3391
|
-
addEventListener(type, listener, options) {
|
|
3392
|
-
this.currentWS?.addEventListener(type, listener, options);
|
|
3393
|
-
}
|
|
3394
|
-
/** forward WebSocket remove event listeners to the current WebSocket instance */
|
|
3395
|
-
removeEventListener(type, listener) {
|
|
3396
|
-
this.currentWS?.removeEventListener(type, listener);
|
|
3397
|
-
}
|
|
3398
|
-
};
|
|
3399
|
-
//#endregion
|
|
3400
|
-
//#region src/host/ComfyHost.ts
|
|
3401
|
-
/** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
|
|
3402
|
-
* 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
|
|
3403
|
-
* (or plain rate limiting on non-cloud hosts). The key value never appears here. */
|
|
3404
|
-
var ComfyHostAuthError = class extends Error {
|
|
3405
|
-
constructor(code, hostId, message) {
|
|
3406
|
-
super(message);
|
|
3407
|
-
this.code = code;
|
|
3408
|
-
this.hostId = hostId;
|
|
3409
|
-
this.name = "ComfyHostAuthError";
|
|
3410
|
-
}
|
|
3411
|
-
};
|
|
3412
|
-
var ComfyHost = class {
|
|
3413
|
-
constructor(data) {
|
|
3414
|
-
this.data = data;
|
|
3415
|
-
this.uploader = new ComfyUploader(this);
|
|
3416
|
-
this.matchRequirements = (requirements) => {
|
|
3417
|
-
const repo = comfyts.registry;
|
|
3418
|
-
for (const req of requirements) {
|
|
3419
|
-
if (req.optional) continue;
|
|
3420
|
-
if (req.type === "customNodesByNodeKey") {
|
|
3421
|
-
if (!(repo.plugins_byNodeKey.get(req.nodeName) ?? []).find((i) => this.manager.isPluginInstalled(i.title))) return false;
|
|
3422
|
-
} else if (req.type === "customNodesByTitle") {
|
|
3423
|
-
const plugin = repo.plugins_byTitle.get(req.title);
|
|
3424
|
-
if (plugin == null) continue;
|
|
3425
|
-
if (!this.manager.isPluginInstalled(plugin.title)) return false;
|
|
3426
|
-
} else if (req.type === "customNodesByURI") {
|
|
3427
|
-
const plugin = repo.plugins_byFile.get(req.uri);
|
|
3428
|
-
if (plugin == null) continue;
|
|
3429
|
-
if (!this.manager.isPluginInstalled(plugin.title)) return false;
|
|
3430
|
-
} else if (req.type === "modelInManager") {
|
|
3431
|
-
if (!this.manager.isModelInstalled(req.modelName)) return false;
|
|
3432
|
-
}
|
|
3433
|
-
}
|
|
3434
|
-
return true;
|
|
3435
|
-
};
|
|
3436
|
-
this.serverLogs = [];
|
|
3437
|
-
this.wantLog = true;
|
|
3438
|
-
this.maxLogs = 200;
|
|
3439
|
-
this.logId = 0;
|
|
3440
|
-
this.toggleServerLogs = () => {
|
|
3441
|
-
this.wantLog = !this.wantLog;
|
|
3442
|
-
return this.manager.configureLogging(this.wantLog);
|
|
3443
|
-
};
|
|
3444
|
-
this.addLog = (content) => {
|
|
3445
|
-
if (this.serverLogs.length > this.maxLogs) this.serverLogs.shift();
|
|
3446
|
-
const d = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
|
|
3447
|
-
this.serverLogs.push({
|
|
3448
|
-
content,
|
|
3449
|
-
id: this.logId++,
|
|
3450
|
-
at: d
|
|
3451
|
-
});
|
|
3452
|
-
};
|
|
3453
|
-
this.installCustomNodeByFile = async (customNodeFile) => {
|
|
3454
|
-
const plugin = comfyts.registry.plugins_byFile.get(customNodeFile);
|
|
3455
|
-
if (plugin == null) throw new Error(`Unknown custom node for file: "${customNodeFile}"`);
|
|
3456
|
-
return this.manager.installPlugin(plugin);
|
|
3457
|
-
};
|
|
3458
|
-
this.installCustomNodeByTitle = async (customNodeTitle) => {
|
|
3459
|
-
const plugin = comfyts.registry.plugins_byTitle.get(customNodeTitle);
|
|
3460
|
-
if (plugin == null) throw new Error(`Unknown custom node for title: "${customNodeTitle}"`);
|
|
3461
|
-
return this.manager.installPlugin(plugin);
|
|
3462
|
-
};
|
|
3463
|
-
this.installCustomNode = async (customNode) => {
|
|
3464
|
-
return this.manager.installPlugin(customNode);
|
|
3465
|
-
};
|
|
3466
|
-
this.getWSUrl = () => {
|
|
3467
|
-
return renderWsUrl(this.base);
|
|
3468
|
-
};
|
|
3469
|
-
this._apiPrefix = null;
|
|
3470
|
-
this.fetch = async (route, init = {}, p = {}) => {
|
|
3471
|
-
const base = this.getServerHostHTTP();
|
|
3472
|
-
const headers = new Headers(init.headers);
|
|
3473
|
-
for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v);
|
|
3474
|
-
const send = (prefixed) => fetch(`${base}${prefixed ? "/api" : ""}${route}`, {
|
|
3475
|
-
...init,
|
|
3476
|
-
headers
|
|
3477
|
-
});
|
|
3478
|
-
const missed = (res) => res.status === 404 || res.status === 405;
|
|
3479
|
-
let res;
|
|
3480
|
-
if (p.apiPrefix === false) res = await send(false);
|
|
3481
|
-
else if (this._apiPrefix != null) {
|
|
3482
|
-
res = await send(this._apiPrefix);
|
|
3483
|
-
if (missed(res)) {
|
|
3484
|
-
const alt = await send(!this._apiPrefix);
|
|
3485
|
-
if (!missed(alt)) res = alt;
|
|
3486
|
-
}
|
|
3487
|
-
} else {
|
|
3488
|
-
res = await send(true);
|
|
3489
|
-
if (missed(res)) {
|
|
3490
|
-
const bare = await send(false);
|
|
3491
|
-
if (!missed(bare)) {
|
|
3492
|
-
this._apiPrefix = false;
|
|
3493
|
-
res = bare;
|
|
3494
|
-
}
|
|
3495
|
-
} else this._apiPrefix = true;
|
|
3496
|
-
}
|
|
3497
|
-
this.throwOnAuthError(res, route);
|
|
3498
|
-
return res;
|
|
3499
|
-
};
|
|
3500
|
-
this.fetchFile = async (route) => {
|
|
3501
|
-
const res = await this.fetch(route, { redirect: "manual" });
|
|
3502
|
-
if (res.status >= 300 && res.status < 400) {
|
|
3503
|
-
const location = res.headers.get("location");
|
|
3504
|
-
if (location == null) throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`);
|
|
3505
|
-
res.body?.cancel();
|
|
3506
|
-
return fetch(new URL(location, this.getServerHostHTTP()));
|
|
3507
|
-
}
|
|
3508
|
-
return res;
|
|
3509
|
-
};
|
|
3510
|
-
this.schemaRetrievalLogs = [];
|
|
3511
|
-
this.resetLog = () => {
|
|
3512
|
-
this.schemaRetrievalLogs.splice(0, this.schemaRetrievalLogs.length);
|
|
3513
|
-
};
|
|
3514
|
-
this.workflow = (p = {}) => {
|
|
3515
|
-
return new ComfyWorkflow(this, {
|
|
3516
|
-
metadata: {},
|
|
3517
|
-
id: p.id ? asComfyWorkflowID(p.id) : void 0
|
|
3518
|
-
});
|
|
3519
|
-
};
|
|
3520
|
-
this.defineWorkflow = (spec) => {
|
|
3521
|
-
return new DefinedWorkflow(this, spec);
|
|
3522
|
-
};
|
|
3523
|
-
this.importWorkflowJson = (json, p = {}) => {
|
|
3524
|
-
const canonical = parseWorkflowJson(json);
|
|
3525
|
-
const apiJson = convertLiteGraphToPrompt(this.schema, canonical);
|
|
3526
|
-
return this.importApiJson(apiJson, p);
|
|
3527
|
-
};
|
|
3528
|
-
this.importApiJson = (json, p = {}) => {
|
|
3529
|
-
const wf = new ComfyWorkflow(this, {
|
|
3530
|
-
apiJson: json,
|
|
3531
|
-
metadata: {},
|
|
3532
|
-
id: p.id ? asComfyWorkflowID(p.id) : void 0
|
|
3533
|
-
});
|
|
3534
|
-
wf.onUpdate(null, wf.data);
|
|
3535
|
-
return wf;
|
|
3536
|
-
};
|
|
3537
|
-
this._ready = null;
|
|
3538
|
-
this._readyResolve = null;
|
|
3539
|
-
this._readyReject = null;
|
|
3540
|
-
this._schemaStrategy = "auto";
|
|
3541
|
-
this._schemaMaxAgeMs = 24 * 36e5;
|
|
3542
|
-
this.connect = (p = {}) => {
|
|
3543
|
-
if (this._ready == null) {
|
|
3544
|
-
this._schemaStrategy = p.schema ?? "auto";
|
|
3545
|
-
this._schemaMaxAgeMs = p.maxAgeMs ?? 24 * 36e5;
|
|
3546
|
-
this._ready = new Promise((res, rej) => {
|
|
3547
|
-
this._readyResolve = res;
|
|
3548
|
-
this._readyReject = rej;
|
|
3549
|
-
});
|
|
3550
|
-
this.initWebsocket();
|
|
3551
|
-
}
|
|
3552
|
-
return this._ready;
|
|
3553
|
-
};
|
|
3554
|
-
this.disconnect = () => {
|
|
3555
|
-
this.ws?.disconnectPermanently();
|
|
3556
|
-
this.ws = null;
|
|
3557
|
-
this._ready = null;
|
|
3558
|
-
};
|
|
3559
|
-
this.ws = null;
|
|
3560
|
-
this._sessionResolve = null;
|
|
3561
|
-
this._isUpdatingSchema = false;
|
|
3562
|
-
this.schemaUpdateResult = null;
|
|
3563
|
-
this._schemaFromCache = null;
|
|
3564
|
-
this.postJSON_ = async (route, body) => {
|
|
3565
|
-
const res = await this.fetch(route, {
|
|
3566
|
-
method: "POST",
|
|
3567
|
-
headers: { "Content-Type": "application/json" },
|
|
3568
|
-
body: JSON.stringify(body)
|
|
3569
|
-
});
|
|
3570
|
-
if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
|
|
3571
|
-
};
|
|
3572
|
-
this.clearQueue = () => {
|
|
3573
|
-
return this.postJSON_("/queue", { clear: true });
|
|
3574
|
-
};
|
|
3575
|
-
this.interrupt = () => {
|
|
3576
|
-
return this.postJSON_("/interrupt", {});
|
|
3577
|
-
};
|
|
3578
|
-
this.fetchRawLogs = async () => {
|
|
3579
|
-
const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
|
|
3580
|
-
if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
|
|
3581
|
-
const json = await res.json();
|
|
3582
|
-
const checked = WsMsgLogsData_ark(json);
|
|
3583
|
-
if (checked instanceof type.errors) {
|
|
3584
|
-
console.log(`[🔴] /!\\ /internal/logs/raw payload does not match schema.`);
|
|
3585
|
-
printArkResultInConsole(checked);
|
|
3586
|
-
}
|
|
3587
|
-
return json;
|
|
3588
|
-
};
|
|
3589
|
-
this.subscribeLogs = async (p) => {
|
|
3590
|
-
const res = await this.fetch("/internal/logs/subscribe", {
|
|
3591
|
-
method: "PATCH",
|
|
3592
|
-
headers: { "Content-Type": "application/json" },
|
|
3593
|
-
body: JSON.stringify({
|
|
3594
|
-
enabled: p.enabled,
|
|
3595
|
-
clientId: p.clientId
|
|
3596
|
-
})
|
|
3597
|
-
}, { apiPrefix: false });
|
|
3598
|
-
if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`);
|
|
3599
|
-
};
|
|
3600
|
-
this.fetchJSON_ = async (route) => {
|
|
3601
|
-
const base = this.getServerHostHTTP();
|
|
3602
|
-
const res = await this.fetch(route);
|
|
3603
|
-
if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`);
|
|
3604
|
-
const contentType = res.headers.get("content-type") ?? "";
|
|
3605
|
-
if (!contentType.includes("json")) throw new Error(`GET ${route} on ${base} answered '${contentType || "no content-type"}' instead of json`);
|
|
3606
|
-
return await res.json();
|
|
3607
|
-
};
|
|
3608
|
-
this.fetchAndUpdateSchema = async () => {
|
|
3609
|
-
try {
|
|
3610
|
-
this.isUpdatingSchema = true;
|
|
3611
|
-
const object_info_json = await this.fetchJSON_("/object_info");
|
|
3612
|
-
const object_info_str = readableStringify(object_info_json, 4);
|
|
3613
|
-
writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
|
|
3614
|
-
const res = ComfySchemaJSON_ark(object_info_json);
|
|
3615
|
-
if (res instanceof type.errors) printArkResultInConsole(res);
|
|
3616
|
-
const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
|
|
3617
|
-
writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
|
|
3618
|
-
this.schema.update({
|
|
3619
|
-
spec: object_info_json,
|
|
3620
|
-
embeddings: embeddings_json
|
|
3621
|
-
});
|
|
3622
|
-
this.schema.RUN_BASIC_CHECKS();
|
|
3623
|
-
await this.writeSDKToDisk();
|
|
3624
|
-
this.isUpdatingSchema = false;
|
|
3625
|
-
this.schemaUpdateResult = { type: "success" };
|
|
3626
|
-
} catch (error) {
|
|
3627
|
-
this.isUpdatingSchema = false;
|
|
3628
|
-
this.schemaUpdateResult = {
|
|
3629
|
-
type: "error",
|
|
3630
|
-
error
|
|
3631
|
-
};
|
|
3632
|
-
console.error(error);
|
|
3633
|
-
console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
|
|
3634
|
-
if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
|
|
3635
|
-
this.markFailed(error);
|
|
3636
|
-
} finally {
|
|
3637
|
-
this.isUpdatingSchema = false;
|
|
3638
|
-
}
|
|
3639
|
-
};
|
|
3640
|
-
this.executions = /* @__PURE__ */ new Map();
|
|
3641
|
-
this._pendingMsgs = /* @__PURE__ */ new Map();
|
|
3642
|
-
this.activePromptID = null;
|
|
3643
|
-
this.latentPreview = null;
|
|
3644
|
-
this.onLatentPreview = null;
|
|
3645
|
-
this.onStatus = null;
|
|
3646
|
-
this.onSession = null;
|
|
3647
|
-
this.onLogs = null;
|
|
3648
|
-
this.comfySessionId = "temp";
|
|
3649
|
-
this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
|
|
3650
|
-
this.status = null;
|
|
3651
|
-
this.base = parseHostBase(this.data);
|
|
3652
|
-
/** folder where file related to the host config will be cached */
|
|
3653
|
-
this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
|
|
3654
|
-
if (!existsSync(this.cacheFolder)) {
|
|
3655
|
-
console.log("🟢 creating folder", this.cacheFolder);
|
|
3656
|
-
mkdirSync(this.cacheFolder, { recursive: true });
|
|
3657
|
-
}
|
|
3658
|
-
this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
|
|
3659
|
-
this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
|
|
3660
|
-
this.sdkDTSPath = comfyts.resolve(this.cacheFolder, `sdk.d.ts`);
|
|
3661
|
-
/** create a new schema */
|
|
3662
|
-
this.schema = new ComfySchema({
|
|
3663
|
-
embeddings: [],
|
|
3664
|
-
spec: {}
|
|
3665
|
-
});
|
|
3666
|
-
}
|
|
3667
|
-
/** root install of ComfyUI on the host filesystem */
|
|
3668
|
-
get absolutePathToComfyUI() {
|
|
3669
|
-
return this.data.installType?.absolutePathToComfyRoot;
|
|
3670
|
-
}
|
|
3671
|
-
get manager() {
|
|
3672
|
-
const value = new ComfyManager(this);
|
|
3673
|
-
Object.defineProperty(this, "manager", { value });
|
|
3674
|
-
return value;
|
|
3675
|
-
}
|
|
3676
|
-
getServerHostHTTP() {
|
|
3677
|
-
return renderHttpBase(this.base);
|
|
3678
|
-
}
|
|
3679
|
-
/** extra headers + X-API-Key, for every http request AND the ws upgrade */
|
|
3680
|
-
authHeaders() {
|
|
3681
|
-
const out = {};
|
|
3682
|
-
if (this.data.headers != null) Object.assign(out, this.data.headers);
|
|
3683
|
-
if (this.data.apiKey != null) out["X-API-Key"] = this.data.apiKey;
|
|
3684
|
-
return out;
|
|
3685
|
-
}
|
|
3686
|
-
throwOnAuthError(res, route) {
|
|
3687
|
-
if (res.status === 401) throw new ComfyHostAuthError(401, this.data.id, this.data.apiKey != null ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired` : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`);
|
|
3688
|
-
if (res.status === 402) throw new ComfyHostAuthError(402, this.data.id, `host '${this.data.id}': 402 on ${route} — insufficient credits`);
|
|
3689
|
-
if (res.status === 429) throw new ComfyHostAuthError(429, this.data.id, `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`);
|
|
3690
|
-
}
|
|
3691
|
-
get isConnected() {
|
|
3692
|
-
return this.ws?.isOpen ?? false;
|
|
3693
|
-
}
|
|
3694
|
-
markReady() {
|
|
3695
|
-
this._readyResolve?.();
|
|
3696
|
-
this._readyResolve = null;
|
|
3697
|
-
this._readyReject = null;
|
|
3698
|
-
}
|
|
3699
|
-
markFailed(error) {
|
|
3700
|
-
this._readyReject?.(error);
|
|
3701
|
-
this._readyResolve = null;
|
|
3702
|
-
this._readyReject = null;
|
|
3703
|
-
}
|
|
3704
|
-
async writeSDKToDisk() {
|
|
3705
|
-
if (this.data.sdkAutoWrite === false) return;
|
|
3706
|
-
const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
|
|
3707
|
-
if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
|
|
3708
|
-
await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
|
|
3709
|
-
}
|
|
3710
|
-
shouldUseSchemaCache() {
|
|
3711
|
-
if (this._schemaStrategy === "refresh") return false;
|
|
3712
|
-
const exists = existsSync(this.comfyJSONPath);
|
|
3713
|
-
if (this._schemaStrategy === "cache") {
|
|
3714
|
-
if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
|
|
3715
|
-
return true;
|
|
3716
|
-
}
|
|
3717
|
-
if (!exists) return false;
|
|
3718
|
-
return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
|
|
3719
|
-
}
|
|
3720
|
-
waitForSession(timeoutMs = 5e3) {
|
|
3721
|
-
if (this.comfySessionId !== "temp") return Promise.resolve();
|
|
3722
|
-
return new Promise((res) => {
|
|
3723
|
-
this._sessionResolve = res;
|
|
3724
|
-
setTimeout(() => {
|
|
3725
|
-
if (this._sessionResolve != null) {
|
|
3726
|
-
console.error(`🔴 no session id from ${this.data.id} after ${timeoutMs}ms — executions may not route back`);
|
|
3727
|
-
this._sessionResolve = null;
|
|
3728
|
-
res();
|
|
3729
|
-
}
|
|
3730
|
-
}, timeoutMs).unref?.();
|
|
3731
|
-
});
|
|
3732
|
-
}
|
|
3733
|
-
initWebsocket() {
|
|
3734
|
-
logInfo(`[👢] WEBSOCKET: starting client to ComfyUI host ${this.data.id}`);
|
|
3735
|
-
this.ws = new ResilientWebSocketClient({
|
|
3736
|
-
onConnectOrReconnect: async () => {
|
|
3737
|
-
logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
|
|
3738
|
-
if (this.shouldUseSchemaCache()) try {
|
|
3739
|
-
await this.loadSchemaFromCache();
|
|
3740
|
-
await this.waitForSession();
|
|
3741
|
-
this.markReady();
|
|
3742
|
-
return;
|
|
3743
|
-
} catch (error) {
|
|
3744
|
-
console.error(`🔴 schema cache load failed, falling back to fetch`, extractErrorMessage(error));
|
|
3745
|
-
}
|
|
3746
|
-
await this.fetchAndUpdateSchema();
|
|
3747
|
-
await this.waitForSession();
|
|
3748
|
-
this.markReady();
|
|
3749
|
-
},
|
|
3750
|
-
onMessage: (e) => this.onMessage(e),
|
|
3751
|
-
url: () => this.getWSUrl(),
|
|
3752
|
-
headers: () => this.authHeaders(),
|
|
3753
|
-
onClose: () => {
|
|
3754
|
-
logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
|
|
3755
|
-
}
|
|
3756
|
-
});
|
|
3757
|
-
return this.ws;
|
|
3758
|
-
}
|
|
3759
|
-
get isUpdatingSchema() {
|
|
3760
|
-
return this._isUpdatingSchema;
|
|
3761
|
-
}
|
|
3762
|
-
set isUpdatingSchema(v) {
|
|
3763
|
-
this._isUpdatingSchema = v;
|
|
3764
|
-
}
|
|
3765
|
-
/** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
|
|
3766
|
-
* idempotent like connect(): N co-imported modules parse the ~4MB cache once.
|
|
3767
|
-
* A MISSING cache degrades LOUDLY to the base types instead of failing the
|
|
3768
|
-
* module import (a fresh consumer project has no cache yet — the bundled
|
|
3769
|
-
* examples must still open in the TUI; run() fetches the real schema through
|
|
3770
|
-
* connect() anyway). Not memoized in that case, so a later gen/connect retries. */
|
|
3771
|
-
loadSchemaFromCache() {
|
|
3772
|
-
if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
|
|
3773
|
-
logError(`no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`);
|
|
3774
|
-
return Promise.resolve();
|
|
3775
|
-
}
|
|
3776
|
-
this._schemaFromCache ??= (async () => {
|
|
3777
|
-
const object_info_json = comfyts.readJSON_(this.comfyJSONPath);
|
|
3778
|
-
const embeddings_json = comfyts.readJSON_(this.embeddingsPath, []);
|
|
3779
|
-
this.schema.update({
|
|
3780
|
-
spec: object_info_json,
|
|
3781
|
-
embeddings: embeddings_json
|
|
3782
|
-
});
|
|
3783
|
-
this.schema.RUN_BASIC_CHECKS();
|
|
3784
|
-
if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
|
|
3785
|
-
})().catch((e) => {
|
|
3786
|
-
this._schemaFromCache = null;
|
|
3787
|
-
throw e;
|
|
3788
|
-
});
|
|
3789
|
-
return this._schemaFromCache;
|
|
3790
|
-
}
|
|
3791
|
-
/** method to either execute or buffer the incoming message */
|
|
3792
|
-
routeOrBuffer(prompt_id, msg) {
|
|
3793
|
-
this.activePromptID = prompt_id;
|
|
3794
|
-
const prompt = this.executions.get(prompt_id);
|
|
3795
|
-
if (prompt == null) {
|
|
3796
|
-
const msgs = this._pendingMsgs.get(prompt_id);
|
|
3797
|
-
if (msgs) msgs.push(msg);
|
|
3798
|
-
else this._pendingMsgs.set(prompt_id, [msg]);
|
|
3799
|
-
return;
|
|
3800
|
-
}
|
|
3801
|
-
prompt.onPromptRelatedMessage(msg);
|
|
3802
|
-
}
|
|
3803
|
-
onMessage(e) {
|
|
3804
|
-
if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
|
|
3805
|
-
if (e.data instanceof ArrayBuffer) {
|
|
3806
|
-
const frame = parseBinaryWsFrame(e.data);
|
|
3807
|
-
if (frame.kind === "preview") {
|
|
3808
|
-
const imageBlob = new Blob([frame.bytes], { type: frame.mime });
|
|
3809
|
-
this.latentPreview = {
|
|
3810
|
-
blob: imageBlob,
|
|
3811
|
-
url: URL.createObjectURL(imageBlob),
|
|
3812
|
-
receivedAt: Date.now(),
|
|
3813
|
-
promptID: this.activePromptID
|
|
3814
|
-
};
|
|
3815
|
-
this.onLatentPreview?.({
|
|
3816
|
-
bytes: frame.bytes,
|
|
3817
|
-
mime: frame.mime,
|
|
3818
|
-
promptID: this.activePromptID
|
|
3819
|
-
});
|
|
3820
|
-
} else if (frame.kind === "unknown" && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
|
|
3821
|
-
this._unknownBinaryFrameTypes.add(frame.eventType);
|
|
3822
|
-
console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`);
|
|
3823
|
-
}
|
|
3824
|
-
return;
|
|
3825
|
-
}
|
|
3826
|
-
const msg_ = JSON.parse(String(e.data));
|
|
3827
|
-
if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
|
|
3828
|
-
if (msg_.type === "crystools.monitor") return;
|
|
3829
|
-
}
|
|
3830
|
-
const res = WsMsg_ark(msg_);
|
|
3831
|
-
if (res instanceof type.errors) {
|
|
3832
|
-
console.log(`[🔴] /!\\ Websocket payload does not match schema.`);
|
|
3833
|
-
printArkResultInConsole(res);
|
|
3834
|
-
}
|
|
3835
|
-
const msg = msg_;
|
|
3836
|
-
if (msg.type === "status") {
|
|
3837
|
-
if (msg.data.sid) {
|
|
3838
|
-
const sidChanged = msg.data.sid !== this.comfySessionId;
|
|
3839
|
-
this.comfySessionId = msg.data.sid;
|
|
3840
|
-
this._sessionResolve?.();
|
|
3841
|
-
this._sessionResolve = null;
|
|
3842
|
-
if (sidChanged) this.onSession?.(msg.data.sid);
|
|
3843
|
-
}
|
|
3844
|
-
this.status = msg.data.status;
|
|
3845
|
-
this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
|
|
3846
|
-
return;
|
|
3847
|
-
}
|
|
3848
|
-
if (msg.type === "progress") {
|
|
3849
|
-
const activePromptID = this.activePromptID;
|
|
3850
|
-
if (activePromptID == null) {
|
|
3851
|
-
console.log(`❌ received a 'progress' msg, but activePromptID is not set`);
|
|
3852
|
-
return;
|
|
3853
|
-
}
|
|
3854
|
-
this.routeOrBuffer(activePromptID, msg);
|
|
3855
|
-
return;
|
|
3856
|
-
}
|
|
3857
|
-
if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
|
|
3858
|
-
this.routeOrBuffer(msg.data.prompt_id, msg);
|
|
3859
|
-
return;
|
|
3860
|
-
}
|
|
3861
|
-
if (msg.type === "manager-terminal-feedback") {
|
|
3862
|
-
this.addLog(msg.data.data);
|
|
3863
|
-
return;
|
|
3864
|
-
}
|
|
3865
|
-
if (msg.type === "logs") {
|
|
3866
|
-
this.onLogs?.(msg.data);
|
|
3867
|
-
return;
|
|
3868
|
-
}
|
|
3869
|
-
console.log("❌", "Unknown message:", msg);
|
|
3870
|
-
logError("Unknown message type: " + JSON.stringify(msg.type));
|
|
3871
|
-
}
|
|
3872
|
-
};
|
|
3873
|
-
//#endregion
|
|
3874
|
-
//#region src/utils/downloadFile.ts
|
|
3875
|
-
/** Usage example
|
|
3876
|
-
* | ;(async () => {
|
|
3877
|
-
* | try {
|
|
3878
|
-
* | await downloadFile('https://example.com/file', 'folder/filename')
|
|
3879
|
-
* | console.log('Download completed successfully')
|
|
3880
|
-
* | } catch (error) {
|
|
3881
|
-
* | console.error('Download failed:', error)
|
|
3882
|
-
* | }
|
|
3883
|
-
* | })()
|
|
3884
|
-
* |
|
|
3885
|
-
*/
|
|
3886
|
-
function downloadFile(url, outputPath, logPrefix = " - ") {
|
|
3887
|
-
mkdirSync(dirname(outputPath), { recursive: true });
|
|
3888
|
-
return new Promise((resolve, reject) => {
|
|
3889
|
-
https.get(url, (response) => {
|
|
3890
|
-
if (response.statusCode === 302 || response.statusCode === 301) {
|
|
3891
|
-
const newUrl = response.headers.location;
|
|
3892
|
-
console.log(`Redirected to ${newUrl}`);
|
|
3893
|
-
resolve(downloadFile(newUrl, outputPath));
|
|
3894
|
-
return;
|
|
3895
|
-
}
|
|
3896
|
-
if (response.statusCode !== 200) {
|
|
3897
|
-
reject(`Failed to download file: Status Code ${response.statusCode}`);
|
|
3898
|
-
return;
|
|
3899
|
-
}
|
|
3900
|
-
const rawLen = response.headers["content-length"];
|
|
3901
|
-
if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
|
|
3902
|
-
else {
|
|
3903
|
-
const totalSize = parseInt(rawLen, 10);
|
|
3904
|
-
let downloaded = 0;
|
|
3905
|
-
let lastLoggedPercentage = 0;
|
|
3906
|
-
response.on("data", (chunk) => {
|
|
3907
|
-
downloaded += chunk.length;
|
|
3908
|
-
const percentage = Math.round(downloaded / totalSize * 100);
|
|
3909
|
-
if (percentage >= lastLoggedPercentage + 1) {
|
|
3910
|
-
stdout.write(`\r${logPrefix}${percentage}% downloaded`);
|
|
3911
|
-
lastLoggedPercentage = percentage;
|
|
3912
|
-
}
|
|
3913
|
-
});
|
|
3914
|
-
}
|
|
3915
|
-
const fileStream = fs.createWriteStream(outputPath);
|
|
3916
|
-
response.pipe(fileStream);
|
|
3917
|
-
fileStream.on("finish", () => {
|
|
3918
|
-
console.log(` (DONE)`);
|
|
3919
|
-
fileStream.close();
|
|
3920
|
-
resolve(true);
|
|
3921
|
-
});
|
|
3922
|
-
}).on("error", (err) => reject(err));
|
|
3923
|
-
});
|
|
3924
|
-
}
|
|
3925
|
-
//#endregion
|
|
3926
|
-
//#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
|
|
3927
|
-
const MANAGER_RAW_BASE = "https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main";
|
|
3928
|
-
const MANAGER_MIRROR_FILES = [
|
|
3929
|
-
"custom-node-list.json",
|
|
3930
|
-
"model-list.json",
|
|
3931
|
-
"extension-node-map.json",
|
|
3932
|
-
"alter-list.json",
|
|
3933
|
-
"github-stats.json"
|
|
3934
|
-
];
|
|
3935
|
-
async function DownloadComfyManagerJSONs() {
|
|
3936
|
-
for (const file of MANAGER_MIRROR_FILES) {
|
|
3937
|
-
const dest = `src/manager/json/${file}`;
|
|
3938
|
-
await downloadFile(`${MANAGER_RAW_BASE}/${file}`, dest, `- downloading ${file}...`);
|
|
3939
|
-
console.log(` saved at ${ansi.blue(dest)}`);
|
|
3940
|
-
}
|
|
3941
|
-
}
|
|
3942
|
-
//#endregion
|
|
3943
|
-
//#region src/utils/githubRegexes.ts
|
|
3944
|
-
const githubRegexpV1 = /https:\/\/github.com\/(.+?)\/(.+?)\/?/;
|
|
3945
|
-
const githubRegexpV2 = /https:\/\/github.com\/(.+?)\/([a-zA-Z0-9-_]+)?/;
|
|
3946
|
-
//#endregion
|
|
3947
|
-
//#region src/manager/json/custom-node-list.extra.ts
|
|
3948
|
-
const ComfyPluginExtra = [{
|
|
3949
|
-
id: "TEMP_ComfyUI-BRIA_AI-RMBG",
|
|
3950
|
-
author: "ZHO-ZHO-ZHO",
|
|
3951
|
-
title: "TEMP_ComfyUI-BRIA_AI-RMBG",
|
|
3952
|
-
reference: "https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG",
|
|
3953
|
-
files: ["https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG"],
|
|
3954
|
-
install_type: "git-clone",
|
|
3955
|
-
description: "better rembg ?"
|
|
3956
|
-
}];
|
|
3957
|
-
//#endregion
|
|
3958
|
-
//#region src/manager/loaders/parseReport.ts
|
|
3959
|
-
/** root shape of a manager mirror file is broken: nothing to salvage, fail loud */
|
|
3960
|
-
var ManagerParseError = class extends Error {
|
|
3961
|
-
constructor(file, detail) {
|
|
3962
|
-
super(`🔴 [manager] ${file} root shape invalid: ${detail}`);
|
|
3963
|
-
this.file = file;
|
|
3964
|
-
this.detail = detail;
|
|
3965
|
-
this.name = "ManagerParseError";
|
|
3966
|
-
}
|
|
3967
|
-
};
|
|
3968
|
-
var FileParseCounter = class {
|
|
3969
|
-
constructor(file) {
|
|
3970
|
-
this.file = file;
|
|
3971
|
-
this.total = 0;
|
|
3972
|
-
this.accepted = 0;
|
|
3973
|
-
this.skipped = /* @__PURE__ */ new Map();
|
|
3974
|
-
}
|
|
3975
|
-
ok() {
|
|
3976
|
-
this.total++;
|
|
3977
|
-
this.accepted++;
|
|
3978
|
-
}
|
|
3979
|
-
skip(reason, firstError) {
|
|
3980
|
-
this.total++;
|
|
3981
|
-
const prev = this.skipped.get(reason);
|
|
3982
|
-
if (prev == null) this.skipped.set(reason, {
|
|
3983
|
-
count: 1,
|
|
3984
|
-
firstError
|
|
3985
|
-
});
|
|
3986
|
-
else prev.count++;
|
|
3987
|
-
}
|
|
3988
|
-
};
|
|
3989
|
-
/** per-file row accounting for the manager mirror parse; printed on every registry build so upstream drift stays visible */
|
|
3990
|
-
var ManagerParseReport = class {
|
|
3991
|
-
constructor() {
|
|
3992
|
-
this.counters = [];
|
|
3993
|
-
}
|
|
3994
|
-
file(name) {
|
|
3995
|
-
const counter = new FileParseCounter(name);
|
|
3996
|
-
this.counters.push(counter);
|
|
3997
|
-
return counter;
|
|
3998
|
-
}
|
|
3999
|
-
print() {
|
|
4000
|
-
console.log(ansi.bold(`[📘 registry] parse report:`));
|
|
4001
|
-
for (const c of this.counters) {
|
|
4002
|
-
const skippedTotal = [...c.skipped.values()].reduce((acc, cur) => acc + cur.count, 0);
|
|
4003
|
-
const headline = ` ${c.file}: ${c.total} rows, ${c.accepted} accepted, ${skippedTotal} skipped`;
|
|
4004
|
-
console.log(skippedTotal === 0 ? headline : ansi.red(headline));
|
|
4005
|
-
for (const [reason, info] of c.skipped) console.log(ansi.red(` - ${reason} x${info.count}, first: ${info.firstError}`));
|
|
4006
|
-
}
|
|
4007
|
-
}
|
|
4008
|
-
};
|
|
4009
|
-
//#endregion
|
|
4010
|
-
//#region src/manager/types/ComfyManagerFilePluginList.ts
|
|
4011
|
-
const ComfyManagerFilePluginListRoot_ark = type({ custom_nodes: "unknown[]" });
|
|
4012
|
-
//#endregion
|
|
4013
|
-
//#region src/manager/types/ComfyManagerPluginInfo.ts
|
|
4014
|
-
const ComfyManagerRawPluginInfo_ark = type({
|
|
4015
|
-
author: "string",
|
|
4016
|
-
title: type.string.as(),
|
|
4017
|
-
reference: "string",
|
|
4018
|
-
files: type.string.as().array(),
|
|
4019
|
-
install_type: "string",
|
|
4020
|
-
description: "string",
|
|
4021
|
-
"id?": type.string.as(),
|
|
4022
|
-
"preemptions?": "string[]",
|
|
4023
|
-
"pip?": "string[]",
|
|
4024
|
-
"nodename_pattern?": "string",
|
|
4025
|
-
"apt_dependency?": "string[]",
|
|
4026
|
-
"js_path?": "string",
|
|
4027
|
-
"version?": "string",
|
|
4028
|
-
"tags?": "string[]",
|
|
4029
|
-
"reference2?": "string",
|
|
4030
|
-
"category?": "string",
|
|
4031
|
-
"name?": "string",
|
|
4032
|
-
"license?": "string",
|
|
4033
|
-
"nickname?": "string",
|
|
4034
|
-
"stars?": "number",
|
|
4035
|
-
"last_update?": "string",
|
|
4036
|
-
"badges?": "string[]",
|
|
4037
|
-
"dependencies?": "string[]"
|
|
4038
|
-
});
|
|
4039
|
-
//#endregion
|
|
4040
|
-
//#region src/manager/loaders/step2_custom-node-list-loader.ts
|
|
4041
|
-
const _getKnownPlugins = (DB) => {
|
|
4042
|
-
const counter = DB.report.file("custom-node-list.json");
|
|
4043
|
-
let totalFileSeen = 0;
|
|
4044
|
-
const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
|
|
4045
|
-
if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
|
|
4046
|
-
const canonical = [];
|
|
4047
|
-
for (const row of root.custom_nodes) {
|
|
4048
|
-
const res = ComfyManagerRawPluginInfo_ark(row);
|
|
4049
|
-
if (res instanceof type.errors) {
|
|
4050
|
-
counter.skip("schema", res.summary);
|
|
4051
|
-
continue;
|
|
4052
|
-
}
|
|
4053
|
-
const plugin = normalizePluginInfo(res);
|
|
4054
|
-
if (plugin == null) {
|
|
4055
|
-
counter.skip("id-unrecoverable", res.reference);
|
|
4056
|
-
continue;
|
|
4057
|
-
}
|
|
4058
|
-
canonical.push(plugin);
|
|
4059
|
-
counter.ok();
|
|
4060
|
-
}
|
|
4061
|
-
const knownPluginList = canonical.concat(ComfyPluginExtra);
|
|
4062
|
-
for (const plugin of knownPluginList) {
|
|
4063
|
-
if (DB.opts.check && DB.plugins_byTitle.has(plugin.title)) console.log(` ❌ plugin.title: "${plugin.title}" is duplicated`);
|
|
4064
|
-
DB.plugins_byTitle.set(plugin.title, plugin);
|
|
4065
|
-
for (const pluginURI of plugin.files) {
|
|
4066
|
-
totalFileSeen++;
|
|
4067
|
-
if (DB.opts.check && DB.plugins_byFile.has(pluginURI)) console.log(` ❌ plugin.file: "${pluginURI}" is duplicated`);
|
|
4068
|
-
DB.plugins_byFile.set(pluginURI, plugin);
|
|
4069
|
-
}
|
|
4070
|
-
}
|
|
4071
|
-
if (DB.opts.genTypes) {
|
|
4072
|
-
let out1 = "";
|
|
4073
|
-
const allPluginsSortedByTitles = [...DB.plugins_byTitle.values()].sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
|
|
4074
|
-
out1 += "// prettier-ignore\n";
|
|
4075
|
-
out1 += "export type KnownComfyPluginTitle =\n";
|
|
4076
|
-
for (const plugin of allPluginsSortedByTitles) {
|
|
4077
|
-
out1 += ` /** ${plugin.id} - ${plugin.reference} */\n`;
|
|
4078
|
-
out1 += ` | ${JSON.stringify(plugin.title)}\n`;
|
|
4079
|
-
}
|
|
4080
|
-
out1 += "\n";
|
|
4081
|
-
const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
|
|
4082
|
-
writeFileSync(out1Path, out1 + "\n", "utf-8");
|
|
4083
|
-
console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
|
|
4084
|
-
let out2 = "";
|
|
4085
|
-
const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
4086
|
-
out2 += "// prettier-ignore\n";
|
|
4087
|
-
out2 += "export type KnownComfyPluginURL =\n";
|
|
4088
|
-
for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
|
|
4089
|
-
const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
|
|
4090
|
-
writeFileSync(out2Path, out2, "utf-8");
|
|
4091
|
-
console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
|
|
4092
|
-
}
|
|
4093
|
-
if (DB.opts.check) {
|
|
4094
|
-
console.log(` - ${knownPluginList.length} CustomNodes in file`);
|
|
4095
|
-
console.log(` - ${DB.plugins_byTitle.size} CustomNodes registered in map`);
|
|
4096
|
-
console.log(` - ${totalFileSeen} CustomNodes-File Seen`);
|
|
4097
|
-
console.log(` - ${DB.plugins_byFile.size} CustomNodes-File registered in map`);
|
|
4098
|
-
}
|
|
4099
|
-
};
|
|
4100
|
-
/**
|
|
4101
|
-
* raw → canonical: recover the missing `id` (absent on ~76% of upstream rows)
|
|
4102
|
-
* from the title, else the github repo name. null = unrecoverable, caller
|
|
4103
|
-
* reports and skips the row.
|
|
4104
|
-
*/
|
|
4105
|
-
function normalizePluginInfo(p) {
|
|
4106
|
-
const id = p.id ?? p.title ?? p.reference.match(githubRegexpV1)?.[2];
|
|
4107
|
-
if (id == null) return null;
|
|
4108
|
-
return {
|
|
4109
|
-
...p,
|
|
4110
|
-
id
|
|
4111
|
-
};
|
|
4112
|
-
}
|
|
4113
|
-
//#endregion
|
|
4114
|
-
//#region src/manager/types/ComfyManagerPluginContentMetadata.ts
|
|
4115
|
-
const ComfyManagerPluginContentMetadata_ark = type({
|
|
4116
|
-
"title_aux?": type.string.or(type.null),
|
|
4117
|
-
"author?": "string",
|
|
4118
|
-
"nickname?": "string",
|
|
4119
|
-
"description?": "string",
|
|
4120
|
-
"nodename_pattern?": "string",
|
|
4121
|
-
"title?": "string",
|
|
4122
|
-
"preemptions?": "string[]"
|
|
4123
|
-
});
|
|
4124
|
-
//#endregion
|
|
4125
|
-
//#region src/manager/types/ComfyManagerPluginEnums.ts
|
|
4126
|
-
const ComfyManagerPluginContentNodeName_ark = type.string.as();
|
|
4127
|
-
type("string");
|
|
4128
|
-
//#endregion
|
|
4129
|
-
//#region src/manager/types/ComfyManagerFilePluginContent.ts
|
|
4130
|
-
const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNodeName_ark.array(), ComfyManagerPluginContentMetadata_ark]);
|
|
4131
|
-
//#endregion
|
|
4132
|
-
//#region src/manager/loaders/step3_extension-node-map-loader.ts
|
|
4133
|
-
const _getCustomNodeRegistry = (DB) => {
|
|
4134
|
-
const counter = DB.report.file("extension-node-map.json");
|
|
4135
|
-
let totalCustomNodeSeen = 0;
|
|
4136
|
-
const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
|
|
4137
|
-
const root = type("Record<string, unknown>")(raw);
|
|
4138
|
-
if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
|
|
4139
|
-
for (const [url, value] of Object.entries(root)) {
|
|
4140
|
-
const res = ComfyManagerExtensionNodeMapEntry_ark(value);
|
|
4141
|
-
if (res instanceof type.errors) {
|
|
4142
|
-
counter.skip("schema", `${url}: ${res.summary}`);
|
|
4143
|
-
continue;
|
|
4144
|
-
}
|
|
4145
|
-
const plugin = DB.plugins_byFile.get(url);
|
|
4146
|
-
if (plugin == null) {
|
|
4147
|
-
counter.skip("unknown-plugin-url", url);
|
|
4148
|
-
continue;
|
|
4149
|
-
}
|
|
4150
|
-
counter.ok();
|
|
4151
|
-
const comfyNodeNames = res[0];
|
|
4152
|
-
totalCustomNodeSeen += comfyNodeNames.length;
|
|
4153
|
-
const pythonModule = reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin);
|
|
4154
|
-
const nodesInPlugin = DB.customNodes_byPluginName.get(plugin.title) ?? [];
|
|
4155
|
-
DB.customNodes_byPluginName.set(plugin.title, nodesInPlugin);
|
|
4156
|
-
for (const nodeNameInComfy of comfyNodeNames) {
|
|
4157
|
-
const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy);
|
|
4158
|
-
const prevEntry = DB.plugins_byNodeKey.get(nodeKey);
|
|
4159
|
-
if (prevEntry == null) DB.plugins_byNodeKey.set(nodeKey, [plugin]);
|
|
4160
|
-
else prevEntry.push(plugin);
|
|
4161
|
-
nodesInPlugin.push(nodeKey);
|
|
4162
|
-
}
|
|
4163
|
-
}
|
|
4164
|
-
if (DB.opts.genTypes) {
|
|
4165
|
-
let out = "";
|
|
4166
|
-
const sortedNodeKeys = [...DB.plugins_byNodeKey.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
4167
|
-
out += "// prettier-ignore\n";
|
|
4168
|
-
out += "export type KnownComfyCustomNodeName =\n";
|
|
4169
|
-
for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
|
|
4170
|
-
out += "\n";
|
|
4171
|
-
const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
|
|
4172
|
-
writeFileSync(outPath, out + "\n", "utf-8");
|
|
4173
|
-
console.log(` > generated: ${ansi.blue.underline(outPath)}`);
|
|
4174
|
-
}
|
|
4175
|
-
if (DB.opts.check) {
|
|
4176
|
-
console.log(` - ${totalCustomNodeSeen} CustomNodes names processed`);
|
|
4177
|
-
console.log(` - ${DB.plugins_byNodeKey.size} unique node keys registered in map`);
|
|
4178
|
-
}
|
|
4179
|
-
};
|
|
4180
|
-
function reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin) {
|
|
4181
|
-
if (plugin.id === "nodes" && plugin.reference === "https://github.com/comfyanonymous/ComfyUI") return "nodes";
|
|
4182
|
-
const repoName = plugin.reference.match(githubRegexpV2)?.[2];
|
|
4183
|
-
if (repoName) return `custom_nodes.${repoName}`;
|
|
4184
|
-
return `custom_nodes.${plugin.id}`;
|
|
4185
|
-
}
|
|
4186
|
-
//#endregion
|
|
4187
|
-
//#region src/manager/json/model-list.extra.ts
|
|
4188
|
-
const extraModels = { models: [{
|
|
4189
|
-
name: "TEMP_briaai_RMBG-1.4",
|
|
4190
|
-
type: "controlnet",
|
|
4191
|
-
base: "SDXL",
|
|
4192
|
-
save_path: "custom_nodes/ComfyUI-BRIA_AI-RMBG/RMBG-1.4",
|
|
4193
|
-
description: "<3 stuff",
|
|
4194
|
-
reference: "https://huggingface.co/briaai/RMBG-1.4",
|
|
4195
|
-
filename: "model.pth",
|
|
4196
|
-
url: "https://huggingface.co/briaai/RMBG-1.4/resolve/main/model.pth?download=true"
|
|
4197
|
-
}, {
|
|
4198
|
-
name: "4x_NMKD-Siax_200k",
|
|
4199
|
-
type: "upscale",
|
|
4200
|
-
base: "upscale",
|
|
4201
|
-
save_path: "default",
|
|
4202
|
-
description: "4xRealWebPhoto_v4_dat2",
|
|
4203
|
-
reference: "https://openmodeldb.info/models/4x-RealWebPhoto-v4-dat2",
|
|
4204
|
-
filename: "4xRealWebPhoto_v4_dat2.pth",
|
|
4205
|
-
url: "https://huggingface.co/gemasai/4x_NMKD-Siax_200k/resolve/main/4xRealWebPhoto_v4_dat2.pth"
|
|
4206
|
-
}] };
|
|
4207
|
-
//#endregion
|
|
4208
|
-
//#region src/manager/types/ComfyManagerFileModelInfo.ts
|
|
4209
|
-
const ComfyManagerFileModelInfoRoot_ark = type({ models: "unknown[]" });
|
|
4210
|
-
//#endregion
|
|
4211
|
-
//#region src/manager/types/ComfyManagerModelInfo.ts
|
|
4212
|
-
const ComfyManagerModelInfo_ark = type({
|
|
4213
|
-
name: type.string.as(),
|
|
4214
|
-
type: type.string.as(),
|
|
4215
|
-
base: type.string.as(),
|
|
4216
|
-
save_path: type.string.as(),
|
|
4217
|
-
description: "string",
|
|
4218
|
-
reference: "string",
|
|
4219
|
-
filename: "string",
|
|
4220
|
-
url: "string",
|
|
4221
|
-
"size?": "string"
|
|
4222
|
-
});
|
|
4223
|
-
//#endregion
|
|
4224
|
-
//#region src/manager/loaders/step4_model-list-loader.ts
|
|
4225
|
-
const _getKnownModels = (DB) => {
|
|
4226
|
-
const counter = DB.report.file("model-list.json");
|
|
4227
|
-
const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
|
|
4228
|
-
if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
|
|
4229
|
-
const canonical = [];
|
|
4230
|
-
for (const row of root.models) {
|
|
4231
|
-
const res = ComfyManagerModelInfo_ark(row);
|
|
4232
|
-
if (res instanceof type.errors) {
|
|
4233
|
-
counter.skip("schema", res.summary);
|
|
4234
|
-
continue;
|
|
4235
|
-
}
|
|
4236
|
-
canonical.push(res);
|
|
4237
|
-
counter.ok();
|
|
4238
|
-
}
|
|
4239
|
-
const knownModelList = canonical.concat(extraModels.models);
|
|
4240
|
-
for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
|
|
4241
|
-
if (DB.opts.genTypes) {
|
|
4242
|
-
let out1 = "";
|
|
4243
|
-
const uniqCategories = knownModelList.reduce((acc, cur) => {
|
|
4244
|
-
if (acc[cur.type] != null) acc[cur.type] += 1;
|
|
4245
|
-
else acc[cur.type] = 1;
|
|
4246
|
-
return acc;
|
|
4247
|
-
}, {});
|
|
4248
|
-
out1 += `// prettier-ignore\n`;
|
|
4249
|
-
out1 += "export type KnownModel_Type =\n";
|
|
4250
|
-
for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\n`;
|
|
4251
|
-
out1 += "\n";
|
|
4252
|
-
out1 += "export const knownModel_Type: KnownModel_Type[] = [\n";
|
|
4253
|
-
for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
|
|
4254
|
-
out1 += "]\n";
|
|
4255
|
-
const out1Path = "src/manager/generated/KnownModel_Type.ts";
|
|
4256
|
-
writeFileSync(out1Path, out1 + "\n", "utf-8");
|
|
4257
|
-
console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
|
|
4258
|
-
let out4 = "";
|
|
4259
|
-
const uniqSavePath = knownModelList.reduce((acc, cur) => {
|
|
4260
|
-
if (acc[cur.save_path] != null) acc[cur.save_path] += 1;
|
|
4261
|
-
else acc[cur.save_path] = 1;
|
|
4262
|
-
return acc;
|
|
4263
|
-
}, {});
|
|
4264
|
-
out4 += `// prettier-ignore\n`;
|
|
4265
|
-
out4 += "export type KnownModel_SavePath =\n";
|
|
4266
|
-
for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` | ${JSON.stringify(cat).padEnd(50)} // x ${count.toString().padStart(3)}\n`;
|
|
4267
|
-
out4 += "\n";
|
|
4268
|
-
out4 += "export const knownModel_SavePath: KnownModel_SavePath[] = [\n";
|
|
4269
|
-
for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
|
|
4270
|
-
out4 += "]\n";
|
|
4271
|
-
const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
|
|
4272
|
-
writeFileSync(out4Path, out4 + "\n", "utf-8");
|
|
4273
|
-
console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
|
|
4274
|
-
let out2 = "";
|
|
4275
|
-
const uniqBases = knownModelList.reduce((acc, cur) => {
|
|
4276
|
-
if (acc[cur.base] != null) acc[cur.base] += 1;
|
|
4277
|
-
else acc[cur.base] = 1;
|
|
4278
|
-
return acc;
|
|
4279
|
-
}, {});
|
|
4280
|
-
out2 += `// prettier-ignore\n`;
|
|
4281
|
-
out2 += "export type KnownModel_Base =\n";
|
|
4282
|
-
for (const [cat, count] of Object.entries(uniqBases)) out2 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\n`;
|
|
4283
|
-
out2 += "\n";
|
|
4284
|
-
out2 += "// prettier-ignore\n";
|
|
4285
|
-
out2 += "export const knownModel_Base: KnownModel_Base[] = [\n";
|
|
4286
|
-
for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
|
|
4287
|
-
out2 += "]\n";
|
|
4288
|
-
const out2Path = "src/manager/generated/KnownModel_Base.ts";
|
|
4289
|
-
writeFileSync(out2Path, out2 + "\n", "utf-8");
|
|
4290
|
-
console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
|
|
4291
|
-
let out3 = "";
|
|
4292
|
-
const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
|
|
4293
|
-
out3 += `// prettier-ignore\n`;
|
|
4294
|
-
out3 += "export type KnownModel_Name =\n";
|
|
4295
|
-
for (const mi of sortedModels) {
|
|
4296
|
-
out3 += ` /** ${mi.description}\n`;
|
|
4297
|
-
out3 += ` * ${mi.size} - ${mi.url}\n`;
|
|
4298
|
-
out3 += ` * see ${mi.reference}\n`;
|
|
4299
|
-
out3 += ` */\n`;
|
|
4300
|
-
out3 += ` | ${JSON.stringify(mi.name)}\n`;
|
|
4301
|
-
}
|
|
4302
|
-
out3 += "\n";
|
|
4303
|
-
const out3Path = "src/manager/generated/KnownModel_Name.ts";
|
|
4304
|
-
writeFileSync(out3Path, out3 + "\n", "utf-8");
|
|
4305
|
-
console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
|
|
4306
|
-
let out99 = "";
|
|
4307
|
-
out99 += `// prettier-ignore\n`;
|
|
4308
|
-
out99 += "export type KnownModel_FileName =\n";
|
|
4309
|
-
for (const mi of sortedModels) {
|
|
4310
|
-
out99 += ` /** ${mi.description}\n`;
|
|
4311
|
-
out99 += ` * ${mi.size} - ${mi.url}\n`;
|
|
4312
|
-
out99 += ` * see ${mi.reference}\n`;
|
|
4313
|
-
out99 += ` */\n`;
|
|
4314
|
-
out99 += ` | ${JSON.stringify(mi.filename)}\n`;
|
|
4315
|
-
}
|
|
4316
|
-
out99 += "\n";
|
|
4317
|
-
const out99Path = "src/manager/generated/KnownModel_FileName.ts";
|
|
4318
|
-
writeFileSync(out99Path, out99 + "\n", "utf-8");
|
|
4319
|
-
console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
|
|
4320
|
-
}
|
|
4321
|
-
if (DB.opts.check) {
|
|
4322
|
-
console.log(`${knownModelList.length} models found`);
|
|
4323
|
-
console.log(`${DB.knownModels.size} models registered map`);
|
|
4324
|
-
if (knownModelList.length !== DB.knownModels.size) console.log(`❌ some models are either duplicated or have overlapping indexing keys`);
|
|
4325
|
-
}
|
|
4326
|
-
};
|
|
4327
|
-
//#endregion
|
|
4328
|
-
//#region src/manager/types/ComfyManagerAlterInfo.ts
|
|
4329
|
-
const ComfyManagerAlterInfo_ark = type({
|
|
4330
|
-
id: "string",
|
|
4331
|
-
tags: "string",
|
|
4332
|
-
description: "string"
|
|
4333
|
-
});
|
|
4334
|
-
const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
|
|
4335
|
-
//#endregion
|
|
4336
|
-
//#region src/manager/loaders/step5_alter-list-loader.ts
|
|
4337
|
-
const _getAlterList = (DB) => {
|
|
4338
|
-
const counter = DB.report.file("alter-list.json");
|
|
4339
|
-
const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
|
|
4340
|
-
if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
|
|
4341
|
-
const canonical = [];
|
|
4342
|
-
for (const row of root.items) {
|
|
4343
|
-
const res = ComfyManagerAlterInfo_ark(row);
|
|
4344
|
-
if (res instanceof type.errors) {
|
|
4345
|
-
counter.skip("schema", res.summary);
|
|
4346
|
-
continue;
|
|
4347
|
-
}
|
|
4348
|
-
canonical.push(res);
|
|
4349
|
-
counter.ok();
|
|
4350
|
-
}
|
|
4351
|
-
DB.alterations = canonical;
|
|
4352
|
-
};
|
|
4353
|
-
//#endregion
|
|
4354
|
-
//#region src/manager/types/ComfyManagerGithubStats.ts
|
|
4355
|
-
const ComfyManagerGithubStatEntry_ark = type({
|
|
4356
|
-
stars: "number",
|
|
4357
|
-
last_update: "string",
|
|
4358
|
-
author_account_age_days: "number"
|
|
4359
|
-
});
|
|
4360
|
-
//#endregion
|
|
4361
|
-
//#region src/manager/loaders/step6_github-stats-loader.ts
|
|
4362
|
-
const _getGithubStats = (DB) => {
|
|
4363
|
-
const counter = DB.report.file("github-stats.json");
|
|
4364
|
-
const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
|
|
4365
|
-
const root = type("Record<string, unknown>")(raw);
|
|
4366
|
-
if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
|
|
4367
|
-
for (const [url, value] of Object.entries(root)) {
|
|
4368
|
-
const res = ComfyManagerGithubStatEntry_ark(value);
|
|
4369
|
-
if (res instanceof type.errors) {
|
|
4370
|
-
counter.skip("schema", `${url}: ${res.summary}`);
|
|
4371
|
-
continue;
|
|
4372
|
-
}
|
|
4373
|
-
DB.githubStats.set(url, res);
|
|
4374
|
-
counter.ok();
|
|
4375
|
-
}
|
|
4376
|
-
};
|
|
4377
|
-
//#endregion
|
|
4378
|
-
//#region src/manager/ComfyRegistry.ts
|
|
4379
|
-
const log = (...args) => console.log(`[📘 registry]`, ...args);
|
|
4380
|
-
const BUILTIN_URL = "https://github.com/comfyanonymous/ComfyUI";
|
|
4381
|
-
const BUILTIN_PLUGIN = {
|
|
4382
|
-
id: "nodes",
|
|
4383
|
-
author: "comfyanonymous",
|
|
4384
|
-
description: "built-in",
|
|
4385
|
-
title: "built-in",
|
|
4386
|
-
files: [BUILTIN_URL],
|
|
4387
|
-
reference: "https://github.com/comfyanonymous/ComfyUI",
|
|
4388
|
-
install_type: ""
|
|
4389
|
-
};
|
|
4390
|
-
var ComfyRegistry = class ComfyRegistry {
|
|
4391
|
-
static async DownloadAndUpdate(download) {
|
|
4392
|
-
if (download) {
|
|
4393
|
-
log(ansi.bold(`1. Downloading comfy-manager JSONs...`));
|
|
4394
|
-
await DownloadComfyManagerJSONs();
|
|
4395
|
-
} else log(`1. Downloading comfy-manager JSONs... ${ansi.bold("[SKIPPED]")}`);
|
|
4396
|
-
return new ComfyRegistry({
|
|
4397
|
-
check: true,
|
|
4398
|
-
genTypes: true
|
|
4399
|
-
});
|
|
4400
|
-
}
|
|
4401
|
-
constructor(opts = {}) {
|
|
4402
|
-
this.opts = opts;
|
|
4403
|
-
this.plugins_byTitle = /* @__PURE__ */ new Map();
|
|
4404
|
-
this.plugins_byFile = /* @__PURE__ */ new Map();
|
|
4405
|
-
this.plugins_byNodeNameInComfy = /* @__PURE__ */ new Map();
|
|
4406
|
-
this.plugins_byNodeKey = /* @__PURE__ */ new Map();
|
|
4407
|
-
this.customNodes_byPluginName = /* @__PURE__ */ new Map();
|
|
4408
|
-
this.knownModels = /* @__PURE__ */ new Map();
|
|
4409
|
-
this.alterations = [];
|
|
4410
|
-
this.githubStats = /* @__PURE__ */ new Map();
|
|
4411
|
-
this.report = new ManagerParseReport();
|
|
4412
|
-
this.getKnownCheckpoints = () => {
|
|
4413
|
-
return [...this.knownModels.values()].filter((i) => i.type === "checkpoint");
|
|
4414
|
-
};
|
|
4415
|
-
this.getModelInfoFinalFilePath = (mi) => {
|
|
4416
|
-
/**
|
|
4417
|
-
* the wide data-lt once told:
|
|
4418
|
-
*
|
|
4419
|
-
* | if save_path is 'default'
|
|
4420
|
-
* | models/type'/filename
|
|
4421
|
-
*
|
|
4422
|
-
* | if type is "checkpoint"
|
|
4423
|
-
* | models/checkpoints/filename
|
|
4424
|
-
*
|
|
4425
|
-
* | if save_path not starting with custom node
|
|
4426
|
-
* | base path is models
|
|
4427
|
-
* | e.g. save_path is "checkpoints/SD1.5"
|
|
4428
|
-
* | models/checkpoints/SD1.5/filename
|
|
4429
|
-
* | save_path is "custom_nodes/AAA/models"
|
|
4430
|
-
* | custom_nodes/AAA/models/filename
|
|
4431
|
-
*
|
|
4432
|
-
*/
|
|
4433
|
-
if (mi.save_path === "default") return `models/${mi.type}/${mi.filename}`;
|
|
4434
|
-
if (mi.type === "checkpoint") return `models/checkpoints/${mi.filename}`;
|
|
4435
|
-
if (mi.save_path.startsWith("custom_nodes")) return `${mi.save_path}/${mi.filename}`;
|
|
4436
|
-
else return `models/${mi.save_path}/${mi.filename}`;
|
|
4437
|
-
};
|
|
4438
|
-
this.getModelInfoEnumName = (mi, prefix = "") => {
|
|
4439
|
-
const relPath = this.getModelInfoFinalFilePath(mi);
|
|
4440
|
-
const winPath = relPath.replace(/\//g, "\\");
|
|
4441
|
-
const winPrefix = prefix?.replace(/\//g, "\\");
|
|
4442
|
-
const isUnderPrefixWin = winPath.startsWith(winPrefix);
|
|
4443
|
-
const nixPath = relPath.replace(/\\/g, "/");
|
|
4444
|
-
const nixPrefix = prefix?.replace(/\//g, "\\");
|
|
4445
|
-
const isUnderPrefix = nixPath.startsWith(nixPrefix) || isUnderPrefixWin;
|
|
4446
|
-
return {
|
|
4447
|
-
win: isUnderPrefix ? winPath.slice(winPrefix.length) : mi.filename,
|
|
4448
|
-
nix: isUnderPrefix ? nixPath.slice(nixPrefix.length) : mi.filename
|
|
4449
|
-
};
|
|
4450
|
-
};
|
|
4451
|
-
this.plugins_byTitle.set(BUILTIN_PLUGIN.title, BUILTIN_PLUGIN);
|
|
4452
|
-
this.plugins_byFile.set(BUILTIN_URL, BUILTIN_PLUGIN);
|
|
4453
|
-
log(`loading src/manager/json/${ansi.yellow("custom-node-list.json")}...`);
|
|
4454
|
-
_getKnownPlugins(this);
|
|
4455
|
-
log(`loading src/manager/json/${ansi.yellow("extension-node-map.json")}...`);
|
|
4456
|
-
_getCustomNodeRegistry(this);
|
|
4457
|
-
log(`loading src/manager/json/${ansi.yellow("model-list.json")}...`);
|
|
4458
|
-
_getKnownModels(this);
|
|
4459
|
-
log(`loading src/manager/json/${ansi.yellow("alter-list.json")}...`);
|
|
4460
|
-
_getAlterList(this);
|
|
4461
|
-
log(`loading src/manager/json/${ansi.yellow("github-stats.json")}...`);
|
|
4462
|
-
_getGithubStats(this);
|
|
4463
|
-
this.report.print();
|
|
4464
|
-
}
|
|
4465
|
-
};
|
|
4466
|
-
//#endregion
|
|
4467
|
-
//#region src/state.ts
|
|
4468
|
-
/** singleton */
|
|
4469
|
-
var ComfyTS = class ComfyTS {
|
|
4470
|
-
constructor(p = {}) {
|
|
4471
|
-
this.version = version;
|
|
4472
|
-
this.hosts = /* @__PURE__ */ new Map();
|
|
4473
|
-
this._registry = null;
|
|
4474
|
-
this.rootPath = asAbsolutePath(process.cwd());
|
|
4475
|
-
this.readJSON_ = (absPath, def) => {
|
|
4476
|
-
if (!existsSync(absPath)) {
|
|
4477
|
-
if (def != null) return def;
|
|
4478
|
-
throw new Error(`file does not exist ${absPath}`);
|
|
4479
|
-
}
|
|
4480
|
-
const str = readFileSync(absPath, "utf8");
|
|
4481
|
-
return JSON.parse(str);
|
|
4482
|
-
};
|
|
4483
|
-
this.autolayoutOpts = {
|
|
4484
|
-
node_hsep: 50,
|
|
4485
|
-
node_vsep: 50,
|
|
4486
|
-
forceLeft: false
|
|
4487
|
-
};
|
|
4488
|
-
const globalHack = globalThis;
|
|
4489
|
-
if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
|
|
4490
|
-
globalHack.comfyts = this;
|
|
4491
|
-
if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
|
|
4492
|
-
this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
|
|
4493
|
-
this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
|
|
4494
|
-
this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
|
|
4495
|
-
}
|
|
4496
|
-
/**
|
|
4497
|
-
* multi-module entrypoint: returns the existing global instance or creates
|
|
4498
|
-
* it. Workflow modules MUST use this (the TUI imports many of them into one
|
|
4499
|
-
* process); `new ComfyTS()` still throws on a second instance.
|
|
4500
|
-
*/
|
|
4501
|
-
static create(p = {}) {
|
|
4502
|
-
const existing = globalThis.comfyts;
|
|
4503
|
-
if (existing == null) return new ComfyTS(p);
|
|
4504
|
-
if (p.rootPath != null && asAbsolutePath(p.rootPath) !== existing.rootPath) throw new Error(`ComfyTS.create({rootPath: '${p.rootPath}'}) conflicts with the existing instance rooted at '${existing.rootPath}'`);
|
|
4505
|
-
return existing;
|
|
4506
|
-
}
|
|
4507
|
-
host(data) {
|
|
4508
|
-
const existing = this.hosts.get(data.id);
|
|
4509
|
-
if (existing != null) {
|
|
4510
|
-
const incoming = parseHostBase(data);
|
|
4511
|
-
const cur = existing.base;
|
|
4512
|
-
const sameBase = cur.scheme === incoming.scheme && cur.host === incoming.host && cur.port === incoming.port && cur.basePath === incoming.basePath;
|
|
4513
|
-
const sameAuth = existing.data.apiKey == null === (data.apiKey == null);
|
|
4514
|
-
if (!sameBase || !sameAuth) throw new Error(`host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? " (authed)" : ""} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? " (authed)" : ""}`);
|
|
4515
|
-
return existing;
|
|
4516
|
-
}
|
|
4517
|
-
const created = new ComfyHost(data);
|
|
4518
|
-
this.hosts.set(data.id, created);
|
|
4519
|
-
return created;
|
|
4520
|
-
}
|
|
4521
|
-
get registry() {
|
|
4522
|
-
if (this._registry == null) this._registry = new ComfyRegistry({
|
|
4523
|
-
check: false,
|
|
4524
|
-
genTypes: false
|
|
4525
|
-
});
|
|
4526
|
-
return this._registry;
|
|
4527
|
-
}
|
|
4528
|
-
resolveFromDrafts(relativePath) {
|
|
4529
|
-
return asAbsolutePath(join(this.baseFolder, "drafts", relativePath));
|
|
4530
|
-
}
|
|
4531
|
-
resolveFromCache(relativePath) {
|
|
4532
|
-
return asAbsolutePath(join(this.baseFolder, "cache", relativePath));
|
|
4533
|
-
}
|
|
4534
|
-
/** local TUI settings (preview mode, last draft per workflow) — gitignored */
|
|
4535
|
-
get settingsPath() {
|
|
4536
|
-
return asAbsolutePath(join(this.baseFolder, "settings.json"));
|
|
4537
|
-
}
|
|
4538
|
-
resolveFromHosts(relativePath) {
|
|
4539
|
-
return asAbsolutePath(join(this.hostsFolder, relativePath));
|
|
4540
|
-
}
|
|
4541
|
-
/**
|
|
4542
|
-
* Resolves a relative path against an absolute path.
|
|
4543
|
-
* @param from - The absolute path to resolve from.
|
|
4544
|
-
* @param relativePath - The relative path to resolve.
|
|
4545
|
-
* @returns The resolved absolute path.
|
|
4546
|
-
*/
|
|
4547
|
-
resolve(from, relativePath) {
|
|
4548
|
-
return asAbsolutePath(join(from, relativePath));
|
|
4549
|
-
}
|
|
4550
|
-
resolveFromOutput(relativePath) {
|
|
4551
|
-
return asAbsolutePath(join(this.outputPath, relativePath));
|
|
4552
|
-
}
|
|
4553
|
-
};
|
|
4554
|
-
//#endregion
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join, resolve } from "pathe";
|
|
4555
7
|
//#region src/cli/gen.ts
|
|
4556
8
|
async function runGen(args) {
|
|
4557
9
|
const getFlag = (name) => {
|
|
@@ -4705,7 +157,7 @@ async function main() {
|
|
|
4705
157
|
if (res.error == null) return res.status ?? 1;
|
|
4706
158
|
console.error(`[comfy-ts tui] bun not found (${res.error.message}) — continuing under node: the examples packaged in node_modules cannot load here, and your own .cflow.ts modules rely on node's type stripping`);
|
|
4707
159
|
}
|
|
4708
|
-
const { runTui } = await import("./run-tui-
|
|
160
|
+
const { runTui } = await import("./run-tui-BAdizWsO.js");
|
|
4709
161
|
return runTui(rest);
|
|
4710
162
|
}
|
|
4711
163
|
console.log(HELP);
|