comfy-ts 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +66 -0
  2. package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/DraftsSt-DcOTn0QR.js +434 -0
  5. package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +476 -202
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +98 -40
  11. package/dist/index.d.ts +117 -59
  12. package/dist/index.js +468 -193
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-CN0DhrsA.js +638 -0
  15. package/dist/run-serve-CN0DhrsA.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
  17. package/dist/run-tui-bN2hSD5i.js.map +1 -0
  18. package/dist/state-COlKYipO.js +4743 -0
  19. package/dist/state-COlKYipO.js.map +1 -0
  20. package/dist/web.d.ts +17340 -0
  21. package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
  22. package/dist/web.js.map +1 -0
  23. package/examples/web/example.ts +71 -0
  24. package/examples/web/index.html +77 -0
  25. package/examples/web/serve.ts +42 -0
  26. package/examples/web/tsconfig.json +15 -0
  27. package/package.json +10 -3
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/StatusBar.tsx +1 -0
  34. package/src/cli/tui/components/TreePanel.tsx +17 -3
  35. package/src/cli/tui/components/TuiApp.tsx +7 -2
  36. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  37. package/src/cli/tui/imageClipboard.ts +39 -0
  38. package/src/cli/tui/listWindow.ts +36 -0
  39. package/src/cli/tui/state/ExecSt.ts +48 -0
  40. package/src/cli/tui/state/TreeSt.ts +25 -0
  41. package/src/cli/tui/state/TuiSt.ts +34 -0
  42. package/src/coreExports.ts +118 -0
  43. package/src/host/ComfyHost.ts +23 -23
  44. package/src/host/ResilientWebsocket.ts +93 -47
  45. package/src/host/hostUrl.ts +2 -1
  46. package/src/host/loraManagerApi.ts +6 -7
  47. package/src/index.ts +8 -107
  48. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  49. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  50. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  51. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  52. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  53. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  54. package/src/runner/ComfyExecution.ts +32 -12
  55. package/src/runner/MediaImage.ts +18 -30
  56. package/src/runner/outputPath.ts +75 -0
  57. package/src/sdk-generator/ComfySchema.ts +2 -2
  58. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  59. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  60. package/src/state.ts +13 -9
  61. package/src/storage/ComfyStorage.ts +144 -0
  62. package/src/storage/nodeStorage.ts +9 -0
  63. package/src/utils/downloadFile.ts +11 -69
  64. package/src/utils/hashArrayBuffer.ts +3 -4
  65. package/src/utils/lazySharp.ts +25 -0
  66. package/src/utils/sha1.ts +69 -0
  67. package/src/vars/ComfyVars.ts +13 -6
  68. package/src/vars/loraKeywords.ts +6 -6
  69. package/src/web.ts +13 -0
  70. package/dist/run-tui-BAdizWsO.js.map +0 -1
  71. package/dist/state-BYbxDgfr.js.map +0 -1
  72. package/src/utils/writeFile.ts +0 -16
@@ -1,895 +1,192 @@
1
- import fs, { existsSync, mkdirSync, readFileSync, statSync, writeFile, writeFileSync } from "node:fs";
2
- import { basename, dirname, isAbsolute, join, resolve } from "pathe";
3
- import crypto from "node:crypto";
1
+ import { basename, isAbsolute, join, resolve } from "pathe";
4
2
  import { scope, type } from "arktype";
5
3
  import { nanoid } from "nanoid";
6
- import sharp from "sharp";
7
4
  import { imageMeta } from "image-meta";
8
- import WebSocket from "ws";
9
- import { homedir } from "node:os";
10
5
  import { action, makeObservable, observable, runInAction } from "mobx";
11
- import https from "node:https";
12
- import { stdout } from "node:process";
13
- //#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
14
- /** having a bunch of sensible default will help slightly */
15
- function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
16
- if (enumName === "KSampler.sampler_name") return "E_SamplerName";
17
- if (enumName === "KSampler.scheduler") return "E_SchedulerName";
18
- if (enumName === "CheckpointLoaderSimple.ckpt_name") return "E_CkptName";
19
- if (enumName === "VAELoader.vae_name") return "E_VaeName";
20
- if (enumName === "LoraLoader.lora_name") return "E_LoraName";
21
- if (enumName === "LatentUpscale.upscale_method") return "E_LatentUpscaleMethod";
22
- if (enumName === "ImageScale.upscale_method") return "E_ImageUpscaleMethod";
23
- if (enumName === "LoadImage.image") return "E_Image";
24
- if (enumName === "LoadImageMask.channel") return "E_Channel";
25
- if (enumName === "KSamplerAdvanced.add_noise") return "E_EnableOrDisable";
26
- if (enumName === "LatentRotate.rotation") return "E_Rotation";
27
- if (enumName === "LatentFlip.flip_method") return "E_FlipMethod";
28
- if (enumName === "CLIPLoader.type") return "E_ClipType";
29
- if (enumName === "UNETLoader.weight_dtype") return "E_WeightDType";
30
- if (enumName === "DualCLIPLoader.type") return "E_DualClipType";
31
- if (enumName === "CheckpointLoader.config_name") return "E_CkptConfigName";
32
- if (enumName === "civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name") return "E_CivitAICkptName";
33
- if (enumName === "Impact-Pack.SAMDetectorCombined.detection_hint") return "E_ImpactDetectionHint";
34
- if (hashContent === "false|true") return "E_TrueOrFalse";
35
- if (hashContent === "CPU|GPU") return "E_CpuOrGpu";
36
- return "E_" + hash;
6
+ //#region src/storage/ComfyStorage.ts
7
+ function dirnameOf(path) {
8
+ const ix = path.lastIndexOf("/");
9
+ return ix <= 0 ? "/" : path.slice(0, ix);
37
10
  }
38
- //#endregion
39
- //#region src/sdk-generator/_pythonModuleToNamespace.ts
40
- function pythonModuleToPrefix(pythonModule) {
41
- if (pythonModule === "nodes") return "";
42
- if (pythonModule.startsWith("comfy_extras.")) return "";
43
- if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
44
- 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, "") + ".";
45
- console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
46
- return `${pythonModule}.`;
11
+ /** node backend built from INJECTED modules: nodeStorage.ts passes its static
12
+ * imports, the autodetect below passes process.getBuiltinModule results */
13
+ function createNodeStorageFrom(fs, os) {
14
+ return {
15
+ kind: "node",
16
+ readText: (p) => fs.readFileSync(p, "utf8"),
17
+ readTextIfExists: (p) => fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null,
18
+ readBytes: (p) => new Uint8Array(fs.readFileSync(p)),
19
+ writeText: (p, text) => {
20
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
21
+ fs.writeFileSync(p, text);
22
+ },
23
+ writeBytes: (p, bytes) => {
24
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
25
+ fs.writeFileSync(p, bytes);
26
+ },
27
+ exists: (p) => fs.existsSync(p),
28
+ mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
29
+ mtimeMs: (p) => fs.existsSync(p) ? fs.statSync(p).mtimeMs : null,
30
+ homedir: () => os.homedir(),
31
+ cwd: () => process.cwd()
32
+ };
33
+ }
34
+ /** in-memory backend: the web default, also handy for hermetic tests.
35
+ * Paths are LITERAL keys (no normalization — core callers resolve through
36
+ * pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp
37
+ * dirs only, never implicit parents. Bytes are copied in AND out so neither
38
+ * side can mutate the store. */
39
+ function createMemoryStorage(p = {}) {
40
+ const files = /* @__PURE__ */ new Map();
41
+ const mtimes = /* @__PURE__ */ new Map();
42
+ const dirs = /* @__PURE__ */ new Set();
43
+ const td = new TextDecoder();
44
+ const te = new TextEncoder();
45
+ const write = (path, bytes) => {
46
+ files.set(path, bytes.slice());
47
+ mtimes.set(path, Date.now());
48
+ };
49
+ return {
50
+ kind: "memory",
51
+ readText: (path) => {
52
+ const hit = files.get(path);
53
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
54
+ return td.decode(hit);
55
+ },
56
+ readTextIfExists: (path) => {
57
+ const hit = files.get(path);
58
+ return hit == null ? null : td.decode(hit);
59
+ },
60
+ readBytes: (path) => {
61
+ const hit = files.get(path);
62
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
63
+ return hit.slice();
64
+ },
65
+ writeText: (path, text) => write(path, te.encode(text)),
66
+ writeBytes: write,
67
+ exists: (path) => files.has(path) || dirs.has(path),
68
+ mkdirp: (path) => void dirs.add(path),
69
+ mtimeMs: (path) => mtimes.get(path) ?? null,
70
+ homedir: () => p.homedir ?? "/home/web",
71
+ cwd: () => p.cwd ?? "/"
72
+ };
73
+ }
74
+ let installedDefault = null;
75
+ /** entries call this at import time: index.ts installs node, web.ts memory */
76
+ function setDefaultComfyStorage(storage) {
77
+ installedDefault = storage;
78
+ }
79
+ function autodetectNodeStorage() {
80
+ const get = globalThis.process?.getBuiltinModule;
81
+ if (typeof get !== "function") return null;
82
+ const fs = get("node:fs");
83
+ const os = get("node:os");
84
+ if (fs == null || os == null) return null;
85
+ return createNodeStorageFrom(fs, os);
86
+ }
87
+ function resolveComfyStorage(explicit) {
88
+ if (explicit != null) return explicit;
89
+ if (installedDefault != null) return installedDefault;
90
+ const detected = autodetectNodeStorage();
91
+ if (detected != null) {
92
+ installedDefault = detected;
93
+ return detected;
94
+ }
95
+ throw new Error(`no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`);
96
+ }
97
+ /** the ONE accessor call sites use: the instance's storage when the global
98
+ * exists, the resolved default otherwise (vars constructed before create()) */
99
+ function getComfyStorage() {
100
+ return globalThis.comfyts?.storage ?? resolveComfyStorage();
47
101
  }
48
102
  //#endregion
49
- //#region src/sdk-generator/_toQualifiedNodeKey.ts
50
- const toQualifiedNodeKey = (pythonModule, nameInComfy) => {
51
- return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`;
52
- };
103
+ //#region package.json
104
+ var version = "1.4.0";
53
105
  //#endregion
54
- //#region src/utils/CodeBuffer.ts
55
- /** this class is used to buffer text and then write it to a file */
56
- var CodeBuffer = class {
57
- constructor(_indent = 0, lines = []) {
58
- this._indent = _indent;
59
- this.tab = " ";
60
- this.content = "";
61
- this.newLine = () => this.content += "\n";
62
- this.line = (...txts) => this.writeLine(txts.join(""));
63
- this.append = (str) => this.content += str;
64
- this.writeLine = (txt) => {
65
- this.content += txt.split("\n").map((line) => repeatStr(this._indent, this.tab) + line).join("\n") + "\n";
66
- return this;
67
- };
68
- this.w = (txt, opts = { if: true }) => {
69
- if (opts.if) this.writeLine(txt);
70
- };
71
- this.indent = () => this._indent++;
72
- this.deindent = () => this._indent--;
73
- this.indented = (fn) => {
74
- this._indent++;
75
- fn();
76
- this._indent--;
77
- };
78
- this.bar = (text) => this.w(renderBar(text, "// "));
79
- for (const line of lines) this.writeLine(line);
80
- }
81
- };
82
- const repeatStr = (x, str) => {
83
- let out = "";
84
- for (let i = 0; i < x; i++) out += str;
85
- return out;
86
- };
87
- const renderBar = (text, prefix = "") => {
88
- const ___bar___ = "=============================================================================";
89
- return `${prefix}|${___bar___}|\n${prefix}| ${text} ${repeatStr(77 - text.length - 4, " ")} |\n${prefix}|${___bar___}|`;
90
- };
106
+ //#region src/litegraph/LiteGraphLinkID.ts
107
+ const asLiteGraphLinkID = (id) => id;
108
+ const LiteGraphLinkID_ = type.number.atLeast(0).as();
91
109
  //#endregion
92
- //#region src/utils/escapeJSKey.ts
93
- const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
94
- const isValidJSKey = (s) => {
95
- return regex.test(s);
96
- };
97
- const escapeJSKey = (s) => {
98
- if (typeof s !== "string") return "string";
99
- if (!isValidJSKey(s)) return `"${s}"`;
100
- return s;
110
+ //#region src/utils/bang.ts
111
+ /** assertNotNull */
112
+ const bang = (x, msg = "") => {
113
+ if (x == null) {
114
+ console.error(`[🔴] BANG FAILED`, msg);
115
+ throw new Error("bang: " + (msg ?? "no message"));
116
+ }
117
+ return x;
101
118
  };
102
119
  //#endregion
103
- //#region src/sdk-generator/Primitives.ts
104
- const ComfyPrimitiveMapping = {
105
- BOOLEAN: "boolean",
106
- FLOAT: "number",
107
- INT: "number",
108
- STRING: "string"
109
- };
110
- const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
120
+ //#region src/litegraph/expandSubgraphs.ts
121
+ /** boundary sentinel ids inside definition link tables */
122
+ const SUBGRAPH_INPUT_NODE_ID = -10;
123
+ const SUBGRAPH_OUTPUT_NODE_ID = -20;
124
+ /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
125
+ const MAX_EXPANSION_PASSES = 32;
111
126
  /**
112
- * when a litegraph node has an input entry with a widget marker, the
113
- * serialized TYPE string decides how many widgets_values it consumed in that era
127
+ * widget-kind fallback when a def input slot has no boundary target carrying a
128
+ * widget marker: these litegraph slot types carry widget values. LOCAL copy on
129
+ * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
130
+ * (the io-widget era serializes exactly one value per exposed widget slot).
114
131
  */
115
- const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
116
- if (type === "INT") {
117
- if (nameInComfy === "seed" || nameInComfy === "noise_seed") return 2;
118
- return 1;
132
+ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
133
+ "INT",
134
+ "FLOAT",
135
+ "STRING",
136
+ "BOOLEAN",
137
+ "COMBO"
138
+ ]);
139
+ /**
140
+ * inline every subgraph instance (node whose `type` is a definition uuid) into
141
+ * the root graph: fresh numeric ids, boundary links rewired, instance widget
142
+ * values promoted into the inner nodes' `named` overrides. Iterative so nested
143
+ * definitions expand on the next pass. Muted instances are dropped (their
144
+ * consumers resolve unconnected); bypassed instances stay for the converter's
145
+ * passthrough walk, which needs no interior.
146
+ */
147
+ const expandSubgraphs = (wf, defs) => {
148
+ let passes = 0;
149
+ while (true) {
150
+ const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
151
+ if (expandable.length === 0) return wf;
152
+ if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
153
+ for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
154
+ else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
119
155
  }
120
- if (type === "BOOLEAN") return 1;
121
- if (type === "FLOAT") return 1;
122
- if (type === "STRING") return 1;
123
- if (type === "COMBO") return 1;
124
- if (type === "INT:seed") return 2;
125
- if (type === "INT:noise_seed") return 2;
126
- return 0;
127
156
  };
128
- const ComfyDefaultNodeWhenUnknown_Name = "UnknownNodeXX";
129
- const ComfyDefaultNodeWhenUnknown_Schema = {
130
- category: "test",
131
- input: {},
132
- output: [],
133
- description: "This is a test node",
134
- output_name: [],
135
- display_name: "UnknownNodeXX",
136
- name: "UnknownNodeXX",
137
- output_is_list: [],
138
- output_node: false,
139
- python_module: "nodes"
157
+ /** converter mute semantics applied early: after expansion there is no single node left to skip */
158
+ const dropMutedInstance = (wf, instance) => {
159
+ const dead = /* @__PURE__ */ new Set();
160
+ for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
161
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
162
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
163
+ pruneDeadLinkRefs(wf, dead);
140
164
  };
141
- //#endregion
142
- //#region src/sdk-generator/ComfyNodeSchema.ts
143
- var ComfyNodeSchema = class {
144
- get singleOutputs() {
145
- if (this._singleOutputs != null) return this._singleOutputs;
146
- const x = {};
147
- for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1;
148
- this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1);
149
- return this._singleOutputs;
150
- }
151
- constructor(raw, nameInComfy, nodeKey, category, inputs, outputs, pythonModule) {
152
- this.raw = raw;
153
- this.nameInComfy = nameInComfy;
154
- this.nodeKey = nodeKey;
155
- this.category = category;
156
- this.inputs = inputs;
157
- this.outputs = outputs;
158
- this.pythonModule = pythonModule;
159
- this._singleOutputs = null;
160
- this.category = this.category.replaceAll("/", "_");
165
+ const pruneDeadLinkRefs = (wf, dead) => {
166
+ if (dead.size === 0) return;
167
+ for (const node of wf.nodes) {
168
+ for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
169
+ for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
161
170
  }
162
- codegenUI() {
163
- const b = new CodeBuffer();
164
- const p = b.w;
165
- p(` ${escapeJSKey(this.nodeKey)}: {`);
166
- this.inputs.forEach((i, _ix) => {
167
- if (i.isPrimitive) {
168
- const tsType = ComfyPrimitiveMapping[i.typeName];
169
- if (tsType == null) return console.log(`[🔶] invariant violation`);
170
- p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`);
171
- } else if (i.isEnum) p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`);
172
- else p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`);
173
- });
174
- p(` }`);
175
- return b.content;
171
+ };
172
+ const expandOneInstance = (wf, instance, def) => {
173
+ let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
174
+ let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
175
+ const newNodeIds = /* @__PURE__ */ new Map();
176
+ for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
177
+ const remapNodeId = (id) => newNodeIds.get(id) ?? null;
178
+ const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
179
+ for (const [k, input] of instance.inputs.entries()) {
180
+ const defSlot = def.inputs.findIndex((d) => d.name === input.name);
181
+ 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(", ")})`);
182
+ defSlotOfInstanceSlot.set(k, defSlot);
176
183
  }
177
- renderOpts(opts) {
178
- if (opts == null) return null;
179
- if (typeof opts === "string") return null;
180
- let out = "/**";
181
- if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`;
182
- if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`;
183
- if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`;
184
- if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`;
185
- out += " */";
186
- return out;
187
- }
188
- };
189
- const wrapQuote = (s) => {
190
- if (s.includes("'")) return `"${s}"`;
191
- return `'${s}'`;
192
- };
193
- //#endregion
194
- //#region src/sdk-generator/inputWidgetKind.ts
195
- const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
196
- /**
197
- * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
198
- * The frontend creates the control widget on truthiness, and real 2026 hosts
199
- * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
200
- * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
201
- * heuristic applies.
202
- */
203
- const controlConsumes = (o, typeName, name) => {
204
- if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
205
- if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
206
- return 1;
207
- };
208
- const flattenInputSections = (inputs) => {
209
- const out = [];
210
- for (const section of ["required", "optional"]) {
211
- const sec = inputs[section];
212
- if (!isRecord(sec)) continue;
213
- for (const [name, spec] of Object.entries(sec)) {
214
- if (!Array.isArray(spec) || spec.length === 0) continue;
215
- const t = spec[0];
216
- if (typeof t !== "string" && !Array.isArray(t)) continue;
217
- out.push({
218
- name,
219
- type: t,
220
- opts: spec[1],
221
- required: section === "required"
222
- });
223
- }
224
- }
225
- return out;
226
- };
227
- /** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
228
- const parseDynamicOptions = (options) => {
229
- if (options.length === 0) return null;
230
- const out = [];
231
- for (const entry of options) {
232
- if (!isRecord(entry)) return null;
233
- const key = entry["key"];
234
- const inputs = entry["inputs"];
235
- if (typeof key !== "string" || !isRecord(inputs)) return null;
236
- out.push({
237
- key,
238
- inputs: flattenInputSections(inputs)
239
- });
240
- }
241
- return out;
242
- };
243
- /**
244
- * autogrow (`template` WITH a nested `input` section): instances are always
245
- * link slots named `decl.<name_i>` (the backend force-inputs widget
246
- * templates), the first `min` of them required WHEN the template input
247
- * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
248
- */
249
- const parseContainer = (template) => {
250
- const input = template["input"];
251
- const min = typeof template["min"] === "number" ? template["min"] : 1;
252
- const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
253
- const max = typeof template["max"] === "number" ? template["max"] : 100;
254
- const rawNames = template["names"];
255
- const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
256
- return {
257
- kind: "dynamic-container",
258
- instanceNames: names,
259
- requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
260
- };
261
- };
262
- /**
263
- * the single template sub-input's slot type of an autogrow container
264
- * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
265
- * autogrow template or the template has several sub-inputs (corpus-absent
266
- * 2026-07-30, 27/27 single on the cloud catalog) — then codegen emits no
267
- * typed instance keys and the container stays builderBase territory.
268
- */
269
- const containerInstanceSlotType = (opts) => {
270
- const template = (isRecord(opts) ? opts : null)?.["template"];
271
- if (!isRecord(template) || !isRecord(template["input"])) return null;
272
- const subs = flattenInputSections(template["input"]);
273
- const first = subs[0];
274
- if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
275
- return first.type;
276
- };
277
- const classifyWidgetInput = (p) => {
278
- const o = isRecord(p.opts) ? p.opts : null;
279
- if (o?.["forceInput"] === true) return { kind: "slot" };
280
- if (Array.isArray(p.type) || p.isEnumUnion === true) {
281
- const tn = typeof p.type === "string" ? p.type : "COMBO";
282
- return {
283
- kind: "widget",
284
- consumes: controlConsumes(o, tn, p.name),
285
- strictValues: true
286
- };
287
- }
288
- if (typeof p.type !== "string") return { kind: "slot" };
289
- const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
290
- if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
291
- kind: "widget",
292
- consumes: controlConsumes(o, widgetTypeName, p.name),
293
- strictValues: true
294
- };
295
- const options = o?.["options"];
296
- if (Array.isArray(options)) {
297
- const dynOptions = parseDynamicOptions(options);
298
- if (dynOptions != null) {
299
- const first = dynOptions[0];
300
- if (first == null) return { kind: "slot" };
301
- return {
302
- kind: "dynamic-combo",
303
- options: dynOptions,
304
- defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
305
- };
306
- }
307
- return {
308
- kind: "widget",
309
- consumes: controlConsumes(o, p.type, p.name),
310
- strictValues: true
311
- };
312
- }
313
- const template = o?.["template"];
314
- if (isRecord(template)) {
315
- if (isRecord(template["input"])) return parseContainer(template);
316
- return { kind: "slot" };
317
- }
318
- if (o?.["socketless"] === true) return {
319
- kind: "widget",
320
- consumes: 1,
321
- strictValues: false
322
- };
323
- return { kind: "slot" };
324
- };
325
- const classifySchemaInput = (input) => classifyWidgetInput({
326
- name: input.nameInComfy,
327
- type: input.typeName,
328
- opts: input.opts,
329
- isEnumUnion: input.isEnum
330
- });
331
- /** how many widgets_values entries this schema input consumes (export path + positional walks) */
332
- const howManyWidgetValuesForThisSchemaType = (input) => {
333
- const kind = classifySchemaInput(input);
334
- return kind.kind === "widget" ? kind.consumes : 0;
335
- };
336
- /**
337
- * what ComfyUI's frontend gives a widget created with no serialized value
338
- * (`getWidgetDefaultValue` semantics), used when a positional array is
339
- * shorter than the schema's widget list. `null` for custom widgets — the
340
- * backend accepts an explicit null but errors on an ABSENT required key.
341
- */
342
- const defaultValueForWidget = (p) => {
343
- const o = isRecord(p.opts) ? p.opts : null;
344
- if (o != null && o["default"] !== void 0) return o["default"];
345
- const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
346
- if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
347
- if (widgetTypeName === "BOOLEAN") return false;
348
- if (widgetTypeName === "STRING") return "";
349
- const options = o?.["options"];
350
- if (Array.isArray(options) && options.length > 0) {
351
- const first = options[0];
352
- if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
353
- }
354
- if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
355
- return null;
356
- };
357
- //#endregion
358
- //#region src/sdk-generator/comfyui-sdk-codegen.ts
359
- /**
360
- * convert a host id to the namespace name it gets inside the global `Comfy` namespace
361
- * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
362
- */
363
- function hostIdToNamespace(hostId) {
364
- const ns = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
365
- if (ns.length === 0) throw new Error(`cannot derive a namespace from host id "${hostId}"`);
366
- return /^[0-9]/.test(ns) ? `Host${ns}` : ns;
367
- }
368
- /**
369
- * emit the typed SDK for one host:
370
- *
371
- * declare global {
372
- * namespace Comfy {
373
- * namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }
374
- * interface Hosts { '<host-id>': <HostNs>.Sdk }
375
- * }
376
- * }
377
- */
378
- function codegenSDK(opts) {
379
- const ns = hostIdToNamespace(opts.hostId);
380
- const packageName = opts.packageName ?? "comfy-ts";
381
- const b = new CodeBuffer();
382
- const p = b.w;
383
- p(`/** generated by comfy-ts for host "${opts.hostId}" — do not edit */`);
384
- p(``);
385
- p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`);
386
- p(``);
387
- p(`declare global {`);
388
- b.indent();
389
- p(`namespace Comfy {`);
390
- b.indent();
391
- p(`namespace ${ns} {`);
392
- b.indent();
393
- p(`// #region PythonModules`);
394
- p(`/** list of all python modules installed on this host */`);
395
- p(`export type PythonModules =`);
396
- b.indent();
397
- const pythonModulesArr = Array.from(this.pythonModules.entries()).toSorted((a, b) => a[0].localeCompare(b[0]));
398
- for (const [k, v] of pythonModulesArr) {
399
- p(`/**`);
400
- p(`* Nodes: ${v.join(", ")}`);
401
- p(`*/`);
402
- p(`| ${wrapQuote(k)}`);
403
- }
404
- b.deindent();
405
- p(`// #endregion`);
406
- const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
407
- p(`interface IN {`);
408
- b.indent();
409
- for (const n of nodes) {
410
- p(`${escapeJSKey(n.nodeKey)}: {`);
411
- for (const i of n.inputs) {
412
- const kind = classifySchemaInput(i);
413
- if (kind.kind === "dynamic-container") {
414
- const instType = containerInstanceSlotType(i.opts);
415
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
416
- const opt = ix >= kind.requiredCount ? "?" : "";
417
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
418
- });
419
- continue;
420
- }
421
- const opts_ = typeof i.opts === "string" ? null : i.opts;
422
- let type = `Accepts[${JSON.stringify(i.typeName)}]`;
423
- const comboOptions = i.typeName === "COMBO" && Array.isArray(opts_?.options) ? opts_.options.filter((o) => typeof o === "string" || typeof o === "number" || typeof o === "boolean") : [];
424
- if (comboOptions.length > 0) type = `${comboOptions.map((o) => JSON.stringify(o)).join(" | ")} | ${type}`;
425
- else if (opts_ && !i.isPrimitive && !i.isEnum) {
426
- if (typeof opts_.default === "string" || opts_.placeholder != null || opts_.multiline != null) type = `string | ${type}`;
427
- else if (typeof opts_.default === "number") type = `number | ${type}`;
428
- else if (typeof opts_.default === "boolean") type = `boolean | ${type}`;
429
- }
430
- if (opts_) {
431
- const rendered = n.renderOpts(opts_);
432
- if (rendered) p(` ${rendered}`);
433
- }
434
- const canBeOmmited = opts_?.default !== void 0 || !i.required;
435
- p(` ${i.nameInComfyEscaped}${canBeOmmited ? "?" : ""}: ${type}`);
436
- }
437
- p(`},`);
438
- }
439
- b.deindent();
440
- p("}");
441
- p("");
442
- p(`interface OUT {`);
443
- b.indent();
444
- for (const n of nodes) {
445
- p(`${escapeJSKey(n.nodeKey)}: {`);
446
- n.outputs.forEach((i, ix) => {
447
- p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`);
448
- });
449
- p(`}`);
450
- }
451
- b.deindent();
452
- p("}");
453
- p(`interface Node {`);
454
- for (const n of nodes) {
455
- p(` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`);
456
- for (const hassingle of n.singleOutputs) p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`);
457
- p(` }`);
458
- }
459
- p("}");
460
- p(`interface Builder {`);
461
- for (const n of nodes) {
462
- const baseDescription = `displayName="${n.raw.display_name}" category="${n.category}" name="${n.nameInComfy}" output=[${n.outputs.map((o) => o.outKey).join(", ")}]`;
463
- if (n.raw.description) {
464
- p(` /**`);
465
- p(n.raw.description.split("\n").map((i) => ` * ${i}`).join("\n"));
466
- p(` * ${baseDescription}`);
467
- p(` **/`);
468
- } else p(` /** ${baseDescription} */`);
469
- p(` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`);
470
- }
471
- p(`}`);
472
- p(`interface Slots {`);
473
- for (const e of this.knownUnionByHash.values()) {
474
- p(" // " + e.unionName);
475
- for (const alias of e.enumNames) p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`);
476
- }
477
- p(`}`);
478
- p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(" | ") || "\"\""}`);
479
- const slotTypes = [...this.knownSlotTypes.values()].map((comfyType) => ({
480
- comfyType,
481
- tsType: this.toTSType(comfyType),
482
- tsType2: this.toAcceptsType(comfyType)
483
- })).sort((a, b) => b.tsType.length - a.tsType.length);
484
- p("");
485
- p("interface Producer {");
486
- b.indent();
487
- for (const tp of slotTypes) {
488
- const allProducingNodes = this.nodesByProduction[tp.comfyType];
489
- if (allProducingNodes) p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(" | ")}>`);
490
- else p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`);
491
- }
492
- b.deindent();
493
- p("}");
494
- p(`interface Accepts {`);
495
- b.indent();
496
- p("// injected bottom type (broken/null input specs land here)");
497
- p(`INVALID_null: any`);
498
- p("");
499
- p("// named slot types: everything an input of that type accepts");
500
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
501
- p("");
502
- p("// enum unions: literal values or an output carrying one");
503
- for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
504
- b.deindent();
505
- p(`}\n`);
506
- p("interface Union {");
507
- for (const e of this.knownUnionByHash.values()) if (e.values.length > 0) {
508
- p(` // ${JSON.stringify(e.enumNames)}`);
509
- p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(" | ")}`);
510
- } else p(` ${e.unionName}: '🔴' // never`);
511
- p("}");
512
- p(`export interface HasSingle {`);
513
- for (const t of slotTypes) p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`);
514
- p(`}`);
515
- for (const t of this.enumsAppearingInOutput.values()) p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`);
516
- p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`);
517
- p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(" | ")}`);
518
- p(``);
519
- p(`/** everything above, packaged for the Comfy.Hosts registry */`);
520
- p(`interface Sdk {`);
521
- p(` IN: IN`);
522
- p(` OUT: OUT`);
523
- p(` Node: Node`);
524
- p(` Builder: Builder`);
525
- p(` Slots: Slots`);
526
- p(` Accepts: Accepts`);
527
- p(` Union: Union`);
528
- p(` Producer: Producer`);
529
- p(` Embeddings: Embeddings`);
530
- p(` Schemas: Schemas`);
531
- p(` NodeType: NodeType`);
532
- p(`}`);
533
- b.deindent();
534
- p(`}`);
535
- p(``);
536
- p(`interface Hosts {`);
537
- p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`);
538
- p(`}`);
539
- b.deindent();
540
- p("}");
541
- b.deindent();
542
- p("}");
543
- p(``);
544
- p(`export {}`);
545
- return b.content;
546
- }
547
- //#endregion
548
- //#region src/sdk-generator/comfyui-types.ts
549
- const asComfyNodeSlotTypeName = (x) => x;
550
- const asComfyNodeSlotName = (x) => x;
551
- //#endregion
552
- //#region src/utils/log.ts
553
- const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
554
- const logInfo = (msg) => {
555
- if (!isQuiet()) console.log(msg);
556
- };
557
- const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
558
- const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
559
- //#endregion
560
- //#region src/sdk-generator/ComfySchema.ts
561
- /**
562
- * ONE host's schema: the parsed view of its object_info.json + embeddings.
563
- * Owns union dedup (by sha1 of values), node indexing, and the per-host
564
- * sdk codegen (`codegenDTS`).
565
- */
566
- var ComfySchema = class {
567
- constructor(data) {
568
- this.data = data;
569
- this.codegenDTS = codegenSDK.bind(this);
570
- this.isInvalid = false;
571
- this.knownSlotTypes = /* @__PURE__ */ new Set();
572
- this.knownUnionBySlotName = /* @__PURE__ */ new Map();
573
- this.knownUnionByHash = /* @__PURE__ */ new Map();
574
- this.knownUnionByName = /* @__PURE__ */ new Map();
575
- this.nodes = [];
576
- this.pythonModuleByNodeKey = /* @__PURE__ */ new Map();
577
- this.pythonModuleByNodeNameInComfy = /* @__PURE__ */ new Map();
578
- this.nodesByNameInComfy = {};
579
- this.nodesByKey = {};
580
- this.nodesByProduction = {};
581
- this.enumsAppearingInOutput = /* @__PURE__ */ new Set();
582
- this.pythonModules = /* @__PURE__ */ new Map();
583
- this.processSlot = (p) => {
584
- const enumValues = [];
585
- for (const enumValue of p.comfyUnionDef) if (typeof enumValue === "string") enumValues.push(enumValue);
586
- else if (typeof enumValue === "boolean") enumValues.push(enumValue);
587
- else if (typeof enumValue === "number") enumValues.push(enumValue);
588
- else enumValues.push(enumValue.content);
589
- const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
590
- const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
591
- let unionInfo = this.knownUnionByHash.get(hash);
592
- if (unionInfo == null) {
593
- const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
594
- unionInfo = {
595
- hash,
596
- unionName,
597
- values: enumValues,
598
- enumNames: []
599
- };
600
- this.knownUnionByHash.set(hash, unionInfo);
601
- this.knownUnionByName.set(unionName, unionInfo);
602
- }
603
- unionInfo.enumNames.push(p.slotName);
604
- this.knownUnionBySlotName.set(p.slotName, unionInfo);
605
- return unionInfo;
606
- };
607
- this.RUN_BASIC_CHECKS = () => {
608
- const numNodesInSource = Object.keys(this.data.spec).length;
609
- const numNodesInSchema = this.nodes.length - 1;
610
- if (numNodesInSource !== numNodesInSchema) console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`);
611
- };
612
- this.getLoras = (filter) => {
613
- const all = this.stringValues("LoraLoader.lora_name");
614
- return filter == null ? all : all.filter((n) => filter.test(n));
615
- };
616
- this.getImages = () => {
617
- return this.stringValues("LoadImage.image");
618
- };
619
- this.unsafely_addImageInSchemaWithoutReloading = (imgName) => {
620
- const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName("LoadImage.image"));
621
- if (enumInfo == null) throw new Error(`LoadImage.image not found`);
622
- enumInfo.values.push(imgName);
623
- };
624
- this.getCheckpoints = () => {
625
- return this.stringValues("CheckpointLoaderSimple.ckpt_name");
626
- };
627
- this.parse();
628
- }
629
- update(data) {
630
- const prev = {
631
- spec: this.data.spec,
632
- embeddings: this.data.embeddings
633
- };
634
- Object.assign(this.data, data);
635
- try {
636
- this.parse();
637
- this.isInvalid = false;
638
- } catch (error) {
639
- console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error);
640
- this.data = prev;
641
- try {
642
- this.parse();
643
- } catch {}
644
- this.isInvalid = true;
645
- }
646
- }
647
- /** number of nodes in the current schema (quick way to check your instance infos) */
648
- get size() {
649
- return Object.keys(this.data.spec).length;
650
- }
651
- parse() {
652
- this.knownSlotTypes.clear();
653
- this.knownUnionBySlotName.clear();
654
- this.knownUnionByHash.clear();
655
- this.knownUnionByName.clear();
656
- this.nodes = [];
657
- this.pythonModuleByNodeKey.clear();
658
- this.pythonModuleByNodeNameInComfy.clear();
659
- this.nodesByNameInComfy = {};
660
- this.nodesByKey = {};
661
- this.nodesByProduction = {};
662
- this.enumsAppearingInOutput.clear();
663
- this.pythonModules.clear();
664
- if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0) this.log(`parsing ComfyUI object_info.json`);
665
- const entries = Object.entries(this.data.spec);
666
- entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema]);
667
- for (const [KK, VV] of entries) {
668
- const pythonModule = VV.python_module;
669
- const prev = this.pythonModules.get(pythonModule);
670
- if (prev == null) this.pythonModules.set(pythonModule, [KK]);
671
- else prev.push(KK);
672
- const nodeNameInComfy = KK;
673
- const nodeDef = VV;
674
- const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy);
675
- if (typeof nodeDef.output === "string") {
676
- console.log(`[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`);
677
- nodeDef.output = [];
678
- }
679
- this.pythonModuleByNodeKey.set(nodeKey, pythonModule);
680
- this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule);
681
- const inputs = [];
682
- const outputs = [];
683
- const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule);
684
- this.nodesByNameInComfy[nodeNameInComfy] = node;
685
- this.nodesByKey[nodeKey] = node;
686
- this.nodes.push(node);
687
- const nameCountDict = {};
688
- for (const [ix, slotType] of nodeDef.output.entries()) {
689
- const outputNameInComfy = nodeDef.output_name[ix] || (typeof slotType === "string" ? slotType : `input_${ix}`);
690
- const at = nameCountDict[outputNameInComfy] ??= 0;
691
- const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`;
692
- nameCountDict[outputNameInComfy]++;
693
- let slotTypeName;
694
- const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`);
695
- if (typeof slotType === "string") {
696
- slotTypeName = asComfyNodeSlotTypeName(slotType);
697
- this.knownSlotTypes.add(slotTypeName);
698
- } else if (Array.isArray(slotType)) {
699
- slotTypeName = asComfyNodeSlotTypeName(this.processSlot({
700
- pythonModule,
701
- slotName: outputSlotName,
702
- comfyUnionDef: slotType
703
- }).unionName);
704
- this.enumsAppearingInOutput.add(slotTypeName);
705
- } else throw new Error(`invalid output ${ix} "${slotType}" in node "${nodeNameInComfy}"`);
706
- const arr = this.nodesByProduction[slotTypeName];
707
- if (arr == null) this.nodesByProduction[slotTypeName] = [node];
708
- else arr.push(node);
709
- outputs.push({
710
- slotName: outputSlotName,
711
- typeName: slotTypeName,
712
- nameInComfy: outputNameInComfy,
713
- outKey: outKeyValue,
714
- isPrimitive: false
715
- });
716
- }
717
- const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}).map(([name, spec]) => ({
718
- required: false,
719
- name,
720
- spec
721
- }));
722
- const allInputs = [...Object.entries(nodeDef.input?.required ?? {}).map(([name, spec]) => ({
723
- required: true,
724
- name,
725
- spec
726
- })).filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null), ...optionalInputs];
727
- for (const ipt of allInputs) {
728
- const inputNameInComfy = ipt.name;
729
- const typeDef = ipt.spec;
730
- const slotType = typeDef[0];
731
- const slotOpts = typeDef[1];
732
- let inputTypeName;
733
- const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`);
734
- if (slotType == null) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
735
- pythonModule,
736
- slotName: inputSlotName,
737
- comfyUnionDef: ["❌"]
738
- }).unionName);
739
- else if (typeof slotType === "string") {
740
- inputTypeName = asComfyNodeSlotTypeName(slotType);
741
- this.knownSlotTypes.add(inputTypeName);
742
- } else if (Array.isArray(slotType)) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
743
- pythonModule,
744
- slotName: inputSlotName,
745
- comfyUnionDef: slotType
746
- }).unionName);
747
- else throw new Error(`invalid schema (${JSON.stringify(slotType)}) for input "${ipt.name}" in node "${nodeNameInComfy}" (type: ${typeof slotType}; expected: Array | string)`);
748
- const isAutogrowContainer = typeof slotType === "string" && classifyWidgetInput({
749
- name: ipt.name,
750
- type: slotType,
751
- opts: slotOpts
752
- }).kind === "dynamic-container";
753
- if (isAutogrowContainer) {
754
- const instType = containerInstanceSlotType(slotOpts);
755
- if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType));
756
- }
757
- node.inputs.push({
758
- slotName: inputSlotName,
759
- required: ipt.required && !isAutogrowContainer,
760
- nameInComfy: inputNameInComfy,
761
- nameInComfyEscaped: escapeJSKey(inputNameInComfy),
762
- typeName: inputTypeName,
763
- opts: slotOpts,
764
- isPrimitive: ComfyPrimitives.includes(inputTypeName),
765
- isEnum: this.knownUnionByName.has(inputTypeName),
766
- index: node.inputs.length
767
- });
768
- }
769
- }
770
- }
771
- log(...args) {
772
- logInfo(`[👅]: ${args.join(" ")}`);
773
- }
774
- toTSType(t) {
775
- if (t === "*") return `string | number | boolean | ComfyNodeOutput<string, number>`;
776
- return ComfyPrimitiveMapping[t] ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>` : `ComfyNodeOutput<'${t}'>`;
777
- }
778
- toAcceptsType(t) {
779
- return `ComfyNodeOutput<'${t}'>`;
780
- }
781
- /**
782
- * every possible value for a given slot, straight from the live schema.
783
- * e.g. schema.values('LoraLoader.lora_name') -> all loras on this host
784
- */
785
- values(slotName) {
786
- return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? [];
787
- }
788
- /** string values only (most enums are), for quick discovery */
789
- stringValues(slotName) {
790
- return this.values(slotName).filter((v) => typeof v === "string");
791
- }
792
- hasEmbedding(embedding) {
793
- return this.data.embeddings.includes(embedding);
794
- }
795
- hasLora(loraName) {
796
- return this.getLoras().includes(loraName);
797
- }
798
- hasImage(imgName) {
799
- return this.getImages().includes(imgName);
800
- }
801
- hasCheckpoint(ckptName) {
802
- return this.getCheckpoints().includes(ckptName);
803
- }
804
- };
805
- //#endregion
806
- //#region package.json
807
- var version = "1.2.0";
808
- //#endregion
809
- //#region src/litegraph/LiteGraphLinkID.ts
810
- const asLiteGraphLinkID = (id) => id;
811
- const LiteGraphLinkID_ = type.number.atLeast(0).as();
812
- //#endregion
813
- //#region src/utils/bang.ts
814
- /** assertNotNull */
815
- const bang = (x, msg = "") => {
816
- if (x == null) {
817
- console.error(`[🔴] BANG FAILED`, msg);
818
- throw new Error("bang: " + (msg ?? "no message"));
819
- }
820
- return x;
821
- };
822
- //#endregion
823
- //#region src/litegraph/expandSubgraphs.ts
824
- /** boundary sentinel ids inside definition link tables */
825
- const SUBGRAPH_INPUT_NODE_ID = -10;
826
- const SUBGRAPH_OUTPUT_NODE_ID = -20;
827
- /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
828
- const MAX_EXPANSION_PASSES = 32;
829
- /**
830
- * widget-kind fallback when a def input slot has no boundary target carrying a
831
- * widget marker: these litegraph slot types carry widget values. LOCAL copy on
832
- * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
833
- * (the io-widget era serializes exactly one value per exposed widget slot).
834
- */
835
- const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
836
- "INT",
837
- "FLOAT",
838
- "STRING",
839
- "BOOLEAN",
840
- "COMBO"
841
- ]);
842
- /**
843
- * inline every subgraph instance (node whose `type` is a definition uuid) into
844
- * the root graph: fresh numeric ids, boundary links rewired, instance widget
845
- * values promoted into the inner nodes' `named` overrides. Iterative so nested
846
- * definitions expand on the next pass. Muted instances are dropped (their
847
- * consumers resolve unconnected); bypassed instances stay for the converter's
848
- * passthrough walk, which needs no interior.
849
- */
850
- const expandSubgraphs = (wf, defs) => {
851
- let passes = 0;
852
- while (true) {
853
- const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
854
- if (expandable.length === 0) return wf;
855
- if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
856
- for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
857
- else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
858
- }
859
- };
860
- /** converter mute semantics applied early: after expansion there is no single node left to skip */
861
- const dropMutedInstance = (wf, instance) => {
862
- const dead = /* @__PURE__ */ new Set();
863
- for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
864
- wf.links = wf.links.filter((l) => !dead.has(l.id));
865
- wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
866
- pruneDeadLinkRefs(wf, dead);
867
- };
868
- const pruneDeadLinkRefs = (wf, dead) => {
869
- if (dead.size === 0) return;
870
- for (const node of wf.nodes) {
871
- for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
872
- for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
873
- }
874
- };
875
- const expandOneInstance = (wf, instance, def) => {
876
- let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
877
- let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
878
- const newNodeIds = /* @__PURE__ */ new Map();
879
- for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
880
- const remapNodeId = (id) => newNodeIds.get(id) ?? null;
881
- const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
882
- for (const [k, input] of instance.inputs.entries()) {
883
- const defSlot = def.inputs.findIndex((d) => d.name === input.name);
884
- 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(", ")})`);
885
- defSlotOfInstanceSlot.set(k, defSlot);
886
- }
887
- const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
888
- for (const link of wf.links) {
889
- if (link.targetId !== instance.id) continue;
890
- const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
891
- if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
892
- outerLinkIntoDefSlot.set(defSlot, link);
184
+ const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
185
+ for (const link of wf.links) {
186
+ if (link.targetId !== instance.id) continue;
187
+ const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
188
+ if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
189
+ outerLinkIntoDefSlot.set(defSlot, link);
893
190
  }
894
191
  const newLinkIds = /* @__PURE__ */ new Map();
895
192
  const splicedLinks = [];
@@ -1390,11 +687,239 @@ function parseBinaryWsFrame(data) {
1390
687
  metadata
1391
688
  };
1392
689
  }
1393
- return {
1394
- kind: "unknown",
1395
- eventType
1396
- };
1397
- }
690
+ return {
691
+ kind: "unknown",
692
+ eventType
693
+ };
694
+ }
695
+ //#endregion
696
+ //#region src/sdk-generator/Primitives.ts
697
+ const ComfyPrimitiveMapping = {
698
+ BOOLEAN: "boolean",
699
+ FLOAT: "number",
700
+ INT: "number",
701
+ STRING: "string"
702
+ };
703
+ const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
704
+ /**
705
+ * when a litegraph node has an input entry with a widget marker, the
706
+ * serialized TYPE string decides how many widgets_values it consumed in that era
707
+ */
708
+ const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
709
+ if (type === "INT") {
710
+ if (nameInComfy === "seed" || nameInComfy === "noise_seed") return 2;
711
+ return 1;
712
+ }
713
+ if (type === "BOOLEAN") return 1;
714
+ if (type === "FLOAT") return 1;
715
+ if (type === "STRING") return 1;
716
+ if (type === "COMBO") return 1;
717
+ if (type === "INT:seed") return 2;
718
+ if (type === "INT:noise_seed") return 2;
719
+ return 0;
720
+ };
721
+ const ComfyDefaultNodeWhenUnknown_Name = "UnknownNodeXX";
722
+ const ComfyDefaultNodeWhenUnknown_Schema = {
723
+ category: "test",
724
+ input: {},
725
+ output: [],
726
+ description: "This is a test node",
727
+ output_name: [],
728
+ display_name: "UnknownNodeXX",
729
+ name: "UnknownNodeXX",
730
+ output_is_list: [],
731
+ output_node: false,
732
+ python_module: "nodes"
733
+ };
734
+ //#endregion
735
+ //#region src/sdk-generator/inputWidgetKind.ts
736
+ const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
737
+ /**
738
+ * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
739
+ * The frontend creates the control widget on truthiness, and real 2026 hosts
740
+ * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
741
+ * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
742
+ * heuristic applies.
743
+ */
744
+ const controlConsumes = (o, typeName, name) => {
745
+ if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
746
+ if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
747
+ return 1;
748
+ };
749
+ const flattenInputSections = (inputs) => {
750
+ const out = [];
751
+ for (const section of ["required", "optional"]) {
752
+ const sec = inputs[section];
753
+ if (!isRecord(sec)) continue;
754
+ for (const [name, spec] of Object.entries(sec)) {
755
+ if (!Array.isArray(spec) || spec.length === 0) continue;
756
+ const t = spec[0];
757
+ if (typeof t !== "string" && !Array.isArray(t)) continue;
758
+ out.push({
759
+ name,
760
+ type: t,
761
+ opts: spec[1],
762
+ required: section === "required"
763
+ });
764
+ }
765
+ }
766
+ return out;
767
+ };
768
+ /** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
769
+ const parseDynamicOptions = (options) => {
770
+ if (options.length === 0) return null;
771
+ const out = [];
772
+ for (const entry of options) {
773
+ if (!isRecord(entry)) return null;
774
+ const key = entry["key"];
775
+ const inputs = entry["inputs"];
776
+ if (typeof key !== "string" || !isRecord(inputs)) return null;
777
+ out.push({
778
+ key,
779
+ inputs: flattenInputSections(inputs)
780
+ });
781
+ }
782
+ return out;
783
+ };
784
+ /**
785
+ * autogrow (`template` WITH a nested `input` section): instances are always
786
+ * link slots named `decl.<name_i>` (the backend force-inputs widget
787
+ * templates), the first `min` of them required WHEN the template input
788
+ * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
789
+ */
790
+ const parseContainer = (template) => {
791
+ const input = template["input"];
792
+ const min = typeof template["min"] === "number" ? template["min"] : 1;
793
+ const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
794
+ const max = typeof template["max"] === "number" ? template["max"] : 100;
795
+ const rawNames = template["names"];
796
+ const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
797
+ return {
798
+ kind: "dynamic-container",
799
+ instanceNames: names,
800
+ requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
801
+ };
802
+ };
803
+ /**
804
+ * the single template sub-input's slot type of an autogrow container
805
+ * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
806
+ * autogrow template or the template has several sub-inputs (corpus-absent
807
+ * 2026-07-30, 27/27 single on the cloud catalog) — then codegen emits no
808
+ * typed instance keys and the container stays builderBase territory.
809
+ */
810
+ const containerInstanceSlotType = (opts) => {
811
+ const template = (isRecord(opts) ? opts : null)?.["template"];
812
+ if (!isRecord(template) || !isRecord(template["input"])) return null;
813
+ const subs = flattenInputSections(template["input"]);
814
+ const first = subs[0];
815
+ if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
816
+ return first.type;
817
+ };
818
+ /**
819
+ * frontend-registered widgets whose object_info opts carry NO config signal —
820
+ * the one exception to config-only classification (architecture.md rule 8).
821
+ * Every entry must quote the frontend widget-creation source.
822
+ *
823
+ * LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified
824
+ * 2026-07-31): the LOAD_3D custom widget handler runs
825
+ * node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)
826
+ * node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)
827
+ * node.addWidget('button', 'clear', 'clear', …)
828
+ * THEN creates the scene widget, so the serialized run is
829
+ * [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved
830
+ * files, an {image, mask, normal, camera_info, …} dict at queue time.
831
+ */
832
+ const EMPTY_CONFIG_FRONTEND_WIDGETS = { LOAD_3D: { prefixValues: [
833
+ "upload3dmodel",
834
+ "uploadExtraResources",
835
+ "clear"
836
+ ] } };
837
+ const classifyWidgetInput = (p) => {
838
+ const o = isRecord(p.opts) ? p.opts : null;
839
+ if (o?.["forceInput"] === true) return { kind: "slot" };
840
+ if (Array.isArray(p.type) || p.isEnumUnion === true) {
841
+ const tn = typeof p.type === "string" ? p.type : "COMBO";
842
+ return {
843
+ kind: "widget",
844
+ consumes: controlConsumes(o, tn, p.name),
845
+ strictValues: true,
846
+ prefixValues: []
847
+ };
848
+ }
849
+ if (typeof p.type !== "string") return { kind: "slot" };
850
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
851
+ if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
852
+ kind: "widget",
853
+ consumes: controlConsumes(o, widgetTypeName, p.name),
854
+ strictValues: true,
855
+ prefixValues: []
856
+ };
857
+ const options = o?.["options"];
858
+ if (Array.isArray(options)) {
859
+ const dynOptions = parseDynamicOptions(options);
860
+ if (dynOptions != null) {
861
+ const first = dynOptions[0];
862
+ if (first == null) return { kind: "slot" };
863
+ return {
864
+ kind: "dynamic-combo",
865
+ options: dynOptions,
866
+ defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
867
+ };
868
+ }
869
+ return {
870
+ kind: "widget",
871
+ consumes: controlConsumes(o, p.type, p.name),
872
+ strictValues: true,
873
+ prefixValues: []
874
+ };
875
+ }
876
+ const template = o?.["template"];
877
+ if (isRecord(template)) {
878
+ if (isRecord(template["input"])) return parseContainer(template);
879
+ return { kind: "slot" };
880
+ }
881
+ if (o?.["socketless"] === true) return {
882
+ kind: "widget",
883
+ consumes: 1,
884
+ strictValues: false,
885
+ prefixValues: []
886
+ };
887
+ const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName];
888
+ if (emptyConfigEntry != null) return {
889
+ kind: "widget",
890
+ consumes: emptyConfigEntry.prefixValues.length + 1,
891
+ strictValues: false,
892
+ prefixValues: emptyConfigEntry.prefixValues
893
+ };
894
+ return { kind: "slot" };
895
+ };
896
+ const classifySchemaInput = (input) => classifyWidgetInput({
897
+ name: input.nameInComfy,
898
+ type: input.typeName,
899
+ opts: input.opts,
900
+ isEnumUnion: input.isEnum
901
+ });
902
+ /**
903
+ * what ComfyUI's frontend gives a widget created with no serialized value
904
+ * (`getWidgetDefaultValue` semantics), used when a positional array is
905
+ * shorter than the schema's widget list. `null` for custom widgets — the
906
+ * backend accepts an explicit null but errors on an ABSENT required key.
907
+ */
908
+ const defaultValueForWidget = (p) => {
909
+ const o = isRecord(p.opts) ? p.opts : null;
910
+ if (o != null && o["default"] !== void 0) return o["default"];
911
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
912
+ if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
913
+ if (widgetTypeName === "BOOLEAN") return false;
914
+ if (widgetTypeName === "STRING") return "";
915
+ const options = o?.["options"];
916
+ if (Array.isArray(options) && options.length > 0) {
917
+ const first = options[0];
918
+ if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
919
+ }
920
+ if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
921
+ return null;
922
+ };
1398
923
  //#endregion
1399
924
  //#region src/sdk-generator/litegraphToApiRequestPayload.ts
1400
925
  /** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
@@ -1475,15 +1000,15 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1475
1000
  if (!p.strict && isRecord(value)) return value;
1476
1001
  throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
1477
1002
  };
1478
- /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
1003
+ /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */
1479
1004
  const resolveWidgetValue = (p) => {
1480
1005
  let value;
1481
1006
  let has = false;
1482
1007
  if (Object.hasOwn(named, p.promptName)) {
1483
1008
  value = named[p.promptName];
1484
1009
  has = true;
1485
- } else if (offset < positional.length) {
1486
- value = positional[offset];
1010
+ } else if (offset + p.prefixLen < positional.length) {
1011
+ value = positional[offset + p.prefixLen];
1487
1012
  has = true;
1488
1013
  }
1489
1014
  if (positional.length > 0) offset += p.consumes;
@@ -1495,7 +1020,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1495
1020
  const consumePlainWidget = (p) => {
1496
1021
  const r = resolveWidgetValue({
1497
1022
  promptName: p.promptName,
1498
- consumes: p.consumes
1023
+ consumes: p.consumes,
1024
+ prefixLen: p.prefixLen
1499
1025
  });
1500
1026
  const raw = r.filled ? defaultValueForWidget({
1501
1027
  type: p.typeName,
@@ -1514,7 +1040,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1514
1040
  const consumeDynamicCombo = (p) => {
1515
1041
  const r = resolveWidgetValue({
1516
1042
  promptName: p.path,
1517
- consumes: 1
1043
+ consumes: 1,
1044
+ prefixLen: 0
1518
1045
  });
1519
1046
  const key = r.filled ? p.defaultKey : r.value;
1520
1047
  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);
@@ -1542,6 +1069,7 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1542
1069
  typeName: typeof sub.type === "string" ? sub.type : "COMBO",
1543
1070
  opts: sub.opts,
1544
1071
  consumes: kind.consumes,
1072
+ prefixLen: kind.prefixValues.length,
1545
1073
  strict: kind.strictValues,
1546
1074
  enumValues: inlineEnum,
1547
1075
  linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
@@ -1553,13 +1081,15 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1553
1081
  if (kind.kind === "slot" && input?.widgetName != null) kind = {
1554
1082
  kind: "widget",
1555
1083
  consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
1556
- strictValues: true
1084
+ strictValues: true,
1085
+ prefixValues: []
1557
1086
  };
1558
1087
  if (kind.kind === "widget") consumePlainWidget({
1559
1088
  promptName: field.nameInComfy,
1560
1089
  typeName: field.typeName,
1561
1090
  opts: field.opts,
1562
1091
  consumes: kind.consumes,
1092
+ prefixLen: kind.prefixValues.length,
1563
1093
  strict: kind.strictValues,
1564
1094
  linkedInput: input
1565
1095
  });
@@ -1714,6 +1244,11 @@ const comfyColors = {
1714
1244
  };
1715
1245
  //#endregion
1716
1246
  //#region src/graph/autoValue.ts
1247
+ /**
1248
+ * you can use this as a placeholder anywhere in your graph
1249
+ * comfy-ts wires the most recent output of a matching type at serialization time
1250
+ */
1251
+ const auto = () => auto_;
1717
1252
  const auto_ = { ___AUTO___: true };
1718
1253
  //#endregion
1719
1254
  //#region src/graph/ComfyNodeOutput.ts
@@ -2054,7 +1589,7 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
2054
1589
  const widgets_values = [];
2055
1590
  for (const ipt of node.$schema.inputs) {
2056
1591
  const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
2057
- const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0;
1592
+ const kind = classifySchemaInput(ipt);
2058
1593
  if (_isLink(raw)) {
2059
1594
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber, `link target node "${raw[0]}" not found in graph`);
2060
1595
  inputs.push({
@@ -2062,9 +1597,10 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
2062
1597
  type: ipt.typeName,
2063
1598
  link: ctx.allocateLink(nodeUidNumber, raw[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), ipt.typeName)
2064
1599
  });
2065
- } else if (isWidget) {
2066
- widgets_values.push(raw);
2067
- if (ipt.typeName === "INT" && (ipt.nameInComfy === "seed" || ipt.nameInComfy === "noise_seed")) widgets_values.push(false);
1600
+ } else if (kind.kind === "widget") {
1601
+ widgets_values.push(...kind.prefixValues, raw);
1602
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1603
+ for (let i = 0; i < phantoms; i++) widgets_values.push(false);
2068
1604
  } else inputs.push({
2069
1605
  name: ipt.nameInComfy,
2070
1606
  type: ipt.typeName,
@@ -2110,8 +1646,94 @@ var LiteGraphCtx = class {
2110
1646
  }
2111
1647
  };
2112
1648
  //#endregion
1649
+ //#region src/runner/outputPath.ts
1650
+ /**
1651
+ * local output naming, relative to `.comfy-ts/outputs/` (his repro
1652
+ * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
1653
+ * `_00001_` counter every run, so trusting it overwrote the same file — and
1654
+ * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
1655
+ * prefix. Local names are ours: dir from the prompt's own filename_prefix
1656
+ * (or an explicit saveFormat.prefix override), then
1657
+ * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
1658
+ * per stem and nothing ever collides.
1659
+ */
1660
+ const localOutputPath = (p) => {
1661
+ const dot = p.filename.lastIndexOf(".");
1662
+ const ext = dot === -1 ? "" : p.filename.slice(dot);
1663
+ const base = dot === -1 ? p.filename : p.filename.slice(0, dot);
1664
+ const counterMatch = /_(\d+)_$/.exec(base);
1665
+ const counter = counterMatch?.[1];
1666
+ const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base;
1667
+ let dir;
1668
+ let stem;
1669
+ if (p.filenamePrefix != null && p.filenamePrefix !== "") {
1670
+ const slash = p.filenamePrefix.lastIndexOf("/");
1671
+ dir = slash === -1 ? "" : p.filenamePrefix.slice(0, slash);
1672
+ stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1);
1673
+ } else {
1674
+ dir = p.subfolder;
1675
+ stem = serverStem;
1676
+ }
1677
+ if (p.localDir != null) dir = p.localDir;
1678
+ const name = [
1679
+ stem === "" ? null : stem,
1680
+ p.timestamp,
1681
+ counter
1682
+ ].filter((x) => x != null).join("_") + ext;
1683
+ return dir === "" ? name : `${dir}/${name}`;
1684
+ };
1685
+ /**
1686
+ * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
1687
+ * was already CLAIMED by a still-downloading retrieval (two same-second runs
1688
+ * on a counter-resetting cloud host compute the same name — reviewer catch).
1689
+ * The chosen path is claimed before returning.
1690
+ */
1691
+ const uniquifyOutputPath = (p) => {
1692
+ let out = p.path;
1693
+ if (p.exists(out) || p.claimed.has(out)) {
1694
+ const dot = out.lastIndexOf(".");
1695
+ const stem = dot === -1 ? out : out.slice(0, dot);
1696
+ const ext = dot === -1 ? "" : out.slice(dot);
1697
+ for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`;
1698
+ }
1699
+ p.claimed.add(out);
1700
+ return out;
1701
+ };
1702
+ /** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */
1703
+ const runTimestamp = (d) => {
1704
+ const pad = (n) => String(n).padStart(2, "0");
1705
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
1706
+ };
1707
+ //#endregion
1708
+ //#region src/utils/extractErrorMessage.ts
1709
+ /** Extracts an error message from an exception stuff. */
1710
+ const extractErrorMessage = (error) => {
1711
+ if (error instanceof Error) return error.message;
1712
+ if (error === null) return "null";
1713
+ if (typeof error === "string") return error;
1714
+ if (typeof error === "object") {
1715
+ if ("message" in error && typeof error.message === "string") return error.message;
1716
+ return JSON.stringify(error);
1717
+ }
1718
+ return String(error);
1719
+ };
1720
+ //#endregion
1721
+ //#region src/utils/lazySharp.ts
1722
+ let cached = null;
1723
+ async function importSharp(reason) {
1724
+ if (cached != null) return cached;
1725
+ const specifier = "sharp";
1726
+ try {
1727
+ cached = (await import(specifier)).default;
1728
+ return cached;
1729
+ } catch (e) {
1730
+ throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
1731
+ }
1732
+ }
1733
+ //#endregion
2113
1734
  //#region src/types/index.ts
2114
1735
  const asAbsolutePath = (path) => path;
1736
+ const asRelativePath = (path) => path;
2115
1737
  const resultSuccess = (value) => ({
2116
1738
  success: true,
2117
1739
  value
@@ -2120,6 +1742,18 @@ const resultFailure = (value) => ({
2120
1742
  success: false,
2121
1743
  value
2122
1744
  });
1745
+ const __OK = (value) => ({
1746
+ success: true,
1747
+ value
1748
+ });
1749
+ const __FAIL = (message, error) => ({
1750
+ success: false,
1751
+ message,
1752
+ error,
1753
+ value: void 0
1754
+ });
1755
+ const asMDContent = (s) => s;
1756
+ const asHTMLContent = (s) => s;
2123
1757
  //#endregion
2124
1758
  //#region src/image-utils/_getPngMetadata.ts
2125
1759
  const getPngMetadataFromUint8Array = (pngData) => {
@@ -2146,10 +1780,78 @@ function exhaust(x) {
2146
1780
  return x;
2147
1781
  }
2148
1782
  //#endregion
1783
+ //#region src/utils/sha1.ts
1784
+ function sha1Hex(data) {
1785
+ const ml = data.length;
1786
+ const total = Math.ceil((ml + 1 + 8) / 64) * 64;
1787
+ const bytes = new Uint8Array(total);
1788
+ bytes.set(data);
1789
+ bytes[ml] = 128;
1790
+ const dv = new DataView(bytes.buffer);
1791
+ const bitLen = ml * 8;
1792
+ dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32));
1793
+ dv.setUint32(total - 4, bitLen >>> 0);
1794
+ let h0 = 1732584193;
1795
+ let h1 = 4023233417;
1796
+ let h2 = 2562383102;
1797
+ let h3 = 271733878;
1798
+ let h4 = 3285377520;
1799
+ const w = /* @__PURE__ */ new Uint32Array(80);
1800
+ for (let i = 0; i < total; i += 64) {
1801
+ for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
1802
+ for (let j = 16; j < 80; j++) {
1803
+ const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0);
1804
+ w[j] = n << 1 | n >>> 31;
1805
+ }
1806
+ let a = h0;
1807
+ let b = h1;
1808
+ let c = h2;
1809
+ let d = h3;
1810
+ let e = h4;
1811
+ for (let j = 0; j < 80; j++) {
1812
+ let f;
1813
+ let k;
1814
+ if (j < 20) {
1815
+ f = b & c | ~b & d;
1816
+ k = 1518500249;
1817
+ } else if (j < 40) {
1818
+ f = b ^ c ^ d;
1819
+ k = 1859775393;
1820
+ } else if (j < 60) {
1821
+ f = b & c | b & d | c & d;
1822
+ k = 2400959708;
1823
+ } else {
1824
+ f = b ^ c ^ d;
1825
+ k = 3395469782;
1826
+ }
1827
+ const temp = (a << 5 | a >>> 27) + f + e + k + (w[j] ?? 0) >>> 0;
1828
+ e = d;
1829
+ d = c;
1830
+ c = b << 30 | b >>> 2;
1831
+ b = a;
1832
+ a = temp;
1833
+ }
1834
+ h0 = h0 + a >>> 0;
1835
+ h1 = h1 + b >>> 0;
1836
+ h2 = h2 + c >>> 0;
1837
+ h3 = h3 + d >>> 0;
1838
+ h4 = h4 + e >>> 0;
1839
+ }
1840
+ return [
1841
+ h0,
1842
+ h1,
1843
+ h2,
1844
+ h3,
1845
+ h4
1846
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
1847
+ }
1848
+ function sha1HexOfString(s) {
1849
+ return sha1Hex(new TextEncoder().encode(s));
1850
+ }
1851
+ //#endregion
2149
1852
  //#region src/utils/hashArrayBuffer.ts
2150
1853
  const hashArrayBuffer = (buffer) => {
2151
- const data = Buffer.from(buffer);
2152
- return crypto.createHash("sha1").update(data).digest("hex");
1854
+ return sha1Hex(buffer);
2153
1855
  };
2154
1856
  //#endregion
2155
1857
  //#region src/graph/ComfyNodeID.ts
@@ -2325,661 +2027,1255 @@ var MediaImage = class MediaImage {
2325
2027
  this._metadata = null;
2326
2028
  this._hash = null;
2327
2029
  this.processWithSharp_inplace = async (fn) => {
2328
- const buff = await fn(sharp(this.absPath)).toBuffer();
2329
- writeFileSync(this.absPath, buff);
2030
+ const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
2031
+ getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
2330
2032
  this.updateBuffer(new Uint8Array(buff));
2331
2033
  return this;
2332
2034
  };
2333
- this.processWithSharp = async (fn, path) => {
2334
- const res = fn(sharp(this.absPath));
2335
- path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
2336
- await res.toFile(path);
2337
- const buffer = await res.toBuffer();
2338
- return new MediaImage({
2339
- path,
2340
- buffer
2035
+ this.processWithSharp = async (fn, path) => {
2036
+ const sharp = await importSharp("processWithSharp");
2037
+ path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
2038
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
2039
+ getComfyStorage().writeBytes(path, buffer);
2040
+ return new MediaImage({
2041
+ path,
2042
+ buffer
2043
+ });
2044
+ };
2045
+ this.absPath = data.path;
2046
+ this.execution = data.execution;
2047
+ this.promptNodeID = data.promptNodeID;
2048
+ if (data.buffer != null) this.updateBuffer(data.buffer);
2049
+ }
2050
+ /** the image as a Blob, e.g. to feed FormData uploads */
2051
+ getAsBlob() {
2052
+ return new Blob([this.buffer], { type: `image/${this.metadata.type ?? "png"}` });
2053
+ }
2054
+ /** return the image filename */
2055
+ get filename() {
2056
+ return basename(this.absPath);
2057
+ }
2058
+ get baseNameWithoutExtension() {
2059
+ const fname = this.filename;
2060
+ return fname.slice(0, fname.lastIndexOf("."));
2061
+ }
2062
+ /**
2063
+ * return file extension including dot
2064
+ * e.g. `.png`, or `.webp`
2065
+ * */
2066
+ get extension() {
2067
+ const fname = this.filename;
2068
+ return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 1);
2069
+ }
2070
+ /** get the expected enum name (hash) */
2071
+ get enumName() {
2072
+ return `${this.hash}${this.extension}`;
2073
+ }
2074
+ /** return the json of the ComfyNode that led to this image */
2075
+ get ComfyNode() {
2076
+ const nodeID = this.promptNodeID;
2077
+ if (nodeID == null) return null;
2078
+ return this.workflow?.apiJson[nodeID];
2079
+ }
2080
+ /**
2081
+ * return the metadata of the ComfyNode that led to this image
2082
+ * null if not generated by comfy through a ComfyTS prompt
2083
+ * null if no metadata associated in the node in ComfyTS
2084
+ */
2085
+ get ComfyNodeMetadata() {
2086
+ const nodeID = this.promptNodeID;
2087
+ if (nodeID == null) return null;
2088
+ return this.workflow?.data.metadata[nodeID];
2089
+ }
2090
+ get width() {
2091
+ return this.metadata.width;
2092
+ }
2093
+ get height() {
2094
+ return this.metadata.height;
2095
+ }
2096
+ get width_orCrash() {
2097
+ return bang(this.metadata.width);
2098
+ }
2099
+ get height_orCrash() {
2100
+ return bang(this.metadata.height);
2101
+ }
2102
+ /**
2103
+ * return the base64 url for this file, regardless of it's exact representation
2104
+ * includes the prefix `data:image/<type>;base64,`
2105
+ */
2106
+ getBase64Url() {
2107
+ return `data:image/${this.metadata.type ?? "png"};base64,${this.getBase64Payload()}`;
2108
+ }
2109
+ /**
2110
+ * return the base64 url for this file, regardless of it's exact representation
2111
+ * does not includes the prefix `data:image/png;base64,`
2112
+ */
2113
+ getBase64Payload() {
2114
+ const bytes = this.buffer;
2115
+ let bin = "";
2116
+ const chunk = 32768;
2117
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
2118
+ return btoa(bin);
2119
+ }
2120
+ get buffer() {
2121
+ if (this._buffer != null) return this._buffer;
2122
+ this._buffer = getComfyStorage().readBytes(this.absPath);
2123
+ return this._buffer;
2124
+ }
2125
+ get metadata() {
2126
+ if (this._metadata != null) return this._metadata;
2127
+ this._metadata = imageMeta(this.buffer);
2128
+ return this._metadata;
2129
+ }
2130
+ get hash() {
2131
+ if (this._hash != null) return this._hash;
2132
+ this._hash = hashArrayBuffer(this.buffer);
2133
+ return this._hash;
2134
+ }
2135
+ };
2136
+ //#endregion
2137
+ //#region src/runner/ComfyExecution.ts
2138
+ /** paths claimed by in-flight retrievals: two same-second runs on a
2139
+ * counter-resetting cloud host compute the same name before either writes */
2140
+ const CLAIMED_OUTPUT_PATHS = /* @__PURE__ */ new Set();
2141
+ var ComfyExecution = class {
2142
+ get host() {
2143
+ return this.workflow.host;
2144
+ }
2145
+ constructor(workflow, data, init = {}) {
2146
+ this.workflow = workflow;
2147
+ this.data = data;
2148
+ this.saveFormat = null;
2149
+ this.snapshot = null;
2150
+ this.onProgress = null;
2151
+ this.logProgress = false;
2152
+ this.startedAt = Date.now();
2153
+ this._lastLoggedLine = "";
2154
+ this.done = new Promise((resolve) => {
2155
+ this._resolve = resolve;
2156
+ });
2157
+ this.onPromptRelatedMessage = (msg) => {
2158
+ const graph = this.workflow;
2159
+ if (msg.type === "execution_start") return;
2160
+ else if (msg.type === "execution_cached") graph.onExecutionCached(msg);
2161
+ else if (msg.type === "executing") this.onExecuting(msg);
2162
+ else if (msg.type === "progress") graph.onProgress(msg);
2163
+ else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2164
+ else if (msg.type === "execution_error") return void this.onError(msg);
2165
+ else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2166
+ else {
2167
+ console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
2168
+ return exhaust(msg);
2169
+ }
2170
+ this.emitProgress();
2171
+ };
2172
+ this.onExecuting = (msg) => {
2173
+ this.workflow.onExecuting(msg);
2174
+ };
2175
+ this.onExecutionSuccess = async (_msg) => {
2176
+ await Promise.all(this.pendingPromises);
2177
+ return this._finish({ status: "Success" });
2178
+ };
2179
+ this.onError = async (msg) => {
2180
+ console.error("❌ Execution error:");
2181
+ console.error(msg);
2182
+ return this._finish({
2183
+ status: "Failure",
2184
+ error: msg
2185
+ });
2186
+ };
2187
+ this.onExecuted = (msg) => {
2188
+ const promptNodeID = msg.data.node;
2189
+ const images = msg.data.output?.images;
2190
+ if (images) for (const img of images) this.pendingPromises.push(this.retrieveImage(img, promptNodeID).catch((e) => {
2191
+ console.error(`🔴 failed to retrieve ${img.filename}:`, e);
2192
+ this.imageErrors.push({
2193
+ image: img,
2194
+ error: e
2195
+ });
2196
+ }));
2197
+ };
2198
+ this.pendingPromises = [];
2199
+ this.imageErrors = [];
2200
+ this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
2201
+ const promptNode = this.workflow.data.apiJson?.[promptNodeID];
2202
+ const promptMeta = this.workflow.data.metadata?.[promptNodeID];
2203
+ if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
2204
+ const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
2205
+ const sf = this.saveFormat;
2206
+ const promptPrefix = promptNode.inputs["filename_prefix"];
2207
+ let absPath = comfyts.resolveFromOutput(localOutputPath({
2208
+ localDir: sf?.prefix,
2209
+ filenamePrefix: typeof promptPrefix === "string" ? promptPrefix : void 0,
2210
+ subfolder: comfyImageInfo.subfolder,
2211
+ filename: comfyImageInfo.filename,
2212
+ timestamp: runTimestamp(new Date(this.startedAt))
2213
+ }));
2214
+ if (sf?.format && sf.format !== "raw") {
2215
+ const extension = sf.format.split("/")[1];
2216
+ absPath += "." + extension;
2217
+ }
2218
+ const storage = getComfyStorage();
2219
+ absPath = uniquifyOutputPath({
2220
+ path: absPath,
2221
+ exists: (p) => storage.exists(p),
2222
+ claimed: CLAIMED_OUTPUT_PATHS
2223
+ });
2224
+ let img;
2225
+ if (sf && sf.format !== "raw") {
2226
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2227
+ let textChunk = {};
2228
+ try {
2229
+ const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
2230
+ if (res.success) textChunk = res.value;
2231
+ } catch {}
2232
+ const format = (() => {
2233
+ if (sf.format === "image/jpeg") return "jpeg";
2234
+ if (sf.format === "image/png") return "png";
2235
+ if (sf.format === "image/webp") return "webp";
2236
+ return "png";
2237
+ })();
2238
+ const encoded = await (await importSharp(`saveFormat '${sf.format}' re-encoding`))(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toBuffer();
2239
+ storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded));
2240
+ img = new MediaImage({
2241
+ path: asAbsolutePath(absPath),
2242
+ buffer: new Uint8Array(encoded),
2243
+ execution: this,
2244
+ promptNodeID,
2245
+ comfyUIInfos: {
2246
+ comfyImageInfo,
2247
+ comfyHostHttpURL: this.host.getServerHostHTTP()
2248
+ }
2249
+ });
2250
+ } else {
2251
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2252
+ const uint8arr = new Uint8Array(buff);
2253
+ storage.writeBytes(asAbsolutePath(absPath), uint8arr);
2254
+ img = new MediaImage({
2255
+ path: asAbsolutePath(absPath),
2256
+ buffer: uint8arr,
2257
+ execution: this,
2258
+ promptNodeID,
2259
+ comfyUIInfos: {
2260
+ comfyImageInfo,
2261
+ comfyHostHttpURL: this.host.getServerHostHTTP()
2262
+ }
2263
+ });
2264
+ }
2265
+ if (promptMeta?.tag) img.tags.push(promptMeta.tag);
2266
+ if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
2267
+ this.images.push(img);
2268
+ };
2269
+ this.images = [];
2270
+ this.alreadyDone = false;
2271
+ this._finish = async (p) => {
2272
+ if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`);
2273
+ this.alreadyDone = true;
2274
+ this.update({
2275
+ ...p,
2276
+ executed: true
2341
2277
  });
2278
+ await Promise.all(this.pendingPromises);
2279
+ this.host.executions.delete(this.data.id);
2280
+ this.host._pendingMsgs.delete(this.data.id);
2281
+ this.finishProgressLine();
2282
+ this._resolve(this);
2342
2283
  };
2343
- this.generatePreview = async (targetPath) => {
2344
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
2345
- mkdirSync(dirname(targetPath), { recursive: true });
2346
- await img.toFile(targetPath);
2347
- };
2348
- this.generateMiniPreview = async () => {
2349
- return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
2350
- };
2351
- this.absPath = data.path;
2352
- this.execution = data.execution;
2353
- this.promptNodeID = data.promptNodeID;
2354
- if (data.buffer != null) this.updateBuffer(data.buffer);
2355
- }
2356
- /** the image as a Blob, e.g. to feed FormData uploads */
2357
- getAsBlob() {
2358
- return new Blob([this.buffer], { type: `image/${this.metadata.type ?? "png"}` });
2359
- }
2360
- /** return the image filename */
2361
- get filename() {
2362
- return basename(this.absPath);
2363
- }
2364
- get baseNameWithoutExtension() {
2365
- const fname = this.filename;
2366
- return fname.slice(0, fname.lastIndexOf("."));
2284
+ this.snapshot = init.snapshot ?? null;
2285
+ this.saveFormat = init.saveFormat ?? null;
2286
+ this.onProgress = init.onProgress ?? null;
2287
+ this.logProgress = init.logProgress ?? false;
2288
+ this.host.executions.set(data.id, this);
2289
+ this.onCreate();
2367
2290
  }
2368
- /**
2369
- * return file extension including dot
2370
- * e.g. `.png`, or `.webp`
2371
- * */
2372
- get extension() {
2373
- const fname = this.filename;
2374
- return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 1);
2291
+ get progress() {
2292
+ return {
2293
+ ...this.progressGlobal,
2294
+ promptId: this.data.id,
2295
+ nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,
2296
+ elapsedMs: Date.now() - this.startedAt
2297
+ };
2375
2298
  }
2376
- /** get the expected enum name (hash) */
2377
- get enumName() {
2378
- return `${this.hash}${this.extension}`;
2299
+ emitProgress() {
2300
+ const p = this.progress;
2301
+ this.onProgress?.(p);
2302
+ if (!this.logProgress) return;
2303
+ const width = 12;
2304
+ const filled = Math.round(p.percent / 100 * width);
2305
+ const bar = "█".repeat(filled) + "░".repeat(width - filled);
2306
+ const node = p.nodeName ? ` · ${p.nodeName}` : "";
2307
+ const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2308
+ if (line === this._lastLoggedLine) return;
2309
+ this._lastLoggedLine = line;
2310
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2311
+ else console.log(line);
2379
2312
  }
2380
- /** return the json of the ComfyNode that led to this image */
2381
- get ComfyNode() {
2382
- const nodeID = this.promptNodeID;
2383
- if (nodeID == null) return null;
2384
- return this.workflow?.apiJson[nodeID];
2313
+ finishProgressLine() {
2314
+ if (!this.logProgress) return;
2315
+ const p = this.progress;
2316
+ const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2317
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2318
+ else console.log(line);
2385
2319
  }
2386
- /**
2387
- * return the metadata of the ComfyNode that led to this image
2388
- * null if not generated by comfy through a ComfyTS prompt
2389
- * null if no metadata associated in the node in ComfyTS
2390
- */
2391
- get ComfyNodeMetadata() {
2392
- const nodeID = this.promptNodeID;
2393
- if (nodeID == null) return null;
2394
- return this.workflow?.data.metadata[nodeID];
2320
+ log(...args) {
2321
+ console.log(`[ComfyExecution#${this.data.id}]`, ...args);
2395
2322
  }
2396
- get width() {
2397
- return this.metadata.width;
2323
+ onCreate() {
2324
+ const data = this.data;
2325
+ const pending = this.host._pendingMsgs.get(data.id);
2326
+ if (pending == null) return;
2327
+ this.log(`🟢 onCreate: ${pending.length} pending messages`);
2328
+ this.host._pendingMsgs.delete(data.id);
2329
+ for (const msg of pending) this.onPromptRelatedMessage(msg);
2398
2330
  }
2399
- get height() {
2400
- return this.metadata.height;
2331
+ get progressGlobal() {
2332
+ if (this.data.status === "Success") return {
2333
+ countDone: 1,
2334
+ countTotal: 1,
2335
+ isDone: true,
2336
+ percent: 100
2337
+ };
2338
+ return this.workflow.progressGlobal;
2401
2339
  }
2402
- get width_orCrash() {
2403
- return bang(this.metadata.width);
2340
+ get status() {
2341
+ return this.data.status ?? "New";
2404
2342
  }
2405
- get height_orCrash() {
2406
- return bang(this.metadata.height);
2343
+ update(data) {
2344
+ Object.assign(this.data, data);
2407
2345
  }
2408
- /**
2409
- * return the base64 url for this file, regardless of it's exact representation
2410
- * includes the prefix `data:image/<type>;base64,`
2411
- */
2412
- getBase64Url() {
2413
- return `data:image/${this.metadata.type ?? "png"};base64,${this.getBase64Payload()}`;
2346
+ };
2347
+ //#endregion
2348
+ //#region src/utils/deepCopyNaive.ts
2349
+ const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
2350
+ //#endregion
2351
+ //#region src/utils/ansi.ts
2352
+ const codes = {
2353
+ bold: [1, 22],
2354
+ underline: [4, 24],
2355
+ red: [31, 39],
2356
+ green: [32, 39],
2357
+ yellow: [33, 39],
2358
+ blue: [34, 39],
2359
+ greenBright: [92, 39]
2360
+ };
2361
+ function styler(open = "", close = "") {
2362
+ const fn = (s) => open + s + close;
2363
+ return new Proxy(fn, { get(_target, prop) {
2364
+ const c = codes[prop];
2365
+ if (c == null) throw new Error(`unknown ansi style: ${prop}`);
2366
+ return styler(`${open}\x1b[${c[0]}m`, `\x1b[${c[1]}m${close}`);
2367
+ } });
2368
+ }
2369
+ const ansi = styler();
2370
+ //#endregion
2371
+ //#region src/utils/log.ts
2372
+ const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
2373
+ const logInfo = (msg) => {
2374
+ if (!isQuiet()) console.log(msg);
2375
+ };
2376
+ const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
2377
+ const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
2378
+ //#endregion
2379
+ //#region src/utils/printArkResultInConsole.ts
2380
+ const MAX_PRINTED_ERRORS = 10;
2381
+ function printArkResultInConsole(res) {
2382
+ if (isQuiet()) return;
2383
+ console.log(ansi.red(" ❌ Ark validation failed:"));
2384
+ for (const error of res.slice(0, MAX_PRINTED_ERRORS)) console.log(ansi.red(` - ${error.path.join(".")} : ${error.message}`));
2385
+ if (res.length > MAX_PRINTED_ERRORS) console.log(ansi.red(` … ${res.length - MAX_PRINTED_ERRORS} more (${res.length} total)`));
2386
+ }
2387
+ //#endregion
2388
+ //#region src/utils/softValidate.ts
2389
+ const softValidate = (schema, stuff) => {
2390
+ const res = schema(stuff);
2391
+ if (res instanceof type.errors) printArkResultInConsole(res);
2392
+ return stuff;
2393
+ };
2394
+ //#endregion
2395
+ //#region src/utils/toposort.ts
2396
+ function toposort(nodes, edges) {
2397
+ return toposortAlgo(nodes, edges);
2398
+ }
2399
+ function toposortAlgo(nodes, edges) {
2400
+ let cursor = nodes.length;
2401
+ const sorted = Array.from({ length: cursor });
2402
+ const visited = {};
2403
+ let k = cursor;
2404
+ while (k--) if (!visited[k]) visit(BONG(nodes[k]), k, []);
2405
+ return sorted;
2406
+ function visit(node, ix, predecessors) {
2407
+ let i = ix;
2408
+ if (predecessors.indexOf(node) >= 0) {
2409
+ console.log(predecessors, node);
2410
+ throw new Error("Cyclic dependency: " + JSON.stringify(node));
2411
+ }
2412
+ 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));
2413
+ if (visited[i]) return;
2414
+ visited[i] = true;
2415
+ const outgoing = edges.filter((edge) => edge[0] === node);
2416
+ i = outgoing.length;
2417
+ if (i) {
2418
+ const preds = predecessors.concat(node);
2419
+ do {
2420
+ const child = BONG(outgoing[--i])[1];
2421
+ visit(child, nodes.indexOf(child), preds);
2422
+ } while (i);
2423
+ }
2424
+ sorted[--cursor] = node;
2414
2425
  }
2415
- /**
2416
- * return the base64 url for this file, regardless of it's exact representation
2417
- * does not includes the prefix `data:image/png;base64,`
2418
- */
2419
- getBase64Payload() {
2420
- return Buffer.from(this.buffer).toString("base64");
2426
+ }
2427
+ function BONG(x) {
2428
+ if (x == null) throw new Error("BONG");
2429
+ return x;
2430
+ }
2431
+ //#endregion
2432
+ //#region src/runner/ComfyWorkflowLayout.ts
2433
+ /**
2434
+ * compute autolayout
2435
+ *
2436
+ * 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive
2437
+ * libraries were pretty bad; ended up writing my own simple algorithm, and I'm
2438
+ * happy with it. Feel free to improve it, but I think it works well enough.
2439
+ * I will accept PRs for new layout algorithms if they don't have massive dependencies.
2440
+ **/
2441
+ function comfyWorkflowAutoLayout(p) {
2442
+ const nodeIds = toposort(this.nodes.map((n) => n.uid), this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid])));
2443
+ const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`));
2444
+ const cols = Array.from({ length: nodeIds.length });
2445
+ const ranges = {};
2446
+ for (const node of nodes) {
2447
+ const parentCols = node.parents.map((p) => ranges[p.uid].minCol);
2448
+ const range = {
2449
+ node,
2450
+ minCol: Math.max(...parentCols, -1) + 1
2451
+ };
2452
+ ranges[node.uid] = range;
2421
2453
  }
2422
- get buffer() {
2423
- if (this._buffer != null) return this._buffer;
2424
- const buff = readFileSync(this.absPath);
2425
- const uint8arr = new Uint8Array(buff);
2426
- this._buffer = uint8arr;
2427
- return this._buffer;
2454
+ if (!p?.forceLeft === true) for (const node of nodes) {
2455
+ const range = ranges[node.uid];
2456
+ for (const p of node.parents) {
2457
+ const parentRange = ranges[p.uid];
2458
+ parentRange.maxCol = parentRange.maxCol != null ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1) : (range.maxCol ?? range.minCol) - 1;
2459
+ }
2428
2460
  }
2429
- get metadata() {
2430
- if (this._metadata != null) return this._metadata;
2431
- const buff = readFileSync(this.absPath);
2432
- const uint8arr = new Uint8Array(buff);
2433
- this._metadata = imageMeta(uint8arr);
2434
- return this._metadata;
2461
+ for (const node of nodes) {
2462
+ const range = ranges[node.uid];
2463
+ const at = range.maxCol ?? range.minCol;
2464
+ if (cols[at]) cols[at].push(node);
2465
+ else cols[at] = [node];
2435
2466
  }
2436
- get hash() {
2437
- if (this._hash != null) return this._hash;
2438
- const buff = readFileSync(this.absPath);
2439
- this._hash = hashArrayBuffer(new Uint8Array(buff));
2440
- return this._hash;
2467
+ const HSEP = p?.node_hsep ?? 100;
2468
+ const VSEP = p?.node_vsep ?? 40;
2469
+ let colX = 0;
2470
+ let maxY = 0;
2471
+ for (const col of cols) {
2472
+ if (col == null) continue;
2473
+ let colWidth = 0;
2474
+ let currNodeY = 32;
2475
+ const nodesSorted = col.toSorted((a, b) => b.height - a.height);
2476
+ for (const node of nodesSorted) {
2477
+ colWidth = Math.max(colWidth, node.width);
2478
+ node.x = colX;
2479
+ node.y = currNodeY;
2480
+ currNodeY += node.height + VSEP;
2481
+ }
2482
+ maxY = Math.max(maxY, currNodeY);
2483
+ colX += colWidth + HSEP;
2441
2484
  }
2442
- };
2485
+ this.height = maxY;
2486
+ this.width = colX;
2487
+ return this;
2488
+ }
2443
2489
  //#endregion
2444
- //#region src/runner/ComfyExecution.ts
2445
- var ComfyExecution = class {
2446
- get host() {
2447
- return this.workflow.host;
2448
- }
2449
- constructor(workflow, data, init = {}) {
2450
- this.workflow = workflow;
2490
+ //#region src/runner/ComfyWorkflow.ts
2491
+ const asComfyWorkflowID = (x) => x;
2492
+ var ComfyWorkflow = class {
2493
+ constructor(host, data) {
2494
+ this.host = host;
2451
2495
  this.data = data;
2452
- this.saveFormat = null;
2453
- this.snapshot = null;
2454
- this.onProgress = null;
2455
- this.logProgress = false;
2456
- this.startedAt = Date.now();
2457
- this._lastLoggedLine = "";
2458
- this.done = new Promise((resolve) => {
2459
- this._resolve = resolve;
2460
- });
2461
- this.onPromptRelatedMessage = (msg) => {
2462
- const graph = this.workflow;
2463
- if (msg.type === "execution_start") return;
2464
- else if (msg.type === "execution_cached") graph.onExecutionCached(msg);
2465
- else if (msg.type === "executing") this.onExecuting(msg);
2466
- else if (msg.type === "progress") graph.onProgress(msg);
2467
- else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2468
- else if (msg.type === "execution_error") return void this.onError(msg);
2469
- else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2470
- else {
2471
- console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
2472
- return exhaust(msg);
2473
- }
2474
- this.emitProgress();
2496
+ this.nodes = [];
2497
+ this.registerNode = (node) => {
2498
+ if (this.data.apiJson == null) throw new Error("graph not hydrated");
2499
+ this.data.apiJson[node.uid] = node.json;
2500
+ this.data.metadata[node.uid] = node.meta;
2501
+ this.nodesIndex.set(node.uid, node);
2502
+ this.nodes.push(node);
2475
2503
  };
2476
- this.onExecuting = (msg) => {
2477
- this.workflow.onExecuting(msg);
2504
+ this.setMetadata = (nodeID, meta) => {
2505
+ this.data.metadata[nodeID] = meta;
2478
2506
  };
2479
- this.onExecutionSuccess = async (_msg) => {
2480
- await Promise.all(this.pendingPromises);
2481
- return this._finish({ status: "Success" });
2507
+ this.getMetadata = (nodeID) => {
2508
+ return this.data.metadata[nodeID] ?? null;
2482
2509
  };
2483
- this.onError = async (msg) => {
2484
- console.error("❌ Execution error:");
2485
- console.error(msg);
2486
- return this._finish({
2487
- status: "Failure",
2488
- error: msg
2510
+ this.problems = [];
2511
+ this.recordProblem = (title, data) => {
2512
+ this.problems.push({
2513
+ title,
2514
+ data
2489
2515
  });
2490
2516
  };
2491
- this.onExecuted = (msg) => {
2492
- const promptNodeID = msg.data.node;
2493
- const images = msg.data.output?.images;
2494
- if (images) for (const img of images) this.pendingPromises.push(this.retrieveImage(img, promptNodeID).catch((e) => {
2495
- console.error(`🔴 failed to retrieve ${img.filename}:`, e);
2496
- this.imageErrors.push({
2497
- image: img,
2498
- error: e
2499
- });
2500
- }));
2517
+ this._builder = null;
2518
+ this.onUpdate = (prev, next) => {
2519
+ if (prev != null) {
2520
+ this.nodes = [];
2521
+ this.nodesIndex.clear();
2522
+ this.currentExecutingNode = null;
2523
+ }
2524
+ for (const [uid, node] of Object.entries(bang(next.apiJson))) {
2525
+ const meta = next.metadata?.[uid];
2526
+ new ComfyNode(this, uid, node, meta);
2527
+ }
2501
2528
  };
2502
- this.pendingPromises = [];
2503
- this.imageErrors = [];
2504
- this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
2505
- const promptNode = this.workflow.data.apiJson?.[promptNodeID];
2506
- const promptMeta = this.workflow.data.metadata?.[promptNodeID];
2507
- if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
2508
- const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
2509
- const sf = this.saveFormat;
2510
- let absPath = comfyts.resolveFromOutput(join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
2511
- if (sf?.format && sf.format !== "raw") {
2512
- const extension = sf.format.split("/")[1];
2513
- absPath += "." + extension;
2529
+ this.nodesIndex = /* @__PURE__ */ new Map();
2530
+ this.toMermaid = (DIR = "LR") => {
2531
+ return [
2532
+ `graph ${DIR}`,
2533
+ this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join("\n"),
2534
+ this.nodes.map((n) => n._incomingEdges().map((i) => {
2535
+ const from = this.nodesIndex.get(i.from);
2536
+ return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${n.$schema.nodeKey}]`;
2537
+ }).join("\n")).join("\n")
2538
+ ].join("\n");
2539
+ };
2540
+ this.toWorkflowJson = async (p = {}) => {
2541
+ if (p.layout !== false) this.autoLayout();
2542
+ return convertFlowToLiteGraphJSON(this);
2543
+ };
2544
+ this.toApiJson = (ns = "use_stringified_numbers_only") => {
2545
+ const json = {};
2546
+ const keyOf = (uid) => ns === "use_stringified_numbers_only" ? uid : this.nodesIndex.get(uid)?.uidPrefixed ?? uid;
2547
+ for (const node of this.nodes) {
2548
+ if (node.disabled) continue;
2549
+ const key = ns === "use_stringified_numbers_only" ? node.uid : node.uidPrefixed;
2550
+ const inputs = {};
2551
+ 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;
2552
+ json[key] = {
2553
+ class_type: node.json.class_type,
2554
+ inputs
2555
+ };
2514
2556
  }
2515
- mkdirSync(dirname(absPath), { recursive: true });
2516
- let img;
2517
- if (sf && sf.format !== "raw") {
2518
- const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2519
- let textChunk = {};
2520
- try {
2521
- const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
2522
- if (res.success) textChunk = res.value;
2523
- } catch {}
2524
- const format = (() => {
2525
- if (sf.format === "image/jpeg") return "jpeg";
2526
- if (sf.format === "image/png") return "png";
2527
- if (sf.format === "image/webp") return "webp";
2528
- return "png";
2529
- })();
2530
- await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
2531
- img = new MediaImage({
2532
- path: asAbsolutePath(absPath),
2533
- execution: this,
2534
- promptNodeID,
2535
- comfyUIInfos: {
2536
- comfyImageInfo,
2537
- comfyHostHttpURL: this.host.getServerHostHTTP()
2538
- }
2539
- });
2540
- } else {
2541
- const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2542
- const uint8arr = new Uint8Array(buff);
2543
- writeFileSync(absPath, uint8arr);
2544
- img = new MediaImage({
2545
- path: asAbsolutePath(absPath),
2546
- buffer: uint8arr,
2547
- execution: this,
2548
- promptNodeID,
2549
- comfyUIInfos: {
2550
- comfyImageInfo,
2551
- comfyHostHttpURL: this.host.getServerHostHTTP()
2552
- }
2553
- });
2557
+ return json;
2558
+ };
2559
+ this.currentExecutingNode = null;
2560
+ this.onProgress = (msg) => {
2561
+ if (this.currentExecutingNode == null) return void console.log("❌ no current executing node", msg);
2562
+ this.currentExecutingNode.progress = msg.data;
2563
+ this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1);
2564
+ };
2565
+ this.getTargetWorkflowFilePath = () => {
2566
+ return join(this.cacheFolderPath, "workflow.json");
2567
+ };
2568
+ this.getTargetPromptFilePath = () => {
2569
+ return join(this.cacheFolderPath, "prompt.json");
2570
+ };
2571
+ this.done = false;
2572
+ this.onExecuting = (msg) => {
2573
+ if (this.currentExecutingNode) this.currentExecutingNode.status = "done";
2574
+ if (msg.data.node == null) {
2575
+ this.currentExecutingNode = null;
2576
+ this.done = true;
2577
+ return;
2554
2578
  }
2555
- if (promptMeta?.tag) img.tags.push(promptMeta.tag);
2556
- if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
2557
- this.images.push(img);
2579
+ this.done = false;
2580
+ const node = this.getNodeOrCrash(msg.data.node);
2581
+ this.currentExecutingNode = node;
2582
+ node.status = "executing";
2583
+ node.updatedAt = Date.now();
2558
2584
  };
2559
- this.images = [];
2560
- this.alreadyDone = false;
2561
- this._finish = async (p) => {
2562
- if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`);
2563
- this.alreadyDone = true;
2564
- this.update({
2565
- ...p,
2566
- executed: true
2585
+ this.onExecutionCached = (msg) => {
2586
+ for (const x of msg.data.nodes) {
2587
+ const node = this.getNodeOrCrash(x);
2588
+ node.status = "cached";
2589
+ }
2590
+ };
2591
+ this._uidNumber = 0;
2592
+ this.getNodeOrCrash = (nodeID) => {
2593
+ const node = this.nodesIndex.get(nodeID);
2594
+ if (node == null) throw new Error("Node not found:" + nodeID);
2595
+ return node;
2596
+ };
2597
+ this.getNode = (nodeID) => {
2598
+ return this.nodesIndex.get(nodeID);
2599
+ };
2600
+ this.width = 100;
2601
+ this.height = 100;
2602
+ this.autoLayout = comfyWorkflowAutoLayout.bind(this);
2603
+ this.run = async (p = {}) => {
2604
+ const execution = await this.start(p);
2605
+ await execution.done;
2606
+ return execution;
2607
+ };
2608
+ this.start = async (p = {}) => {
2609
+ this.resetRunState();
2610
+ const snapshot = {
2611
+ apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
2612
+ workflowJson: await this.toWorkflowJson()
2613
+ };
2614
+ const out = {
2615
+ client_id: this.host.comfySessionId,
2616
+ prompt: snapshot.apiJson,
2617
+ extra_data: { extra_pnginfo: {
2618
+ workflow: snapshot.workflowJson,
2619
+ comfy_ts_workflow_id: this.id,
2620
+ comfy_ts_version: comfyts.version
2621
+ } }
2622
+ };
2623
+ const res = await this.host.fetch("/prompt", {
2624
+ method: "POST",
2625
+ headers: { "Content-Type": "application/json" },
2626
+ body: JSON.stringify(out)
2627
+ });
2628
+ const promptInfo = softValidate(PromptInfo_ark, await res.json());
2629
+ if (res.status !== 200) throw new InvalidPromptError("ComfyUI /prompt request failed", snapshot, promptInfo);
2630
+ return new ComfyExecution(this, {
2631
+ id: promptInfo.prompt_id,
2632
+ executed: false,
2633
+ graphID: this.id
2634
+ }, {
2635
+ snapshot,
2636
+ saveFormat: p.saveFormat,
2637
+ onProgress: p.onProgress,
2638
+ logProgress: p.log ?? false
2567
2639
  });
2568
- await Promise.all(this.pendingPromises);
2569
- this.host.executions.delete(this.data.id);
2570
- this.host._pendingMsgs.delete(this.data.id);
2571
- this.finishProgressLine();
2572
- this._resolve(this);
2573
2640
  };
2574
- this.snapshot = init.snapshot ?? null;
2575
- this.saveFormat = init.saveFormat ?? null;
2576
- this.onProgress = init.onProgress ?? null;
2577
- this.logProgress = init.logProgress ?? false;
2578
- this.host.executions.set(data.id, this);
2579
- this.onCreate();
2641
+ this.id = data.id ?? nanoid(8);
2642
+ this.apiJson = data.apiJson ?? {};
2643
+ data.apiJson = this.apiJson;
2644
+ this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`);
2580
2645
  }
2581
- get progress() {
2582
- return {
2583
- ...this.progressGlobal,
2584
- promptId: this.data.id,
2585
- nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,
2586
- elapsedMs: Date.now() - this.startedAt
2587
- };
2646
+ /** number of node in the graph */
2647
+ get size() {
2648
+ return this.nodes.length;
2588
2649
  }
2589
- emitProgress() {
2590
- const p = this.progress;
2591
- this.onProgress?.(p);
2592
- if (!this.logProgress) return;
2593
- const width = 12;
2594
- const filled = Math.round(p.percent / 100 * width);
2595
- const bar = "█".repeat(filled) + "░".repeat(width - filled);
2596
- const node = p.nodeName ? ` · ${p.nodeName}` : "";
2597
- const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2598
- if (line === this._lastLoggedLine) return;
2599
- this._lastLoggedLine = line;
2600
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2601
- else console.log(line);
2650
+ get builder() {
2651
+ if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this);
2652
+ return this._builder;
2602
2653
  }
2603
- finishProgressLine() {
2604
- if (!this.logProgress) return;
2605
- const p = this.progress;
2606
- const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2607
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2608
- else console.log(line);
2654
+ /** base (untyped) view of the same builder, for generic library code */
2655
+ get builderBase() {
2656
+ if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this);
2657
+ return this._builder;
2609
2658
  }
2610
- log(...args) {
2611
- console.log(`[ComfyExecution#${this.data.id}]`, ...args);
2659
+ /** proxy to this.db.schema */
2660
+ get schema() {
2661
+ return this.host.schema;
2612
2662
  }
2613
- onCreate() {
2614
- const data = this.data;
2615
- const pending = this.host._pendingMsgs.get(data.id);
2616
- if (pending == null) return;
2617
- this.log(`🟢 onCreate: ${pending.length} pending messages`);
2618
- this.host._pendingMsgs.delete(data.id);
2619
- for (const msg of pending) this.onPromptRelatedMessage(msg);
2663
+ /** nodes that are still pending execution */
2664
+ get pendingNodes() {
2665
+ return this.nodes.filter((n) => n.status == null || n.status === "waiting");
2666
+ }
2667
+ get nodesByUpdatedAt() {
2668
+ return this.nodes.filter((n) => n.status != null && n.status !== "waiting").sort((a, b) => b.updatedAt - a.updatedAt);
2669
+ }
2670
+ get progressCurrentNode() {
2671
+ return this.currentExecutingNode?.progressReport;
2620
2672
  }
2621
2673
  get progressGlobal() {
2622
- if (this.data.status === "Success") return {
2623
- countDone: 1,
2624
- countTotal: 1,
2625
- isDone: true,
2626
- percent: 100
2674
+ const totalNode = this.nodes.length;
2675
+ const doneNodes = this.nodes.filter((n) => n.status === "done" || n.status === "cached").length;
2676
+ const bonus = this.currentExecutingNode?.progressRatio ?? 0;
2677
+ const score = (doneNodes + bonus) / totalNode;
2678
+ return {
2679
+ percent: this.done ? 100 : score * 100,
2680
+ isDone: this.done,
2681
+ countDone: doneNodes + bonus,
2682
+ countTotal: totalNode
2627
2683
  };
2628
- return this.workflow.progressGlobal;
2629
2684
  }
2630
- get status() {
2631
- return this.data.status ?? "New";
2685
+ get cacheFolderPath() {
2686
+ return comfyts.resolveFromOutput(`workflows/${this.id}`);
2632
2687
  }
2633
- update(data) {
2634
- Object.assign(this.data, data);
2688
+ /** reset per-run node state so the same workflow can run again cleanly */
2689
+ resetRunState() {
2690
+ this.done = false;
2691
+ this.currentExecutingNode = null;
2692
+ for (const node of this.nodes) {
2693
+ node.status = null;
2694
+ node.progress = null;
2695
+ node.progressRatio = 0;
2696
+ }
2635
2697
  }
2636
2698
  };
2637
2699
  //#endregion
2638
- //#region src/utils/deepCopyNaive.ts
2639
- const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
2700
+ //#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
2701
+ /** having a bunch of sensible default will help slightly */
2702
+ function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
2703
+ if (enumName === "KSampler.sampler_name") return "E_SamplerName";
2704
+ if (enumName === "KSampler.scheduler") return "E_SchedulerName";
2705
+ if (enumName === "CheckpointLoaderSimple.ckpt_name") return "E_CkptName";
2706
+ if (enumName === "VAELoader.vae_name") return "E_VaeName";
2707
+ if (enumName === "LoraLoader.lora_name") return "E_LoraName";
2708
+ if (enumName === "LatentUpscale.upscale_method") return "E_LatentUpscaleMethod";
2709
+ if (enumName === "ImageScale.upscale_method") return "E_ImageUpscaleMethod";
2710
+ if (enumName === "LoadImage.image") return "E_Image";
2711
+ if (enumName === "LoadImageMask.channel") return "E_Channel";
2712
+ if (enumName === "KSamplerAdvanced.add_noise") return "E_EnableOrDisable";
2713
+ if (enumName === "LatentRotate.rotation") return "E_Rotation";
2714
+ if (enumName === "LatentFlip.flip_method") return "E_FlipMethod";
2715
+ if (enumName === "CLIPLoader.type") return "E_ClipType";
2716
+ if (enumName === "UNETLoader.weight_dtype") return "E_WeightDType";
2717
+ if (enumName === "DualCLIPLoader.type") return "E_DualClipType";
2718
+ if (enumName === "CheckpointLoader.config_name") return "E_CkptConfigName";
2719
+ if (enumName === "civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name") return "E_CivitAICkptName";
2720
+ if (enumName === "Impact-Pack.SAMDetectorCombined.detection_hint") return "E_ImpactDetectionHint";
2721
+ if (hashContent === "false|true") return "E_TrueOrFalse";
2722
+ if (hashContent === "CPU|GPU") return "E_CpuOrGpu";
2723
+ return "E_" + hash;
2724
+ }
2640
2725
  //#endregion
2641
- //#region src/utils/ansi.ts
2642
- const codes = {
2643
- bold: [1, 22],
2644
- underline: [4, 24],
2645
- red: [31, 39],
2646
- green: [32, 39],
2647
- yellow: [33, 39],
2648
- blue: [34, 39],
2649
- greenBright: [92, 39]
2726
+ //#region src/sdk-generator/_pythonModuleToNamespace.ts
2727
+ function pythonModuleToPrefix(pythonModule) {
2728
+ if (pythonModule === "nodes") return "";
2729
+ if (pythonModule.startsWith("comfy_extras.")) return "";
2730
+ if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
2731
+ 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, "") + ".";
2732
+ console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
2733
+ return `${pythonModule}.`;
2734
+ }
2735
+ //#endregion
2736
+ //#region src/sdk-generator/_toQualifiedNodeKey.ts
2737
+ const toQualifiedNodeKey = (pythonModule, nameInComfy) => {
2738
+ return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`;
2739
+ };
2740
+ //#endregion
2741
+ //#region src/utils/CodeBuffer.ts
2742
+ /** this class is used to buffer text and then write it to a file */
2743
+ var CodeBuffer = class {
2744
+ constructor(_indent = 0, lines = []) {
2745
+ this._indent = _indent;
2746
+ this.tab = " ";
2747
+ this.content = "";
2748
+ this.newLine = () => this.content += "\n";
2749
+ this.line = (...txts) => this.writeLine(txts.join(""));
2750
+ this.append = (str) => this.content += str;
2751
+ this.writeLine = (txt) => {
2752
+ this.content += txt.split("\n").map((line) => repeatStr(this._indent, this.tab) + line).join("\n") + "\n";
2753
+ return this;
2754
+ };
2755
+ this.w = (txt, opts = { if: true }) => {
2756
+ if (opts.if) this.writeLine(txt);
2757
+ };
2758
+ this.indent = () => this._indent++;
2759
+ this.deindent = () => this._indent--;
2760
+ this.indented = (fn) => {
2761
+ this._indent++;
2762
+ fn();
2763
+ this._indent--;
2764
+ };
2765
+ this.bar = (text) => this.w(renderBar(text, "// "));
2766
+ for (const line of lines) this.writeLine(line);
2767
+ }
2768
+ };
2769
+ const repeatStr = (x, str) => {
2770
+ let out = "";
2771
+ for (let i = 0; i < x; i++) out += str;
2772
+ return out;
2773
+ };
2774
+ const renderBar = (text, prefix = "") => {
2775
+ const ___bar___ = "=============================================================================";
2776
+ return `${prefix}|${___bar___}|\n${prefix}| ${text} ${repeatStr(77 - text.length - 4, " ")} |\n${prefix}|${___bar___}|`;
2777
+ };
2778
+ //#endregion
2779
+ //#region src/utils/escapeJSKey.ts
2780
+ const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
2781
+ const isValidJSKey = (s) => {
2782
+ return regex.test(s);
2783
+ };
2784
+ const escapeJSKey = (s) => {
2785
+ if (typeof s !== "string") return "string";
2786
+ if (!isValidJSKey(s)) return `"${s}"`;
2787
+ return s;
2788
+ };
2789
+ //#endregion
2790
+ //#region src/sdk-generator/ComfyNodeSchema.ts
2791
+ var ComfyNodeSchema = class {
2792
+ get singleOutputs() {
2793
+ if (this._singleOutputs != null) return this._singleOutputs;
2794
+ const x = {};
2795
+ for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1;
2796
+ this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1);
2797
+ return this._singleOutputs;
2798
+ }
2799
+ constructor(raw, nameInComfy, nodeKey, category, inputs, outputs, pythonModule) {
2800
+ this.raw = raw;
2801
+ this.nameInComfy = nameInComfy;
2802
+ this.nodeKey = nodeKey;
2803
+ this.category = category;
2804
+ this.inputs = inputs;
2805
+ this.outputs = outputs;
2806
+ this.pythonModule = pythonModule;
2807
+ this._singleOutputs = null;
2808
+ this.category = this.category.replaceAll("/", "_");
2809
+ }
2810
+ codegenUI() {
2811
+ const b = new CodeBuffer();
2812
+ const p = b.w;
2813
+ p(` ${escapeJSKey(this.nodeKey)}: {`);
2814
+ this.inputs.forEach((i, _ix) => {
2815
+ if (i.isPrimitive) {
2816
+ const tsType = ComfyPrimitiveMapping[i.typeName];
2817
+ if (tsType == null) return console.log(`[🔶] invariant violation`);
2818
+ p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`);
2819
+ } else if (i.isEnum) p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`);
2820
+ else p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`);
2821
+ });
2822
+ p(` }`);
2823
+ return b.content;
2824
+ }
2825
+ renderOpts(opts) {
2826
+ if (opts == null) return null;
2827
+ if (typeof opts === "string") return null;
2828
+ let out = "/**";
2829
+ if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`;
2830
+ if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`;
2831
+ if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`;
2832
+ if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`;
2833
+ out += " */";
2834
+ return out;
2835
+ }
2650
2836
  };
2651
- function styler(open = "", close = "") {
2652
- const fn = (s) => open + s + close;
2653
- return new Proxy(fn, { get(_target, prop) {
2654
- const c = codes[prop];
2655
- if (c == null) throw new Error(`unknown ansi style: ${prop}`);
2656
- return styler(`${open}\x1b[${c[0]}m`, `\x1b[${c[1]}m${close}`);
2657
- } });
2658
- }
2659
- const ansi = styler();
2660
- const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g;
2661
- function stripAnsi(s) {
2662
- return s.replace(ANSI_RE, "");
2663
- }
2664
- //#endregion
2665
- //#region src/utils/printArkResultInConsole.ts
2666
- const MAX_PRINTED_ERRORS = 10;
2667
- function printArkResultInConsole(res) {
2668
- if (isQuiet()) return;
2669
- console.log(ansi.red(" ❌ Ark validation failed:"));
2670
- for (const error of res.slice(0, MAX_PRINTED_ERRORS)) console.log(ansi.red(` - ${error.path.join(".")} : ${error.message}`));
2671
- if (res.length > MAX_PRINTED_ERRORS) console.log(ansi.red(` … ${res.length - MAX_PRINTED_ERRORS} more (${res.length} total)`));
2672
- }
2673
- //#endregion
2674
- //#region src/utils/softValidate.ts
2675
- const softValidate = (schema, stuff) => {
2676
- const res = schema(stuff);
2677
- if (res instanceof type.errors) printArkResultInConsole(res);
2678
- return stuff;
2837
+ const wrapQuote = (s) => {
2838
+ if (s.includes("'")) return `"${s}"`;
2839
+ return `'${s}'`;
2679
2840
  };
2680
2841
  //#endregion
2681
- //#region src/utils/toposort.ts
2682
- function toposort(nodes, edges) {
2683
- return toposortAlgo(nodes, edges);
2684
- }
2685
- function toposortAlgo(nodes, edges) {
2686
- let cursor = nodes.length;
2687
- const sorted = Array.from({ length: cursor });
2688
- const visited = {};
2689
- let k = cursor;
2690
- while (k--) if (!visited[k]) visit(BONG(nodes[k]), k, []);
2691
- return sorted;
2692
- function visit(node, ix, predecessors) {
2693
- let i = ix;
2694
- if (predecessors.indexOf(node) >= 0) {
2695
- console.log(predecessors, node);
2696
- throw new Error("Cyclic dependency: " + JSON.stringify(node));
2697
- }
2698
- 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));
2699
- if (visited[i]) return;
2700
- visited[i] = true;
2701
- const outgoing = edges.filter((edge) => edge[0] === node);
2702
- i = outgoing.length;
2703
- if (i) {
2704
- const preds = predecessors.concat(node);
2705
- do {
2706
- const child = BONG(outgoing[--i])[1];
2707
- visit(child, nodes.indexOf(child), preds);
2708
- } while (i);
2709
- }
2710
- sorted[--cursor] = node;
2711
- }
2712
- }
2713
- function BONG(x) {
2714
- if (x == null) throw new Error("BONG");
2715
- return x;
2842
+ //#region src/sdk-generator/comfyui-sdk-codegen.ts
2843
+ /**
2844
+ * convert a host id to the namespace name it gets inside the global `Comfy` namespace
2845
+ * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
2846
+ */
2847
+ function hostIdToNamespace(hostId) {
2848
+ const ns = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
2849
+ if (ns.length === 0) throw new Error(`cannot derive a namespace from host id "${hostId}"`);
2850
+ return /^[0-9]/.test(ns) ? `Host${ns}` : ns;
2716
2851
  }
2717
- //#endregion
2718
- //#region src/runner/ComfyWorkflowLayout.ts
2719
2852
  /**
2720
- * compute autolayout
2853
+ * emit the typed SDK for one host:
2721
2854
  *
2722
- * 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive
2723
- * libraries were pretty bad; ended up writing my own simple algorithm, and I'm
2724
- * happy with it. Feel free to improve it, but I think it works well enough.
2725
- * I will accept PRs for new layout algorithms if they don't have massive dependencies.
2726
- **/
2727
- function comfyWorkflowAutoLayout(p) {
2728
- const nodeIds = toposort(this.nodes.map((n) => n.uid), this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid])));
2729
- const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`));
2730
- const cols = Array.from({ length: nodeIds.length });
2731
- const ranges = {};
2732
- for (const node of nodes) {
2733
- const parentCols = node.parents.map((p) => ranges[p.uid].minCol);
2734
- const range = {
2735
- node,
2736
- minCol: Math.max(...parentCols, -1) + 1
2737
- };
2738
- ranges[node.uid] = range;
2855
+ * declare global {
2856
+ * namespace Comfy {
2857
+ * namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }
2858
+ * interface Hosts { '<host-id>': <HostNs>.Sdk }
2859
+ * }
2860
+ * }
2861
+ */
2862
+ function codegenSDK(opts) {
2863
+ const ns = hostIdToNamespace(opts.hostId);
2864
+ const packageName = opts.packageName ?? "comfy-ts";
2865
+ const b = new CodeBuffer();
2866
+ const p = b.w;
2867
+ p(`/** generated by comfy-ts for host "${opts.hostId}" — do not edit */`);
2868
+ p(``);
2869
+ p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`);
2870
+ p(``);
2871
+ p(`declare global {`);
2872
+ b.indent();
2873
+ p(`namespace Comfy {`);
2874
+ b.indent();
2875
+ p(`namespace ${ns} {`);
2876
+ b.indent();
2877
+ p(`// #region PythonModules`);
2878
+ p(`/** list of all python modules installed on this host */`);
2879
+ p(`export type PythonModules =`);
2880
+ b.indent();
2881
+ const pythonModulesArr = Array.from(this.pythonModules.entries()).toSorted((a, b) => a[0].localeCompare(b[0]));
2882
+ for (const [k, v] of pythonModulesArr) {
2883
+ p(`/**`);
2884
+ p(`* Nodes: ${v.join(", ")}`);
2885
+ p(`*/`);
2886
+ p(`| ${wrapQuote(k)}`);
2739
2887
  }
2740
- if (!p?.forceLeft === true) for (const node of nodes) {
2741
- const range = ranges[node.uid];
2742
- for (const p of node.parents) {
2743
- const parentRange = ranges[p.uid];
2744
- parentRange.maxCol = parentRange.maxCol != null ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1) : (range.maxCol ?? range.minCol) - 1;
2888
+ b.deindent();
2889
+ p(`// #endregion`);
2890
+ const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
2891
+ p(`interface IN {`);
2892
+ b.indent();
2893
+ for (const n of nodes) {
2894
+ p(`${escapeJSKey(n.nodeKey)}: {`);
2895
+ for (const i of n.inputs) {
2896
+ const kind = classifySchemaInput(i);
2897
+ if (kind.kind === "dynamic-container") {
2898
+ const instType = containerInstanceSlotType(i.opts);
2899
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
2900
+ const opt = ix >= kind.requiredCount ? "?" : "";
2901
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
2902
+ });
2903
+ continue;
2904
+ }
2905
+ const opts_ = typeof i.opts === "string" ? null : i.opts;
2906
+ let type = `Accepts[${JSON.stringify(i.typeName)}]`;
2907
+ const comboOptions = i.typeName === "COMBO" && Array.isArray(opts_?.options) ? opts_.options.filter((o) => typeof o === "string" || typeof o === "number" || typeof o === "boolean") : [];
2908
+ if (comboOptions.length > 0) type = `${comboOptions.map((o) => JSON.stringify(o)).join(" | ")} | ${type}`;
2909
+ else if (opts_ && !i.isPrimitive && !i.isEnum) {
2910
+ if (typeof opts_.default === "string" || opts_.placeholder != null || opts_.multiline != null) type = `string | ${type}`;
2911
+ else if (typeof opts_.default === "number") type = `number | ${type}`;
2912
+ else if (typeof opts_.default === "boolean") type = `boolean | ${type}`;
2913
+ }
2914
+ if (opts_) {
2915
+ const rendered = n.renderOpts(opts_);
2916
+ if (rendered) p(` ${rendered}`);
2917
+ }
2918
+ const canBeOmmited = opts_?.default !== void 0 || !i.required;
2919
+ p(` ${i.nameInComfyEscaped}${canBeOmmited ? "?" : ""}: ${type}`);
2745
2920
  }
2921
+ p(`},`);
2746
2922
  }
2747
- for (const node of nodes) {
2748
- const range = ranges[node.uid];
2749
- const at = range.maxCol ?? range.minCol;
2750
- if (cols[at]) cols[at].push(node);
2751
- else cols[at] = [node];
2923
+ b.deindent();
2924
+ p("}");
2925
+ p("");
2926
+ p(`interface OUT {`);
2927
+ b.indent();
2928
+ for (const n of nodes) {
2929
+ p(`${escapeJSKey(n.nodeKey)}: {`);
2930
+ n.outputs.forEach((i, ix) => {
2931
+ p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`);
2932
+ });
2933
+ p(`}`);
2752
2934
  }
2753
- const HSEP = p?.node_hsep ?? 100;
2754
- const VSEP = p?.node_vsep ?? 40;
2755
- let colX = 0;
2756
- let maxY = 0;
2757
- for (const col of cols) {
2758
- if (col == null) continue;
2759
- let colWidth = 0;
2760
- let currNodeY = 32;
2761
- const nodesSorted = col.toSorted((a, b) => b.height - a.height);
2762
- for (const node of nodesSorted) {
2763
- colWidth = Math.max(colWidth, node.width);
2764
- node.x = colX;
2765
- node.y = currNodeY;
2766
- currNodeY += node.height + VSEP;
2767
- }
2768
- maxY = Math.max(maxY, currNodeY);
2769
- colX += colWidth + HSEP;
2935
+ b.deindent();
2936
+ p("}");
2937
+ p(`interface Node {`);
2938
+ for (const n of nodes) {
2939
+ p(` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`);
2940
+ for (const hassingle of n.singleOutputs) p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`);
2941
+ p(` }`);
2770
2942
  }
2771
- this.height = maxY;
2772
- this.width = colX;
2773
- return this;
2943
+ p("}");
2944
+ p(`interface Builder {`);
2945
+ for (const n of nodes) {
2946
+ const baseDescription = `displayName="${n.raw.display_name}" category="${n.category}" name="${n.nameInComfy}" output=[${n.outputs.map((o) => o.outKey).join(", ")}]`;
2947
+ if (n.raw.description) {
2948
+ p(` /**`);
2949
+ p(n.raw.description.split("\n").map((i) => ` * ${i}`).join("\n"));
2950
+ p(` * ${baseDescription}`);
2951
+ p(` **/`);
2952
+ } else p(` /** ${baseDescription} */`);
2953
+ p(` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`);
2954
+ }
2955
+ p(`}`);
2956
+ p(`interface Slots {`);
2957
+ for (const e of this.knownUnionByHash.values()) {
2958
+ p(" // " + e.unionName);
2959
+ for (const alias of e.enumNames) p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`);
2960
+ }
2961
+ p(`}`);
2962
+ p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(" | ") || "\"\""}`);
2963
+ const slotTypes = [...this.knownSlotTypes.values()].map((comfyType) => ({
2964
+ comfyType,
2965
+ tsType: this.toTSType(comfyType),
2966
+ tsType2: this.toAcceptsType(comfyType)
2967
+ })).sort((a, b) => b.tsType.length - a.tsType.length);
2968
+ p("");
2969
+ p("interface Producer {");
2970
+ b.indent();
2971
+ for (const tp of slotTypes) {
2972
+ const allProducingNodes = this.nodesByProduction[tp.comfyType];
2973
+ if (allProducingNodes) p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(" | ")}>`);
2974
+ else p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`);
2975
+ }
2976
+ b.deindent();
2977
+ p("}");
2978
+ p(`interface Accepts {`);
2979
+ b.indent();
2980
+ p("// injected bottom type (broken/null input specs land here)");
2981
+ p(`INVALID_null: any`);
2982
+ p("");
2983
+ p("// named slot types: everything an input of that type accepts");
2984
+ for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
2985
+ p("");
2986
+ p("// enum unions: literal values or an output carrying one");
2987
+ for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
2988
+ b.deindent();
2989
+ p(`}\n`);
2990
+ p("interface Union {");
2991
+ for (const e of this.knownUnionByHash.values()) if (e.values.length > 0) {
2992
+ p(` // ${JSON.stringify(e.enumNames)}`);
2993
+ p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(" | ")}`);
2994
+ } else p(` ${e.unionName}: '🔴' // never`);
2995
+ p("}");
2996
+ p(`export interface HasSingle {`);
2997
+ for (const t of slotTypes) p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`);
2998
+ p(`}`);
2999
+ for (const t of this.enumsAppearingInOutput.values()) p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`);
3000
+ p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`);
3001
+ p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(" | ")}`);
3002
+ p(``);
3003
+ p(`/** everything above, packaged for the Comfy.Hosts registry */`);
3004
+ p(`interface Sdk {`);
3005
+ p(` IN: IN`);
3006
+ p(` OUT: OUT`);
3007
+ p(` Node: Node`);
3008
+ p(` Builder: Builder`);
3009
+ p(` Slots: Slots`);
3010
+ p(` Accepts: Accepts`);
3011
+ p(` Union: Union`);
3012
+ p(` Producer: Producer`);
3013
+ p(` Embeddings: Embeddings`);
3014
+ p(` Schemas: Schemas`);
3015
+ p(` NodeType: NodeType`);
3016
+ p(`}`);
3017
+ b.deindent();
3018
+ p(`}`);
3019
+ p(``);
3020
+ p(`interface Hosts {`);
3021
+ p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`);
3022
+ p(`}`);
3023
+ b.deindent();
3024
+ p("}");
3025
+ b.deindent();
3026
+ p("}");
3027
+ p(``);
3028
+ p(`export {}`);
3029
+ return b.content;
2774
3030
  }
2775
3031
  //#endregion
2776
- //#region src/runner/ComfyWorkflow.ts
2777
- const asComfyWorkflowID = (x) => x;
2778
- var ComfyWorkflow = class {
2779
- constructor(host, data) {
2780
- this.host = host;
3032
+ //#region src/sdk-generator/comfyui-types.ts
3033
+ const asComfyNodeSlotTypeName = (x) => x;
3034
+ const asComfyNodeSlotName = (x) => x;
3035
+ //#endregion
3036
+ //#region src/sdk-generator/ComfySchema.ts
3037
+ /**
3038
+ * ONE host's schema: the parsed view of its object_info.json + embeddings.
3039
+ * Owns union dedup (by sha1 of values), node indexing, and the per-host
3040
+ * sdk codegen (`codegenDTS`).
3041
+ */
3042
+ var ComfySchema = class {
3043
+ constructor(data) {
2781
3044
  this.data = data;
3045
+ this.codegenDTS = codegenSDK.bind(this);
3046
+ this.isInvalid = false;
3047
+ this.knownSlotTypes = /* @__PURE__ */ new Set();
3048
+ this.knownUnionBySlotName = /* @__PURE__ */ new Map();
3049
+ this.knownUnionByHash = /* @__PURE__ */ new Map();
3050
+ this.knownUnionByName = /* @__PURE__ */ new Map();
2782
3051
  this.nodes = [];
2783
- this.registerNode = (node) => {
2784
- if (this.data.apiJson == null) throw new Error("graph not hydrated");
2785
- this.data.apiJson[node.uid] = node.json;
2786
- this.data.metadata[node.uid] = node.meta;
2787
- this.nodesIndex.set(node.uid, node);
2788
- this.nodes.push(node);
2789
- };
2790
- this.setMetadata = (nodeID, meta) => {
2791
- this.data.metadata[nodeID] = meta;
2792
- };
2793
- this.getMetadata = (nodeID) => {
2794
- return this.data.metadata[nodeID] ?? null;
2795
- };
2796
- this.problems = [];
2797
- this.recordProblem = (title, data) => {
2798
- this.problems.push({
2799
- title,
2800
- data
2801
- });
2802
- };
2803
- this._builder = null;
2804
- this.onUpdate = (prev, next) => {
2805
- if (prev != null) {
2806
- this.nodes = [];
2807
- this.nodesIndex.clear();
2808
- this.currentExecutingNode = null;
2809
- }
2810
- for (const [uid, node] of Object.entries(bang(next.apiJson))) {
2811
- const meta = next.metadata?.[uid];
2812
- new ComfyNode(this, uid, node, meta);
2813
- }
2814
- };
2815
- this.nodesIndex = /* @__PURE__ */ new Map();
2816
- this.toMermaid = (DIR = "LR") => {
2817
- return [
2818
- `graph ${DIR}`,
2819
- this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join("\n"),
2820
- this.nodes.map((n) => n._incomingEdges().map((i) => {
2821
- const from = this.nodesIndex.get(i.from);
2822
- return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${n.$schema.nodeKey}]`;
2823
- }).join("\n")).join("\n")
2824
- ].join("\n");
2825
- };
2826
- this.toWorkflowJson = async (p = {}) => {
2827
- if (p.layout !== false) this.autoLayout();
2828
- return convertFlowToLiteGraphJSON(this);
2829
- };
2830
- this.toApiJson = (ns = "use_stringified_numbers_only") => {
2831
- const json = {};
2832
- const keyOf = (uid) => ns === "use_stringified_numbers_only" ? uid : this.nodesIndex.get(uid)?.uidPrefixed ?? uid;
2833
- for (const node of this.nodes) {
2834
- if (node.disabled) continue;
2835
- const key = ns === "use_stringified_numbers_only" ? node.uid : node.uidPrefixed;
2836
- const inputs = {};
2837
- 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;
2838
- json[key] = {
2839
- class_type: node.json.class_type,
2840
- inputs
3052
+ this.pythonModuleByNodeKey = /* @__PURE__ */ new Map();
3053
+ this.pythonModuleByNodeNameInComfy = /* @__PURE__ */ new Map();
3054
+ this.nodesByNameInComfy = {};
3055
+ this.nodesByKey = {};
3056
+ this.nodesByProduction = {};
3057
+ this.enumsAppearingInOutput = /* @__PURE__ */ new Set();
3058
+ this.pythonModules = /* @__PURE__ */ new Map();
3059
+ this.processSlot = (p) => {
3060
+ const enumValues = [];
3061
+ for (const enumValue of p.comfyUnionDef) if (typeof enumValue === "string") enumValues.push(enumValue);
3062
+ else if (typeof enumValue === "boolean") enumValues.push(enumValue);
3063
+ else if (typeof enumValue === "number") enumValues.push(enumValue);
3064
+ else enumValues.push(enumValue.content);
3065
+ const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
3066
+ const hash = sha1HexOfString(hashContent).slice(0, 8);
3067
+ let unionInfo = this.knownUnionByHash.get(hash);
3068
+ if (unionInfo == null) {
3069
+ const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
3070
+ unionInfo = {
3071
+ hash,
3072
+ unionName,
3073
+ values: enumValues,
3074
+ enumNames: []
2841
3075
  };
3076
+ this.knownUnionByHash.set(hash, unionInfo);
3077
+ this.knownUnionByName.set(unionName, unionInfo);
2842
3078
  }
2843
- return json;
2844
- };
2845
- this.currentExecutingNode = null;
2846
- this.onProgress = (msg) => {
2847
- if (this.currentExecutingNode == null) return void console.log("❌ no current executing node", msg);
2848
- this.currentExecutingNode.progress = msg.data;
2849
- this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1);
2850
- };
2851
- this.getTargetWorkflowFilePath = () => {
2852
- return join(this.cacheFolderPath, "workflow.json");
2853
- };
2854
- this.getTargetPromptFilePath = () => {
2855
- return join(this.cacheFolderPath, "prompt.json");
3079
+ unionInfo.enumNames.push(p.slotName);
3080
+ this.knownUnionBySlotName.set(p.slotName, unionInfo);
3081
+ return unionInfo;
2856
3082
  };
2857
- this.done = false;
2858
- this.onExecuting = (msg) => {
2859
- if (this.currentExecutingNode) this.currentExecutingNode.status = "done";
2860
- if (msg.data.node == null) {
2861
- this.currentExecutingNode = null;
2862
- this.done = true;
2863
- return;
2864
- }
2865
- this.done = false;
2866
- const node = this.getNodeOrCrash(msg.data.node);
2867
- this.currentExecutingNode = node;
2868
- node.status = "executing";
2869
- node.updatedAt = Date.now();
3083
+ this.RUN_BASIC_CHECKS = () => {
3084
+ const numNodesInSource = Object.keys(this.data.spec).length;
3085
+ const numNodesInSchema = this.nodes.length - 1;
3086
+ if (numNodesInSource !== numNodesInSchema) console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`);
2870
3087
  };
2871
- this.onExecutionCached = (msg) => {
2872
- for (const x of msg.data.nodes) {
2873
- const node = this.getNodeOrCrash(x);
2874
- node.status = "cached";
2875
- }
3088
+ this.getLoras = (filter) => {
3089
+ const all = this.stringValues("LoraLoader.lora_name");
3090
+ return filter == null ? all : all.filter((n) => filter.test(n));
2876
3091
  };
2877
- this._uidNumber = 0;
2878
- this.getNodeOrCrash = (nodeID) => {
2879
- const node = this.nodesIndex.get(nodeID);
2880
- if (node == null) throw new Error("Node not found:" + nodeID);
2881
- return node;
3092
+ this.getImages = () => {
3093
+ return this.stringValues("LoadImage.image");
2882
3094
  };
2883
- this.getNode = (nodeID) => {
2884
- return this.nodesIndex.get(nodeID);
3095
+ this.unsafely_addImageInSchemaWithoutReloading = (imgName) => {
3096
+ const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName("LoadImage.image"));
3097
+ if (enumInfo == null) throw new Error(`LoadImage.image not found`);
3098
+ enumInfo.values.push(imgName);
2885
3099
  };
2886
- this.width = 100;
2887
- this.height = 100;
2888
- this.autoLayout = comfyWorkflowAutoLayout.bind(this);
2889
- this.run = async (p = {}) => {
2890
- const execution = await this.start(p);
2891
- await execution.done;
2892
- return execution;
3100
+ this.getCheckpoints = () => {
3101
+ return this.stringValues("CheckpointLoaderSimple.ckpt_name");
2893
3102
  };
2894
- this.start = async (p = {}) => {
2895
- this.resetRunState();
2896
- const snapshot = {
2897
- apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
2898
- workflowJson: await this.toWorkflowJson()
2899
- };
2900
- const out = {
2901
- client_id: this.host.comfySessionId,
2902
- prompt: snapshot.apiJson,
2903
- extra_data: { extra_pnginfo: {
2904
- workflow: snapshot.workflowJson,
2905
- comfy_ts_workflow_id: this.id,
2906
- comfy_ts_version: comfyts.version
2907
- } }
2908
- };
2909
- const res = await this.host.fetch("/prompt", {
2910
- method: "POST",
2911
- headers: { "Content-Type": "application/json" },
2912
- body: JSON.stringify(out)
2913
- });
2914
- const promptInfo = softValidate(PromptInfo_ark, await res.json());
2915
- if (res.status !== 200) throw new InvalidPromptError("ComfyUI /prompt request failed", snapshot, promptInfo);
2916
- return new ComfyExecution(this, {
2917
- id: promptInfo.prompt_id,
2918
- executed: false,
2919
- graphID: this.id
2920
- }, {
2921
- snapshot,
2922
- saveFormat: p.saveFormat,
2923
- onProgress: p.onProgress,
2924
- logProgress: p.log ?? false
2925
- });
3103
+ this.parse();
3104
+ }
3105
+ update(data) {
3106
+ const prev = {
3107
+ spec: this.data.spec,
3108
+ embeddings: this.data.embeddings
2926
3109
  };
2927
- this.id = data.id ?? nanoid(8);
2928
- this.apiJson = data.apiJson ?? {};
2929
- data.apiJson = this.apiJson;
2930
- this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`);
3110
+ Object.assign(this.data, data);
3111
+ try {
3112
+ this.parse();
3113
+ this.isInvalid = false;
3114
+ } catch (error) {
3115
+ console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error);
3116
+ this.data = prev;
3117
+ try {
3118
+ this.parse();
3119
+ } catch {}
3120
+ this.isInvalid = true;
3121
+ }
2931
3122
  }
2932
- /** number of node in the graph */
3123
+ /** number of nodes in the current schema (quick way to check your instance infos) */
2933
3124
  get size() {
2934
- return this.nodes.length;
3125
+ return Object.keys(this.data.spec).length;
2935
3126
  }
2936
- get builder() {
2937
- if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this);
2938
- return this._builder;
3127
+ parse() {
3128
+ this.knownSlotTypes.clear();
3129
+ this.knownUnionBySlotName.clear();
3130
+ this.knownUnionByHash.clear();
3131
+ this.knownUnionByName.clear();
3132
+ this.nodes = [];
3133
+ this.pythonModuleByNodeKey.clear();
3134
+ this.pythonModuleByNodeNameInComfy.clear();
3135
+ this.nodesByNameInComfy = {};
3136
+ this.nodesByKey = {};
3137
+ this.nodesByProduction = {};
3138
+ this.enumsAppearingInOutput.clear();
3139
+ this.pythonModules.clear();
3140
+ if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0) this.log(`parsing ComfyUI object_info.json`);
3141
+ const entries = Object.entries(this.data.spec);
3142
+ entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema]);
3143
+ for (const [KK, VV] of entries) {
3144
+ const pythonModule = VV.python_module;
3145
+ const prev = this.pythonModules.get(pythonModule);
3146
+ if (prev == null) this.pythonModules.set(pythonModule, [KK]);
3147
+ else prev.push(KK);
3148
+ const nodeNameInComfy = KK;
3149
+ const nodeDef = VV;
3150
+ const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy);
3151
+ if (typeof nodeDef.output === "string") {
3152
+ console.log(`[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`);
3153
+ nodeDef.output = [];
3154
+ }
3155
+ this.pythonModuleByNodeKey.set(nodeKey, pythonModule);
3156
+ this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule);
3157
+ const inputs = [];
3158
+ const outputs = [];
3159
+ const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule);
3160
+ this.nodesByNameInComfy[nodeNameInComfy] = node;
3161
+ this.nodesByKey[nodeKey] = node;
3162
+ this.nodes.push(node);
3163
+ const nameCountDict = {};
3164
+ for (const [ix, slotType] of nodeDef.output.entries()) {
3165
+ const outputNameInComfy = nodeDef.output_name[ix] || (typeof slotType === "string" ? slotType : `input_${ix}`);
3166
+ const at = nameCountDict[outputNameInComfy] ??= 0;
3167
+ const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`;
3168
+ nameCountDict[outputNameInComfy]++;
3169
+ let slotTypeName;
3170
+ const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`);
3171
+ if (typeof slotType === "string") {
3172
+ slotTypeName = asComfyNodeSlotTypeName(slotType);
3173
+ this.knownSlotTypes.add(slotTypeName);
3174
+ } else if (Array.isArray(slotType)) {
3175
+ slotTypeName = asComfyNodeSlotTypeName(this.processSlot({
3176
+ pythonModule,
3177
+ slotName: outputSlotName,
3178
+ comfyUnionDef: slotType
3179
+ }).unionName);
3180
+ this.enumsAppearingInOutput.add(slotTypeName);
3181
+ } else throw new Error(`invalid output ${ix} "${slotType}" in node "${nodeNameInComfy}"`);
3182
+ const arr = this.nodesByProduction[slotTypeName];
3183
+ if (arr == null) this.nodesByProduction[slotTypeName] = [node];
3184
+ else arr.push(node);
3185
+ outputs.push({
3186
+ slotName: outputSlotName,
3187
+ typeName: slotTypeName,
3188
+ nameInComfy: outputNameInComfy,
3189
+ outKey: outKeyValue,
3190
+ isPrimitive: false
3191
+ });
3192
+ }
3193
+ const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}).map(([name, spec]) => ({
3194
+ required: false,
3195
+ name,
3196
+ spec
3197
+ }));
3198
+ const allInputs = [...Object.entries(nodeDef.input?.required ?? {}).map(([name, spec]) => ({
3199
+ required: true,
3200
+ name,
3201
+ spec
3202
+ })).filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null), ...optionalInputs];
3203
+ for (const ipt of allInputs) {
3204
+ const inputNameInComfy = ipt.name;
3205
+ const typeDef = ipt.spec;
3206
+ const slotType = typeDef[0];
3207
+ const slotOpts = typeDef[1];
3208
+ let inputTypeName;
3209
+ const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`);
3210
+ if (slotType == null) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
3211
+ pythonModule,
3212
+ slotName: inputSlotName,
3213
+ comfyUnionDef: ["❌"]
3214
+ }).unionName);
3215
+ else if (typeof slotType === "string") {
3216
+ inputTypeName = asComfyNodeSlotTypeName(slotType);
3217
+ this.knownSlotTypes.add(inputTypeName);
3218
+ } else if (Array.isArray(slotType)) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
3219
+ pythonModule,
3220
+ slotName: inputSlotName,
3221
+ comfyUnionDef: slotType
3222
+ }).unionName);
3223
+ else throw new Error(`invalid schema (${JSON.stringify(slotType)}) for input "${ipt.name}" in node "${nodeNameInComfy}" (type: ${typeof slotType}; expected: Array | string)`);
3224
+ const isAutogrowContainer = typeof slotType === "string" && classifyWidgetInput({
3225
+ name: ipt.name,
3226
+ type: slotType,
3227
+ opts: slotOpts
3228
+ }).kind === "dynamic-container";
3229
+ if (isAutogrowContainer) {
3230
+ const instType = containerInstanceSlotType(slotOpts);
3231
+ if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType));
3232
+ }
3233
+ node.inputs.push({
3234
+ slotName: inputSlotName,
3235
+ required: ipt.required && !isAutogrowContainer,
3236
+ nameInComfy: inputNameInComfy,
3237
+ nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3238
+ typeName: inputTypeName,
3239
+ opts: slotOpts,
3240
+ isPrimitive: ComfyPrimitives.includes(inputTypeName),
3241
+ isEnum: this.knownUnionByName.has(inputTypeName),
3242
+ index: node.inputs.length
3243
+ });
3244
+ }
3245
+ }
2939
3246
  }
2940
- /** base (untyped) view of the same builder, for generic library code */
2941
- get builderBase() {
2942
- if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this);
2943
- return this._builder;
3247
+ log(...args) {
3248
+ logInfo(`[👅]: ${args.join(" ")}`);
2944
3249
  }
2945
- /** proxy to this.db.schema */
2946
- get schema() {
2947
- return this.host.schema;
3250
+ toTSType(t) {
3251
+ if (t === "*") return `string | number | boolean | ComfyNodeOutput<string, number>`;
3252
+ return ComfyPrimitiveMapping[t] ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>` : `ComfyNodeOutput<'${t}'>`;
2948
3253
  }
2949
- /** nodes that are still pending execution */
2950
- get pendingNodes() {
2951
- return this.nodes.filter((n) => n.status == null || n.status === "waiting");
3254
+ toAcceptsType(t) {
3255
+ return `ComfyNodeOutput<'${t}'>`;
2952
3256
  }
2953
- get nodesByUpdatedAt() {
2954
- return this.nodes.filter((n) => n.status != null && n.status !== "waiting").sort((a, b) => b.updatedAt - a.updatedAt);
3257
+ /**
3258
+ * every possible value for a given slot, straight from the live schema.
3259
+ * e.g. schema.values('LoraLoader.lora_name') -> all loras on this host
3260
+ */
3261
+ values(slotName) {
3262
+ return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? [];
2955
3263
  }
2956
- get progressCurrentNode() {
2957
- return this.currentExecutingNode?.progressReport;
3264
+ /** string values only (most enums are), for quick discovery */
3265
+ stringValues(slotName) {
3266
+ return this.values(slotName).filter((v) => typeof v === "string");
2958
3267
  }
2959
- get progressGlobal() {
2960
- const totalNode = this.nodes.length;
2961
- const doneNodes = this.nodes.filter((n) => n.status === "done" || n.status === "cached").length;
2962
- const bonus = this.currentExecutingNode?.progressRatio ?? 0;
2963
- const score = (doneNodes + bonus) / totalNode;
2964
- return {
2965
- percent: this.done ? 100 : score * 100,
2966
- isDone: this.done,
2967
- countDone: doneNodes + bonus,
2968
- countTotal: totalNode
2969
- };
3268
+ hasEmbedding(embedding) {
3269
+ return this.data.embeddings.includes(embedding);
2970
3270
  }
2971
- get cacheFolderPath() {
2972
- return comfyts.resolveFromOutput(`workflows/${this.id}`);
3271
+ hasLora(loraName) {
3272
+ return this.getLoras().includes(loraName);
2973
3273
  }
2974
- /** reset per-run node state so the same workflow can run again cleanly */
2975
- resetRunState() {
2976
- this.done = false;
2977
- this.currentExecutingNode = null;
2978
- for (const node of this.nodes) {
2979
- node.status = null;
2980
- node.progress = null;
2981
- node.progressRatio = 0;
2982
- }
3274
+ hasImage(imgName) {
3275
+ return this.getImages().includes(imgName);
3276
+ }
3277
+ hasCheckpoint(ckptName) {
3278
+ return this.getCheckpoints().includes(ckptName);
2983
3279
  }
2984
3280
  };
2985
3281
  const types = scope({
@@ -3051,19 +3347,6 @@ types.ComfyInputType;
3051
3347
  types.ComfyEnumDef;
3052
3348
  types.ComfyInputOpts;
3053
3349
  //#endregion
3054
- //#region src/utils/extractErrorMessage.ts
3055
- /** Extracts an error message from an exception stuff. */
3056
- const extractErrorMessage = (error) => {
3057
- if (error instanceof Error) return error.message;
3058
- if (error === null) return "null";
3059
- if (typeof error === "string") return error;
3060
- if (typeof error === "object") {
3061
- if ("message" in error && typeof error.message === "string") return error.message;
3062
- return JSON.stringify(error);
3063
- }
3064
- return String(error);
3065
- };
3066
- //#endregion
3067
3350
  //#region src/utils/stringifyReadable.ts
3068
3351
  const tab = " ";
3069
3352
  function readableStringify(obj, maxLevel = 3, level = 0) {
@@ -3091,17 +3374,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3091
3374
  return result;
3092
3375
  }
3093
3376
  //#endregion
3094
- //#region src/utils/writeFile.ts
3095
- const writeFileAsync = async (path, data, fmt) => {
3096
- return new Promise((resolve, reject) => {
3097
- logInfo(`writing file: ${ansi.blue(path)}`);
3098
- writeFile(path, data, fmt, (err) => {
3099
- if (err) reject(err);
3100
- else resolve();
3101
- });
3102
- });
3103
- };
3104
- //#endregion
3105
3377
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3106
3378
  const ComfyManagerAPIModelList_ark = type({ models: type({
3107
3379
  name: type.string.as(),
@@ -3339,7 +3611,8 @@ function parseHostBase(p) {
3339
3611
  function renderHttpBase(p) {
3340
3612
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3341
3613
  }
3342
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3614
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
3615
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
3343
3616
  function renderWsUrl(p) {
3344
3617
  return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3345
3618
  }
@@ -3349,6 +3622,27 @@ function renderPort(p) {
3349
3622
  }
3350
3623
  //#endregion
3351
3624
  //#region src/host/ResilientWebsocket.ts
3625
+ let transportPromise = null;
3626
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
3627
+ function resolveWsTransport() {
3628
+ transportPromise ??= (async () => {
3629
+ const specifier = "ws";
3630
+ try {
3631
+ return {
3632
+ ctor: (await import(specifier)).default,
3633
+ supportsHeaders: true
3634
+ };
3635
+ } catch {
3636
+ const native = globalThis.WebSocket;
3637
+ if (native != null) return {
3638
+ ctor: native,
3639
+ supportsHeaders: false
3640
+ };
3641
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
3642
+ }
3643
+ })();
3644
+ return transportPromise;
3645
+ }
3352
3646
  var ResilientWebSocketClient = class {
3353
3647
  addInfo(msg) {
3354
3648
  this.debugMessages.push({
@@ -3383,7 +3677,17 @@ var ResilientWebSocketClient = class {
3383
3677
  this.currentWS = null;
3384
3678
  this.isOpen = false;
3385
3679
  }
3386
- connect() {
3680
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
3681
+ headerlessUrl(headers) {
3682
+ const rest = { ...headers };
3683
+ const apiKey = rest["X-API-Key"];
3684
+ delete rest["X-API-Key"];
3685
+ const extra = Object.keys(rest);
3686
+ if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
3687
+ if (apiKey == null) return this.url;
3688
+ return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
3689
+ }
3690
+ async connect() {
3387
3691
  this.isOpen = false;
3388
3692
  const prevWS = this.currentWS;
3389
3693
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
@@ -3392,13 +3696,24 @@ var ResilientWebSocketClient = class {
3392
3696
  this.addInfo("Previous WebSocket discarded");
3393
3697
  prevWS.close();
3394
3698
  }
3395
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
3699
+ let ws;
3700
+ try {
3701
+ const transport = await resolveWsTransport();
3702
+ if (this.permanentlyClosed) return;
3703
+ const headers = this.options.headers?.() ?? {};
3704
+ ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
3705
+ } catch (e) {
3706
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
3707
+ this.permanentlyClosed = true;
3708
+ this.options.onTransportDead?.(e);
3709
+ return;
3710
+ }
3396
3711
  ws.binaryType = "arraybuffer";
3397
3712
  this.currentWS = ws;
3398
- if (this.options.onMessage) ws.onmessage = (event) => {
3713
+ ws.onmessage = (event) => {
3399
3714
  this.options.onMessage(event);
3400
3715
  };
3401
- ws.onopen = (_event) => {
3716
+ ws.onopen = () => {
3402
3717
  if (ws !== this.currentWS) return;
3403
3718
  this.addInfo("✅ WebSocket connected to " + this.url);
3404
3719
  this.isOpen = true;
@@ -3412,7 +3727,7 @@ var ResilientWebSocketClient = class {
3412
3727
  if (this.permanentlyClosed) return;
3413
3728
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3414
3729
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3415
- this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
3730
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3416
3731
  };
3417
3732
  ws.onerror = (event) => {
3418
3733
  if (ws !== this.currentWS) return;
@@ -3430,14 +3745,6 @@ var ResilientWebSocketClient = class {
3430
3745
  this.currentWS?.send(message);
3431
3746
  }
3432
3747
  }
3433
- /** forward WebSocket add event listeners to the current WebSocket instance */
3434
- addEventListener(type, listener, options) {
3435
- this.currentWS?.addEventListener(type, listener, options);
3436
- }
3437
- /** forward WebSocket remove event listeners to the current WebSocket instance */
3438
- removeEventListener(type, listener) {
3439
- this.currentWS?.removeEventListener(type, listener);
3440
- }
3441
3748
  };
3442
3749
  //#endregion
3443
3750
  //#region src/vars/loraKeywords.ts
@@ -3457,9 +3764,10 @@ function loadOnce() {
3457
3764
  if (loaded) return;
3458
3765
  loaded = true;
3459
3766
  const path = filePath();
3460
- if (!existsSync(path)) return;
3767
+ const text = getComfyStorage().readTextIfExists(path);
3768
+ if (text == null) return;
3461
3769
  try {
3462
- const raw = JSON.parse(readFileSync(path, "utf8"));
3770
+ const raw = JSON.parse(text);
3463
3771
  if (raw == null || typeof raw !== "object") return;
3464
3772
  runInAction(() => {
3465
3773
  for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
@@ -3482,8 +3790,7 @@ function setLoraKeyword(name, keyword) {
3482
3790
  });
3483
3791
  const path = filePath();
3484
3792
  try {
3485
- mkdirSync(dirname(path), { recursive: true });
3486
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3793
+ getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3487
3794
  } catch (e) {
3488
3795
  logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
3489
3796
  }
@@ -3679,6 +3986,12 @@ var SeedVar = class extends ComfyVar {
3679
3986
  afterRun() {
3680
3987
  this.advance();
3681
3988
  }
3989
+ /** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive
3990
+ * ('=' is the construction default; drafts restore their own mode via loadJSON) */
3991
+ reset() {
3992
+ this.setMode("=");
3993
+ return super.reset();
3994
+ }
3682
3995
  /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
3683
3996
  parse(raw) {
3684
3997
  const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
@@ -3746,6 +4059,20 @@ var ChoiceVar = class extends ComfyVar {
3746
4059
  return true;
3747
4060
  }
3748
4061
  };
4062
+ /** normalize a loras record into what a standard LoraLoader chain consumes */
4063
+ function activeLoras(loras) {
4064
+ const out = [];
4065
+ for (const [lora_name, s] of Object.entries(loras)) {
4066
+ if (s == null || s === false) continue;
4067
+ const [strength_model, strength_clip] = Array.isArray(s) ? s : s === true ? [1, 1] : [s, s];
4068
+ out.push({
4069
+ lora_name,
4070
+ strength_model,
4071
+ strength_clip
4072
+ });
4073
+ }
4074
+ return out;
4075
+ }
3749
4076
  /**
3750
4077
  * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
3751
4078
  * against the host's loras at define time (DefinedWorkflow calls bindHost),
@@ -3907,7 +4234,7 @@ var SizeVar = class extends ComfyVar {
3907
4234
  if (iv == null || iv.value === "") return null;
3908
4235
  try {
3909
4236
  const abs = iv.absPath();
3910
- const meta = imageMeta(new Uint8Array(readFileSync(abs)));
4237
+ const meta = imageMeta(getComfyStorage().readBytes(abs));
3911
4238
  if (meta.width == null || meta.height == null) return null;
3912
4239
  return {
3913
4240
  width: meta.width,
@@ -3961,7 +4288,7 @@ var ImageVarEmptyError = class extends Error {
3961
4288
  /** trim + expand a leading `~/` — every ImageVar write funnels through this */
3962
4289
  function expandUserPath(raw) {
3963
4290
  const trimmed = raw.trim();
3964
- return trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
4291
+ return trimmed.startsWith("~/") ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed;
3965
4292
  }
3966
4293
  /**
3967
4294
  * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
@@ -3997,7 +4324,7 @@ var ImageVar = class extends ComfyVar {
3997
4324
  absPath() {
3998
4325
  if (!this.isSet()) throw this.emptyError();
3999
4326
  if (isAbsolute(this.value)) return this.value;
4000
- return resolve(this.opts.folder ?? process.cwd(), this.value);
4327
+ return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value);
4001
4328
  }
4002
4329
  /** empty = unset: the build fails LOUD here (varValues calls outValue) */
4003
4330
  outValue() {
@@ -4006,7 +4333,7 @@ var ImageVar = class extends ComfyVar {
4006
4333
  }
4007
4334
  display() {
4008
4335
  if (!this.isSet()) return "(unset) pick a file";
4009
- const home = homedir();
4336
+ const home = getComfyStorage().homedir();
4010
4337
  return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
4011
4338
  }
4012
4339
  };
@@ -4304,11 +4631,11 @@ var ComfyHost = class {
4304
4631
  this.isUpdatingSchema = true;
4305
4632
  const object_info_json = await this.fetchJSON_("/object_info");
4306
4633
  const object_info_str = readableStringify(object_info_json, 4);
4307
- writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
4634
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
4308
4635
  const res = ComfySchemaJSON_ark(object_info_json);
4309
4636
  if (res instanceof type.errors) printArkResultInConsole(res);
4310
4637
  const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
4311
- writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
4638
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
4312
4639
  this.schema.update({
4313
4640
  spec: object_info_json,
4314
4641
  embeddings: embeddings_json
@@ -4325,7 +4652,7 @@ var ComfyHost = class {
4325
4652
  };
4326
4653
  console.error(error);
4327
4654
  console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
4328
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4655
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4329
4656
  this.markFailed(error);
4330
4657
  } finally {
4331
4658
  this.isUpdatingSchema = false;
@@ -4346,9 +4673,10 @@ var ComfyHost = class {
4346
4673
  this.base = parseHostBase(this.data);
4347
4674
  /** folder where file related to the host config will be cached */
4348
4675
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
4349
- if (!existsSync(this.cacheFolder)) {
4676
+ const storage = getComfyStorage();
4677
+ if (!storage.exists(this.cacheFolder)) {
4350
4678
  console.log("🟢 creating folder", this.cacheFolder);
4351
- mkdirSync(this.cacheFolder, { recursive: true });
4679
+ storage.mkdirp(this.cacheFolder);
4352
4680
  }
4353
4681
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
4354
4682
  this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
@@ -4398,19 +4726,20 @@ var ComfyHost = class {
4398
4726
  }
4399
4727
  async writeSDKToDisk() {
4400
4728
  if (this.data.sdkAutoWrite === false) return;
4729
+ const storage = getComfyStorage();
4401
4730
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
4402
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
4403
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
4731
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
4732
+ storage.writeText(this.sdkDTSPath, comfySchemaTs);
4404
4733
  }
4405
4734
  shouldUseSchemaCache() {
4406
4735
  if (this._schemaStrategy === "refresh") return false;
4407
- const exists = existsSync(this.comfyJSONPath);
4736
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
4408
4737
  if (this._schemaStrategy === "cache") {
4409
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4738
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4410
4739
  return true;
4411
4740
  }
4412
- if (!exists) return false;
4413
- return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
4741
+ if (mtimeMs == null) return false;
4742
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs;
4414
4743
  }
4415
4744
  waitForSession(timeoutMs = 5e3) {
4416
4745
  if (this.comfySessionId !== "temp") return Promise.resolve();
@@ -4445,6 +4774,7 @@ var ComfyHost = class {
4445
4774
  onMessage: (e) => this.onMessage(e),
4446
4775
  url: () => this.getWSUrl(),
4447
4776
  headers: () => this.authHeaders(),
4777
+ onTransportDead: (e) => this.markFailed(e),
4448
4778
  onClose: () => {
4449
4779
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
4450
4780
  }
@@ -4464,7 +4794,7 @@ var ComfyHost = class {
4464
4794
  * examples must still open in the TUI; run() fetches the real schema through
4465
4795
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
4466
4796
  loadSchemaFromCache() {
4467
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
4797
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
4468
4798
  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`);
4469
4799
  return Promise.resolve();
4470
4800
  }
@@ -4476,7 +4806,7 @@ var ComfyHost = class {
4476
4806
  embeddings: embeddings_json
4477
4807
  });
4478
4808
  this.schema.RUN_BASIC_CHECKS();
4479
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4809
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4480
4810
  })().catch((e) => {
4481
4811
  this._schemaFromCache = null;
4482
4812
  throw e;
@@ -4568,55 +4898,13 @@ var ComfyHost = class {
4568
4898
  };
4569
4899
  //#endregion
4570
4900
  //#region src/utils/downloadFile.ts
4571
- /** Usage example
4572
- * | ;(async () => {
4573
- * | try {
4574
- * | await downloadFile('https://example.com/file', 'folder/filename')
4575
- * | console.log('Download completed successfully')
4576
- * | } catch (error) {
4577
- * | console.error('Download failed:', error)
4578
- * | }
4579
- * | })()
4580
- * |
4581
- */
4582
- function downloadFile(url, outputPath, logPrefix = " - ") {
4583
- mkdirSync(dirname(outputPath), { recursive: true });
4584
- return new Promise((resolve, reject) => {
4585
- https.get(url, (response) => {
4586
- if (response.statusCode === 302 || response.statusCode === 301) {
4587
- const newUrl = response.headers.location;
4588
- console.log(`Redirected to ${newUrl}`);
4589
- resolve(downloadFile(newUrl, outputPath));
4590
- return;
4591
- }
4592
- if (response.statusCode !== 200) {
4593
- reject(`Failed to download file: Status Code ${response.statusCode}`);
4594
- return;
4595
- }
4596
- const rawLen = response.headers["content-length"];
4597
- if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
4598
- else {
4599
- const totalSize = parseInt(rawLen, 10);
4600
- let downloaded = 0;
4601
- let lastLoggedPercentage = 0;
4602
- response.on("data", (chunk) => {
4603
- downloaded += chunk.length;
4604
- const percentage = Math.round(downloaded / totalSize * 100);
4605
- if (percentage >= lastLoggedPercentage + 1) {
4606
- stdout.write(`\r${logPrefix}${percentage}% downloaded`);
4607
- lastLoggedPercentage = percentage;
4608
- }
4609
- });
4610
- }
4611
- const fileStream = fs.createWriteStream(outputPath);
4612
- response.pipe(fileStream);
4613
- fileStream.on("finish", () => {
4614
- console.log(` (DONE)`);
4615
- fileStream.close();
4616
- resolve(true);
4617
- });
4618
- }).on("error", (err) => reject(err));
4619
- });
4901
+ async function downloadFile(url, outputPath, logPrefix = " - ") {
4902
+ const res = await fetch(url);
4903
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
4904
+ const bytes = new Uint8Array(await res.arrayBuffer());
4905
+ getComfyStorage().writeBytes(outputPath, bytes);
4906
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
4907
+ return true;
4620
4908
  }
4621
4909
  //#endregion
4622
4910
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
@@ -4737,7 +5025,7 @@ const ComfyManagerRawPluginInfo_ark = type({
4737
5025
  const _getKnownPlugins = (DB) => {
4738
5026
  const counter = DB.report.file("custom-node-list.json");
4739
5027
  let totalFileSeen = 0;
4740
- const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
5028
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
4741
5029
  if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4742
5030
  const canonical = [];
4743
5031
  for (const row of root.custom_nodes) {
@@ -4775,7 +5063,7 @@ const _getKnownPlugins = (DB) => {
4775
5063
  }
4776
5064
  out1 += "\n";
4777
5065
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
4778
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5066
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4779
5067
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4780
5068
  let out2 = "";
4781
5069
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -4783,7 +5071,7 @@ const _getKnownPlugins = (DB) => {
4783
5071
  out2 += "export type KnownComfyPluginURL =\n";
4784
5072
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
4785
5073
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
4786
- writeFileSync(out2Path, out2, "utf-8");
5074
+ getComfyStorage().writeText(out2Path, out2);
4787
5075
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4788
5076
  }
4789
5077
  if (DB.opts.check) {
@@ -4829,7 +5117,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNod
4829
5117
  const _getCustomNodeRegistry = (DB) => {
4830
5118
  const counter = DB.report.file("extension-node-map.json");
4831
5119
  let totalCustomNodeSeen = 0;
4832
- const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
5120
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
4833
5121
  const root = type("Record<string, unknown>")(raw);
4834
5122
  if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4835
5123
  for (const [url, value] of Object.entries(root)) {
@@ -4865,7 +5153,7 @@ const _getCustomNodeRegistry = (DB) => {
4865
5153
  for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
4866
5154
  out += "\n";
4867
5155
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
4868
- writeFileSync(outPath, out + "\n", "utf-8");
5156
+ getComfyStorage().writeText(outPath, out + "\n");
4869
5157
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
4870
5158
  }
4871
5159
  if (DB.opts.check) {
@@ -4920,7 +5208,7 @@ const ComfyManagerModelInfo_ark = type({
4920
5208
  //#region src/manager/loaders/step4_model-list-loader.ts
4921
5209
  const _getKnownModels = (DB) => {
4922
5210
  const counter = DB.report.file("model-list.json");
4923
- const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
5211
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
4924
5212
  if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
4925
5213
  const canonical = [];
4926
5214
  for (const row of root.models) {
@@ -4949,7 +5237,7 @@ const _getKnownModels = (DB) => {
4949
5237
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4950
5238
  out1 += "]\n";
4951
5239
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
4952
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5240
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4953
5241
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4954
5242
  let out4 = "";
4955
5243
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -4965,7 +5253,7 @@ const _getKnownModels = (DB) => {
4965
5253
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
4966
5254
  out4 += "]\n";
4967
5255
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
4968
- writeFileSync(out4Path, out4 + "\n", "utf-8");
5256
+ getComfyStorage().writeText(out4Path, out4 + "\n");
4969
5257
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
4970
5258
  let out2 = "";
4971
5259
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -4982,7 +5270,7 @@ const _getKnownModels = (DB) => {
4982
5270
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4983
5271
  out2 += "]\n";
4984
5272
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
4985
- writeFileSync(out2Path, out2 + "\n", "utf-8");
5273
+ getComfyStorage().writeText(out2Path, out2 + "\n");
4986
5274
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4987
5275
  let out3 = "";
4988
5276
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -4997,7 +5285,7 @@ const _getKnownModels = (DB) => {
4997
5285
  }
4998
5286
  out3 += "\n";
4999
5287
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
5000
- writeFileSync(out3Path, out3 + "\n", "utf-8");
5288
+ getComfyStorage().writeText(out3Path, out3 + "\n");
5001
5289
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
5002
5290
  let out99 = "";
5003
5291
  out99 += `// prettier-ignore\n`;
@@ -5011,7 +5299,7 @@ const _getKnownModels = (DB) => {
5011
5299
  }
5012
5300
  out99 += "\n";
5013
5301
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
5014
- writeFileSync(out99Path, out99 + "\n", "utf-8");
5302
+ getComfyStorage().writeText(out99Path, out99 + "\n");
5015
5303
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
5016
5304
  }
5017
5305
  if (DB.opts.check) {
@@ -5032,7 +5320,7 @@ const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
5032
5320
  //#region src/manager/loaders/step5_alter-list-loader.ts
5033
5321
  const _getAlterList = (DB) => {
5034
5322
  const counter = DB.report.file("alter-list.json");
5035
- const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
5323
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
5036
5324
  if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
5037
5325
  const canonical = [];
5038
5326
  for (const row of root.items) {
@@ -5057,7 +5345,7 @@ const ComfyManagerGithubStatEntry_ark = type({
5057
5345
  //#region src/manager/loaders/step6_github-stats-loader.ts
5058
5346
  const _getGithubStats = (DB) => {
5059
5347
  const counter = DB.report.file("github-stats.json");
5060
- const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
5348
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
5061
5349
  const root = type("Record<string, unknown>")(raw);
5062
5350
  if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
5063
5351
  for (const [url, value] of Object.entries(root)) {
@@ -5172,13 +5460,12 @@ var ComfyTS = class ComfyTS {
5172
5460
  this.version = version;
5173
5461
  this.hosts = /* @__PURE__ */ new Map();
5174
5462
  this._registry = null;
5175
- this.rootPath = asAbsolutePath(process.cwd());
5176
5463
  this.readJSON_ = (absPath, def) => {
5177
- if (!existsSync(absPath)) {
5464
+ const str = this.storage.readTextIfExists(absPath);
5465
+ if (str == null) {
5178
5466
  if (def != null) return def;
5179
5467
  throw new Error(`file does not exist ${absPath}`);
5180
5468
  }
5181
- const str = readFileSync(absPath, "utf8");
5182
5469
  return JSON.parse(str);
5183
5470
  };
5184
5471
  this.autolayoutOpts = {
@@ -5189,7 +5476,8 @@ var ComfyTS = class ComfyTS {
5189
5476
  const globalHack = globalThis;
5190
5477
  if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
5191
5478
  globalHack.comfyts = this;
5192
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
5479
+ this.storage = resolveComfyStorage(p.storage);
5480
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
5193
5481
  this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
5194
5482
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
5195
5483
  this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
@@ -5253,6 +5541,29 @@ var ComfyTS = class ComfyTS {
5253
5541
  }
5254
5542
  };
5255
5543
  //#endregion
5256
- export { PromptVar as a, readableStringify as c, ComfySchema as d, logError as f, LorasVar as i, extractErrorMessage as l, settingsPathFor as n, getLoraKeyword as o, DefinedWorkflow as r, setLoraKeyword as s, ComfyTS as t, stripAnsi as u };
5544
+ //#region src/utils/loraTag.ts
5545
+ /**
5546
+ * build a LoraManager-style lora tag: `<lora:name:strength>` or
5547
+ * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5548
+ * autocomplete + validation:
5549
+ *
5550
+ * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5551
+ */
5552
+ function loraTag(name, strength = 1, clipStrength) {
5553
+ return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5554
+ }
5555
+ //#endregion
5556
+ //#region src/web.ts
5557
+ /**
5558
+ * comfy-ts/web — the BROWSER entry (architecture item 13): same library,
5559
+ * in-memory storage, native WebSocket, no sharp. Types still come from a
5560
+ * generated sdk.d.ts included in the consumer's tsconfig.
5561
+ * Importing both entries in one process: the LAST import wins the default
5562
+ * backend — pass ComfyTS.create({ storage }) to be explicit (SSR setups).
5563
+ * @packageDocumentation
5564
+ */
5565
+ setDefaultComfyStorage(createMemoryStorage());
5566
+ //#endregion
5567
+ export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, getComfyStorage, getLoraKeyword, hostIdToNamespace, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, v };
5257
5568
 
5258
- //# sourceMappingURL=state-BYbxDgfr.js.map
5569
+ //# sourceMappingURL=web.js.map