comfy-ts 1.0.0 → 1.2.0

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