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