comfy-ts 0.4.0 → 1.0.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 (59) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1167 -172
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +401 -115
  9. package/dist/index.d.ts +401 -115
  10. package/dist/index.js +1159 -173
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-BFhba_oG.js} +132 -609
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -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 +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +6 -1
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/TreePanel.tsx +15 -2
  25. package/src/cli/tui/discoverWorkflows.ts +79 -0
  26. package/src/cli/tui/run-tui.tsx +51 -23
  27. package/src/cli/tui/state/HostSt.ts +2 -3
  28. package/src/cli/tui/state/TreeSt.ts +30 -6
  29. package/src/cli/tui/state/TuiSt.ts +21 -3
  30. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  31. package/src/host/ComfyHost.ts +203 -77
  32. package/src/host/ComfyManager.ts +10 -9
  33. package/src/host/ComfyUploader.ts +1 -2
  34. package/src/host/ResilientWebsocket.ts +3 -1
  35. package/src/host/hostUrl.ts +59 -0
  36. package/src/host/loraManagerApi.ts +5 -4
  37. package/src/index.ts +20 -1
  38. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  39. package/src/litegraph/LiteGraphGroup.ts +9 -7
  40. package/src/litegraph/LiteGraphJSON.ts +34 -13
  41. package/src/litegraph/LiteGraphLink.ts +32 -2
  42. package/src/litegraph/LiteGraphNode.ts +18 -33
  43. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  44. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  45. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  46. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  47. package/src/litegraph/expandSubgraphs.ts +352 -0
  48. package/src/litegraph/normalizeWorkflow.ts +141 -0
  49. package/src/runner/ComfyExecution.ts +4 -5
  50. package/src/runner/ComfyWorkflow.ts +2 -2
  51. package/src/runner/wsBinaryFrame.ts +48 -0
  52. package/src/sdk-generator/Primitives.ts +6 -24
  53. package/src/sdk-generator/comfy-api-json.ts +3 -1
  54. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  55. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  56. package/src/state.ts +13 -2
  57. package/dist/log-CdfgILde.js +0 -10
  58. package/dist/log-CdfgILde.js.map +0 -1
  59. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
package/dist/index.js CHANGED
@@ -11,7 +11,597 @@ import https from "node:https";
11
11
  import { stdout } from "node:process";
12
12
  import { readFileSync as readFileSync$1, writeFileSync as writeFileSync$1 } from "fs";
13
13
  //#region package.json
14
- var version = "0.4.0";
14
+ var version = "1.0.0";
15
+ //#endregion
16
+ //#region src/litegraph/LiteGraphLinkID.ts
17
+ const asLiteGraphLinkID = (id) => id;
18
+ const LiteGraphLinkID_ = type.number.atLeast(0).as();
19
+ //#endregion
20
+ //#region src/utils/bang.ts
21
+ /** assertNotNull */
22
+ const bang = (x, msg = "") => {
23
+ if (x == null) {
24
+ console.error(`[🔴] BANG FAILED`, msg);
25
+ throw new Error("bang: " + (msg ?? "no message"));
26
+ }
27
+ return x;
28
+ };
29
+ //#endregion
30
+ //#region src/litegraph/expandSubgraphs.ts
31
+ /** boundary sentinel ids inside definition link tables */
32
+ const SUBGRAPH_INPUT_NODE_ID = -10;
33
+ const SUBGRAPH_OUTPUT_NODE_ID = -20;
34
+ /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
35
+ const MAX_EXPANSION_PASSES = 32;
36
+ /**
37
+ * widget-kind fallback when a def input slot has no boundary target carrying a
38
+ * widget marker: these litegraph slot types carry widget values. LOCAL copy on
39
+ * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
40
+ * (the io-widget era serializes exactly one value per exposed widget slot).
41
+ */
42
+ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
43
+ "INT",
44
+ "FLOAT",
45
+ "STRING",
46
+ "BOOLEAN",
47
+ "COMBO"
48
+ ]);
49
+ /**
50
+ * inline every subgraph instance (node whose `type` is a definition uuid) into
51
+ * the root graph: fresh numeric ids, boundary links rewired, instance widget
52
+ * values promoted into the inner nodes' `named` overrides. Iterative so nested
53
+ * definitions expand on the next pass. Muted instances are dropped (their
54
+ * consumers resolve unconnected); bypassed instances stay for the converter's
55
+ * passthrough walk, which needs no interior.
56
+ */
57
+ const expandSubgraphs = (wf, defs) => {
58
+ let passes = 0;
59
+ while (true) {
60
+ const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
61
+ if (expandable.length === 0) return wf;
62
+ if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
63
+ for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
64
+ else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
65
+ }
66
+ };
67
+ /** converter mute semantics applied early: after expansion there is no single node left to skip */
68
+ const dropMutedInstance = (wf, instance) => {
69
+ const dead = /* @__PURE__ */ new Set();
70
+ for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
71
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
72
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
73
+ pruneDeadLinkRefs(wf, dead);
74
+ };
75
+ const pruneDeadLinkRefs = (wf, dead) => {
76
+ if (dead.size === 0) return;
77
+ for (const node of wf.nodes) {
78
+ for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
79
+ for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
80
+ }
81
+ };
82
+ const expandOneInstance = (wf, instance, def) => {
83
+ let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
84
+ let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
85
+ const newNodeIds = /* @__PURE__ */ new Map();
86
+ for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
87
+ const remapNodeId = (id) => newNodeIds.get(id) ?? null;
88
+ const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
89
+ for (const [k, input] of instance.inputs.entries()) {
90
+ const defSlot = def.inputs.findIndex((d) => d.name === input.name);
91
+ 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(", ")})`);
92
+ defSlotOfInstanceSlot.set(k, defSlot);
93
+ }
94
+ const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
95
+ for (const link of wf.links) {
96
+ if (link.targetId !== instance.id) continue;
97
+ const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
98
+ if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
99
+ outerLinkIntoDefSlot.set(defSlot, link);
100
+ }
101
+ const newLinkIds = /* @__PURE__ */ new Map();
102
+ const splicedLinks = [];
103
+ const producerByOutSlot = /* @__PURE__ */ new Map();
104
+ const passthroughOutSlot = /* @__PURE__ */ new Map();
105
+ const boundaryTargetsByInSlot = /* @__PURE__ */ new Map();
106
+ for (const link of def.links) {
107
+ const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID;
108
+ const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID;
109
+ if (fromInputBoundary && toOutputBoundary) {
110
+ passthroughOutSlot.set(link.targetSlot, link.originSlot);
111
+ continue;
112
+ }
113
+ if (toOutputBoundary) {
114
+ const producerId = remapNodeId(link.originId);
115
+ if (producerId != null && !producerByOutSlot.has(link.targetSlot)) producerByOutSlot.set(link.targetSlot, {
116
+ nodeId: producerId,
117
+ slot: link.originSlot
118
+ });
119
+ continue;
120
+ }
121
+ if (fromInputBoundary) {
122
+ const targetId = remapNodeId(link.targetId);
123
+ if (targetId == null) continue;
124
+ const target = {
125
+ nodeId: targetId,
126
+ slot: link.targetSlot
127
+ };
128
+ const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? [];
129
+ targets.push(target);
130
+ boundaryTargetsByInSlot.set(link.originSlot, targets);
131
+ const outer = outerLinkIntoDefSlot.get(link.originSlot);
132
+ if (outer == null) continue;
133
+ const fresh = asLiteGraphLinkID(++nextLinkId);
134
+ newLinkIds.set(link.id, fresh);
135
+ splicedLinks.push({
136
+ id: fresh,
137
+ originId: outer.originId,
138
+ originSlot: outer.originSlot,
139
+ targetId: target.nodeId,
140
+ targetSlot: target.slot,
141
+ type: link.type
142
+ });
143
+ wf.nodes.find((n) => n.id === outer.originId)?.outputs[outer.originSlot]?.links.push(fresh);
144
+ continue;
145
+ }
146
+ const interiorOrigin = remapNodeId(link.originId);
147
+ const interiorTarget = remapNodeId(link.targetId);
148
+ if (interiorOrigin == null || interiorTarget == null) continue;
149
+ const fresh = asLiteGraphLinkID(++nextLinkId);
150
+ newLinkIds.set(link.id, fresh);
151
+ splicedLinks.push({
152
+ id: fresh,
153
+ originId: interiorOrigin,
154
+ originSlot: link.originSlot,
155
+ targetId: interiorTarget,
156
+ targetSlot: link.targetSlot,
157
+ type: link.type
158
+ });
159
+ }
160
+ const splicedNodes = def.nodes.map((inner) => ({
161
+ id: bang(newNodeIds.get(inner.id)),
162
+ type: inner.type,
163
+ title: inner.title,
164
+ mode: inner.mode,
165
+ isVirtualNode: inner.isVirtualNode,
166
+ inputs: inner.inputs.map((i) => ({
167
+ name: i.name,
168
+ type: i.type,
169
+ link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
170
+ widgetName: i.widgetName
171
+ })),
172
+ outputs: inner.outputs.map((o) => ({
173
+ name: o.name,
174
+ type: o.type,
175
+ links: o.links.map((id) => newLinkIds.get(id)).filter((id) => id != null)
176
+ })),
177
+ widgets: {
178
+ positional: [...inner.widgets.positional],
179
+ named: { ...inner.widgets.named }
180
+ },
181
+ pos: [inner.pos[0], inner.pos[1]],
182
+ size: [inner.size[0], inner.size[1]],
183
+ properties: { ...inner.properties }
184
+ }));
185
+ const dead = /* @__PURE__ */ new Set();
186
+ for (const link of wf.links) {
187
+ if (link.targetId === instance.id) {
188
+ dead.add(link.id);
189
+ continue;
190
+ }
191
+ if (link.originId !== instance.id) continue;
192
+ const producer = producerByOutSlot.get(link.originSlot);
193
+ if (producer != null) {
194
+ link.originId = producer.nodeId;
195
+ link.originSlot = producer.slot;
196
+ splicedNodes.find((n) => n.id === producer.nodeId)?.outputs[producer.slot]?.links.push(link.id);
197
+ continue;
198
+ }
199
+ const passthroughInSlot = passthroughOutSlot.get(link.originSlot);
200
+ const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null;
201
+ if (outer != null) {
202
+ link.originId = outer.originId;
203
+ link.originSlot = outer.originSlot;
204
+ continue;
205
+ }
206
+ dead.add(link.id);
207
+ }
208
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
209
+ pruneDeadLinkRefs(wf, dead);
210
+ promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
211
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
212
+ wf.nodes.push(...splicedNodes);
213
+ wf.links.push(...splicedLinks);
214
+ };
215
+ /**
216
+ * instance widget values land in inner nodes' `named` overrides. TWO eras for
217
+ * the POSITIONAL values:
218
+ * - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]
219
+ * zip against the instance's positional values (incl. `control_after_generate`
220
+ * phantom pairs — written to `named` and simply never read, no schema input
221
+ * has that name).
222
+ * - io-widget era (no proxyWidgets): positional values zip against the def's
223
+ * widget-kind input slots in def order, one value per slot (no phantom —
224
+ * corpus-verified). An outer link into the same slot wins in the converter;
225
+ * the named override is still written, matching ComfyUI.
226
+ * PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:
227
+ * that is how a NESTED instance receives its outer values (the previous pass
228
+ * wrote them to `named`), so they must forward through THIS expansion too —
229
+ * named wins over positional, same precedence as the converter.
230
+ */
231
+ const promoteInstanceWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot) => {
232
+ const promoteToSlotTargets = (slot, value) => {
233
+ for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {
234
+ const target = splicedNodes.find((n) => n.id === t.nodeId);
235
+ const input = innerInputAt(splicedNodes, t);
236
+ if (target == null || input == null) continue;
237
+ target.widgets.named[input.name] = value;
238
+ }
239
+ };
240
+ promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets);
241
+ for (const [slot, io] of def.inputs.entries()) {
242
+ if (!Object.hasOwn(instance.widgets.named, io.name)) continue;
243
+ promoteToSlotTargets(slot, instance.widgets.named[io.name]);
244
+ }
245
+ };
246
+ const promotePositionalWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets) => {
247
+ const values = instance.widgets.positional;
248
+ if (values.length === 0) return;
249
+ const proxy = instance.properties["proxyWidgets"];
250
+ if (Array.isArray(proxy) && proxy.length > 0) {
251
+ const count = Math.min(values.length, proxy.length);
252
+ for (let k = 0; k < count; k++) {
253
+ const pair = proxy[k];
254
+ 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)}`);
255
+ const innerId = Number(pair[0]);
256
+ const widgetName = String(pair[1]);
257
+ if (innerId < 0) {
258
+ const slot = def.inputs.findIndex((d) => d.name === widgetName);
259
+ 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`);
260
+ promoteToSlotTargets(slot, values[k]);
261
+ continue;
262
+ }
263
+ const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId));
264
+ 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])}`);
265
+ target.widgets.named[widgetName] = values[k];
266
+ }
267
+ return;
268
+ }
269
+ let valueIndex = 0;
270
+ for (const [slot, io] of def.inputs.entries()) {
271
+ const targets = boundaryTargetsByInSlot.get(slot) ?? [];
272
+ if (!(targets.length > 0 ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null) : PRIMITIVE_WIDGET_TYPES.has(io.type))) continue;
273
+ if (valueIndex >= values.length) break;
274
+ promoteToSlotTargets(slot, values[valueIndex++]);
275
+ }
276
+ };
277
+ const innerInputAt = (splicedNodes, t) => {
278
+ return splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot] ?? null;
279
+ };
280
+ //#endregion
281
+ //#region src/litegraph/LiteGraphGroup.ts
282
+ const LiteGraphGroup_ark = type({
283
+ "id?": "number",
284
+ title: "string",
285
+ bounding: type([
286
+ "number",
287
+ "number",
288
+ "number",
289
+ "number"
290
+ ]),
291
+ "color?": "string",
292
+ "font_size?": "number",
293
+ "flags?": type.Record("string", "unknown").as()
294
+ });
295
+ //#endregion
296
+ //#region src/litegraph/LiteGraphLink.ts
297
+ const LiteGraphLinkTuple_ark = type([
298
+ LiteGraphLinkID_,
299
+ "number",
300
+ "number",
301
+ "number",
302
+ "number",
303
+ "string"
304
+ ]);
305
+ const LiteGraphLinkObject_ark = type({
306
+ id: LiteGraphLinkID_,
307
+ origin_id: "number",
308
+ origin_slot: "number",
309
+ target_id: "number",
310
+ target_slot: "number",
311
+ type: "string",
312
+ "parentId?": "number"
313
+ });
314
+ const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark);
315
+ //#endregion
316
+ //#region src/litegraph/LiteGraphNodeInput.ts
317
+ const LiteGraphNodeInput_ark = type({
318
+ name: "string",
319
+ type: "string",
320
+ "link?": LiteGraphLinkID_.or(type.null),
321
+ "shape?": "number",
322
+ "label?": "string",
323
+ "widget?": type({
324
+ name: "string",
325
+ "config?": "unknown"
326
+ })
327
+ });
328
+ //#endregion
329
+ //#region src/litegraph/LiteGraphSlotIndex.ts
330
+ const asLiteGraphSlotIndex = (id) => id;
331
+ const LiteGraphSlotIndex_ = type.number.atLeast(0).as();
332
+ //#endregion
333
+ //#region src/litegraph/LiteGraphNodeOutput.ts
334
+ const LiteGraphNodeOutput_ark = type({
335
+ name: "string",
336
+ type: "string",
337
+ "links?": LiteGraphLinkID_.array().or(type.null),
338
+ "shape?": "number",
339
+ "slot_index?": LiteGraphSlotIndex_
340
+ });
341
+ //#endregion
342
+ //#region src/litegraph/LiteGraphNode.ts
343
+ const LiteGraphNode_ark = type({
344
+ id: "number",
345
+ type: "string",
346
+ "title?": "string",
347
+ "color?": "string",
348
+ "bgcolor?": "string",
349
+ pos: {
350
+ "0": "number",
351
+ "1": "number"
352
+ },
353
+ size: {
354
+ "0": "number",
355
+ "1": "number"
356
+ },
357
+ "flags?": type.Record("string", "unknown"),
358
+ "order?": "number",
359
+ "mode?": "number",
360
+ "inputs?": LiteGraphNodeInput_ark.array(),
361
+ "outputs?": LiteGraphNodeOutput_ark.array(),
362
+ "isVirtualNode?": "boolean",
363
+ "properties?": type.Record("string", "unknown"),
364
+ "widgets_values?": type("unknown[]").or(type.Record("string", "unknown"))
365
+ });
366
+ //#endregion
367
+ //#region src/litegraph/LiteGraphSubgraphDef.ts
368
+ const LiteGraphSubgraphIO_ark = type({
369
+ id: "string",
370
+ name: "string",
371
+ type: "string",
372
+ "linkIds?": LiteGraphLinkID_.array(),
373
+ "label?": "string",
374
+ "localized_name?": "string",
375
+ "pos?": {
376
+ "0": "number",
377
+ "1": "number"
378
+ },
379
+ "shape?": "number"
380
+ });
381
+ const LiteGraphSubgraphDef_ark = type({
382
+ id: "string",
383
+ name: "string",
384
+ version: "number",
385
+ "state?": type.Record("string", "unknown"),
386
+ "revision?": "number",
387
+ "config?": type.Record("string", "unknown").as(),
388
+ "extra?": "unknown",
389
+ nodes: LiteGraphNode_ark.array(),
390
+ links: LiteGraphLinkObject_ark.array(),
391
+ "groups?": LiteGraphGroup_ark.array(),
392
+ inputNode: {
393
+ id: "number",
394
+ bounding: "number[]"
395
+ },
396
+ outputNode: {
397
+ id: "number",
398
+ bounding: "number[]"
399
+ },
400
+ inputs: LiteGraphSubgraphIO_ark.array(),
401
+ outputs: LiteGraphSubgraphIO_ark.array(),
402
+ widgets: "unknown[]"
403
+ });
404
+ //#endregion
405
+ //#region src/litegraph/LiteGraphJSON.ts
406
+ const LiteGraphJSON_ark = type({
407
+ "id?": "string",
408
+ "revision?": "number",
409
+ "last_node_id?": "number",
410
+ "last_link_id?": "number",
411
+ "state?": type.Record("string", "unknown"),
412
+ nodes: LiteGraphNode_ark.array(),
413
+ links: LiteGraphLink_ark.array(),
414
+ "groups?": LiteGraphGroup_ark.array(),
415
+ "config?": type.Record("never", "never"),
416
+ "extra?": { "ds?": {
417
+ scale: "number",
418
+ offset: {
419
+ "0": "number",
420
+ "1": "number"
421
+ }
422
+ } },
423
+ "models?": "unknown[]",
424
+ "definitions?": { subgraphs: LiteGraphSubgraphDef_ark.array() },
425
+ "reroutes?": "unknown[]",
426
+ "floatingLinks?": "unknown[]",
427
+ version: "0.4 | 1"
428
+ });
429
+ //#endregion
430
+ //#region src/litegraph/normalizeWorkflow.ts
431
+ /** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */
432
+ var WorkflowNormalizeError = class extends Error {
433
+ constructor(code, message, detail) {
434
+ super(`[workflow ${code}] ${message}`);
435
+ this.code = code;
436
+ this.detail = detail;
437
+ this.name = "WorkflowNormalizeError";
438
+ }
439
+ };
440
+ /**
441
+ * THE one entry for foreign workflow JSON (files, clipboard, imports):
442
+ * tolerant ark validation, then normalization to the strict canonical shape.
443
+ */
444
+ const parseWorkflowJson = (json) => {
445
+ const out = LiteGraphJSON_ark(json);
446
+ if (out instanceof type.errors) throw new WorkflowNormalizeError("schema-reject", out.summary, out);
447
+ return normalizeWorkflow(out);
448
+ };
449
+ /**
450
+ * loose wire document → strict canonical document. Defaults filled, both link
451
+ * eras unified, cosmetic fields dropped, subgraph definitions expanded away
452
+ * (see expandSubgraphs.ts — def interiors go through the SAME per-shape
453
+ * normalizers, they are v1 bodies).
454
+ */
455
+ const normalizeWorkflow = (raw) => {
456
+ const wf = {
457
+ nodes: raw.nodes.map(normalizeNode),
458
+ links: raw.links.map(normalizeLink),
459
+ groups: (raw.groups ?? []).map(normalizeGroup)
460
+ };
461
+ const rawDefs = raw.definitions?.subgraphs ?? [];
462
+ if (rawDefs.length === 0) return wf;
463
+ const defs = /* @__PURE__ */ new Map();
464
+ for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d));
465
+ return expandSubgraphs(wf, defs);
466
+ };
467
+ const normalizeSubgraphDef = (d) => {
468
+ return {
469
+ id: d.id,
470
+ name: d.name,
471
+ inputs: d.inputs.map((io) => ({
472
+ name: io.name,
473
+ type: io.type
474
+ })),
475
+ outputs: d.outputs.map((io) => ({
476
+ name: io.name,
477
+ type: io.type
478
+ })),
479
+ nodes: d.nodes.map(normalizeNode),
480
+ links: d.links.map(normalizeLink)
481
+ };
482
+ };
483
+ const normalizeMode = (mode) => {
484
+ if (mode === 2) return "muted";
485
+ if (mode === 4) return "bypassed";
486
+ return "normal";
487
+ };
488
+ const normalizeNode = (n) => {
489
+ return {
490
+ id: n.id,
491
+ type: n.type,
492
+ title: n.title ?? null,
493
+ mode: normalizeMode(n.mode),
494
+ isVirtualNode: n.isVirtualNode ?? false,
495
+ inputs: (n.inputs ?? []).map(normalizeInput),
496
+ outputs: (n.outputs ?? []).map(normalizeOutput),
497
+ widgets: normalizeWidgetValues(n.widgets_values),
498
+ pos: [n.pos[0], n.pos[1]],
499
+ size: [n.size[0], n.size[1]],
500
+ properties: { ...n.properties }
501
+ };
502
+ };
503
+ const normalizeInput = (i) => {
504
+ return {
505
+ name: i.name,
506
+ type: i.type,
507
+ link: i.link ?? null,
508
+ widgetName: i.widget?.name ?? null
509
+ };
510
+ };
511
+ const normalizeOutput = (o) => {
512
+ return {
513
+ name: o.name,
514
+ type: o.type,
515
+ links: [...o.links ?? []]
516
+ };
517
+ };
518
+ const normalizeWidgetValues = (wv) => {
519
+ if (wv == null) return {
520
+ positional: [],
521
+ named: {}
522
+ };
523
+ if (Array.isArray(wv)) return {
524
+ positional: [...wv],
525
+ named: {}
526
+ };
527
+ return {
528
+ positional: [],
529
+ named: { ...wv }
530
+ };
531
+ };
532
+ const normalizeLink = (l) => {
533
+ if (Array.isArray(l)) return {
534
+ id: l[0],
535
+ originId: l[1],
536
+ originSlot: l[2],
537
+ targetId: l[3],
538
+ targetSlot: l[4],
539
+ type: l[5]
540
+ };
541
+ return {
542
+ id: l.id,
543
+ originId: l.origin_id,
544
+ originSlot: l.origin_slot,
545
+ targetId: l.target_id,
546
+ targetSlot: l.target_slot,
547
+ type: l.type
548
+ };
549
+ };
550
+ const normalizeGroup = (g) => {
551
+ return {
552
+ title: g.title,
553
+ bounding: [
554
+ g.bounding[0],
555
+ g.bounding[1],
556
+ g.bounding[2],
557
+ g.bounding[3]
558
+ ],
559
+ color: g.color ?? "#3f789e",
560
+ fontSize: g.font_size ?? 24
561
+ };
562
+ };
563
+ //#endregion
564
+ //#region src/runner/wsBinaryFrame.ts
565
+ function parseBinaryWsFrame(data) {
566
+ const view = new DataView(data);
567
+ const eventType = view.getUint32(0);
568
+ if (eventType === 1) {
569
+ const imageType = view.getUint32(4);
570
+ return {
571
+ kind: "preview",
572
+ bytes: new Uint8Array(data.slice(8)),
573
+ mime: imageType === 2 ? "image/png" : "image/jpeg",
574
+ metadata: null
575
+ };
576
+ }
577
+ if (eventType === 3) {
578
+ const nodeIdLen = view.getUint32(4);
579
+ const decoder = new TextDecoder();
580
+ return {
581
+ kind: "text",
582
+ nodeId: decoder.decode(data.slice(8, 8 + nodeIdLen)),
583
+ text: decoder.decode(data.slice(8 + nodeIdLen))
584
+ };
585
+ }
586
+ if (eventType === 4) {
587
+ const metadataLen = view.getUint32(4);
588
+ let metadata = null;
589
+ try {
590
+ metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)));
591
+ } catch {}
592
+ const bytes = new Uint8Array(data.slice(8 + metadataLen));
593
+ return {
594
+ kind: "preview",
595
+ bytes,
596
+ mime: bytes[0] === 137 && bytes[1] === 80 ? "image/png" : "image/jpeg",
597
+ metadata
598
+ };
599
+ }
600
+ return {
601
+ kind: "unknown",
602
+ eventType
603
+ };
604
+ }
15
605
  //#endregion
16
606
  //#region src/sdk-generator/Primitives.ts
17
607
  const ComfyPrimitiveMapping = {
@@ -22,20 +612,8 @@ const ComfyPrimitiveMapping = {
22
612
  };
23
613
  const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
24
614
  /**
25
- * when a litegraph node has no input for a given ComfyUI node input
26
- * (e.g. a seed or an enum that has not been turned into a primitive)
27
- */
28
- const howManyWidgetValuesForThisSchemaType = (input) => {
29
- if (input.typeName === "INT") {
30
- if (input.nameInComfy === "seed" || input.nameInComfy === "noise_seed") return 2;
31
- }
32
- if (input.isPrimitive) return 1;
33
- if (input.typeName.startsWith("E_")) return 1;
34
- return 0;
35
- };
36
- /**
37
- * then a litegraph node has an input entry, some convoluted logic seems to be necessary
38
- * to determine how many Field_values need to be consumed for this input
615
+ * when a litegraph node has an input entry with a widget marker, the
616
+ * serialized TYPE string decides how many widgets_values it consumed in that era
39
617
  */
40
618
  const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
41
619
  if (type === "INT") {
@@ -63,94 +641,433 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
63
641
  output_node: false,
64
642
  python_module: "nodes"
65
643
  };
66
- var UnknownCustomNode = class extends Error {
67
- constructor(node) {
68
- super(`❌ node ${node.id}(${node.type}) has no known schema; you probably need to install some custom node`);
69
- this.node = node;
644
+ //#endregion
645
+ //#region src/sdk-generator/inputWidgetKind.ts
646
+ const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
647
+ /**
648
+ * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
649
+ * The frontend creates the control widget on truthiness, and real 2026 hosts
650
+ * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
651
+ * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
652
+ * heuristic applies.
653
+ */
654
+ const controlConsumes = (o, typeName, name) => {
655
+ if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
656
+ if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
657
+ return 1;
658
+ };
659
+ const flattenInputSections = (inputs) => {
660
+ const out = [];
661
+ for (const section of ["required", "optional"]) {
662
+ const sec = inputs[section];
663
+ if (!isRecord(sec)) continue;
664
+ for (const [name, spec] of Object.entries(sec)) {
665
+ if (!Array.isArray(spec) || spec.length === 0) continue;
666
+ const t = spec[0];
667
+ if (typeof t !== "string" && !Array.isArray(t)) continue;
668
+ out.push({
669
+ name,
670
+ type: t,
671
+ opts: spec[1],
672
+ required: section === "required"
673
+ });
674
+ }
675
+ }
676
+ return out;
677
+ };
678
+ /** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
679
+ const parseDynamicOptions = (options) => {
680
+ if (options.length === 0) return null;
681
+ const out = [];
682
+ for (const entry of options) {
683
+ if (!isRecord(entry)) return null;
684
+ const key = entry["key"];
685
+ const inputs = entry["inputs"];
686
+ if (typeof key !== "string" || !isRecord(inputs)) return null;
687
+ out.push({
688
+ key,
689
+ inputs: flattenInputSections(inputs)
690
+ });
691
+ }
692
+ return out;
693
+ };
694
+ /**
695
+ * autogrow (`template` WITH a nested `input` section): instances are always
696
+ * link slots named `decl.<name_i>` (the backend force-inputs widget
697
+ * templates), the first `min` of them required WHEN the template input
698
+ * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
699
+ */
700
+ const parseContainer = (template) => {
701
+ const input = template["input"];
702
+ const min = typeof template["min"] === "number" ? template["min"] : 1;
703
+ const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
704
+ const max = typeof template["max"] === "number" ? template["max"] : 100;
705
+ const rawNames = template["names"];
706
+ const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
707
+ return {
708
+ kind: "dynamic-container",
709
+ instanceNames: names,
710
+ requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
711
+ };
712
+ };
713
+ const classifyWidgetInput = (p) => {
714
+ const o = isRecord(p.opts) ? p.opts : null;
715
+ if (o?.["forceInput"] === true) return { kind: "slot" };
716
+ if (Array.isArray(p.type) || p.isEnumUnion === true) {
717
+ const tn = typeof p.type === "string" ? p.type : "COMBO";
718
+ return {
719
+ kind: "widget",
720
+ consumes: controlConsumes(o, tn, p.name),
721
+ strictValues: true
722
+ };
70
723
  }
724
+ if (typeof p.type !== "string") return { kind: "slot" };
725
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
726
+ if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
727
+ kind: "widget",
728
+ consumes: controlConsumes(o, widgetTypeName, p.name),
729
+ strictValues: true
730
+ };
731
+ const options = o?.["options"];
732
+ if (Array.isArray(options)) {
733
+ const dynOptions = parseDynamicOptions(options);
734
+ if (dynOptions != null) {
735
+ const first = dynOptions[0];
736
+ if (first == null) return { kind: "slot" };
737
+ return {
738
+ kind: "dynamic-combo",
739
+ options: dynOptions,
740
+ defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
741
+ };
742
+ }
743
+ return {
744
+ kind: "widget",
745
+ consumes: controlConsumes(o, p.type, p.name),
746
+ strictValues: true
747
+ };
748
+ }
749
+ const template = o?.["template"];
750
+ if (isRecord(template)) {
751
+ if (isRecord(template["input"])) return parseContainer(template);
752
+ return { kind: "slot" };
753
+ }
754
+ if (o?.["socketless"] === true) return {
755
+ kind: "widget",
756
+ consumes: 1,
757
+ strictValues: false
758
+ };
759
+ return { kind: "slot" };
760
+ };
761
+ const classifySchemaInput = (input) => classifyWidgetInput({
762
+ name: input.nameInComfy,
763
+ type: input.typeName,
764
+ opts: input.opts,
765
+ isEnumUnion: input.isEnum
766
+ });
767
+ /** how many widgets_values entries this schema input consumes (export path + positional walks) */
768
+ const howManyWidgetValuesForThisSchemaType = (input) => {
769
+ const kind = classifySchemaInput(input);
770
+ return kind.kind === "widget" ? kind.consumes : 0;
771
+ };
772
+ /**
773
+ * what ComfyUI's frontend gives a widget created with no serialized value
774
+ * (`getWidgetDefaultValue` semantics), used when a positional array is
775
+ * shorter than the schema's widget list. `null` for custom widgets — the
776
+ * backend accepts an explicit null but errors on an ABSENT required key.
777
+ */
778
+ const defaultValueForWidget = (p) => {
779
+ const o = isRecord(p.opts) ? p.opts : null;
780
+ if (o != null && o["default"] !== void 0) return o["default"];
781
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
782
+ if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
783
+ if (widgetTypeName === "BOOLEAN") return false;
784
+ if (widgetTypeName === "STRING") return "";
785
+ const options = o?.["options"];
786
+ if (Array.isArray(options) && options.length > 0) {
787
+ const first = options[0];
788
+ if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
789
+ }
790
+ if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
791
+ return null;
71
792
  };
72
793
  //#endregion
73
794
  //#region src/sdk-generator/litegraphToApiRequestPayload.ts
795
+ /** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
796
+ var WorkflowConvertError = class extends Error {
797
+ constructor(code, message, node) {
798
+ super(`[workflow ${code}] ${message}`);
799
+ this.code = code;
800
+ this.node = node;
801
+ this.name = "WorkflowConvertError";
802
+ }
803
+ };
804
+ /**
805
+ * closed set: frontend-only node types that NEVER execute. PrimitiveString /
806
+ * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.
807
+ */
808
+ const VIRTUAL_NODE_TYPES = /* @__PURE__ */ new Set([
809
+ "Note",
810
+ "MarkdownNote",
811
+ "Reroute",
812
+ "PrimitiveNode"
813
+ ]);
814
+ const isNeverExecuted = (node) => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type);
815
+ /** exact match, or `*` wildcard on either side (Reroute-style slots) */
816
+ /** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */
817
+ const linkTypeMatches = (a, b) => {
818
+ if (a === b || a === "*" || b === "*") return true;
819
+ if (!a.includes(",") && !b.includes(",")) return false;
820
+ const as = a.split(",");
821
+ const bs = b.split(",");
822
+ return as.some((x) => bs.includes(x));
823
+ };
824
+ /** what an inlined PrimitiveNode may contribute: scalar widget values only */
825
+ const isPromptScalar = (v) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean";
74
826
  /**
75
- * convert a saved ComfyUI workflow.json (litegraph format) into the api.json
76
- * (prompt format) ComfyUI's POST /prompt takes.
77
- * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes
78
- * unwrapped, primitives inlined into their consumers), widget-value offsets
79
- * (incl. the phantom `control_after_generate` value after seeds).
827
+ * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)
828
+ * into the api.json (prompt format) ComfyUI's POST /prompt takes.
829
+ * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed
830
+ * nodes (mode 4: link resolution walks through to the first type-matching
831
+ * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes
832
+ * unwrapped, primitives inlined into their consumers), widget values both
833
+ * positional (with the phantom `control_after_generate` offset after seeds)
834
+ * and named (object-form widgets_values + subgraph promotion overrides —
835
+ * named wins, but a live link wins over both). Widget-ness is decided from
836
+ * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types
837
+ * (COMBO options, dynamic combos, autogrow containers, socketless customs)
838
+ * and 2024-era enums go through ONE classifier; a positional array shorter
839
+ * than the schema's widget list fills schema defaults, never throws
840
+ * (agent/architecture.md owns both decisions).
80
841
  */
81
842
  const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
82
843
  const prompt = {};
83
844
  const LOG = opts.verbose ? (...args) => console.log("[🔥] converter:", ...args) : () => {};
84
845
  const PRIMITIVE_VALUES = {};
85
- for (const node of workflow.nodes) if (node.type === "PrimitiveNode") {
86
- const widgetValues = node.widgets_values;
87
- if (widgetValues == null || widgetValues.length === 0) throw new Error(`PrimitiveNode#${node.id} has no widget values`);
88
- PRIMITIVE_VALUES[node.id] = widgetValues[0];
846
+ for (const node of workflow.nodes) {
847
+ if (node.type !== "PrimitiveNode") continue;
848
+ if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
849
+ else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
89
850
  }
90
851
  for (const node of workflow.nodes) {
91
- if (node.isVirtualNode) continue;
92
- if (node.mode === 2) continue;
93
- if (node.type === "Reroute") continue;
94
- if (node.type === "Note") continue;
95
- if (node.type === "PrimitiveNode") continue;
852
+ if (isNeverExecuted(node)) continue;
853
+ if (node.mode !== "normal") continue;
96
854
  const inputs = {};
97
- const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name));
855
+ const fieldNamesPresent = new Set(node.inputs.map((i) => i.name));
98
856
  const nodeSchema_ = schema.nodesByNameInComfy[node.type];
99
- if (nodeSchema_ == null) throw new UnknownCustomNode(node);
857
+ 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);
100
858
  const nodeSchema = nodeSchema_;
101
859
  let offset = 0;
102
- const inputsInNodeJSON = node.inputs ?? [];
860
+ const positional = node.widgets.positional;
861
+ const named = node.widgets.named;
862
+ const widgetFallback = /* @__PURE__ */ new Map();
863
+ const inputsInNodeJSON = node.inputs;
103
864
  const inputsInNodeSchema = nodeSchema.inputs;
865
+ /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */
866
+ const toPromptValue = (value, p) => {
867
+ if (value == null) return null;
868
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
869
+ if (Array.isArray(value)) return { __value__: value };
870
+ if (!p.strict && isRecord(value)) return value;
871
+ throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
872
+ };
873
+ /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
874
+ const resolveWidgetValue = (p) => {
875
+ let value;
876
+ let has = false;
877
+ if (Object.hasOwn(named, p.promptName)) {
878
+ value = named[p.promptName];
879
+ has = true;
880
+ } else if (offset < positional.length) {
881
+ value = positional[offset];
882
+ has = true;
883
+ }
884
+ if (positional.length > 0) offset += p.consumes;
885
+ return {
886
+ value,
887
+ filled: !has
888
+ };
889
+ };
890
+ const consumePlainWidget = (p) => {
891
+ const r = resolveWidgetValue({
892
+ promptName: p.promptName,
893
+ consumes: p.consumes
894
+ });
895
+ const raw = r.filled ? defaultValueForWidget({
896
+ type: p.typeName,
897
+ opts: p.opts,
898
+ enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values
899
+ }) : r.value;
900
+ const value = toPromptValue(raw, {
901
+ promptName: p.promptName,
902
+ strict: p.strict
903
+ });
904
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`);
905
+ if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value);
906
+ else inputs[p.promptName] = value;
907
+ };
908
+ /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
909
+ const consumeDynamicCombo = (p) => {
910
+ const r = resolveWidgetValue({
911
+ promptName: p.path,
912
+ consumes: 1
913
+ });
914
+ const key = r.filled ? p.defaultKey : r.value;
915
+ 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);
916
+ const opt = p.options.find((o) => o.key === key);
917
+ 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);
918
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`);
919
+ inputs[p.path] = key;
920
+ for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
921
+ };
922
+ const consumeBranchInput = (subPath, sub) => {
923
+ const kind = classifyWidgetInput({
924
+ name: sub.name,
925
+ type: sub.type,
926
+ opts: sub.opts
927
+ });
928
+ if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
929
+ if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
930
+ path: subPath,
931
+ options: kind.options,
932
+ defaultKey: kind.defaultKey
933
+ });
934
+ const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
935
+ consumePlainWidget({
936
+ promptName: subPath,
937
+ typeName: typeof sub.type === "string" ? sub.type : "COMBO",
938
+ opts: sub.opts,
939
+ consumes: kind.consumes,
940
+ strict: kind.strictValues,
941
+ enumValues: inlineEnum,
942
+ linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
943
+ });
944
+ };
104
945
  for (const field of inputsInNodeSchema) {
105
946
  const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy);
106
- const MUST_CONSUME = input?.type ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) : howManyWidgetValuesForThisSchemaType(field);
107
- if (MUST_CONSUME > 0) {
108
- if (node.widgets_values == null) throw new Error(`node ${node.id}(${node.type}) has no widgets_values but "${field.nameInComfy}" needs one`);
109
- if (node.widgets_values.length < offset + 1) throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for "${field.nameInComfy}"`);
110
- const _value = node.widgets_values[offset];
111
- LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`);
112
- if (!isValidValue(_value)) throw new Error(`node ${node.id}(${node.type}) has an invalid widget value for "${field.nameInComfy}": ${JSON.stringify(_value)}`);
113
- inputs[field.nameInComfy] = _value;
114
- offset += MUST_CONSUME;
115
- } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {
116
- if (field.required) throw new Error(`node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`);
947
+ let kind = classifySchemaInput(field);
948
+ if (kind.kind === "slot" && input?.widgetName != null) kind = {
949
+ kind: "widget",
950
+ consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
951
+ strictValues: true
952
+ };
953
+ if (kind.kind === "widget") consumePlainWidget({
954
+ promptName: field.nameInComfy,
955
+ typeName: field.typeName,
956
+ opts: field.opts,
957
+ consumes: kind.consumes,
958
+ strict: kind.strictValues,
959
+ linkedInput: input
960
+ });
961
+ else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
962
+ path: field.nameInComfy,
963
+ options: kind.options,
964
+ defaultKey: kind.defaultKey
965
+ });
966
+ else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
967
+ const iname = `${field.nameInComfy}.${instName}`;
968
+ 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);
969
+ }
970
+ else if (!fieldNamesPresent.has(field.nameInComfy)) {
971
+ 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);
117
972
  }
118
973
  }
119
974
  const getParentNode = (linkId) => {
120
- const link = workflow.links.find((link) => link[0] === linkId);
121
- if (link == null) throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`);
122
- const parentId = link[1];
123
- const parentNode = workflow.nodes.find((n) => n.id === parentId);
124
- if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`);
975
+ const link = workflow.links.find((link) => link.id === linkId);
976
+ if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
977
+ const parentNode = workflow.nodes.find((n) => n.id === link.originId);
978
+ if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
125
979
  return {
126
980
  node: parentNode,
127
981
  link
128
982
  };
129
983
  };
130
- INPT: for (const ipt of node.inputs ?? []) {
131
- if (howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0) continue;
984
+ const pickBypassInput = (p) => {
985
+ const sameSlot = p.inputs[p.outSlot];
986
+ if (p.consumerType === "*" || p.consumerType === "") return sameSlot ?? p.inputs[0] ?? null;
987
+ if (sameSlot != null && linkTypeMatches(sameSlot.type, p.outputType) && linkTypeMatches(sameSlot.type, p.consumerType)) return sameSlot;
988
+ const exact = p.inputs.find((i) => i.type === p.consumerType);
989
+ if (exact != null) return exact;
990
+ return p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ?? null;
991
+ };
992
+ const resolveThroughParents = (startLink, consumerType) => {
993
+ const visited = /* @__PURE__ */ new Set();
994
+ let linkId = startLink;
995
+ let effectiveType = consumerType;
996
+ while (true) {
997
+ const parent = getParentNode(linkId);
998
+ 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);
999
+ visited.add(parent.node.id);
1000
+ if (parent.node.type === "Reroute") {
1001
+ const rerouteIn = parent.node.inputs[0]?.link;
1002
+ if (rerouteIn == null) return {
1003
+ kind: "unconnected",
1004
+ reason: "reroute chain ends on an empty slot"
1005
+ };
1006
+ linkId = rerouteIn;
1007
+ continue;
1008
+ }
1009
+ if (parent.node.mode === "muted") return {
1010
+ kind: "unconnected",
1011
+ reason: `parent ${parent.node.id}(${parent.node.type}) is muted`
1012
+ };
1013
+ if (parent.node.mode === "bypassed") {
1014
+ const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type;
1015
+ const through = pickBypassInput({
1016
+ inputs: parent.node.inputs,
1017
+ outSlot: parent.link.originSlot,
1018
+ outputType,
1019
+ consumerType: effectiveType
1020
+ });
1021
+ if (through?.link == null) return {
1022
+ kind: "unconnected",
1023
+ reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`
1024
+ };
1025
+ linkId = through.link;
1026
+ effectiveType = through.type;
1027
+ continue;
1028
+ }
1029
+ if (parent.node.type === "PrimitiveNode") {
1030
+ if (!(parent.node.id in PRIMITIVE_VALUES)) return {
1031
+ kind: "unconnected",
1032
+ reason: `PrimitiveNode#${parent.node.id} has no widget value`
1033
+ };
1034
+ return {
1035
+ kind: "primitive",
1036
+ nodeId: parent.node.id
1037
+ };
1038
+ }
1039
+ return {
1040
+ kind: "link",
1041
+ nodeId: parent.node.id,
1042
+ slot: parent.link.originSlot
1043
+ };
1044
+ }
1045
+ };
1046
+ for (const ipt of node.inputs) {
132
1047
  if (ipt.link == null) {
133
- LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`);
1048
+ LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`);
134
1049
  continue;
135
1050
  }
136
- let parent = getParentNode(ipt.link);
137
- let max = 100;
138
- while (parent != null && parent.node.type === "Reroute" && max-- > 0) {
139
- const firstParentInput = parent.node.inputs?.[0];
140
- if (firstParentInput?.link == null) {
141
- LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`);
142
- continue INPT;
143
- }
144
- parent = getParentNode(firstParentInput.link);
1051
+ const resolved = resolveThroughParents(ipt.link, ipt.type);
1052
+ if (resolved.kind === "primitive") {
1053
+ const pv = PRIMITIVE_VALUES[resolved.nodeId];
1054
+ 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);
1055
+ inputs[ipt.name] = pv;
1056
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`);
1057
+ continue;
1058
+ }
1059
+ if (resolved.kind === "link") {
1060
+ LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`);
1061
+ inputs[ipt.name] = [String(resolved.nodeId), resolved.slot];
1062
+ continue;
145
1063
  }
146
- if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`);
147
- if (parent.node.type === "PrimitiveNode") {
148
- inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id];
149
- LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`);
1064
+ if (widgetFallback.has(ipt.name)) {
1065
+ inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null;
1066
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`);
150
1067
  continue;
151
1068
  }
152
- LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`);
153
- inputs[ipt.name] = [String(parent.node.id), parent.link[2]];
1069
+ 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);
1070
+ LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`);
154
1071
  }
155
1072
  prompt[String(node.id)] = {
156
1073
  inputs,
@@ -159,14 +1076,6 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
159
1076
  }
160
1077
  return prompt;
161
1078
  };
162
- function isValidValue(value) {
163
- if (value == null) return true;
164
- if (typeof value === "string") return true;
165
- if (typeof value === "number") return true;
166
- if (typeof value === "boolean") return true;
167
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number") return true;
168
- return false;
169
- }
170
1079
  //#endregion
171
1080
  //#region src/errors/InvalidPromptError.ts
172
1081
  var InvalidPromptError = class extends Error {
@@ -515,24 +1424,6 @@ var ComfyWorkflowBuilder = class {
515
1424
  }
516
1425
  };
517
1426
  //#endregion
518
- //#region src/utils/bang.ts
519
- /** assertNotNull */
520
- const bang = (x, msg = "") => {
521
- if (x == null) {
522
- console.error(`[🔴] BANG FAILED`, msg);
523
- throw new Error("bang: " + (msg ?? "no message"));
524
- }
525
- return x;
526
- };
527
- //#endregion
528
- //#region src/litegraph/LiteGraphLinkID.ts
529
- const asLiteGraphLinkID = (id) => id;
530
- type.number.atLeast(0).as();
531
- //#endregion
532
- //#region src/litegraph/LiteGraphSlotIndex.ts
533
- const asLiteGraphSlotIndex = (id) => id;
534
- type.number.atLeast(0).as();
535
- //#endregion
536
1427
  //#region src/litegraph/convertFlowToLiteGraphJSON.ts
537
1428
  const convertFlowToLiteGraphJSON = (graph) => {
538
1429
  const ctx = new LiteGraphCtx(graph);
@@ -545,7 +1436,7 @@ const convertFlowToLiteGraphJSON = (graph) => {
545
1436
  const n = xx.liteGraphNode;
546
1437
  n.pos[0] = bang(xx.comfyNode.x);
547
1438
  n.pos[1] = bang(xx.comfyNode.y);
548
- for (const o of n.outputs) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
1439
+ for (const o of n.outputs ?? []) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
549
1440
  }
550
1441
  return {
551
1442
  last_node_id,
@@ -1027,7 +1918,7 @@ var ComfyExecution = class {
1027
1918
  const promptNode = this.workflow.data.apiJson?.[promptNodeID];
1028
1919
  const promptMeta = this.workflow.data.metadata?.[promptNodeID];
1029
1920
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
1030
- const imgUrl = this.host.getServerHostHTTP() + "/view?" + new URLSearchParams(comfyImageInfo).toString();
1921
+ const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
1031
1922
  const sf = this.saveFormat;
1032
1923
  let absPath = comfyts.resolveFromOutput(join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
1033
1924
  if (sf?.format && sf.format !== "raw") {
@@ -1037,10 +1928,7 @@ var ComfyExecution = class {
1037
1928
  mkdirSync(dirname(absPath), { recursive: true });
1038
1929
  let img;
1039
1930
  if (sf && sf.format !== "raw") {
1040
- const buff = await (await fetch(imgUrl, {
1041
- headers: { "Content-Type": "image/png" },
1042
- method: "GET"
1043
- })).arrayBuffer();
1931
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1044
1932
  let textChunk = {};
1045
1933
  try {
1046
1934
  const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
@@ -1063,10 +1951,7 @@ var ComfyExecution = class {
1063
1951
  }
1064
1952
  });
1065
1953
  } else {
1066
- const buff = await (await fetch(imgUrl, {
1067
- headers: { "Content-Type": "image/png" },
1068
- method: "GET"
1069
- })).arrayBuffer();
1954
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1070
1955
  const uint8arr = new Uint8Array(buff);
1071
1956
  writeFileSync(absPath, uint8arr);
1072
1957
  img = new MediaImage({
@@ -1438,9 +2323,9 @@ var ComfyWorkflow = class {
1438
2323
  comfy_ts_version: comfyts.version
1439
2324
  } }
1440
2325
  };
1441
- const promptEndpoint = `${this.host.getServerHostHTTP()}/prompt`;
1442
- const res = await fetch(promptEndpoint, {
2326
+ const res = await this.host.fetch("/prompt", {
1443
2327
  method: "POST",
2328
+ headers: { "Content-Type": "application/json" },
1444
2329
  body: JSON.stringify(out)
1445
2330
  });
1446
2331
  const promptInfo = softValidate(PromptInfo_ark, await res.json());
@@ -2306,8 +3191,7 @@ var ComfyManager = class {
2306
3191
  }
2307
3192
  };
2308
3193
  this.fetchPost = async (endpoint, body, validator) => {
2309
- const url = this.host.getServerHostHTTP() + endpoint;
2310
- const response = await fetch(url, {
3194
+ const response = await this.host.fetch(endpoint, {
2311
3195
  method: "POST",
2312
3196
  headers: { "Content-Type": "application/json" },
2313
3197
  body: JSON.stringify(body)
@@ -2318,16 +3202,14 @@ var ComfyManager = class {
2318
3202
  return status;
2319
3203
  };
2320
3204
  this.fetchGetJSON = async (endpoint, validator) => {
2321
- const url = this.host.getServerHostHTTP() + endpoint;
2322
- const response = await fetch(url);
3205
+ const response = await this.host.fetch(endpoint);
2323
3206
  if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
2324
3207
  const jsonResult = await response.json();
2325
3208
  if (validator) return softValidate(validator, jsonResult);
2326
3209
  return jsonResult;
2327
3210
  };
2328
3211
  this.fetchGetText = async (endopint) => {
2329
- const url = this.host.getServerHostHTTP() + endopint;
2330
- return await (await fetch(url)).text();
3212
+ return await (await this.host.fetch(endopint)).text();
2331
3213
  };
2332
3214
  }
2333
3215
  get registry() {
@@ -2345,11 +3227,10 @@ var ComfyManager = class {
2345
3227
  no();
2346
3228
  }
2347
3229
  if (abortCtrl) abortCtrl.abort();
2348
- const url = this.host.getServerHostHTTP();
2349
3230
  abortCtrl = new AbortController();
2350
3231
  try {
2351
3232
  console.log(` - trying...`);
2352
- await fetch(url, { signal: abortCtrl.signal });
3233
+ await this.host.fetch("/", { signal: abortCtrl.signal }, { apiPrefix: false });
2353
3234
  clearInterval(interval);
2354
3235
  yes(true);
2355
3236
  } catch {}
@@ -2387,8 +3268,7 @@ var ComfyUploader = class {
2387
3268
  if (p.type) form.set("type", p.type);
2388
3269
  if (p.override ?? true) form.set("override", "true");
2389
3270
  if (p.subfolder) form.set("subfolder", p.subfolder);
2390
- const uploadURL = this.host.getServerHostHTTP() + "/upload/image";
2391
- const resp = await fetch(uploadURL, {
3271
+ const resp = await this.host.fetch("/upload/image", {
2392
3272
  method: "POST",
2393
3273
  body: form
2394
3274
  });
@@ -2404,6 +3284,51 @@ var ComfyUploader = class {
2404
3284
  }
2405
3285
  };
2406
3286
  //#endregion
3287
+ //#region src/host/hostUrl.ts
3288
+ /** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
3289
+ function parseHostBase(p) {
3290
+ const hasLegacy = p.host != null || p.port != null || p.https != null;
3291
+ if (p.url != null && hasLegacy) throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`);
3292
+ if (p.url == null) {
3293
+ 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})`);
3294
+ return {
3295
+ scheme: p.https ? "https" : "http",
3296
+ host: p.host,
3297
+ port: p.port,
3298
+ basePath: ""
3299
+ };
3300
+ }
3301
+ let parsed;
3302
+ try {
3303
+ parsed = new URL(p.url);
3304
+ } catch {
3305
+ throw new Error(`host '${p.id}': unparseable url '${p.url}'`);
3306
+ }
3307
+ 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}'`);
3308
+ if (parsed.search !== "" || parsed.hash !== "") throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`);
3309
+ const scheme = parsed.protocol === "https:" ? "https" : "http";
3310
+ const port = parsed.port !== "" ? Number(parsed.port) : scheme === "https" ? 443 : 80;
3311
+ const basePath = parsed.pathname.replace(/\/+$/, "");
3312
+ return {
3313
+ scheme,
3314
+ host: parsed.hostname,
3315
+ port,
3316
+ basePath
3317
+ };
3318
+ }
3319
+ /** http(s) base, port omitted when it is the scheme default */
3320
+ function renderHttpBase(p) {
3321
+ return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3322
+ }
3323
+ /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3324
+ function renderWsUrl(p) {
3325
+ return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3326
+ }
3327
+ function renderPort(p) {
3328
+ const schemeDefault = p.scheme === "https" ? 443 : 80;
3329
+ return p.port === schemeDefault ? "" : `:${p.port}`;
3330
+ }
3331
+ //#endregion
2407
3332
  //#region src/host/ResilientWebsocket.ts
2408
3333
  var ResilientWebSocketClient = class {
2409
3334
  addInfo(msg) {
@@ -2448,7 +3373,7 @@ var ResilientWebSocketClient = class {
2448
3373
  this.addInfo("Previous WebSocket discarded");
2449
3374
  prevWS.close();
2450
3375
  }
2451
- const ws = new WebSocket(this.url);
3376
+ const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
2452
3377
  ws.binaryType = "arraybuffer";
2453
3378
  this.currentWS = ws;
2454
3379
  if (this.options.onMessage) ws.onmessage = (event) => {
@@ -3058,6 +3983,17 @@ var DefinedWorkflow = class {
3058
3983
  };
3059
3984
  //#endregion
3060
3985
  //#region src/host/ComfyHost.ts
3986
+ /** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
3987
+ * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
3988
+ * (or plain rate limiting on non-cloud hosts). The key value never appears here. */
3989
+ var ComfyHostAuthError = class extends Error {
3990
+ constructor(code, hostId, message) {
3991
+ super(message);
3992
+ this.code = code;
3993
+ this.hostId = hostId;
3994
+ this.name = "ComfyHostAuthError";
3995
+ }
3996
+ };
3061
3997
  var ComfyHost = class {
3062
3998
  constructor(data) {
3063
3999
  this.data = data;
@@ -3113,7 +4049,48 @@ var ComfyHost = class {
3113
4049
  return this.manager.installPlugin(customNode);
3114
4050
  };
3115
4051
  this.getWSUrl = () => {
3116
- return `${this.data.https ? "wss" : "ws"}://${this.data.host}:${this.data.port}/ws`;
4052
+ return renderWsUrl(this.base);
4053
+ };
4054
+ this._apiPrefix = null;
4055
+ this.fetch = async (route, init = {}, p = {}) => {
4056
+ const base = this.getServerHostHTTP();
4057
+ const headers = new Headers(init.headers);
4058
+ for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v);
4059
+ const send = (prefixed) => fetch(`${base}${prefixed ? "/api" : ""}${route}`, {
4060
+ ...init,
4061
+ headers
4062
+ });
4063
+ const missed = (res) => res.status === 404 || res.status === 405;
4064
+ let res;
4065
+ if (p.apiPrefix === false) res = await send(false);
4066
+ else if (this._apiPrefix != null) {
4067
+ res = await send(this._apiPrefix);
4068
+ if (missed(res)) {
4069
+ const alt = await send(!this._apiPrefix);
4070
+ if (!missed(alt)) res = alt;
4071
+ }
4072
+ } else {
4073
+ res = await send(true);
4074
+ if (missed(res)) {
4075
+ const bare = await send(false);
4076
+ if (!missed(bare)) {
4077
+ this._apiPrefix = false;
4078
+ res = bare;
4079
+ }
4080
+ } else this._apiPrefix = true;
4081
+ }
4082
+ this.throwOnAuthError(res, route);
4083
+ return res;
4084
+ };
4085
+ this.fetchFile = async (route) => {
4086
+ const res = await this.fetch(route, { redirect: "manual" });
4087
+ if (res.status >= 300 && res.status < 400) {
4088
+ const location = res.headers.get("location");
4089
+ if (location == null) throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`);
4090
+ res.body?.cancel();
4091
+ return fetch(new URL(location, this.getServerHostHTTP()));
4092
+ }
4093
+ return res;
3117
4094
  };
3118
4095
  this.schemaRetrievalLogs = [];
3119
4096
  this.resetLog = () => {
@@ -3129,7 +4106,8 @@ var ComfyHost = class {
3129
4106
  return new DefinedWorkflow(this, spec);
3130
4107
  };
3131
4108
  this.importWorkflowJson = (json, p = {}) => {
3132
- const apiJson = convertLiteGraphToPrompt(this.schema, json);
4109
+ const canonical = parseWorkflowJson(json);
4110
+ const apiJson = convertLiteGraphToPrompt(this.schema, canonical);
3133
4111
  return this.importApiJson(apiJson, p);
3134
4112
  };
3135
4113
  this.importApiJson = (json, p = {}) => {
@@ -3169,13 +4147,12 @@ var ComfyHost = class {
3169
4147
  this.schemaUpdateResult = null;
3170
4148
  this._schemaFromCache = null;
3171
4149
  this.postJSON_ = async (route, body) => {
3172
- const base = this.getServerHostHTTP();
3173
- for (const url of [`${base}/api${route}`, `${base}${route}`]) if ((await fetch(url, {
4150
+ const res = await this.fetch(route, {
3174
4151
  method: "POST",
3175
4152
  headers: { "Content-Type": "application/json" },
3176
4153
  body: JSON.stringify(body)
3177
- })).ok) return;
3178
- throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`);
4154
+ });
4155
+ if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
3179
4156
  };
3180
4157
  this.clearQueue = () => {
3181
4158
  return this.postJSON_("/queue", { clear: true });
@@ -3184,7 +4161,7 @@ var ComfyHost = class {
3184
4161
  return this.postJSON_("/interrupt", {});
3185
4162
  };
3186
4163
  this.fetchRawLogs = async () => {
3187
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`);
4164
+ const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
3188
4165
  if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
3189
4166
  const json = await res.json();
3190
4167
  const checked = WsMsgLogsData_ark(json);
@@ -3195,25 +4172,23 @@ var ComfyHost = class {
3195
4172
  return json;
3196
4173
  };
3197
4174
  this.subscribeLogs = async (p) => {
3198
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {
4175
+ const res = await this.fetch("/internal/logs/subscribe", {
3199
4176
  method: "PATCH",
3200
4177
  headers: { "Content-Type": "application/json" },
3201
4178
  body: JSON.stringify({
3202
4179
  enabled: p.enabled,
3203
4180
  clientId: p.clientId
3204
4181
  })
3205
- });
4182
+ }, { apiPrefix: false });
3206
4183
  if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`);
3207
4184
  };
3208
4185
  this.fetchJSON_ = async (route) => {
3209
4186
  const base = this.getServerHostHTTP();
3210
- for (const url of [`${base}/api${route}`, `${base}${route}`]) {
3211
- const res = await fetch(url, { method: "GET" });
3212
- if (!res.ok) continue;
3213
- if (!(res.headers.get("content-type") ?? "").includes("json")) continue;
3214
- return await res.json();
3215
- }
3216
- throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`);
4187
+ const res = await this.fetch(route);
4188
+ if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`);
4189
+ const contentType = res.headers.get("content-type") ?? "";
4190
+ if (!contentType.includes("json")) throw new Error(`GET ${route} on ${base} answered '${contentType || "no content-type"}' instead of json`);
4191
+ return await res.json();
3217
4192
  };
3218
4193
  this.fetchAndUpdateSchema = async () => {
3219
4194
  try {
@@ -3256,7 +4231,9 @@ var ComfyHost = class {
3256
4231
  this.onSession = null;
3257
4232
  this.onLogs = null;
3258
4233
  this.comfySessionId = "temp";
4234
+ this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
3259
4235
  this.status = null;
4236
+ this.base = parseHostBase(this.data);
3260
4237
  /** folder where file related to the host config will be cached */
3261
4238
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
3262
4239
  if (!existsSync(this.cacheFolder)) {
@@ -3282,7 +4259,19 @@ var ComfyHost = class {
3282
4259
  return value;
3283
4260
  }
3284
4261
  getServerHostHTTP() {
3285
- return `${this.data.https ? "https" : "http"}://${this.data.host}:${this.data.port}`;
4262
+ return renderHttpBase(this.base);
4263
+ }
4264
+ /** extra headers + X-API-Key, for every http request AND the ws upgrade */
4265
+ authHeaders() {
4266
+ const out = {};
4267
+ if (this.data.headers != null) Object.assign(out, this.data.headers);
4268
+ if (this.data.apiKey != null) out["X-API-Key"] = this.data.apiKey;
4269
+ return out;
4270
+ }
4271
+ throwOnAuthError(res, route) {
4272
+ 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`);
4273
+ if (res.status === 402) throw new ComfyHostAuthError(402, this.data.id, `host '${this.data.id}': 402 on ${route} — insufficient credits`);
4274
+ if (res.status === 429) throw new ComfyHostAuthError(429, this.data.id, `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`);
3286
4275
  }
3287
4276
  get isConnected() {
3288
4277
  return this.ws?.isOpen ?? false;
@@ -3298,6 +4287,7 @@ var ComfyHost = class {
3298
4287
  this._readyReject = null;
3299
4288
  }
3300
4289
  async writeSDKToDisk() {
4290
+ if (this.data.sdkAutoWrite === false) return;
3301
4291
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
3302
4292
  if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
3303
4293
  await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
@@ -3344,6 +4334,7 @@ var ComfyHost = class {
3344
4334
  },
3345
4335
  onMessage: (e) => this.onMessage(e),
3346
4336
  url: () => this.getWSUrl(),
4337
+ headers: () => this.authHeaders(),
3347
4338
  onClose: () => {
3348
4339
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
3349
4340
  }
@@ -3357,8 +4348,16 @@ var ComfyHost = class {
3357
4348
  this._isUpdatingSchema = v;
3358
4349
  }
3359
4350
  /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
3360
- * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
4351
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once.
4352
+ * A MISSING cache degrades LOUDLY to the base types instead of failing the
4353
+ * module import (a fresh consumer project has no cache yet — the bundled
4354
+ * examples must still open in the TUI; run() fetches the real schema through
4355
+ * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
3361
4356
  loadSchemaFromCache() {
4357
+ if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
4358
+ 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`);
4359
+ return Promise.resolve();
4360
+ }
3362
4361
  this._schemaFromCache ??= (async () => {
3363
4362
  const object_info_json = comfyts.readJSON_(this.comfyJSONPath);
3364
4363
  const embeddings_json = comfyts.readJSON_(this.embeddingsPath, []);
@@ -3389,40 +4388,23 @@ var ComfyHost = class {
3389
4388
  onMessage(e) {
3390
4389
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
3391
4390
  if (e.data instanceof ArrayBuffer) {
3392
- const eventType = new DataView(e.data).getUint32(0);
3393
- const buffer = e.data.slice(4);
3394
- switch (eventType) {
3395
- case 1: {
3396
- const imageType = new DataView(e.data).getUint32(4);
3397
- let imageMime;
3398
- switch (imageType) {
3399
- case 1:
3400
- imageMime = "image/jpeg";
3401
- break;
3402
- case 2:
3403
- imageMime = "image/png";
3404
- break;
3405
- default:
3406
- imageMime = "image/jpeg";
3407
- break;
3408
- }
3409
- const imageBytes = buffer.slice(4);
3410
- const imageBlob = new Blob([imageBytes], { type: imageMime });
3411
- const imagePreview = URL.createObjectURL(imageBlob);
3412
- this.latentPreview = {
3413
- blob: imageBlob,
3414
- url: imagePreview,
3415
- receivedAt: Date.now(),
3416
- promptID: this.activePromptID
3417
- };
3418
- this.onLatentPreview?.({
3419
- bytes: new Uint8Array(imageBytes),
3420
- mime: imageMime,
3421
- promptID: this.activePromptID
3422
- });
3423
- break;
3424
- }
3425
- default: throw new Error(`Unknown binary websocket message of type ${eventType}`);
4391
+ const frame = parseBinaryWsFrame(e.data);
4392
+ if (frame.kind === "preview") {
4393
+ const imageBlob = new Blob([frame.bytes], { type: frame.mime });
4394
+ this.latentPreview = {
4395
+ blob: imageBlob,
4396
+ url: URL.createObjectURL(imageBlob),
4397
+ receivedAt: Date.now(),
4398
+ promptID: this.activePromptID
4399
+ };
4400
+ this.onLatentPreview?.({
4401
+ bytes: frame.bytes,
4402
+ mime: frame.mime,
4403
+ promptID: this.activePromptID
4404
+ });
4405
+ } else if (frame.kind === "unknown" && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
4406
+ this._unknownBinaryFrameTypes.add(frame.eventType);
4407
+ console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`);
3426
4408
  }
3427
4409
  return;
3428
4410
  }
@@ -4029,7 +5011,11 @@ var ComfyTS = class ComfyTS {
4029
5011
  host(data) {
4030
5012
  const existing = this.hosts.get(data.id);
4031
5013
  if (existing != null) {
4032
- if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https) throw new Error(`host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`);
5014
+ const incoming = parseHostBase(data);
5015
+ const cur = existing.base;
5016
+ const sameBase = cur.scheme === incoming.scheme && cur.host === incoming.host && cur.port === incoming.port && cur.basePath === incoming.basePath;
5017
+ const sameAuth = existing.data.apiKey == null === (data.apiKey == null);
5018
+ 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)" : ""}`);
4033
5019
  return existing;
4034
5020
  }
4035
5021
  const created = new ComfyHost(data);
@@ -4088,6 +5074,6 @@ function loraTag(name, strength = 1, clipStrength) {
4088
5074
  return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
4089
5075
  }
4090
5076
  //#endregion
4091
- export { ChoiceVar, ComfyExecution, ComfyHost, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, getLoraKeyword, hostIdToNamespace, isTuiActive, loraTag, resultFailure, resultSuccess, setLoraKeyword, v };
5077
+ export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, getLoraKeyword, hostIdToNamespace, isTuiActive, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setLoraKeyword, v };
4092
5078
 
4093
5079
  //# sourceMappingURL=index.js.map