comfy-ts 0.2.0 → 0.4.0

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