comfy-ts 1.2.0 → 1.4.0

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