comfy-ts 0.4.0 → 1.1.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 (158) hide show
  1. package/README.md +385 -255
  2. package/dist/DefinedWorkflow-BYyu5dK9.js +669 -0
  3. package/dist/DefinedWorkflow-BYyu5dK9.js.map +1 -0
  4. package/dist/cli.js +4106 -152
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1560 -333
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +7826 -467
  9. package/dist/index.d.ts +7808 -449
  10. package/dist/index.js +1550 -333
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-DZ22HDHI.js} +631 -657
  13. package/dist/run-tui-DZ22HDHI.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +55 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +51 -0
  19. package/examples/README.md +30 -0
  20. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +79 -0
  21. package/examples/comfy-cloud/anima-t2i.cflow.ts +57 -0
  22. package/examples/comfy-cloud/boogu-i2i.cflow.ts +76 -0
  23. package/examples/comfy-cloud/capybara-i2i.cflow.ts +85 -0
  24. package/examples/comfy-cloud/capybara-i2v.cflow.ts +90 -0
  25. package/examples/comfy-cloud/capybara-t2i.cflow.ts +67 -0
  26. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +79 -0
  27. package/examples/comfy-cloud/chroma-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/cloudHost.ts +41 -0
  29. package/examples/comfy-cloud/ernie-t2i.cflow.ts +59 -0
  30. package/examples/comfy-cloud/firered-i2i.cflow.ts +74 -0
  31. package/examples/comfy-cloud/flux1-i2i.cflow.ts +76 -0
  32. package/examples/comfy-cloud/flux1-t2i.cflow.ts +63 -0
  33. package/examples/comfy-cloud/flux2-i2i.cflow.ts +80 -0
  34. package/examples/comfy-cloud/flux2-t2i.cflow.ts +57 -0
  35. package/examples/comfy-cloud/hidream-i2i.cflow.ts +89 -0
  36. package/examples/comfy-cloud/hidream-t2i.cflow.ts +65 -0
  37. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +93 -0
  38. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +74 -0
  39. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +80 -0
  40. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +95 -0
  41. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +60 -0
  42. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +78 -0
  43. package/examples/comfy-cloud/krea2-t2i.cflow.ts +59 -0
  44. package/examples/comfy-cloud/lens-t2i.cflow.ts +62 -0
  45. package/examples/comfy-cloud/longcat-i2i.cflow.ts +74 -0
  46. package/examples/comfy-cloud/longcat-t2i.cflow.ts +65 -0
  47. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +92 -0
  48. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +78 -0
  49. package/examples/comfy-cloud/newbie-t2i.cflow.ts +67 -0
  50. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +86 -0
  51. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +62 -0
  52. package/examples/comfy-cloud/ovis-t2i.cflow.ts +56 -0
  53. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +63 -0
  54. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +69 -0
  55. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +55 -0
  56. package/examples/comfy-cloud/sd35-t2i.cflow.ts +48 -0
  57. package/examples/comfy-cloud/sdk.d.ts +123062 -0
  58. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +69 -0
  59. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +53 -0
  60. package/examples/comfy-cloud/svd-i2v.cflow.ts +75 -0
  61. package/examples/comfy-cloud/wan21-i2v.cflow.ts +83 -0
  62. package/examples/comfy-cloud/wan21-t2v.cflow.ts +64 -0
  63. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +69 -0
  64. package/examples/comfy-cloud/wan22-i2v.cflow.ts +107 -0
  65. package/examples/comfy-cloud/wan22-t2v.cflow.ts +98 -0
  66. package/examples/comfy-cloud/z-image-t2i.cflow.ts +62 -0
  67. package/examples/images/README.md +18 -0
  68. package/examples/images/bear_1024x1024.jpg +0 -0
  69. package/examples/images/deer_768x1344.jpg +0 -0
  70. package/examples/images/dog_512x512.jpg +0 -0
  71. package/examples/images/lioness_768x768.jpg +0 -0
  72. package/examples/images/pug_200x300.jpg +0 -0
  73. package/examples/images/walrus_1344x768.jpg +0 -0
  74. package/guide-for-agents.md +172 -0
  75. package/package.json +20 -4
  76. package/src/cli/comfy-ts-cli.ts +19 -2
  77. package/src/cli/gen.ts +21 -12
  78. package/src/cli/tui/components/PreviewPanel.tsx +9 -8
  79. package/src/cli/tui/components/StatusBar.tsx +11 -0
  80. package/src/cli/tui/components/TreePanel.tsx +15 -2
  81. package/src/cli/tui/components/TuiApp.tsx +18 -0
  82. package/src/cli/tui/discoverWorkflows.ts +45 -0
  83. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +72 -0
  84. package/src/cli/tui/imagePicker/ImagePickerSt.ts +288 -0
  85. package/src/cli/tui/imagePicker/fsListing.ts +46 -0
  86. package/src/cli/tui/imagePicker/pickerPrefs.ts +78 -0
  87. package/src/cli/tui/run-tui.tsx +52 -23
  88. package/src/cli/tui/state/HostSt.ts +2 -3
  89. package/src/cli/tui/state/LorasSt.ts +14 -36
  90. package/src/cli/tui/state/PreviewSt.ts +28 -2
  91. package/src/cli/tui/state/TreeSt.ts +30 -6
  92. package/src/cli/tui/state/TuiSt.ts +27 -3
  93. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  94. package/src/exampleAssets.ts +56 -0
  95. package/src/graph/ComfyNode.ts +4 -1
  96. package/src/host/ComfyHost.ts +203 -77
  97. package/src/host/ComfyManager.ts +10 -9
  98. package/src/host/ComfyUploader.ts +1 -2
  99. package/src/host/ResilientWebsocket.ts +3 -1
  100. package/src/host/hostUrl.ts +59 -0
  101. package/src/host/loraManagerApi.ts +5 -4
  102. package/src/index.ts +27 -1
  103. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  104. package/src/litegraph/LiteGraphGroup.ts +9 -7
  105. package/src/litegraph/LiteGraphJSON.ts +34 -13
  106. package/src/litegraph/LiteGraphLink.ts +32 -2
  107. package/src/litegraph/LiteGraphNode.ts +18 -33
  108. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  109. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  110. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  111. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  112. package/src/litegraph/expandSubgraphs.ts +352 -0
  113. package/src/litegraph/normalizeWorkflow.ts +141 -0
  114. package/src/manager/ComfyRegistry.ts +37 -9
  115. package/src/manager/generated/KnownComfyCustomNodeName.ts +23852 -1926
  116. package/src/manager/generated/KnownComfyPluginTitle.ts +6854 -236
  117. package/src/manager/generated/KnownComfyPluginURL.ts +3425 -111
  118. package/src/manager/generated/KnownModel_Base.ts +23 -7
  119. package/src/manager/generated/KnownModel_FileName.ts +421 -0
  120. package/src/manager/generated/KnownModel_Name.ts +421 -0
  121. package/src/manager/generated/KnownModel_SavePath.ts +34 -8
  122. package/src/manager/generated/KnownModel_Type.ts +18 -14
  123. package/src/manager/json/alter-list.json +221 -221
  124. package/src/manager/json/custom-node-list.json +61020 -21946
  125. package/src/manager/json/extension-node-map.json +81077 -31176
  126. package/src/manager/json/github-stats.json +29321 -12601
  127. package/src/manager/json/model-list.json +5935 -4997
  128. package/src/manager/loaders/parseReport.ts +55 -0
  129. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +15 -49
  130. package/src/manager/loaders/step2_custom-node-list-loader.ts +38 -83
  131. package/src/manager/loaders/step3_extension-node-map-loader.ts +36 -142
  132. package/src/manager/loaders/step4_model-list-loader.ts +25 -36
  133. package/src/manager/loaders/step5_alter-list-loader.ts +29 -0
  134. package/src/manager/loaders/step6_github-stats-loader.ts +23 -0
  135. package/src/manager/script-update-manager.bun.ts +9 -1
  136. package/src/manager/types/ComfyManagerAlterInfo.ts +13 -0
  137. package/src/manager/types/ComfyManagerFileModelInfo.ts +7 -3
  138. package/src/manager/types/ComfyManagerFilePluginContent.ts +6 -9
  139. package/src/manager/types/ComfyManagerFilePluginList.ts +3 -3
  140. package/src/manager/types/ComfyManagerGithubStats.ts +9 -0
  141. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +2 -3
  142. package/src/manager/types/ComfyManagerPluginInfo.ts +48 -34
  143. package/src/runner/ComfyExecution.ts +4 -5
  144. package/src/runner/ComfyWorkflow.ts +2 -2
  145. package/src/runner/wsBinaryFrame.ts +48 -0
  146. package/src/sdk-generator/ComfySchema.ts +14 -1
  147. package/src/sdk-generator/Primitives.ts +6 -24
  148. package/src/sdk-generator/comfy-api-json.ts +3 -1
  149. package/src/sdk-generator/comfyui-sdk-codegen.ts +15 -0
  150. package/src/sdk-generator/inputWidgetKind.ts +196 -0
  151. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  152. package/src/state.ts +13 -2
  153. package/src/vars/ComfyVars.ts +82 -2
  154. package/src/vars/DefinedWorkflow.ts +7 -2
  155. package/dist/log-CdfgILde.js +0 -10
  156. package/dist/log-CdfgILde.js.map +0 -1
  157. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
  158. package/src/utils/tryExtracting.ts +0 -41
package/dist/index.cjs CHANGED
@@ -33,13 +33,604 @@ let node_crypto = require("node:crypto");
33
33
  node_crypto = __toESM(node_crypto, 1);
34
34
  let ws = require("ws");
35
35
  ws = __toESM(ws, 1);
36
+ let node_os = require("node:os");
36
37
  let mobx = require("mobx");
37
38
  let node_https = require("node:https");
38
39
  node_https = __toESM(node_https, 1);
39
40
  let node_process = require("node:process");
40
- let fs = require("fs");
41
+ let node_url = require("node:url");
41
42
  //#region package.json
42
- var version = "0.4.0";
43
+ var version = "1.1.0";
44
+ //#endregion
45
+ //#region src/litegraph/LiteGraphLinkID.ts
46
+ const asLiteGraphLinkID = (id) => id;
47
+ const LiteGraphLinkID_ = arktype.type.number.atLeast(0).as();
48
+ //#endregion
49
+ //#region src/utils/bang.ts
50
+ /** assertNotNull */
51
+ const bang = (x, msg = "") => {
52
+ if (x == null) {
53
+ console.error(`[🔴] BANG FAILED`, msg);
54
+ throw new Error("bang: " + (msg ?? "no message"));
55
+ }
56
+ return x;
57
+ };
58
+ //#endregion
59
+ //#region src/litegraph/expandSubgraphs.ts
60
+ /** boundary sentinel ids inside definition link tables */
61
+ const SUBGRAPH_INPUT_NODE_ID = -10;
62
+ const SUBGRAPH_OUTPUT_NODE_ID = -20;
63
+ /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
64
+ const MAX_EXPANSION_PASSES = 32;
65
+ /**
66
+ * widget-kind fallback when a def input slot has no boundary target carrying a
67
+ * widget marker: these litegraph slot types carry widget values. LOCAL copy on
68
+ * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
69
+ * (the io-widget era serializes exactly one value per exposed widget slot).
70
+ */
71
+ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
72
+ "INT",
73
+ "FLOAT",
74
+ "STRING",
75
+ "BOOLEAN",
76
+ "COMBO"
77
+ ]);
78
+ /**
79
+ * inline every subgraph instance (node whose `type` is a definition uuid) into
80
+ * the root graph: fresh numeric ids, boundary links rewired, instance widget
81
+ * values promoted into the inner nodes' `named` overrides. Iterative so nested
82
+ * definitions expand on the next pass. Muted instances are dropped (their
83
+ * consumers resolve unconnected); bypassed instances stay for the converter's
84
+ * passthrough walk, which needs no interior.
85
+ */
86
+ const expandSubgraphs = (wf, defs) => {
87
+ let passes = 0;
88
+ while (true) {
89
+ const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
90
+ if (expandable.length === 0) return wf;
91
+ if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
92
+ for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
93
+ else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
94
+ }
95
+ };
96
+ /** converter mute semantics applied early: after expansion there is no single node left to skip */
97
+ const dropMutedInstance = (wf, instance) => {
98
+ const dead = /* @__PURE__ */ new Set();
99
+ for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
100
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
101
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
102
+ pruneDeadLinkRefs(wf, dead);
103
+ };
104
+ const pruneDeadLinkRefs = (wf, dead) => {
105
+ if (dead.size === 0) return;
106
+ for (const node of wf.nodes) {
107
+ for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
108
+ for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
109
+ }
110
+ };
111
+ const expandOneInstance = (wf, instance, def) => {
112
+ let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
113
+ let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
114
+ const newNodeIds = /* @__PURE__ */ new Map();
115
+ for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
116
+ const remapNodeId = (id) => newNodeIds.get(id) ?? null;
117
+ const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
118
+ for (const [k, input] of instance.inputs.entries()) {
119
+ const defSlot = def.inputs.findIndex((d) => d.name === input.name);
120
+ if (defSlot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): input "${input.name}" (slot ${k}) matches no definition input (defined: ${def.inputs.map((d) => d.name).join(", ")})`);
121
+ defSlotOfInstanceSlot.set(k, defSlot);
122
+ }
123
+ const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
124
+ for (const link of wf.links) {
125
+ if (link.targetId !== instance.id) continue;
126
+ const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
127
+ if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
128
+ outerLinkIntoDefSlot.set(defSlot, link);
129
+ }
130
+ const newLinkIds = /* @__PURE__ */ new Map();
131
+ const splicedLinks = [];
132
+ const producerByOutSlot = /* @__PURE__ */ new Map();
133
+ const passthroughOutSlot = /* @__PURE__ */ new Map();
134
+ const boundaryTargetsByInSlot = /* @__PURE__ */ new Map();
135
+ for (const link of def.links) {
136
+ const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID;
137
+ const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID;
138
+ if (fromInputBoundary && toOutputBoundary) {
139
+ passthroughOutSlot.set(link.targetSlot, link.originSlot);
140
+ continue;
141
+ }
142
+ if (toOutputBoundary) {
143
+ const producerId = remapNodeId(link.originId);
144
+ if (producerId != null && !producerByOutSlot.has(link.targetSlot)) producerByOutSlot.set(link.targetSlot, {
145
+ nodeId: producerId,
146
+ slot: link.originSlot
147
+ });
148
+ continue;
149
+ }
150
+ if (fromInputBoundary) {
151
+ const targetId = remapNodeId(link.targetId);
152
+ if (targetId == null) continue;
153
+ const target = {
154
+ nodeId: targetId,
155
+ slot: link.targetSlot
156
+ };
157
+ const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? [];
158
+ targets.push(target);
159
+ boundaryTargetsByInSlot.set(link.originSlot, targets);
160
+ const outer = outerLinkIntoDefSlot.get(link.originSlot);
161
+ if (outer == null) continue;
162
+ const fresh = asLiteGraphLinkID(++nextLinkId);
163
+ newLinkIds.set(link.id, fresh);
164
+ splicedLinks.push({
165
+ id: fresh,
166
+ originId: outer.originId,
167
+ originSlot: outer.originSlot,
168
+ targetId: target.nodeId,
169
+ targetSlot: target.slot,
170
+ type: link.type
171
+ });
172
+ wf.nodes.find((n) => n.id === outer.originId)?.outputs[outer.originSlot]?.links.push(fresh);
173
+ continue;
174
+ }
175
+ const interiorOrigin = remapNodeId(link.originId);
176
+ const interiorTarget = remapNodeId(link.targetId);
177
+ if (interiorOrigin == null || interiorTarget == null) continue;
178
+ const fresh = asLiteGraphLinkID(++nextLinkId);
179
+ newLinkIds.set(link.id, fresh);
180
+ splicedLinks.push({
181
+ id: fresh,
182
+ originId: interiorOrigin,
183
+ originSlot: link.originSlot,
184
+ targetId: interiorTarget,
185
+ targetSlot: link.targetSlot,
186
+ type: link.type
187
+ });
188
+ }
189
+ const splicedNodes = def.nodes.map((inner) => ({
190
+ id: bang(newNodeIds.get(inner.id)),
191
+ type: inner.type,
192
+ title: inner.title,
193
+ mode: inner.mode,
194
+ isVirtualNode: inner.isVirtualNode,
195
+ inputs: inner.inputs.map((i) => ({
196
+ name: i.name,
197
+ type: i.type,
198
+ link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
199
+ widgetName: i.widgetName
200
+ })),
201
+ outputs: inner.outputs.map((o) => ({
202
+ name: o.name,
203
+ type: o.type,
204
+ links: o.links.map((id) => newLinkIds.get(id)).filter((id) => id != null)
205
+ })),
206
+ widgets: {
207
+ positional: [...inner.widgets.positional],
208
+ named: { ...inner.widgets.named }
209
+ },
210
+ pos: [inner.pos[0], inner.pos[1]],
211
+ size: [inner.size[0], inner.size[1]],
212
+ properties: { ...inner.properties }
213
+ }));
214
+ const dead = /* @__PURE__ */ new Set();
215
+ for (const link of wf.links) {
216
+ if (link.targetId === instance.id) {
217
+ dead.add(link.id);
218
+ continue;
219
+ }
220
+ if (link.originId !== instance.id) continue;
221
+ const producer = producerByOutSlot.get(link.originSlot);
222
+ if (producer != null) {
223
+ link.originId = producer.nodeId;
224
+ link.originSlot = producer.slot;
225
+ splicedNodes.find((n) => n.id === producer.nodeId)?.outputs[producer.slot]?.links.push(link.id);
226
+ continue;
227
+ }
228
+ const passthroughInSlot = passthroughOutSlot.get(link.originSlot);
229
+ const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null;
230
+ if (outer != null) {
231
+ link.originId = outer.originId;
232
+ link.originSlot = outer.originSlot;
233
+ continue;
234
+ }
235
+ dead.add(link.id);
236
+ }
237
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
238
+ pruneDeadLinkRefs(wf, dead);
239
+ promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
240
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
241
+ wf.nodes.push(...splicedNodes);
242
+ wf.links.push(...splicedLinks);
243
+ };
244
+ /**
245
+ * instance widget values land in inner nodes' `named` overrides. TWO eras for
246
+ * the POSITIONAL values:
247
+ * - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]
248
+ * zip against the instance's positional values (incl. `control_after_generate`
249
+ * phantom pairs — written to `named` and simply never read, no schema input
250
+ * has that name).
251
+ * - io-widget era (no proxyWidgets): positional values zip against the def's
252
+ * widget-kind input slots in def order, one value per slot (no phantom —
253
+ * corpus-verified). An outer link into the same slot wins in the converter;
254
+ * the named override is still written, matching ComfyUI.
255
+ * PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:
256
+ * that is how a NESTED instance receives its outer values (the previous pass
257
+ * wrote them to `named`), so they must forward through THIS expansion too —
258
+ * named wins over positional, same precedence as the converter.
259
+ */
260
+ const promoteInstanceWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot) => {
261
+ const promoteToSlotTargets = (slot, value) => {
262
+ for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {
263
+ const target = splicedNodes.find((n) => n.id === t.nodeId);
264
+ const input = innerInputAt(splicedNodes, t);
265
+ if (target == null || input == null) continue;
266
+ target.widgets.named[input.name] = value;
267
+ }
268
+ };
269
+ promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets);
270
+ for (const [slot, io] of def.inputs.entries()) {
271
+ if (!Object.hasOwn(instance.widgets.named, io.name)) continue;
272
+ promoteToSlotTargets(slot, instance.widgets.named[io.name]);
273
+ }
274
+ };
275
+ const promotePositionalWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets) => {
276
+ const values = instance.widgets.positional;
277
+ if (values.length === 0) return;
278
+ const proxy = instance.properties["proxyWidgets"];
279
+ if (Array.isArray(proxy) && proxy.length > 0) {
280
+ const count = Math.min(values.length, proxy.length);
281
+ for (let k = 0; k < count; k++) {
282
+ const pair = proxy[k];
283
+ if (!Array.isArray(pair) || pair.length !== 2) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): malformed proxyWidgets entry ${JSON.stringify(pair)}`);
284
+ const innerId = Number(pair[0]);
285
+ const widgetName = String(pair[1]);
286
+ if (innerId < 0) {
287
+ const slot = def.inputs.findIndex((d) => d.name === widgetName);
288
+ if (slot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names io widget "${widgetName}" but no definition input matches`);
289
+ promoteToSlotTargets(slot, values[k]);
290
+ continue;
291
+ }
292
+ const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId));
293
+ if (target == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names unknown inner node ${String(pair[0])}`);
294
+ target.widgets.named[widgetName] = values[k];
295
+ }
296
+ return;
297
+ }
298
+ let valueIndex = 0;
299
+ for (const [slot, io] of def.inputs.entries()) {
300
+ const targets = boundaryTargetsByInSlot.get(slot) ?? [];
301
+ if (!(targets.length > 0 ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null) : PRIMITIVE_WIDGET_TYPES.has(io.type))) continue;
302
+ if (valueIndex >= values.length) break;
303
+ promoteToSlotTargets(slot, values[valueIndex++]);
304
+ }
305
+ };
306
+ const innerInputAt = (splicedNodes, t) => {
307
+ return splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot] ?? null;
308
+ };
309
+ //#endregion
310
+ //#region src/litegraph/LiteGraphGroup.ts
311
+ const LiteGraphGroup_ark = (0, arktype.type)({
312
+ "id?": "number",
313
+ title: "string",
314
+ bounding: (0, arktype.type)([
315
+ "number",
316
+ "number",
317
+ "number",
318
+ "number"
319
+ ]),
320
+ "color?": "string",
321
+ "font_size?": "number",
322
+ "flags?": arktype.type.Record("string", "unknown").as()
323
+ });
324
+ //#endregion
325
+ //#region src/litegraph/LiteGraphLink.ts
326
+ const LiteGraphLinkTuple_ark = (0, arktype.type)([
327
+ LiteGraphLinkID_,
328
+ "number",
329
+ "number",
330
+ "number",
331
+ "number",
332
+ "string"
333
+ ]);
334
+ const LiteGraphLinkObject_ark = (0, arktype.type)({
335
+ id: LiteGraphLinkID_,
336
+ origin_id: "number",
337
+ origin_slot: "number",
338
+ target_id: "number",
339
+ target_slot: "number",
340
+ type: "string",
341
+ "parentId?": "number"
342
+ });
343
+ const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark);
344
+ //#endregion
345
+ //#region src/litegraph/LiteGraphNodeInput.ts
346
+ const LiteGraphNodeInput_ark = (0, arktype.type)({
347
+ name: "string",
348
+ type: "string",
349
+ "link?": LiteGraphLinkID_.or(arktype.type.null),
350
+ "shape?": "number",
351
+ "label?": "string",
352
+ "widget?": (0, arktype.type)({
353
+ name: "string",
354
+ "config?": "unknown"
355
+ })
356
+ });
357
+ //#endregion
358
+ //#region src/litegraph/LiteGraphSlotIndex.ts
359
+ const asLiteGraphSlotIndex = (id) => id;
360
+ const LiteGraphSlotIndex_ = arktype.type.number.atLeast(0).as();
361
+ //#endregion
362
+ //#region src/litegraph/LiteGraphNodeOutput.ts
363
+ const LiteGraphNodeOutput_ark = (0, arktype.type)({
364
+ name: "string",
365
+ type: "string",
366
+ "links?": LiteGraphLinkID_.array().or(arktype.type.null),
367
+ "shape?": "number",
368
+ "slot_index?": LiteGraphSlotIndex_
369
+ });
370
+ //#endregion
371
+ //#region src/litegraph/LiteGraphNode.ts
372
+ const LiteGraphNode_ark = (0, arktype.type)({
373
+ id: "number",
374
+ type: "string",
375
+ "title?": "string",
376
+ "color?": "string",
377
+ "bgcolor?": "string",
378
+ pos: {
379
+ "0": "number",
380
+ "1": "number"
381
+ },
382
+ size: {
383
+ "0": "number",
384
+ "1": "number"
385
+ },
386
+ "flags?": arktype.type.Record("string", "unknown"),
387
+ "order?": "number",
388
+ "mode?": "number",
389
+ "inputs?": LiteGraphNodeInput_ark.array(),
390
+ "outputs?": LiteGraphNodeOutput_ark.array(),
391
+ "isVirtualNode?": "boolean",
392
+ "properties?": arktype.type.Record("string", "unknown"),
393
+ "widgets_values?": (0, arktype.type)("unknown[]").or(arktype.type.Record("string", "unknown"))
394
+ });
395
+ //#endregion
396
+ //#region src/litegraph/LiteGraphSubgraphDef.ts
397
+ const LiteGraphSubgraphIO_ark = (0, arktype.type)({
398
+ id: "string",
399
+ name: "string",
400
+ type: "string",
401
+ "linkIds?": LiteGraphLinkID_.array(),
402
+ "label?": "string",
403
+ "localized_name?": "string",
404
+ "pos?": {
405
+ "0": "number",
406
+ "1": "number"
407
+ },
408
+ "shape?": "number"
409
+ });
410
+ const LiteGraphSubgraphDef_ark = (0, arktype.type)({
411
+ id: "string",
412
+ name: "string",
413
+ version: "number",
414
+ "state?": arktype.type.Record("string", "unknown"),
415
+ "revision?": "number",
416
+ "config?": arktype.type.Record("string", "unknown").as(),
417
+ "extra?": "unknown",
418
+ nodes: LiteGraphNode_ark.array(),
419
+ links: LiteGraphLinkObject_ark.array(),
420
+ "groups?": LiteGraphGroup_ark.array(),
421
+ inputNode: {
422
+ id: "number",
423
+ bounding: "number[]"
424
+ },
425
+ outputNode: {
426
+ id: "number",
427
+ bounding: "number[]"
428
+ },
429
+ inputs: LiteGraphSubgraphIO_ark.array(),
430
+ outputs: LiteGraphSubgraphIO_ark.array(),
431
+ widgets: "unknown[]"
432
+ });
433
+ //#endregion
434
+ //#region src/litegraph/LiteGraphJSON.ts
435
+ const LiteGraphJSON_ark = (0, arktype.type)({
436
+ "id?": "string",
437
+ "revision?": "number",
438
+ "last_node_id?": "number",
439
+ "last_link_id?": "number",
440
+ "state?": arktype.type.Record("string", "unknown"),
441
+ nodes: LiteGraphNode_ark.array(),
442
+ links: LiteGraphLink_ark.array(),
443
+ "groups?": LiteGraphGroup_ark.array(),
444
+ "config?": arktype.type.Record("never", "never"),
445
+ "extra?": { "ds?": {
446
+ scale: "number",
447
+ offset: {
448
+ "0": "number",
449
+ "1": "number"
450
+ }
451
+ } },
452
+ "models?": "unknown[]",
453
+ "definitions?": { subgraphs: LiteGraphSubgraphDef_ark.array() },
454
+ "reroutes?": "unknown[]",
455
+ "floatingLinks?": "unknown[]",
456
+ version: "0.4 | 1"
457
+ });
458
+ //#endregion
459
+ //#region src/litegraph/normalizeWorkflow.ts
460
+ /** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */
461
+ var WorkflowNormalizeError = class extends Error {
462
+ constructor(code, message, detail) {
463
+ super(`[workflow ${code}] ${message}`);
464
+ this.code = code;
465
+ this.detail = detail;
466
+ this.name = "WorkflowNormalizeError";
467
+ }
468
+ };
469
+ /**
470
+ * THE one entry for foreign workflow JSON (files, clipboard, imports):
471
+ * tolerant ark validation, then normalization to the strict canonical shape.
472
+ */
473
+ const parseWorkflowJson = (json) => {
474
+ const out = LiteGraphJSON_ark(json);
475
+ if (out instanceof arktype.type.errors) throw new WorkflowNormalizeError("schema-reject", out.summary, out);
476
+ return normalizeWorkflow(out);
477
+ };
478
+ /**
479
+ * loose wire document → strict canonical document. Defaults filled, both link
480
+ * eras unified, cosmetic fields dropped, subgraph definitions expanded away
481
+ * (see expandSubgraphs.ts — def interiors go through the SAME per-shape
482
+ * normalizers, they are v1 bodies).
483
+ */
484
+ const normalizeWorkflow = (raw) => {
485
+ const wf = {
486
+ nodes: raw.nodes.map(normalizeNode),
487
+ links: raw.links.map(normalizeLink),
488
+ groups: (raw.groups ?? []).map(normalizeGroup)
489
+ };
490
+ const rawDefs = raw.definitions?.subgraphs ?? [];
491
+ if (rawDefs.length === 0) return wf;
492
+ const defs = /* @__PURE__ */ new Map();
493
+ for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d));
494
+ return expandSubgraphs(wf, defs);
495
+ };
496
+ const normalizeSubgraphDef = (d) => {
497
+ return {
498
+ id: d.id,
499
+ name: d.name,
500
+ inputs: d.inputs.map((io) => ({
501
+ name: io.name,
502
+ type: io.type
503
+ })),
504
+ outputs: d.outputs.map((io) => ({
505
+ name: io.name,
506
+ type: io.type
507
+ })),
508
+ nodes: d.nodes.map(normalizeNode),
509
+ links: d.links.map(normalizeLink)
510
+ };
511
+ };
512
+ const normalizeMode = (mode) => {
513
+ if (mode === 2) return "muted";
514
+ if (mode === 4) return "bypassed";
515
+ return "normal";
516
+ };
517
+ const normalizeNode = (n) => {
518
+ return {
519
+ id: n.id,
520
+ type: n.type,
521
+ title: n.title ?? null,
522
+ mode: normalizeMode(n.mode),
523
+ isVirtualNode: n.isVirtualNode ?? false,
524
+ inputs: (n.inputs ?? []).map(normalizeInput),
525
+ outputs: (n.outputs ?? []).map(normalizeOutput),
526
+ widgets: normalizeWidgetValues(n.widgets_values),
527
+ pos: [n.pos[0], n.pos[1]],
528
+ size: [n.size[0], n.size[1]],
529
+ properties: { ...n.properties }
530
+ };
531
+ };
532
+ const normalizeInput = (i) => {
533
+ return {
534
+ name: i.name,
535
+ type: i.type,
536
+ link: i.link ?? null,
537
+ widgetName: i.widget?.name ?? null
538
+ };
539
+ };
540
+ const normalizeOutput = (o) => {
541
+ return {
542
+ name: o.name,
543
+ type: o.type,
544
+ links: [...o.links ?? []]
545
+ };
546
+ };
547
+ const normalizeWidgetValues = (wv) => {
548
+ if (wv == null) return {
549
+ positional: [],
550
+ named: {}
551
+ };
552
+ if (Array.isArray(wv)) return {
553
+ positional: [...wv],
554
+ named: {}
555
+ };
556
+ return {
557
+ positional: [],
558
+ named: { ...wv }
559
+ };
560
+ };
561
+ const normalizeLink = (l) => {
562
+ if (Array.isArray(l)) return {
563
+ id: l[0],
564
+ originId: l[1],
565
+ originSlot: l[2],
566
+ targetId: l[3],
567
+ targetSlot: l[4],
568
+ type: l[5]
569
+ };
570
+ return {
571
+ id: l.id,
572
+ originId: l.origin_id,
573
+ originSlot: l.origin_slot,
574
+ targetId: l.target_id,
575
+ targetSlot: l.target_slot,
576
+ type: l.type
577
+ };
578
+ };
579
+ const normalizeGroup = (g) => {
580
+ return {
581
+ title: g.title,
582
+ bounding: [
583
+ g.bounding[0],
584
+ g.bounding[1],
585
+ g.bounding[2],
586
+ g.bounding[3]
587
+ ],
588
+ color: g.color ?? "#3f789e",
589
+ fontSize: g.font_size ?? 24
590
+ };
591
+ };
592
+ //#endregion
593
+ //#region src/runner/wsBinaryFrame.ts
594
+ function parseBinaryWsFrame(data) {
595
+ const view = new DataView(data);
596
+ const eventType = view.getUint32(0);
597
+ if (eventType === 1) {
598
+ const imageType = view.getUint32(4);
599
+ return {
600
+ kind: "preview",
601
+ bytes: new Uint8Array(data.slice(8)),
602
+ mime: imageType === 2 ? "image/png" : "image/jpeg",
603
+ metadata: null
604
+ };
605
+ }
606
+ if (eventType === 3) {
607
+ const nodeIdLen = view.getUint32(4);
608
+ const decoder = new TextDecoder();
609
+ return {
610
+ kind: "text",
611
+ nodeId: decoder.decode(data.slice(8, 8 + nodeIdLen)),
612
+ text: decoder.decode(data.slice(8 + nodeIdLen))
613
+ };
614
+ }
615
+ if (eventType === 4) {
616
+ const metadataLen = view.getUint32(4);
617
+ let metadata = null;
618
+ try {
619
+ metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)));
620
+ } catch {}
621
+ const bytes = new Uint8Array(data.slice(8 + metadataLen));
622
+ return {
623
+ kind: "preview",
624
+ bytes,
625
+ mime: bytes[0] === 137 && bytes[1] === 80 ? "image/png" : "image/jpeg",
626
+ metadata
627
+ };
628
+ }
629
+ return {
630
+ kind: "unknown",
631
+ eventType
632
+ };
633
+ }
43
634
  //#endregion
44
635
  //#region src/sdk-generator/Primitives.ts
45
636
  const ComfyPrimitiveMapping = {
@@ -50,20 +641,8 @@ const ComfyPrimitiveMapping = {
50
641
  };
51
642
  const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
52
643
  /**
53
- * when a litegraph node has no input for a given ComfyUI node input
54
- * (e.g. a seed or an enum that has not been turned into a primitive)
55
- */
56
- const howManyWidgetValuesForThisSchemaType = (input) => {
57
- if (input.typeName === "INT") {
58
- if (input.nameInComfy === "seed" || input.nameInComfy === "noise_seed") return 2;
59
- }
60
- if (input.isPrimitive) return 1;
61
- if (input.typeName.startsWith("E_")) return 1;
62
- return 0;
63
- };
64
- /**
65
- * then a litegraph node has an input entry, some convoluted logic seems to be necessary
66
- * to determine how many Field_values need to be consumed for this input
644
+ * when a litegraph node has an input entry with a widget marker, the
645
+ * serialized TYPE string decides how many widgets_values it consumed in that era
67
646
  */
68
647
  const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
69
648
  if (type === "INT") {
@@ -91,94 +670,448 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
91
670
  output_node: false,
92
671
  python_module: "nodes"
93
672
  };
94
- var UnknownCustomNode = class extends Error {
95
- constructor(node) {
96
- super(`❌ node ${node.id}(${node.type}) has no known schema; you probably need to install some custom node`);
97
- this.node = node;
673
+ //#endregion
674
+ //#region src/sdk-generator/inputWidgetKind.ts
675
+ const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
676
+ /**
677
+ * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
678
+ * The frontend creates the control widget on truthiness, and real 2026 hosts
679
+ * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
680
+ * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
681
+ * heuristic applies.
682
+ */
683
+ const controlConsumes = (o, typeName, name) => {
684
+ if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
685
+ if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
686
+ return 1;
687
+ };
688
+ const flattenInputSections = (inputs) => {
689
+ const out = [];
690
+ for (const section of ["required", "optional"]) {
691
+ const sec = inputs[section];
692
+ if (!isRecord(sec)) continue;
693
+ for (const [name, spec] of Object.entries(sec)) {
694
+ if (!Array.isArray(spec) || spec.length === 0) continue;
695
+ const t = spec[0];
696
+ if (typeof t !== "string" && !Array.isArray(t)) continue;
697
+ out.push({
698
+ name,
699
+ type: t,
700
+ opts: spec[1],
701
+ required: section === "required"
702
+ });
703
+ }
704
+ }
705
+ return out;
706
+ };
707
+ /** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
708
+ const parseDynamicOptions = (options) => {
709
+ if (options.length === 0) return null;
710
+ const out = [];
711
+ for (const entry of options) {
712
+ if (!isRecord(entry)) return null;
713
+ const key = entry["key"];
714
+ const inputs = entry["inputs"];
715
+ if (typeof key !== "string" || !isRecord(inputs)) return null;
716
+ out.push({
717
+ key,
718
+ inputs: flattenInputSections(inputs)
719
+ });
98
720
  }
721
+ return out;
722
+ };
723
+ /**
724
+ * autogrow (`template` WITH a nested `input` section): instances are always
725
+ * link slots named `decl.<name_i>` (the backend force-inputs widget
726
+ * templates), the first `min` of them required WHEN the template input
727
+ * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
728
+ */
729
+ const parseContainer = (template) => {
730
+ const input = template["input"];
731
+ const min = typeof template["min"] === "number" ? template["min"] : 1;
732
+ const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
733
+ const max = typeof template["max"] === "number" ? template["max"] : 100;
734
+ const rawNames = template["names"];
735
+ const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
736
+ return {
737
+ kind: "dynamic-container",
738
+ instanceNames: names,
739
+ requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
740
+ };
741
+ };
742
+ /**
743
+ * the single template sub-input's slot type of an autogrow container
744
+ * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
745
+ * autogrow template or the template has several sub-inputs (corpus-absent
746
+ * 2026-07-30, 27/27 single on the cloud catalog) — then codegen emits no
747
+ * typed instance keys and the container stays builderBase territory.
748
+ */
749
+ const containerInstanceSlotType = (opts) => {
750
+ const template = (isRecord(opts) ? opts : null)?.["template"];
751
+ if (!isRecord(template) || !isRecord(template["input"])) return null;
752
+ const subs = flattenInputSections(template["input"]);
753
+ const first = subs[0];
754
+ if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
755
+ return first.type;
756
+ };
757
+ const classifyWidgetInput = (p) => {
758
+ const o = isRecord(p.opts) ? p.opts : null;
759
+ if (o?.["forceInput"] === true) return { kind: "slot" };
760
+ if (Array.isArray(p.type) || p.isEnumUnion === true) {
761
+ const tn = typeof p.type === "string" ? p.type : "COMBO";
762
+ return {
763
+ kind: "widget",
764
+ consumes: controlConsumes(o, tn, p.name),
765
+ strictValues: true
766
+ };
767
+ }
768
+ if (typeof p.type !== "string") return { kind: "slot" };
769
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
770
+ if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
771
+ kind: "widget",
772
+ consumes: controlConsumes(o, widgetTypeName, p.name),
773
+ strictValues: true
774
+ };
775
+ const options = o?.["options"];
776
+ if (Array.isArray(options)) {
777
+ const dynOptions = parseDynamicOptions(options);
778
+ if (dynOptions != null) {
779
+ const first = dynOptions[0];
780
+ if (first == null) return { kind: "slot" };
781
+ return {
782
+ kind: "dynamic-combo",
783
+ options: dynOptions,
784
+ defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
785
+ };
786
+ }
787
+ return {
788
+ kind: "widget",
789
+ consumes: controlConsumes(o, p.type, p.name),
790
+ strictValues: true
791
+ };
792
+ }
793
+ const template = o?.["template"];
794
+ if (isRecord(template)) {
795
+ if (isRecord(template["input"])) return parseContainer(template);
796
+ return { kind: "slot" };
797
+ }
798
+ if (o?.["socketless"] === true) return {
799
+ kind: "widget",
800
+ consumes: 1,
801
+ strictValues: false
802
+ };
803
+ return { kind: "slot" };
804
+ };
805
+ const classifySchemaInput = (input) => classifyWidgetInput({
806
+ name: input.nameInComfy,
807
+ type: input.typeName,
808
+ opts: input.opts,
809
+ isEnumUnion: input.isEnum
810
+ });
811
+ /** how many widgets_values entries this schema input consumes (export path + positional walks) */
812
+ const howManyWidgetValuesForThisSchemaType = (input) => {
813
+ const kind = classifySchemaInput(input);
814
+ return kind.kind === "widget" ? kind.consumes : 0;
815
+ };
816
+ /**
817
+ * what ComfyUI's frontend gives a widget created with no serialized value
818
+ * (`getWidgetDefaultValue` semantics), used when a positional array is
819
+ * shorter than the schema's widget list. `null` for custom widgets — the
820
+ * backend accepts an explicit null but errors on an ABSENT required key.
821
+ */
822
+ const defaultValueForWidget = (p) => {
823
+ const o = isRecord(p.opts) ? p.opts : null;
824
+ if (o != null && o["default"] !== void 0) return o["default"];
825
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
826
+ if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
827
+ if (widgetTypeName === "BOOLEAN") return false;
828
+ if (widgetTypeName === "STRING") return "";
829
+ const options = o?.["options"];
830
+ if (Array.isArray(options) && options.length > 0) {
831
+ const first = options[0];
832
+ if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
833
+ }
834
+ if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
835
+ return null;
99
836
  };
100
837
  //#endregion
101
838
  //#region src/sdk-generator/litegraphToApiRequestPayload.ts
839
+ /** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
840
+ var WorkflowConvertError = class extends Error {
841
+ constructor(code, message, node) {
842
+ super(`[workflow ${code}] ${message}`);
843
+ this.code = code;
844
+ this.node = node;
845
+ this.name = "WorkflowConvertError";
846
+ }
847
+ };
102
848
  /**
103
- * convert a saved ComfyUI workflow.json (litegraph format) into the api.json
104
- * (prompt format) ComfyUI's POST /prompt takes.
105
- * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes
106
- * unwrapped, primitives inlined into their consumers), widget-value offsets
107
- * (incl. the phantom `control_after_generate` value after seeds).
849
+ * closed set: frontend-only node types that NEVER execute. PrimitiveString /
850
+ * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.
851
+ */
852
+ const VIRTUAL_NODE_TYPES = /* @__PURE__ */ new Set([
853
+ "Note",
854
+ "MarkdownNote",
855
+ "Reroute",
856
+ "PrimitiveNode"
857
+ ]);
858
+ const isNeverExecuted = (node) => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type);
859
+ /** exact match, or `*` wildcard on either side (Reroute-style slots) */
860
+ /** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */
861
+ const linkTypeMatches = (a, b) => {
862
+ if (a === b || a === "*" || b === "*") return true;
863
+ if (!a.includes(",") && !b.includes(",")) return false;
864
+ const as = a.split(",");
865
+ const bs = b.split(",");
866
+ return as.some((x) => bs.includes(x));
867
+ };
868
+ /** what an inlined PrimitiveNode may contribute: scalar widget values only */
869
+ const isPromptScalar = (v) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean";
870
+ /**
871
+ * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)
872
+ * into the api.json (prompt format) ComfyUI's POST /prompt takes.
873
+ * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed
874
+ * nodes (mode 4: link resolution walks through to the first type-matching
875
+ * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes
876
+ * unwrapped, primitives inlined into their consumers), widget values both
877
+ * positional (with the phantom `control_after_generate` offset after seeds)
878
+ * and named (object-form widgets_values + subgraph promotion overrides —
879
+ * named wins, but a live link wins over both). Widget-ness is decided from
880
+ * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types
881
+ * (COMBO options, dynamic combos, autogrow containers, socketless customs)
882
+ * and 2024-era enums go through ONE classifier; a positional array shorter
883
+ * than the schema's widget list fills schema defaults, never throws
884
+ * (agent/architecture.md owns both decisions).
108
885
  */
109
886
  const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
110
887
  const prompt = {};
111
888
  const LOG = opts.verbose ? (...args) => console.log("[🔥] converter:", ...args) : () => {};
112
889
  const PRIMITIVE_VALUES = {};
113
- for (const node of workflow.nodes) if (node.type === "PrimitiveNode") {
114
- const widgetValues = node.widgets_values;
115
- if (widgetValues == null || widgetValues.length === 0) throw new Error(`PrimitiveNode#${node.id} has no widget values`);
116
- PRIMITIVE_VALUES[node.id] = widgetValues[0];
890
+ for (const node of workflow.nodes) {
891
+ if (node.type !== "PrimitiveNode") continue;
892
+ if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
893
+ else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
117
894
  }
118
895
  for (const node of workflow.nodes) {
119
- if (node.isVirtualNode) continue;
120
- if (node.mode === 2) continue;
121
- if (node.type === "Reroute") continue;
122
- if (node.type === "Note") continue;
123
- if (node.type === "PrimitiveNode") continue;
896
+ if (isNeverExecuted(node)) continue;
897
+ if (node.mode !== "normal") continue;
124
898
  const inputs = {};
125
- const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name));
899
+ const fieldNamesPresent = new Set(node.inputs.map((i) => i.name));
126
900
  const nodeSchema_ = schema.nodesByNameInComfy[node.type];
127
- if (nodeSchema_ == null) throw new UnknownCustomNode(node);
901
+ if (nodeSchema_ == null) throw new WorkflowConvertError("unknown-node", `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`, node);
128
902
  const nodeSchema = nodeSchema_;
129
903
  let offset = 0;
130
- const inputsInNodeJSON = node.inputs ?? [];
904
+ const positional = node.widgets.positional;
905
+ const named = node.widgets.named;
906
+ const widgetFallback = /* @__PURE__ */ new Map();
907
+ const inputsInNodeJSON = node.inputs;
131
908
  const inputsInNodeSchema = nodeSchema.inputs;
909
+ /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */
910
+ const toPromptValue = (value, p) => {
911
+ if (value == null) return null;
912
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
913
+ if (Array.isArray(value)) return { __value__: value };
914
+ if (!p.strict && isRecord(value)) return value;
915
+ throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
916
+ };
917
+ /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
918
+ const resolveWidgetValue = (p) => {
919
+ let value;
920
+ let has = false;
921
+ if (Object.hasOwn(named, p.promptName)) {
922
+ value = named[p.promptName];
923
+ has = true;
924
+ } else if (offset < positional.length) {
925
+ value = positional[offset];
926
+ has = true;
927
+ }
928
+ if (positional.length > 0) offset += p.consumes;
929
+ return {
930
+ value,
931
+ filled: !has
932
+ };
933
+ };
934
+ const consumePlainWidget = (p) => {
935
+ const r = resolveWidgetValue({
936
+ promptName: p.promptName,
937
+ consumes: p.consumes
938
+ });
939
+ const raw = r.filled ? defaultValueForWidget({
940
+ type: p.typeName,
941
+ opts: p.opts,
942
+ enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values
943
+ }) : r.value;
944
+ const value = toPromptValue(raw, {
945
+ promptName: p.promptName,
946
+ strict: p.strict
947
+ });
948
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`);
949
+ if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value);
950
+ else inputs[p.promptName] = value;
951
+ };
952
+ /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
953
+ const consumeDynamicCombo = (p) => {
954
+ const r = resolveWidgetValue({
955
+ promptName: p.path,
956
+ consumes: 1
957
+ });
958
+ const key = r.filled ? p.defaultKey : r.value;
959
+ if (typeof key !== "string") throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): dynamic combo "${p.path}" key is not a string: ${JSON.stringify(key)}`, node);
960
+ const opt = p.options.find((o) => o.key === key);
961
+ if (opt == null) throw new WorkflowConvertError("unknown-dynamic-combo-option", `node ${node.id}(${node.type}): "${key}" is not an option of dynamic combo "${p.path}" (options: ${p.options.map((o) => o.key).join(", ")})`, node);
962
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`);
963
+ inputs[p.path] = key;
964
+ for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
965
+ };
966
+ const consumeBranchInput = (subPath, sub) => {
967
+ const kind = classifyWidgetInput({
968
+ name: sub.name,
969
+ type: sub.type,
970
+ opts: sub.opts
971
+ });
972
+ if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
973
+ if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
974
+ path: subPath,
975
+ options: kind.options,
976
+ defaultKey: kind.defaultKey
977
+ });
978
+ const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
979
+ consumePlainWidget({
980
+ promptName: subPath,
981
+ typeName: typeof sub.type === "string" ? sub.type : "COMBO",
982
+ opts: sub.opts,
983
+ consumes: kind.consumes,
984
+ strict: kind.strictValues,
985
+ enumValues: inlineEnum,
986
+ linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
987
+ });
988
+ };
132
989
  for (const field of inputsInNodeSchema) {
133
990
  const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy);
134
- const MUST_CONSUME = input?.type ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) : howManyWidgetValuesForThisSchemaType(field);
135
- if (MUST_CONSUME > 0) {
136
- if (node.widgets_values == null) throw new Error(`node ${node.id}(${node.type}) has no widgets_values but "${field.nameInComfy}" needs one`);
137
- if (node.widgets_values.length < offset + 1) throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for "${field.nameInComfy}"`);
138
- const _value = node.widgets_values[offset];
139
- LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`);
140
- if (!isValidValue(_value)) throw new Error(`node ${node.id}(${node.type}) has an invalid widget value for "${field.nameInComfy}": ${JSON.stringify(_value)}`);
141
- inputs[field.nameInComfy] = _value;
142
- offset += MUST_CONSUME;
143
- } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {
144
- if (field.required) throw new Error(`node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`);
991
+ let kind = classifySchemaInput(field);
992
+ if (kind.kind === "slot" && input?.widgetName != null) kind = {
993
+ kind: "widget",
994
+ consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
995
+ strictValues: true
996
+ };
997
+ if (kind.kind === "widget") consumePlainWidget({
998
+ promptName: field.nameInComfy,
999
+ typeName: field.typeName,
1000
+ opts: field.opts,
1001
+ consumes: kind.consumes,
1002
+ strict: kind.strictValues,
1003
+ linkedInput: input
1004
+ });
1005
+ else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1006
+ path: field.nameInComfy,
1007
+ options: kind.options,
1008
+ defaultKey: kind.defaultKey
1009
+ });
1010
+ else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1011
+ const iname = `${field.nameInComfy}.${instName}`;
1012
+ if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
1013
+ }
1014
+ else if (!fieldNamesPresent.has(field.nameInComfy)) {
1015
+ if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
145
1016
  }
146
1017
  }
147
1018
  const getParentNode = (linkId) => {
148
- const link = workflow.links.find((link) => link[0] === linkId);
149
- if (link == null) throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`);
150
- const parentId = link[1];
151
- const parentNode = workflow.nodes.find((n) => n.id === parentId);
152
- if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`);
1019
+ const link = workflow.links.find((link) => link.id === linkId);
1020
+ if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
1021
+ const parentNode = workflow.nodes.find((n) => n.id === link.originId);
1022
+ if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
153
1023
  return {
154
1024
  node: parentNode,
155
1025
  link
156
1026
  };
157
1027
  };
158
- INPT: for (const ipt of node.inputs ?? []) {
159
- if (howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0) continue;
1028
+ const pickBypassInput = (p) => {
1029
+ const sameSlot = p.inputs[p.outSlot];
1030
+ if (p.consumerType === "*" || p.consumerType === "") return sameSlot ?? p.inputs[0] ?? null;
1031
+ if (sameSlot != null && linkTypeMatches(sameSlot.type, p.outputType) && linkTypeMatches(sameSlot.type, p.consumerType)) return sameSlot;
1032
+ const exact = p.inputs.find((i) => i.type === p.consumerType);
1033
+ if (exact != null) return exact;
1034
+ return p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ?? null;
1035
+ };
1036
+ const resolveThroughParents = (startLink, consumerType) => {
1037
+ const visited = /* @__PURE__ */ new Set();
1038
+ let linkId = startLink;
1039
+ let effectiveType = consumerType;
1040
+ while (true) {
1041
+ const parent = getParentNode(linkId);
1042
+ if (visited.has(parent.node.id)) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`, node);
1043
+ visited.add(parent.node.id);
1044
+ if (parent.node.type === "Reroute") {
1045
+ const rerouteIn = parent.node.inputs[0]?.link;
1046
+ if (rerouteIn == null) return {
1047
+ kind: "unconnected",
1048
+ reason: "reroute chain ends on an empty slot"
1049
+ };
1050
+ linkId = rerouteIn;
1051
+ continue;
1052
+ }
1053
+ if (parent.node.mode === "muted") return {
1054
+ kind: "unconnected",
1055
+ reason: `parent ${parent.node.id}(${parent.node.type}) is muted`
1056
+ };
1057
+ if (parent.node.mode === "bypassed") {
1058
+ const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type;
1059
+ const through = pickBypassInput({
1060
+ inputs: parent.node.inputs,
1061
+ outSlot: parent.link.originSlot,
1062
+ outputType,
1063
+ consumerType: effectiveType
1064
+ });
1065
+ if (through?.link == null) return {
1066
+ kind: "unconnected",
1067
+ reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`
1068
+ };
1069
+ linkId = through.link;
1070
+ effectiveType = through.type;
1071
+ continue;
1072
+ }
1073
+ if (parent.node.type === "PrimitiveNode") {
1074
+ if (!(parent.node.id in PRIMITIVE_VALUES)) return {
1075
+ kind: "unconnected",
1076
+ reason: `PrimitiveNode#${parent.node.id} has no widget value`
1077
+ };
1078
+ return {
1079
+ kind: "primitive",
1080
+ nodeId: parent.node.id
1081
+ };
1082
+ }
1083
+ return {
1084
+ kind: "link",
1085
+ nodeId: parent.node.id,
1086
+ slot: parent.link.originSlot
1087
+ };
1088
+ }
1089
+ };
1090
+ for (const ipt of node.inputs) {
160
1091
  if (ipt.link == null) {
161
- LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`);
1092
+ LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`);
162
1093
  continue;
163
1094
  }
164
- let parent = getParentNode(ipt.link);
165
- let max = 100;
166
- while (parent != null && parent.node.type === "Reroute" && max-- > 0) {
167
- const firstParentInput = parent.node.inputs?.[0];
168
- if (firstParentInput?.link == null) {
169
- LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`);
170
- continue INPT;
171
- }
172
- parent = getParentNode(firstParentInput.link);
1095
+ const resolved = resolveThroughParents(ipt.link, ipt.type);
1096
+ if (resolved.kind === "primitive") {
1097
+ const pv = PRIMITIVE_VALUES[resolved.nodeId];
1098
+ if (!isPromptScalar(pv)) throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`, node);
1099
+ inputs[ipt.name] = pv;
1100
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`);
1101
+ continue;
1102
+ }
1103
+ if (resolved.kind === "link") {
1104
+ LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`);
1105
+ inputs[ipt.name] = [String(resolved.nodeId), resolved.slot];
1106
+ continue;
173
1107
  }
174
- if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`);
175
- if (parent.node.type === "PrimitiveNode") {
176
- inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id];
177
- LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`);
1108
+ if (widgetFallback.has(ipt.name)) {
1109
+ inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null;
1110
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`);
178
1111
  continue;
179
1112
  }
180
- LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`);
181
- inputs[ipt.name] = [String(parent.node.id), parent.link[2]];
1113
+ if (inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)?.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${ipt.name}" resolves unconnected (${resolved.reason}) and no widget value covers it`, node);
1114
+ LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`);
182
1115
  }
183
1116
  prompt[String(node.id)] = {
184
1117
  inputs,
@@ -187,14 +1120,6 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
187
1120
  }
188
1121
  return prompt;
189
1122
  };
190
- function isValidValue(value) {
191
- if (value == null) return true;
192
- if (typeof value === "string") return true;
193
- if (typeof value === "number") return true;
194
- if (typeof value === "boolean") return true;
195
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number") return true;
196
- return false;
197
- }
198
1123
  //#endregion
199
1124
  //#region src/errors/InvalidPromptError.ts
200
1125
  var InvalidPromptError = class extends Error {
@@ -341,7 +1266,7 @@ var ComfyNode = class ComfyNode {
341
1266
  for (const i of this.$schema.inputs) {
342
1267
  _done.add(i.nameInComfy);
343
1268
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
344
- inputs[i.nameInComfy] = value;
1269
+ if (value !== void 0) inputs[i.nameInComfy] = value;
345
1270
  }
346
1271
  for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {
347
1272
  if (_done.has(nameInComfy)) continue;
@@ -543,24 +1468,6 @@ var ComfyWorkflowBuilder = class {
543
1468
  }
544
1469
  };
545
1470
  //#endregion
546
- //#region src/utils/bang.ts
547
- /** assertNotNull */
548
- const bang = (x, msg = "") => {
549
- if (x == null) {
550
- console.error(`[🔴] BANG FAILED`, msg);
551
- throw new Error("bang: " + (msg ?? "no message"));
552
- }
553
- return x;
554
- };
555
- //#endregion
556
- //#region src/litegraph/LiteGraphLinkID.ts
557
- const asLiteGraphLinkID = (id) => id;
558
- arktype.type.number.atLeast(0).as();
559
- //#endregion
560
- //#region src/litegraph/LiteGraphSlotIndex.ts
561
- const asLiteGraphSlotIndex = (id) => id;
562
- arktype.type.number.atLeast(0).as();
563
- //#endregion
564
1471
  //#region src/litegraph/convertFlowToLiteGraphJSON.ts
565
1472
  const convertFlowToLiteGraphJSON = (graph) => {
566
1473
  const ctx = new LiteGraphCtx(graph);
@@ -573,7 +1480,7 @@ const convertFlowToLiteGraphJSON = (graph) => {
573
1480
  const n = xx.liteGraphNode;
574
1481
  n.pos[0] = bang(xx.comfyNode.x);
575
1482
  n.pos[1] = bang(xx.comfyNode.y);
576
- for (const o of n.outputs) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
1483
+ for (const o of n.outputs ?? []) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
577
1484
  }
578
1485
  return {
579
1486
  last_node_id,
@@ -1058,7 +1965,7 @@ var ComfyExecution = class {
1058
1965
  const promptNode = this.workflow.data.apiJson?.[promptNodeID];
1059
1966
  const promptMeta = this.workflow.data.metadata?.[promptNodeID];
1060
1967
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
1061
- const imgUrl = this.host.getServerHostHTTP() + "/view?" + new URLSearchParams(comfyImageInfo).toString();
1968
+ const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
1062
1969
  const sf = this.saveFormat;
1063
1970
  let absPath = comfyts.resolveFromOutput((0, pathe.join)(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
1064
1971
  if (sf?.format && sf.format !== "raw") {
@@ -1068,10 +1975,7 @@ var ComfyExecution = class {
1068
1975
  (0, node_fs.mkdirSync)((0, pathe.dirname)(absPath), { recursive: true });
1069
1976
  let img;
1070
1977
  if (sf && sf.format !== "raw") {
1071
- const buff = await (await fetch(imgUrl, {
1072
- headers: { "Content-Type": "image/png" },
1073
- method: "GET"
1074
- })).arrayBuffer();
1978
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1075
1979
  let textChunk = {};
1076
1980
  try {
1077
1981
  const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
@@ -1094,10 +1998,7 @@ var ComfyExecution = class {
1094
1998
  }
1095
1999
  });
1096
2000
  } else {
1097
- const buff = await (await fetch(imgUrl, {
1098
- headers: { "Content-Type": "image/png" },
1099
- method: "GET"
1100
- })).arrayBuffer();
2001
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1101
2002
  const uint8arr = new Uint8Array(buff);
1102
2003
  (0, node_fs.writeFileSync)(absPath, uint8arr);
1103
2004
  img = new MediaImage({
@@ -1469,9 +2370,9 @@ var ComfyWorkflow = class {
1469
2370
  comfy_ts_version: comfyts.version
1470
2371
  } }
1471
2372
  };
1472
- const promptEndpoint = `${this.host.getServerHostHTTP()}/prompt`;
1473
- const res = await fetch(promptEndpoint, {
2373
+ const res = await this.host.fetch("/prompt", {
1474
2374
  method: "POST",
2375
+ headers: { "Content-Type": "application/json" },
1475
2376
  body: JSON.stringify(out)
1476
2377
  });
1477
2378
  const promptInfo = softValidate(PromptInfo_ark, await res.json());
@@ -1742,6 +2643,15 @@ function codegenSDK(opts) {
1742
2643
  for (const n of nodes) {
1743
2644
  p(`${escapeJSKey(n.nodeKey)}: {`);
1744
2645
  for (const i of n.inputs) {
2646
+ const kind = classifySchemaInput(i);
2647
+ if (kind.kind === "dynamic-container") {
2648
+ const instType = containerInstanceSlotType(i.opts);
2649
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
2650
+ const opt = ix >= kind.requiredCount ? "?" : "";
2651
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
2652
+ });
2653
+ continue;
2654
+ }
1745
2655
  const opts_ = typeof i.opts === "string" ? null : i.opts;
1746
2656
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
1747
2657
  const comboOptions = i.typeName === "COMBO" && Array.isArray(opts_?.options) ? opts_.options.filter((o) => typeof o === "string" || typeof o === "number" || typeof o === "boolean") : [];
@@ -2061,9 +2971,18 @@ var ComfySchema = class {
2061
2971
  comfyUnionDef: slotType
2062
2972
  }).unionName);
2063
2973
  else throw new Error(`invalid schema (${JSON.stringify(slotType)}) for input "${ipt.name}" in node "${nodeNameInComfy}" (type: ${typeof slotType}; expected: Array | string)`);
2974
+ const isAutogrowContainer = typeof slotType === "string" && classifyWidgetInput({
2975
+ name: ipt.name,
2976
+ type: slotType,
2977
+ opts: slotOpts
2978
+ }).kind === "dynamic-container";
2979
+ if (isAutogrowContainer) {
2980
+ const instType = containerInstanceSlotType(slotOpts);
2981
+ if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType));
2982
+ }
2064
2983
  node.inputs.push({
2065
2984
  slotName: inputSlotName,
2066
- required: ipt.required,
2985
+ required: ipt.required && !isAutogrowContainer,
2067
2986
  nameInComfy: inputNameInComfy,
2068
2987
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
2069
2988
  typeName: inputTypeName,
@@ -2337,8 +3256,7 @@ var ComfyManager = class {
2337
3256
  }
2338
3257
  };
2339
3258
  this.fetchPost = async (endpoint, body, validator) => {
2340
- const url = this.host.getServerHostHTTP() + endpoint;
2341
- const response = await fetch(url, {
3259
+ const response = await this.host.fetch(endpoint, {
2342
3260
  method: "POST",
2343
3261
  headers: { "Content-Type": "application/json" },
2344
3262
  body: JSON.stringify(body)
@@ -2349,16 +3267,14 @@ var ComfyManager = class {
2349
3267
  return status;
2350
3268
  };
2351
3269
  this.fetchGetJSON = async (endpoint, validator) => {
2352
- const url = this.host.getServerHostHTTP() + endpoint;
2353
- const response = await fetch(url);
3270
+ const response = await this.host.fetch(endpoint);
2354
3271
  if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
2355
3272
  const jsonResult = await response.json();
2356
3273
  if (validator) return softValidate(validator, jsonResult);
2357
3274
  return jsonResult;
2358
3275
  };
2359
3276
  this.fetchGetText = async (endopint) => {
2360
- const url = this.host.getServerHostHTTP() + endopint;
2361
- return await (await fetch(url)).text();
3277
+ return await (await this.host.fetch(endopint)).text();
2362
3278
  };
2363
3279
  }
2364
3280
  get registry() {
@@ -2376,11 +3292,10 @@ var ComfyManager = class {
2376
3292
  no();
2377
3293
  }
2378
3294
  if (abortCtrl) abortCtrl.abort();
2379
- const url = this.host.getServerHostHTTP();
2380
3295
  abortCtrl = new AbortController();
2381
3296
  try {
2382
3297
  console.log(` - trying...`);
2383
- await fetch(url, { signal: abortCtrl.signal });
3298
+ await this.host.fetch("/", { signal: abortCtrl.signal }, { apiPrefix: false });
2384
3299
  clearInterval(interval);
2385
3300
  yes(true);
2386
3301
  } catch {}
@@ -2418,8 +3333,7 @@ var ComfyUploader = class {
2418
3333
  if (p.type) form.set("type", p.type);
2419
3334
  if (p.override ?? true) form.set("override", "true");
2420
3335
  if (p.subfolder) form.set("subfolder", p.subfolder);
2421
- const uploadURL = this.host.getServerHostHTTP() + "/upload/image";
2422
- const resp = await fetch(uploadURL, {
3336
+ const resp = await this.host.fetch("/upload/image", {
2423
3337
  method: "POST",
2424
3338
  body: form
2425
3339
  });
@@ -2435,6 +3349,51 @@ var ComfyUploader = class {
2435
3349
  }
2436
3350
  };
2437
3351
  //#endregion
3352
+ //#region src/host/hostUrl.ts
3353
+ /** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
3354
+ function parseHostBase(p) {
3355
+ const hasLegacy = p.host != null || p.port != null || p.https != null;
3356
+ if (p.url != null && hasLegacy) throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`);
3357
+ if (p.url == null) {
3358
+ if (p.host == null || p.port == null) throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`);
3359
+ return {
3360
+ scheme: p.https ? "https" : "http",
3361
+ host: p.host,
3362
+ port: p.port,
3363
+ basePath: ""
3364
+ };
3365
+ }
3366
+ let parsed;
3367
+ try {
3368
+ parsed = new URL(p.url);
3369
+ } catch {
3370
+ throw new Error(`host '${p.id}': unparseable url '${p.url}'`);
3371
+ }
3372
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`);
3373
+ if (parsed.search !== "" || parsed.hash !== "") throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`);
3374
+ const scheme = parsed.protocol === "https:" ? "https" : "http";
3375
+ const port = parsed.port !== "" ? Number(parsed.port) : scheme === "https" ? 443 : 80;
3376
+ const basePath = parsed.pathname.replace(/\/+$/, "");
3377
+ return {
3378
+ scheme,
3379
+ host: parsed.hostname,
3380
+ port,
3381
+ basePath
3382
+ };
3383
+ }
3384
+ /** http(s) base, port omitted when it is the scheme default */
3385
+ function renderHttpBase(p) {
3386
+ return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3387
+ }
3388
+ /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3389
+ function renderWsUrl(p) {
3390
+ return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3391
+ }
3392
+ function renderPort(p) {
3393
+ const schemeDefault = p.scheme === "https" ? 443 : 80;
3394
+ return p.port === schemeDefault ? "" : `:${p.port}`;
3395
+ }
3396
+ //#endregion
2438
3397
  //#region src/host/ResilientWebsocket.ts
2439
3398
  var ResilientWebSocketClient = class {
2440
3399
  addInfo(msg) {
@@ -2479,7 +3438,7 @@ var ResilientWebSocketClient = class {
2479
3438
  this.addInfo("Previous WebSocket discarded");
2480
3439
  prevWS.close();
2481
3440
  }
2482
- const ws$1 = new ws.default(this.url);
3441
+ const ws$1 = new ws.default(this.url, { headers: this.options.headers?.() });
2483
3442
  ws$1.binaryType = "arraybuffer";
2484
3443
  this.currentWS = ws$1;
2485
3444
  if (this.options.onMessage) ws$1.onmessage = (event) => {
@@ -3023,7 +3982,73 @@ var SizeVar = class extends ComfyVar {
3023
3982
  return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
3024
3983
  }
3025
3984
  };
3026
- /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size */
3985
+ const DEFAULT_IMAGE_EXTENSIONS = [
3986
+ "png",
3987
+ "jpg",
3988
+ "jpeg",
3989
+ "webp",
3990
+ "gif"
3991
+ ];
3992
+ /** empty image var consumed at build time — typed so drivers surface it apart from real crashes */
3993
+ var ImageVarEmptyError = class extends Error {
3994
+ constructor(varName) {
3995
+ super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`);
3996
+ this.varName = varName;
3997
+ }
3998
+ };
3999
+ /** trim + expand a leading `~/` — every ImageVar write funnels through this */
4000
+ function expandUserPath(raw) {
4001
+ const trimmed = raw.trim();
4002
+ return trimmed.startsWith("~/") ? (0, pathe.join)((0, node_os.homedir)(), trimmed.slice(2)) : trimmed;
4003
+ }
4004
+ /**
4005
+ * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
4006
+ * drafts persist it verbatim (toJSON = the string), hand-editable in the
4007
+ * draft json. Empty = unset: outValue()/absPath() throw ImageVarEmptyError,
4008
+ * so a build never runs on a silent placeholder. The TUI opens the image
4009
+ * picker overlay for kind 'image'.
4010
+ */
4011
+ var ImageVar = class extends ComfyVar {
4012
+ constructor(defaultValue, opts = {}) {
4013
+ super(expandUserPath(defaultValue), opts.label);
4014
+ this.opts = opts;
4015
+ this.kind = "image";
4016
+ }
4017
+ /** what the picker lists (lowercase, no dots) */
4018
+ get extensions() {
4019
+ return this.opts.extensions ?? DEFAULT_IMAGE_EXTENSIONS;
4020
+ }
4021
+ set(value) {
4022
+ return super.set(expandUserPath(value));
4023
+ }
4024
+ parse(raw) {
4025
+ this.set(raw);
4026
+ return true;
4027
+ }
4028
+ isSet() {
4029
+ return this.value !== "";
4030
+ }
4031
+ emptyError() {
4032
+ return new ImageVarEmptyError(this.name ?? this.label ?? "image");
4033
+ }
4034
+ /** the ONE resolution helper: absolute kept as-is, relative resolved against opts.folder, else cwd */
4035
+ absPath() {
4036
+ if (!this.isSet()) throw this.emptyError();
4037
+ if ((0, pathe.isAbsolute)(this.value)) return this.value;
4038
+ return (0, pathe.resolve)(this.opts.folder ?? process.cwd(), this.value);
4039
+ }
4040
+ /** empty = unset: the build fails LOUD here (varValues calls outValue) */
4041
+ outValue() {
4042
+ if (!this.isSet()) throw this.emptyError();
4043
+ return this.value;
4044
+ }
4045
+ display() {
4046
+ if (!this.isSet()) return "(unset) pick a file";
4047
+ const home = (0, node_os.homedir)();
4048
+ return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
4049
+ }
4050
+ };
4051
+ /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */
3027
4052
  const v = {
3028
4053
  text: (defaultValue, label) => new TextVar(defaultValue, label),
3029
4054
  prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
@@ -3033,7 +4058,8 @@ const v = {
3033
4058
  toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
3034
4059
  choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
3035
4060
  loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
3036
- size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label)
4061
+ size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label),
4062
+ image: (defaultValue, opts = {}) => new ImageVar(defaultValue, opts)
3037
4063
  };
3038
4064
  function varValues(vars) {
3039
4065
  const out = {};
@@ -3057,7 +4083,10 @@ var DefinedWorkflow = class {
3057
4083
  this.lastWorkflow = null;
3058
4084
  this.lastExecution = null;
3059
4085
  this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
3060
- for (const [, varDef] of this.entries()) varDef.bindHost?.(this.host);
4086
+ for (const [key, varDef] of this.entries()) {
4087
+ varDef.name = key;
4088
+ varDef.bindHost?.(this.host);
4089
+ }
3061
4090
  }
3062
4091
  /** [name, var] pairs, for drivers that enumerate the knobs */
3063
4092
  entries() {
@@ -3089,6 +4118,17 @@ var DefinedWorkflow = class {
3089
4118
  };
3090
4119
  //#endregion
3091
4120
  //#region src/host/ComfyHost.ts
4121
+ /** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
4122
+ * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
4123
+ * (or plain rate limiting on non-cloud hosts). The key value never appears here. */
4124
+ var ComfyHostAuthError = class extends Error {
4125
+ constructor(code, hostId, message) {
4126
+ super(message);
4127
+ this.code = code;
4128
+ this.hostId = hostId;
4129
+ this.name = "ComfyHostAuthError";
4130
+ }
4131
+ };
3092
4132
  var ComfyHost = class {
3093
4133
  constructor(data) {
3094
4134
  this.data = data;
@@ -3144,7 +4184,48 @@ var ComfyHost = class {
3144
4184
  return this.manager.installPlugin(customNode);
3145
4185
  };
3146
4186
  this.getWSUrl = () => {
3147
- return `${this.data.https ? "wss" : "ws"}://${this.data.host}:${this.data.port}/ws`;
4187
+ return renderWsUrl(this.base);
4188
+ };
4189
+ this._apiPrefix = null;
4190
+ this.fetch = async (route, init = {}, p = {}) => {
4191
+ const base = this.getServerHostHTTP();
4192
+ const headers = new Headers(init.headers);
4193
+ for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v);
4194
+ const send = (prefixed) => fetch(`${base}${prefixed ? "/api" : ""}${route}`, {
4195
+ ...init,
4196
+ headers
4197
+ });
4198
+ const missed = (res) => res.status === 404 || res.status === 405;
4199
+ let res;
4200
+ if (p.apiPrefix === false) res = await send(false);
4201
+ else if (this._apiPrefix != null) {
4202
+ res = await send(this._apiPrefix);
4203
+ if (missed(res)) {
4204
+ const alt = await send(!this._apiPrefix);
4205
+ if (!missed(alt)) res = alt;
4206
+ }
4207
+ } else {
4208
+ res = await send(true);
4209
+ if (missed(res)) {
4210
+ const bare = await send(false);
4211
+ if (!missed(bare)) {
4212
+ this._apiPrefix = false;
4213
+ res = bare;
4214
+ }
4215
+ } else this._apiPrefix = true;
4216
+ }
4217
+ this.throwOnAuthError(res, route);
4218
+ return res;
4219
+ };
4220
+ this.fetchFile = async (route) => {
4221
+ const res = await this.fetch(route, { redirect: "manual" });
4222
+ if (res.status >= 300 && res.status < 400) {
4223
+ const location = res.headers.get("location");
4224
+ if (location == null) throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`);
4225
+ res.body?.cancel();
4226
+ return fetch(new URL(location, this.getServerHostHTTP()));
4227
+ }
4228
+ return res;
3148
4229
  };
3149
4230
  this.schemaRetrievalLogs = [];
3150
4231
  this.resetLog = () => {
@@ -3160,7 +4241,8 @@ var ComfyHost = class {
3160
4241
  return new DefinedWorkflow(this, spec);
3161
4242
  };
3162
4243
  this.importWorkflowJson = (json, p = {}) => {
3163
- const apiJson = convertLiteGraphToPrompt(this.schema, json);
4244
+ const canonical = parseWorkflowJson(json);
4245
+ const apiJson = convertLiteGraphToPrompt(this.schema, canonical);
3164
4246
  return this.importApiJson(apiJson, p);
3165
4247
  };
3166
4248
  this.importApiJson = (json, p = {}) => {
@@ -3200,13 +4282,12 @@ var ComfyHost = class {
3200
4282
  this.schemaUpdateResult = null;
3201
4283
  this._schemaFromCache = null;
3202
4284
  this.postJSON_ = async (route, body) => {
3203
- const base = this.getServerHostHTTP();
3204
- for (const url of [`${base}/api${route}`, `${base}${route}`]) if ((await fetch(url, {
4285
+ const res = await this.fetch(route, {
3205
4286
  method: "POST",
3206
4287
  headers: { "Content-Type": "application/json" },
3207
4288
  body: JSON.stringify(body)
3208
- })).ok) return;
3209
- throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`);
4289
+ });
4290
+ if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
3210
4291
  };
3211
4292
  this.clearQueue = () => {
3212
4293
  return this.postJSON_("/queue", { clear: true });
@@ -3215,7 +4296,7 @@ var ComfyHost = class {
3215
4296
  return this.postJSON_("/interrupt", {});
3216
4297
  };
3217
4298
  this.fetchRawLogs = async () => {
3218
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`);
4299
+ const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
3219
4300
  if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
3220
4301
  const json = await res.json();
3221
4302
  const checked = WsMsgLogsData_ark(json);
@@ -3226,25 +4307,23 @@ var ComfyHost = class {
3226
4307
  return json;
3227
4308
  };
3228
4309
  this.subscribeLogs = async (p) => {
3229
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {
4310
+ const res = await this.fetch("/internal/logs/subscribe", {
3230
4311
  method: "PATCH",
3231
4312
  headers: { "Content-Type": "application/json" },
3232
4313
  body: JSON.stringify({
3233
4314
  enabled: p.enabled,
3234
4315
  clientId: p.clientId
3235
4316
  })
3236
- });
4317
+ }, { apiPrefix: false });
3237
4318
  if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`);
3238
4319
  };
3239
4320
  this.fetchJSON_ = async (route) => {
3240
4321
  const base = this.getServerHostHTTP();
3241
- for (const url of [`${base}/api${route}`, `${base}${route}`]) {
3242
- const res = await fetch(url, { method: "GET" });
3243
- if (!res.ok) continue;
3244
- if (!(res.headers.get("content-type") ?? "").includes("json")) continue;
3245
- return await res.json();
3246
- }
3247
- throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`);
4322
+ const res = await this.fetch(route);
4323
+ if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`);
4324
+ const contentType = res.headers.get("content-type") ?? "";
4325
+ if (!contentType.includes("json")) throw new Error(`GET ${route} on ${base} answered '${contentType || "no content-type"}' instead of json`);
4326
+ return await res.json();
3248
4327
  };
3249
4328
  this.fetchAndUpdateSchema = async () => {
3250
4329
  try {
@@ -3287,7 +4366,9 @@ var ComfyHost = class {
3287
4366
  this.onSession = null;
3288
4367
  this.onLogs = null;
3289
4368
  this.comfySessionId = "temp";
4369
+ this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
3290
4370
  this.status = null;
4371
+ this.base = parseHostBase(this.data);
3291
4372
  /** folder where file related to the host config will be cached */
3292
4373
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
3293
4374
  if (!(0, node_fs.existsSync)(this.cacheFolder)) {
@@ -3313,7 +4394,19 @@ var ComfyHost = class {
3313
4394
  return value;
3314
4395
  }
3315
4396
  getServerHostHTTP() {
3316
- return `${this.data.https ? "https" : "http"}://${this.data.host}:${this.data.port}`;
4397
+ return renderHttpBase(this.base);
4398
+ }
4399
+ /** extra headers + X-API-Key, for every http request AND the ws upgrade */
4400
+ authHeaders() {
4401
+ const out = {};
4402
+ if (this.data.headers != null) Object.assign(out, this.data.headers);
4403
+ if (this.data.apiKey != null) out["X-API-Key"] = this.data.apiKey;
4404
+ return out;
4405
+ }
4406
+ throwOnAuthError(res, route) {
4407
+ if (res.status === 401) throw new ComfyHostAuthError(401, this.data.id, this.data.apiKey != null ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired` : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`);
4408
+ if (res.status === 402) throw new ComfyHostAuthError(402, this.data.id, `host '${this.data.id}': 402 on ${route} — insufficient credits`);
4409
+ if (res.status === 429) throw new ComfyHostAuthError(429, this.data.id, `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`);
3317
4410
  }
3318
4411
  get isConnected() {
3319
4412
  return this.ws?.isOpen ?? false;
@@ -3329,6 +4422,7 @@ var ComfyHost = class {
3329
4422
  this._readyReject = null;
3330
4423
  }
3331
4424
  async writeSDKToDisk() {
4425
+ if (this.data.sdkAutoWrite === false) return;
3332
4426
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
3333
4427
  if ((0, node_fs.existsSync)(this.sdkDTSPath) && (0, node_fs.readFileSync)(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
3334
4428
  await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
@@ -3375,6 +4469,7 @@ var ComfyHost = class {
3375
4469
  },
3376
4470
  onMessage: (e) => this.onMessage(e),
3377
4471
  url: () => this.getWSUrl(),
4472
+ headers: () => this.authHeaders(),
3378
4473
  onClose: () => {
3379
4474
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
3380
4475
  }
@@ -3388,8 +4483,16 @@ var ComfyHost = class {
3388
4483
  this._isUpdatingSchema = v;
3389
4484
  }
3390
4485
  /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
3391
- * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
4486
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once.
4487
+ * A MISSING cache degrades LOUDLY to the base types instead of failing the
4488
+ * module import (a fresh consumer project has no cache yet — the bundled
4489
+ * examples must still open in the TUI; run() fetches the real schema through
4490
+ * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
3392
4491
  loadSchemaFromCache() {
4492
+ if (this._schemaFromCache == null && !(0, node_fs.existsSync)(this.comfyJSONPath)) {
4493
+ logError(`no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`);
4494
+ return Promise.resolve();
4495
+ }
3393
4496
  this._schemaFromCache ??= (async () => {
3394
4497
  const object_info_json = comfyts.readJSON_(this.comfyJSONPath);
3395
4498
  const embeddings_json = comfyts.readJSON_(this.embeddingsPath, []);
@@ -3420,40 +4523,23 @@ var ComfyHost = class {
3420
4523
  onMessage(e) {
3421
4524
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
3422
4525
  if (e.data instanceof ArrayBuffer) {
3423
- const eventType = new DataView(e.data).getUint32(0);
3424
- const buffer = e.data.slice(4);
3425
- switch (eventType) {
3426
- case 1: {
3427
- const imageType = new DataView(e.data).getUint32(4);
3428
- let imageMime;
3429
- switch (imageType) {
3430
- case 1:
3431
- imageMime = "image/jpeg";
3432
- break;
3433
- case 2:
3434
- imageMime = "image/png";
3435
- break;
3436
- default:
3437
- imageMime = "image/jpeg";
3438
- break;
3439
- }
3440
- const imageBytes = buffer.slice(4);
3441
- const imageBlob = new Blob([imageBytes], { type: imageMime });
3442
- const imagePreview = URL.createObjectURL(imageBlob);
3443
- this.latentPreview = {
3444
- blob: imageBlob,
3445
- url: imagePreview,
3446
- receivedAt: Date.now(),
3447
- promptID: this.activePromptID
3448
- };
3449
- this.onLatentPreview?.({
3450
- bytes: new Uint8Array(imageBytes),
3451
- mime: imageMime,
3452
- promptID: this.activePromptID
3453
- });
3454
- break;
3455
- }
3456
- default: throw new Error(`Unknown binary websocket message of type ${eventType}`);
4526
+ const frame = parseBinaryWsFrame(e.data);
4527
+ if (frame.kind === "preview") {
4528
+ const imageBlob = new Blob([frame.bytes], { type: frame.mime });
4529
+ this.latentPreview = {
4530
+ blob: imageBlob,
4531
+ url: URL.createObjectURL(imageBlob),
4532
+ receivedAt: Date.now(),
4533
+ promptID: this.activePromptID
4534
+ };
4535
+ this.onLatentPreview?.({
4536
+ bytes: frame.bytes,
4537
+ mime: frame.mime,
4538
+ promptID: this.activePromptID
4539
+ });
4540
+ } else if (frame.kind === "unknown" && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
4541
+ this._unknownBinaryFrameTypes.add(frame.eventType);
4542
+ console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`);
3457
4543
  }
3458
4544
  return;
3459
4545
  }
@@ -3558,31 +4644,19 @@ function downloadFile(url, outputPath, logPrefix = " - ") {
3558
4644
  }
3559
4645
  //#endregion
3560
4646
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
4647
+ const MANAGER_RAW_BASE = "https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main";
4648
+ const MANAGER_MIRROR_FILES = [
4649
+ "custom-node-list.json",
4650
+ "model-list.json",
4651
+ "extension-node-map.json",
4652
+ "alter-list.json",
4653
+ "github-stats.json"
4654
+ ];
3561
4655
  async function DownloadComfyManagerJSONs() {
3562
- await SYNC_modelList();
3563
- await SYNC_customNodeList();
3564
- await SYNC_extensionNodeMap();
3565
- await SYNC_alterList();
3566
- await SYNC_githubStats();
3567
- async function SYNC_modelList() {
3568
- await downloadFile("https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/model-list.json", "src/manager/json/model-list.json", `- downloading ynchronizing model-list.json...`);
3569
- console.log(` saved at ${ansi.blue("src/manager/json/model-list.json")}`);
3570
- }
3571
- async function SYNC_customNodeList() {
3572
- await downloadFile("https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json", "src/manager/json/custom-node-list.json", `- downloading synchronizing custom-node-list.json...`);
3573
- console.log(` saved at ${ansi.blue("src/manager/json/custom-node-list.json")}`);
3574
- }
3575
- async function SYNC_extensionNodeMap() {
3576
- await downloadFile("https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json", "src/manager/json/extension-node-map.json", `- downloading synchronizing extension-node-map.json...`);
3577
- console.log(` saved at ${ansi.blue("src/manager/json/extension-node-map.json")}`);
3578
- }
3579
- async function SYNC_alterList() {
3580
- await downloadFile("https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/alter-list.json", "src/manager/json/alter-list.json", `- downloading synchronizing alter-list.json...`);
3581
- console.log(` saved at ${ansi.blue("src/manager/json/alter-list.json")}`);
3582
- }
3583
- async function SYNC_githubStats() {
3584
- await downloadFile("https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/refs/heads/main/github-stats.json", "src/manager/json/github-stats.json", `- downloading ynchronizing githubStats.json...`);
3585
- console.log(` saved at ${ansi.blue("src/manager/json/github-stats.json")}`);
4656
+ for (const file of MANAGER_MIRROR_FILES) {
4657
+ const dest = `src/manager/json/${file}`;
4658
+ await downloadFile(`${MANAGER_RAW_BASE}/${file}`, dest, `- downloading ${file}...`);
4659
+ console.log(` saved at ${ansi.blue(dest)}`);
3586
4660
  }
3587
4661
  }
3588
4662
  //#endregion
@@ -3590,24 +4664,6 @@ async function DownloadComfyManagerJSONs() {
3590
4664
  const githubRegexpV1 = /https:\/\/github.com\/(.+?)\/(.+?)\/?/;
3591
4665
  const githubRegexpV2 = /https:\/\/github.com\/(.+?)\/([a-zA-Z0-9-_]+)?/;
3592
4666
  //#endregion
3593
- //#region src/utils/tryExtracting.ts
3594
- function tryRecovering({ verbose = 0, property, hacks, onFail, onSuccess }) {
3595
- if (verbose >= 2) console.log(`[🔶] trying to find a suitable value for ${property}...`);
3596
- for (const hack of hacks) {
3597
- if (verbose >= 2) console.log(` > trying to use ${hack.attempt}...`);
3598
- const value = hack.fn();
3599
- if (value != null) {
3600
- if (verbose >= (hack.level ?? 1)) {
3601
- if (verbose) console.log(` 🔶 recovered ${property} using ${hack.attempt}.`);
3602
- }
3603
- onSuccess?.(property, value);
3604
- return value;
3605
- }
3606
- }
3607
- onFail?.(property);
3608
- throw new Error(`[🔶] ${property} could not be recovered`);
3609
- }
3610
- //#endregion
3611
4667
  //#region src/manager/json/custom-node-list.extra.ts
3612
4668
  const ComfyPluginExtra = [{
3613
4669
  id: "TEMP_ComfyUI-BRIA_AI-RMBG",
@@ -3619,46 +4675,111 @@ const ComfyPluginExtra = [{
3619
4675
  description: "better rembg ?"
3620
4676
  }];
3621
4677
  //#endregion
4678
+ //#region src/manager/loaders/parseReport.ts
4679
+ /** root shape of a manager mirror file is broken: nothing to salvage, fail loud */
4680
+ var ManagerParseError = class extends Error {
4681
+ constructor(file, detail) {
4682
+ super(`🔴 [manager] ${file} root shape invalid: ${detail}`);
4683
+ this.file = file;
4684
+ this.detail = detail;
4685
+ this.name = "ManagerParseError";
4686
+ }
4687
+ };
4688
+ var FileParseCounter = class {
4689
+ constructor(file) {
4690
+ this.file = file;
4691
+ this.total = 0;
4692
+ this.accepted = 0;
4693
+ this.skipped = /* @__PURE__ */ new Map();
4694
+ }
4695
+ ok() {
4696
+ this.total++;
4697
+ this.accepted++;
4698
+ }
4699
+ skip(reason, firstError) {
4700
+ this.total++;
4701
+ const prev = this.skipped.get(reason);
4702
+ if (prev == null) this.skipped.set(reason, {
4703
+ count: 1,
4704
+ firstError
4705
+ });
4706
+ else prev.count++;
4707
+ }
4708
+ };
4709
+ /** per-file row accounting for the manager mirror parse; printed on every registry build so upstream drift stays visible */
4710
+ var ManagerParseReport = class {
4711
+ constructor() {
4712
+ this.counters = [];
4713
+ }
4714
+ file(name) {
4715
+ const counter = new FileParseCounter(name);
4716
+ this.counters.push(counter);
4717
+ return counter;
4718
+ }
4719
+ print() {
4720
+ console.log(ansi.bold(`[📘 registry] parse report:`));
4721
+ for (const c of this.counters) {
4722
+ const skippedTotal = [...c.skipped.values()].reduce((acc, cur) => acc + cur.count, 0);
4723
+ const headline = ` ${c.file}: ${c.total} rows, ${c.accepted} accepted, ${skippedTotal} skipped`;
4724
+ console.log(skippedTotal === 0 ? headline : ansi.red(headline));
4725
+ for (const [reason, info] of c.skipped) console.log(ansi.red(` - ${reason} x${info.count}, first: ${info.firstError}`));
4726
+ }
4727
+ }
4728
+ };
4729
+ //#endregion
4730
+ //#region src/manager/types/ComfyManagerFilePluginList.ts
4731
+ const ComfyManagerFilePluginListRoot_ark = (0, arktype.type)({ custom_nodes: "unknown[]" });
4732
+ //#endregion
3622
4733
  //#region src/manager/types/ComfyManagerPluginInfo.ts
3623
- const ComfyManagerPluginInfo_ark = (0, arktype.type)({
4734
+ const ComfyManagerRawPluginInfo_ark = (0, arktype.type)({
3624
4735
  author: "string",
3625
4736
  title: arktype.type.string.as(),
3626
4737
  reference: "string",
3627
4738
  files: arktype.type.string.as().array(),
3628
4739
  install_type: "string",
3629
4740
  description: "string",
3630
- id: arktype.type.string.as(),
4741
+ "id?": arktype.type.string.as(),
3631
4742
  "preemptions?": "string[]",
3632
4743
  "pip?": "string[]",
3633
4744
  "nodename_pattern?": "string",
3634
4745
  "apt_dependency?": "string[]",
3635
4746
  "js_path?": "string",
3636
4747
  "version?": "string",
3637
- "tags?": "string[]"
4748
+ "tags?": "string[]",
4749
+ "reference2?": "string",
4750
+ "category?": "string",
4751
+ "name?": "string",
4752
+ "license?": "string",
4753
+ "nickname?": "string",
4754
+ "stars?": "number",
4755
+ "last_update?": "string",
4756
+ "badges?": "string[]",
4757
+ "dependencies?": "string[]"
3638
4758
  });
3639
4759
  //#endregion
3640
- //#region src/manager/types/ComfyManagerFilePluginList.ts
3641
- const ComfyManagerFilePluginList_ark = (0, arktype.type)({ custom_nodes: ComfyManagerPluginInfo_ark.array() });
3642
- //#endregion
3643
4760
  //#region src/manager/loaders/step2_custom-node-list-loader.ts
3644
4761
  const _getKnownPlugins = (DB) => {
4762
+ const counter = DB.report.file("custom-node-list.json");
3645
4763
  let totalFileSeen = 0;
3646
- let totalPluginSeen = 0;
3647
- const knownPluginFile = JSON.parse((0, fs.readFileSync)("src/manager/json/custom-node-list.json", "utf8"));
3648
- const knownPluginList = knownPluginFile.custom_nodes.concat(ComfyPluginExtra);
3649
- for (const plugin of knownPluginList) {
3650
- plugin.id ??= tryRecoveringPluginId(plugin, 1);
3651
- plugin.title ??= tryRecoveringPluginTitle(plugin, 1);
3652
- }
3653
- const res = ComfyManagerFilePluginList_ark(knownPluginFile);
3654
- if (DB.opts.check) {
4764
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse((0, node_fs.readFileSync)("src/manager/json/custom-node-list.json", "utf8")));
4765
+ if (root instanceof arktype.type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4766
+ const canonical = [];
4767
+ for (const row of root.custom_nodes) {
4768
+ const res = ComfyManagerRawPluginInfo_ark(row);
3655
4769
  if (res instanceof arktype.type.errors) {
3656
- printArkResultInConsole(res);
3657
- process.exit(1);
4770
+ counter.skip("schema", res.summary);
4771
+ continue;
4772
+ }
4773
+ const plugin = normalizePluginInfo(res);
4774
+ if (plugin == null) {
4775
+ counter.skip("id-unrecoverable", res.reference);
4776
+ continue;
3658
4777
  }
4778
+ canonical.push(plugin);
4779
+ counter.ok();
3659
4780
  }
4781
+ const knownPluginList = canonical.concat(ComfyPluginExtra);
3660
4782
  for (const plugin of knownPluginList) {
3661
- totalPluginSeen++;
3662
4783
  if (DB.opts.check && DB.plugins_byTitle.has(plugin.title)) console.log(` ❌ plugin.title: "${plugin.title}" is duplicated`);
3663
4784
  DB.plugins_byTitle.set(plugin.title, plugin);
3664
4785
  for (const pluginURI of plugin.files) {
@@ -3669,7 +4790,7 @@ const _getKnownPlugins = (DB) => {
3669
4790
  }
3670
4791
  if (DB.opts.genTypes) {
3671
4792
  let out1 = "";
3672
- const allPluginsSortedByTitles = [...DB.plugins_byTitle.values()].sort((a, b) => (a.title ?? "❌missing-title").toLowerCase().localeCompare((b.title ?? "❌missing-title").toLowerCase()));
4793
+ const allPluginsSortedByTitles = [...DB.plugins_byTitle.values()].sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
3673
4794
  out1 += "// prettier-ignore\n";
3674
4795
  out1 += "export type KnownComfyPluginTitle =\n";
3675
4796
  for (const plugin of allPluginsSortedByTitles) {
@@ -3678,7 +4799,7 @@ const _getKnownPlugins = (DB) => {
3678
4799
  }
3679
4800
  out1 += "\n";
3680
4801
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
3681
- (0, fs.writeFileSync)(out1Path, out1 + "\n", "utf-8");
4802
+ (0, node_fs.writeFileSync)(out1Path, out1 + "\n", "utf-8");
3682
4803
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
3683
4804
  let out2 = "";
3684
4805
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -3686,47 +4807,33 @@ const _getKnownPlugins = (DB) => {
3686
4807
  out2 += "export type KnownComfyPluginURL =\n";
3687
4808
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
3688
4809
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
3689
- (0, fs.writeFileSync)(out2Path, out2, "utf-8");
4810
+ (0, node_fs.writeFileSync)(out2Path, out2, "utf-8");
3690
4811
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
3691
4812
  }
3692
4813
  if (DB.opts.check) {
3693
- console.log(` - ${totalPluginSeen} CustomNodes in file`);
4814
+ console.log(` - ${knownPluginList.length} CustomNodes in file`);
3694
4815
  console.log(` - ${DB.plugins_byTitle.size} CustomNodes registered in map`);
3695
4816
  console.log(` - ${totalFileSeen} CustomNodes-File Seen`);
3696
4817
  console.log(` - ${DB.plugins_byFile.size} CustomNodes-File registered in map`);
3697
4818
  }
3698
4819
  };
3699
- function tryRecoveringPluginTitle(plugin, verbose = 0) {
3700
- return tryRecovering({
3701
- property: "plugin.title",
3702
- verbose,
3703
- hacks: [{
3704
- attempt: "id",
3705
- fn: () => plugin.id
3706
- }, {
3707
- attempt: "github repo name",
3708
- fn: () => plugin.reference
3709
- }]
3710
- });
3711
- }
3712
- function tryRecoveringPluginId(plugin, verbose = 0) {
3713
- return tryRecovering({
3714
- property: "plugin.id",
3715
- verbose,
3716
- hacks: [{
3717
- level: 2,
3718
- attempt: "title",
3719
- fn: () => plugin.title
3720
- }, {
3721
- attempt: "github repo name",
3722
- fn: () => plugin.reference.match(githubRegexpV1)?.[2]
3723
- }]
3724
- });
4820
+ /**
4821
+ * raw → canonical: recover the missing `id` (absent on ~76% of upstream rows)
4822
+ * from the title, else the github repo name. null = unrecoverable, caller
4823
+ * reports and skips the row.
4824
+ */
4825
+ function normalizePluginInfo(p) {
4826
+ const id = p.id ?? p.title ?? p.reference.match(githubRegexpV1)?.[2];
4827
+ if (id == null) return null;
4828
+ return {
4829
+ ...p,
4830
+ id
4831
+ };
3725
4832
  }
3726
4833
  //#endregion
3727
4834
  //#region src/manager/types/ComfyManagerPluginContentMetadata.ts
3728
4835
  const ComfyManagerPluginContentMetadata_ark = (0, arktype.type)({
3729
- title_aux: arktype.type.string.or(arktype.type.null),
4836
+ "title_aux?": arktype.type.string.or(arktype.type.null),
3730
4837
  "author?": "string",
3731
4838
  "nickname?": "string",
3732
4839
  "description?": "string",
@@ -3740,42 +4847,37 @@ const ComfyManagerPluginContentNodeName_ark = arktype.type.string.as();
3740
4847
  (0, arktype.type)("string");
3741
4848
  //#endregion
3742
4849
  //#region src/manager/types/ComfyManagerFilePluginContent.ts
3743
- const ComfyManagerFilePluginContent_ark = arktype.type.Record("string", (0, arktype.type)([ComfyManagerPluginContentNodeName_ark.array(), ComfyManagerPluginContentMetadata_ark]));
4850
+ const ComfyManagerExtensionNodeMapEntry_ark = (0, arktype.type)([ComfyManagerPluginContentNodeName_ark.array(), ComfyManagerPluginContentMetadata_ark]);
3744
4851
  //#endregion
3745
4852
  //#region src/manager/loaders/step3_extension-node-map-loader.ts
3746
4853
  const _getCustomNodeRegistry = (DB) => {
4854
+ const counter = DB.report.file("extension-node-map.json");
3747
4855
  let totalCustomNodeSeen = 0;
3748
- const extensionNodeMapFile = JSON.parse((0, node_fs.readFileSync)("src/manager/json/extension-node-map.json", "utf8"));
3749
- const res = ComfyManagerFilePluginContent_ark(extensionNodeMapFile);
3750
- if (DB.opts.check) {
4856
+ const raw = JSON.parse((0, node_fs.readFileSync)("src/manager/json/extension-node-map.json", "utf8"));
4857
+ const root = (0, arktype.type)("Record<string, unknown>")(raw);
4858
+ if (root instanceof arktype.type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4859
+ for (const [url, value] of Object.entries(root)) {
4860
+ const res = ComfyManagerExtensionNodeMapEntry_ark(value);
3751
4861
  if (res instanceof arktype.type.errors) {
3752
- printArkResultInConsole(res);
3753
- process.exit(1);
4862
+ counter.skip("schema", `${url}: ${res.summary}`);
4863
+ continue;
3754
4864
  }
3755
- }
3756
- const enmEntries = Object.entries(extensionNodeMapFile).map((x) => {
3757
- const url = x[0];
3758
- const [comfyNodeNames, meta] = x[1];
3759
- const confyPlugin = DB.plugins_byFile.get(url);
3760
- if (confyPlugin == null) throw new Error(`[❌] plugin not found for ${url}`);
3761
- return {
3762
- url,
3763
- comfyNodeNames,
3764
- meta,
3765
- plugin: confyPlugin,
3766
- pythonModule: reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(confyPlugin, url, meta)
3767
- };
3768
- });
3769
- for (const enmEntry of enmEntries) {
3770
- totalCustomNodeSeen += enmEntry.comfyNodeNames.length;
3771
- const plugin = enmEntry.plugin;
4865
+ const plugin = DB.plugins_byFile.get(url);
4866
+ if (plugin == null) {
4867
+ counter.skip("unknown-plugin-url", url);
4868
+ continue;
4869
+ }
4870
+ counter.ok();
4871
+ const comfyNodeNames = res[0];
4872
+ totalCustomNodeSeen += comfyNodeNames.length;
4873
+ const pythonModule = reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin);
3772
4874
  const nodesInPlugin = DB.customNodes_byPluginName.get(plugin.title) ?? [];
3773
4875
  DB.customNodes_byPluginName.set(plugin.title, nodesInPlugin);
3774
- for (const nodeNameInComfy of enmEntry.comfyNodeNames) {
3775
- const nodeKey = toQualifiedNodeKey(enmEntry.pythonModule, nodeNameInComfy);
3776
- const prevEntry2 = DB.plugins_byNodeKey.get(nodeKey);
3777
- if (prevEntry2 == null) DB.plugins_byNodeKey.set(nodeKey, [plugin]);
3778
- else prevEntry2.push(plugin);
4876
+ for (const nodeNameInComfy of comfyNodeNames) {
4877
+ const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy);
4878
+ const prevEntry = DB.plugins_byNodeKey.get(nodeKey);
4879
+ if (prevEntry == null) DB.plugins_byNodeKey.set(nodeKey, [plugin]);
4880
+ else prevEntry.push(plugin);
3779
4881
  nodesInPlugin.push(nodeKey);
3780
4882
  }
3781
4883
  }
@@ -3784,23 +4886,22 @@ const _getCustomNodeRegistry = (DB) => {
3784
4886
  const sortedNodeKeys = [...DB.plugins_byNodeKey.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
3785
4887
  out += "// prettier-ignore\n";
3786
4888
  out += "export type KnownComfyCustomNodeName =\n";
3787
- for (const nodeName of sortedNodeKeys) {
3788
- if (nodeName === "sd_perturbed_attention.PerturbedAttention") console.log(`[🤠] 🔴`, DB.plugins_byNodeKey.get(nodeName));
3789
- out += ` | ${JSON.stringify(nodeName)}\n`;
3790
- }
4889
+ for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
3791
4890
  out += "\n";
3792
4891
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
3793
4892
  (0, node_fs.writeFileSync)(outPath, out + "\n", "utf-8");
3794
4893
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
3795
4894
  }
3796
- if (DB.opts.check) console.log(` - ${totalCustomNodeSeen} CustomNodes unique names processed`);
4895
+ if (DB.opts.check) {
4896
+ console.log(` - ${totalCustomNodeSeen} CustomNodes names processed`);
4897
+ console.log(` - ${DB.plugins_byNodeKey.size} unique node keys registered in map`);
4898
+ }
3797
4899
  };
3798
- function reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin, _url, _meta) {
4900
+ function reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin) {
3799
4901
  if (plugin.id === "nodes" && plugin.reference === "https://github.com/comfyanonymous/ComfyUI") return "nodes";
3800
4902
  const repoName = plugin.reference.match(githubRegexpV2)?.[2];
3801
4903
  if (repoName) return `custom_nodes.${repoName}`;
3802
- if (plugin.id) return `custom_nodes.${plugin.id}`;
3803
- return "🔴";
4904
+ return `custom_nodes.${plugin.id}`;
3804
4905
  }
3805
4906
  //#endregion
3806
4907
  //#region src/manager/json/model-list.extra.ts
@@ -3824,6 +4925,9 @@ const extraModels = { models: [{
3824
4925
  url: "https://huggingface.co/gemasai/4x_NMKD-Siax_200k/resolve/main/4xRealWebPhoto_v4_dat2.pth"
3825
4926
  }] };
3826
4927
  //#endregion
4928
+ //#region src/manager/types/ComfyManagerFileModelInfo.ts
4929
+ const ComfyManagerFileModelInfoRoot_ark = (0, arktype.type)({ models: "unknown[]" });
4930
+ //#endregion
3827
4931
  //#region src/manager/types/ComfyManagerModelInfo.ts
3828
4932
  const ComfyManagerModelInfo_ark = (0, arktype.type)({
3829
4933
  name: arktype.type.string.as(),
@@ -3839,20 +4943,21 @@ const ComfyManagerModelInfo_ark = (0, arktype.type)({
3839
4943
  //#endregion
3840
4944
  //#region src/manager/loaders/step4_model-list-loader.ts
3841
4945
  const _getKnownModels = (DB) => {
3842
- const knownModelList = JSON.parse((0, fs.readFileSync)("src/manager/json/model-list.json", "utf8")).models.concat(extraModels.models);
3843
- let hasErrors = false;
3844
- for (const modelInfo of knownModelList) {
3845
- DB.knownModels.set(modelInfo.name, modelInfo);
3846
- if (!hasErrors && DB.opts.check) {
3847
- const res = ComfyManagerModelInfo_ark(modelInfo);
3848
- if (res instanceof arktype.type.errors) {
3849
- const errors = res;
3850
- console.error(`❌ model doesn't match schema:`, modelInfo);
3851
- printArkResultInConsole(errors);
3852
- hasErrors = true;
3853
- }
4946
+ const counter = DB.report.file("model-list.json");
4947
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse((0, node_fs.readFileSync)("src/manager/json/model-list.json", "utf8")));
4948
+ if (root instanceof arktype.type.errors) throw new ManagerParseError("model-list.json", root.summary);
4949
+ const canonical = [];
4950
+ for (const row of root.models) {
4951
+ const res = ComfyManagerModelInfo_ark(row);
4952
+ if (res instanceof arktype.type.errors) {
4953
+ counter.skip("schema", res.summary);
4954
+ continue;
3854
4955
  }
4956
+ canonical.push(res);
4957
+ counter.ok();
3855
4958
  }
4959
+ const knownModelList = canonical.concat(extraModels.models);
4960
+ for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
3856
4961
  if (DB.opts.genTypes) {
3857
4962
  let out1 = "";
3858
4963
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -3868,7 +4973,7 @@ const _getKnownModels = (DB) => {
3868
4973
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
3869
4974
  out1 += "]\n";
3870
4975
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
3871
- (0, fs.writeFileSync)(out1Path, out1 + "\n", "utf-8");
4976
+ (0, node_fs.writeFileSync)(out1Path, out1 + "\n", "utf-8");
3872
4977
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
3873
4978
  let out4 = "";
3874
4979
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -3884,7 +4989,7 @@ const _getKnownModels = (DB) => {
3884
4989
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
3885
4990
  out4 += "]\n";
3886
4991
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
3887
- (0, fs.writeFileSync)(out4Path, out4 + "\n", "utf-8");
4992
+ (0, node_fs.writeFileSync)(out4Path, out4 + "\n", "utf-8");
3888
4993
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
3889
4994
  let out2 = "";
3890
4995
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -3901,7 +5006,7 @@ const _getKnownModels = (DB) => {
3901
5006
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
3902
5007
  out2 += "]\n";
3903
5008
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
3904
- (0, fs.writeFileSync)(out2Path, out2 + "\n", "utf-8");
5009
+ (0, node_fs.writeFileSync)(out2Path, out2 + "\n", "utf-8");
3905
5010
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
3906
5011
  let out3 = "";
3907
5012
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -3916,7 +5021,7 @@ const _getKnownModels = (DB) => {
3916
5021
  }
3917
5022
  out3 += "\n";
3918
5023
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
3919
- (0, fs.writeFileSync)(out3Path, out3 + "\n", "utf-8");
5024
+ (0, node_fs.writeFileSync)(out3Path, out3 + "\n", "utf-8");
3920
5025
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
3921
5026
  let out99 = "";
3922
5027
  out99 += `// prettier-ignore\n`;
@@ -3930,20 +5035,78 @@ const _getKnownModels = (DB) => {
3930
5035
  }
3931
5036
  out99 += "\n";
3932
5037
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
3933
- (0, fs.writeFileSync)(out99Path, out99 + "\n", "utf-8");
5038
+ (0, node_fs.writeFileSync)(out99Path, out99 + "\n", "utf-8");
3934
5039
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
3935
5040
  }
3936
5041
  if (DB.opts.check) {
3937
5042
  console.log(`${knownModelList.length} models found`);
3938
5043
  console.log(`${DB.knownModels.size} models registered map`);
3939
5044
  if (knownModelList.length !== DB.knownModels.size) console.log(`❌ some models are either duplicated or have overlapping indexing keys`);
3940
- if (hasErrors) console.log(`❌ some models don't match schema`);
3941
- else console.log(`✅ all models match schema`);
5045
+ }
5046
+ };
5047
+ //#endregion
5048
+ //#region src/manager/types/ComfyManagerAlterInfo.ts
5049
+ const ComfyManagerAlterInfo_ark = (0, arktype.type)({
5050
+ id: "string",
5051
+ tags: "string",
5052
+ description: "string"
5053
+ });
5054
+ const ComfyManagerFileAlterListRoot_ark = (0, arktype.type)({ items: "unknown[]" });
5055
+ //#endregion
5056
+ //#region src/manager/loaders/step5_alter-list-loader.ts
5057
+ const _getAlterList = (DB) => {
5058
+ const counter = DB.report.file("alter-list.json");
5059
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse((0, node_fs.readFileSync)("src/manager/json/alter-list.json", "utf8")));
5060
+ if (root instanceof arktype.type.errors) throw new ManagerParseError("alter-list.json", root.summary);
5061
+ const canonical = [];
5062
+ for (const row of root.items) {
5063
+ const res = ComfyManagerAlterInfo_ark(row);
5064
+ if (res instanceof arktype.type.errors) {
5065
+ counter.skip("schema", res.summary);
5066
+ continue;
5067
+ }
5068
+ canonical.push(res);
5069
+ counter.ok();
5070
+ }
5071
+ DB.alterations = canonical;
5072
+ };
5073
+ //#endregion
5074
+ //#region src/manager/types/ComfyManagerGithubStats.ts
5075
+ const ComfyManagerGithubStatEntry_ark = (0, arktype.type)({
5076
+ stars: "number",
5077
+ last_update: "string",
5078
+ author_account_age_days: "number"
5079
+ });
5080
+ //#endregion
5081
+ //#region src/manager/loaders/step6_github-stats-loader.ts
5082
+ const _getGithubStats = (DB) => {
5083
+ const counter = DB.report.file("github-stats.json");
5084
+ const raw = JSON.parse((0, node_fs.readFileSync)("src/manager/json/github-stats.json", "utf8"));
5085
+ const root = (0, arktype.type)("Record<string, unknown>")(raw);
5086
+ if (root instanceof arktype.type.errors) throw new ManagerParseError("github-stats.json", root.summary);
5087
+ for (const [url, value] of Object.entries(root)) {
5088
+ const res = ComfyManagerGithubStatEntry_ark(value);
5089
+ if (res instanceof arktype.type.errors) {
5090
+ counter.skip("schema", `${url}: ${res.summary}`);
5091
+ continue;
5092
+ }
5093
+ DB.githubStats.set(url, res);
5094
+ counter.ok();
3942
5095
  }
3943
5096
  };
3944
5097
  //#endregion
3945
5098
  //#region src/manager/ComfyRegistry.ts
3946
5099
  const log = (...args) => console.log(`[📘 registry]`, ...args);
5100
+ const BUILTIN_URL = "https://github.com/comfyanonymous/ComfyUI";
5101
+ const BUILTIN_PLUGIN = {
5102
+ id: "nodes",
5103
+ author: "comfyanonymous",
5104
+ description: "built-in",
5105
+ title: "built-in",
5106
+ files: [BUILTIN_URL],
5107
+ reference: "https://github.com/comfyanonymous/ComfyUI",
5108
+ install_type: ""
5109
+ };
3947
5110
  var ComfyRegistry = class ComfyRegistry {
3948
5111
  static async DownloadAndUpdate(download) {
3949
5112
  if (download) {
@@ -3963,6 +5126,9 @@ var ComfyRegistry = class ComfyRegistry {
3963
5126
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
3964
5127
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
3965
5128
  this.knownModels = /* @__PURE__ */ new Map();
5129
+ this.alterations = [];
5130
+ this.githubStats = /* @__PURE__ */ new Map();
5131
+ this.report = new ManagerParseReport();
3966
5132
  this.getKnownCheckpoints = () => {
3967
5133
  return [...this.knownModels.values()].filter((i) => i.type === "checkpoint");
3968
5134
  };
@@ -4002,21 +5168,19 @@ var ComfyRegistry = class ComfyRegistry {
4002
5168
  nix: isUnderPrefix ? nixPath.slice(nixPrefix.length) : mi.filename
4003
5169
  };
4004
5170
  };
4005
- this.plugins_byFile.set("https://github.com/comfyanonymous/ComfyUI", {
4006
- id: "nodes",
4007
- author: "comfyanonymous",
4008
- description: "built-in",
4009
- title: "built-in",
4010
- files: [],
4011
- reference: "https://github.com/comfyanonymous/ComfyUI",
4012
- install_type: ""
4013
- });
5171
+ this.plugins_byTitle.set(BUILTIN_PLUGIN.title, BUILTIN_PLUGIN);
5172
+ this.plugins_byFile.set(BUILTIN_URL, BUILTIN_PLUGIN);
4014
5173
  log(`loading src/manager/json/${ansi.yellow("custom-node-list.json")}...`);
4015
5174
  _getKnownPlugins(this);
4016
5175
  log(`loading src/manager/json/${ansi.yellow("extension-node-map.json")}...`);
4017
5176
  _getCustomNodeRegistry(this);
4018
5177
  log(`loading src/manager/json/${ansi.yellow("model-list.json")}...`);
4019
5178
  _getKnownModels(this);
5179
+ log(`loading src/manager/json/${ansi.yellow("alter-list.json")}...`);
5180
+ _getAlterList(this);
5181
+ log(`loading src/manager/json/${ansi.yellow("github-stats.json")}...`);
5182
+ _getGithubStats(this);
5183
+ this.report.print();
4020
5184
  }
4021
5185
  };
4022
5186
  //#endregion
@@ -4063,7 +5227,11 @@ var ComfyTS = class ComfyTS {
4063
5227
  host(data) {
4064
5228
  const existing = this.hosts.get(data.id);
4065
5229
  if (existing != null) {
4066
- if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https) throw new Error(`host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`);
5230
+ const incoming = parseHostBase(data);
5231
+ const cur = existing.base;
5232
+ const sameBase = cur.scheme === incoming.scheme && cur.host === incoming.host && cur.port === incoming.port && cur.basePath === incoming.basePath;
5233
+ const sameAuth = existing.data.apiKey == null === (data.apiKey == null);
5234
+ if (!sameBase || !sameAuth) throw new Error(`host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? " (authed)" : ""} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? " (authed)" : ""}`);
4067
5235
  return existing;
4068
5236
  }
4069
5237
  const created = new ComfyHost(data);
@@ -4104,6 +5272,52 @@ var ComfyTS = class ComfyTS {
4104
5272
  }
4105
5273
  };
4106
5274
  //#endregion
5275
+ //#region src/exampleAssets.ts
5276
+ /**
5277
+ * the examples/ folder shipped in the npm tarball, resolved from THIS module's
5278
+ * own location (NEVER cwd): walking up to the nearest NAMED package.json finds
5279
+ * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/ and from
5280
+ * this repo's src/. Returns null when the examples are absent (a consumer may
5281
+ * prune the folder) or when the nearest named package is not comfy-ts (the lib
5282
+ * was inlined into someone else's bundle — its examples are not on disk); no
5283
+ * package.json all the way up is a broken install and throws.
5284
+ */
5285
+ function bundledExamplesDir(moduleUrl = require("url").pathToFileURL(__filename).href) {
5286
+ let dir = (0, pathe.dirname)((0, node_url.fileURLToPath)(moduleUrl));
5287
+ let prev = "";
5288
+ while (dir !== prev) {
5289
+ const pkgPath = (0, pathe.join)(dir, "package.json");
5290
+ if ((0, node_fs.existsSync)(pkgPath)) {
5291
+ let pkg = {};
5292
+ try {
5293
+ pkg = JSON.parse((0, node_fs.readFileSync)(pkgPath, "utf8"));
5294
+ } catch {}
5295
+ if (pkg.name === "comfy-ts") {
5296
+ const examples = (0, pathe.join)(dir, "examples");
5297
+ return (0, node_fs.existsSync)(examples) ? examples : null;
5298
+ }
5299
+ if (pkg.name != null) return null;
5300
+ }
5301
+ prev = dir;
5302
+ dir = (0, pathe.dirname)(dir);
5303
+ }
5304
+ throw new Error(`[comfy-ts] no package.json found walking up from ${(0, node_url.fileURLToPath)(moduleUrl)}`);
5305
+ }
5306
+ /**
5307
+ * absolute path of a bundled `examples/images/` input image, e.g.
5308
+ * `exampleImagePath('bear_1024x1024.jpg')` — the out-of-the-box default for
5309
+ * i2i/i2v example image vars, valid from this repo AND from a consumer's
5310
+ * node_modules/comfy-ts/. Loud throw naming the path when the file is missing
5311
+ * or the package's examples/ folder was pruned.
5312
+ */
5313
+ function exampleImagePath(name) {
5314
+ const examples = bundledExamplesDir();
5315
+ if (examples == null) throw new Error(`[comfy-ts] cannot resolve bundled example image '${name}': the package's examples/ folder is not on disk`);
5316
+ const abs = (0, pathe.join)(examples, "images", name);
5317
+ if (!(0, node_fs.existsSync)(abs)) throw new Error(`[comfy-ts] bundled example image not found: ${abs}`);
5318
+ return abs;
5319
+ }
5320
+ //#endregion
4107
5321
  //#region src/cli/tui-env.ts
4108
5322
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
4109
5323
  function isTuiActive() {
@@ -4125,6 +5339,7 @@ function loraTag(name, strength = 1, clipStrength) {
4125
5339
  exports.ChoiceVar = ChoiceVar;
4126
5340
  exports.ComfyExecution = ComfyExecution;
4127
5341
  exports.ComfyHost = ComfyHost;
5342
+ exports.ComfyHostAuthError = ComfyHostAuthError;
4128
5343
  exports.ComfyManager = ComfyManager;
4129
5344
  exports.ComfyNode = ComfyNode;
4130
5345
  exports.ComfyNodeOutput = ComfyNodeOutput;
@@ -4135,9 +5350,12 @@ exports.ComfyVar = ComfyVar;
4135
5350
  exports.ComfyVarBase = ComfyVarBase;
4136
5351
  exports.ComfyWorkflow = ComfyWorkflow;
4137
5352
  exports.ComfyWorkflowBuilder = ComfyWorkflowBuilder;
5353
+ exports.DEFAULT_IMAGE_EXTENSIONS = DEFAULT_IMAGE_EXTENSIONS;
4138
5354
  exports.DEFAULT_SIZE_PRESETS = DEFAULT_SIZE_PRESETS;
4139
5355
  exports.DefinedWorkflow = DefinedWorkflow;
4140
5356
  exports.FloatVar = FloatVar;
5357
+ exports.ImageVar = ImageVar;
5358
+ exports.ImageVarEmptyError = ImageVarEmptyError;
4141
5359
  exports.IntVar = IntVar;
4142
5360
  exports.InvalidPromptError = InvalidPromptError;
4143
5361
  exports.LorasVar = LorasVar;
@@ -4148,6 +5366,8 @@ exports.SeedVar = SeedVar;
4148
5366
  exports.SizeVar = SizeVar;
4149
5367
  exports.TextVar = TextVar;
4150
5368
  exports.ToggleVar = ToggleVar;
5369
+ exports.WorkflowConvertError = WorkflowConvertError;
5370
+ exports.WorkflowNormalizeError = WorkflowNormalizeError;
4151
5371
  exports.__FAIL = __FAIL;
4152
5372
  exports.__OK = __OK;
4153
5373
  exports.activeLoras = activeLoras;
@@ -4159,10 +5379,17 @@ exports.auto = auto;
4159
5379
  exports.auto_ = auto_;
4160
5380
  exports.codegenSDK = codegenSDK;
4161
5381
  exports.convertFlowToLiteGraphJSON = convertFlowToLiteGraphJSON;
5382
+ exports.convertLiteGraphToPrompt = convertLiteGraphToPrompt;
5383
+ exports.exampleImagePath = exampleImagePath;
4162
5384
  exports.getLoraKeyword = getLoraKeyword;
4163
5385
  exports.hostIdToNamespace = hostIdToNamespace;
4164
5386
  exports.isTuiActive = isTuiActive;
4165
5387
  exports.loraTag = loraTag;
5388
+ exports.normalizeWorkflow = normalizeWorkflow;
5389
+ exports.parseHostBase = parseHostBase;
5390
+ exports.parseWorkflowJson = parseWorkflowJson;
5391
+ exports.renderHttpBase = renderHttpBase;
5392
+ exports.renderWsUrl = renderWsUrl;
4166
5393
  exports.resultFailure = resultFailure;
4167
5394
  exports.resultSuccess = resultSuccess;
4168
5395
  exports.setLoraKeyword = setLoraKeyword;