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