comfy-ts 1.1.0 → 1.3.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 (66) hide show
  1. package/README.md +61 -8
  2. package/dist/{DefinedWorkflow-BYyu5dK9.js → DefinedWorkflow-gpknV-5f.js} +52 -35
  3. package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
  4. package/dist/DraftsSt-DmA0jWGl.js +434 -0
  5. package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
  6. package/dist/cli.js +17 -4555
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +184 -32
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +54 -23
  11. package/dist/index.d.ts +36 -5
  12. package/dist/index.js +184 -32
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-Bn6yIJB0.js +638 -0
  15. package/dist/run-serve-Bn6yIJB0.js.map +1 -0
  16. package/dist/{run-tui-DZ22HDHI.js → run-tui-BtjaOXRh.js} +791 -395
  17. package/dist/run-tui-BtjaOXRh.js.map +1 -0
  18. package/dist/state-DKCPy105.js +4690 -0
  19. package/dist/state-DKCPy105.js.map +1 -0
  20. package/examples/README.md +6 -4
  21. package/examples/{01-txt2img.cflow.ts → rvion/01-txt2img.cflow.ts} +1 -1
  22. package/examples/{02-img2img-upload.cflow.ts → rvion/02-img2img-upload.cflow.ts} +1 -1
  23. package/examples/{03-export-workflow-json.cflow.ts → rvion/03-export-workflow-json.cflow.ts} +1 -1
  24. package/examples/{04-krea2-turbo-t2i.cflow.ts → rvion/04-krea2-turbo-t2i.cflow.ts} +2 -2
  25. package/examples/{05-comfy-cloud.cflow.ts → rvion/05-comfy-cloud.cflow.ts} +2 -2
  26. package/examples/rvion/06-qwen-image-edit.cflow.ts +89 -0
  27. package/package.json +6 -2
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/CopyOverlay.tsx +25 -0
  34. package/src/cli/tui/components/Header.tsx +9 -4
  35. package/src/cli/tui/components/HostPanel.tsx +3 -2
  36. package/src/cli/tui/components/HostsOverlay.tsx +33 -0
  37. package/src/cli/tui/components/StatusBar.tsx +29 -9
  38. package/src/cli/tui/components/TreePanel.tsx +33 -9
  39. package/src/cli/tui/components/TuiApp.tsx +54 -7
  40. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  41. package/src/cli/tui/imageClipboard.ts +39 -0
  42. package/src/cli/tui/imagePicker/fsListing.ts +6 -4
  43. package/src/cli/tui/listWindow.ts +36 -0
  44. package/src/cli/tui/run-tui.tsx +47 -7
  45. package/src/cli/tui/state/DraftsSt.ts +3 -2
  46. package/src/cli/tui/state/ExecSt.ts +156 -12
  47. package/src/cli/tui/state/HostSt.ts +94 -10
  48. package/src/cli/tui/state/PickerSt.ts +8 -2
  49. package/src/cli/tui/state/QueueSt.ts +2 -2
  50. package/src/cli/tui/state/SettingsSt.ts +25 -7
  51. package/src/cli/tui/state/TreeSt.ts +164 -36
  52. package/src/cli/tui/state/TuiSt.ts +81 -6
  53. package/src/cli/tui/state/WorkflowsSt.ts +14 -2
  54. package/src/cli/tui/treeRows.ts +165 -0
  55. package/src/host/ComfyHost.ts +7 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  57. package/src/runner/ComfyExecution.ts +21 -4
  58. package/src/runner/ComfyWorkflowLayout.ts +6 -4
  59. package/src/runner/outputPath.ts +75 -0
  60. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  61. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  62. package/src/state.ts +7 -1
  63. package/src/vars/ComfyVars.ts +33 -4
  64. package/src/vars/DefinedWorkflow.ts +21 -8
  65. package/dist/DefinedWorkflow-BYyu5dK9.js.map +0 -1
  66. package/dist/run-tui-DZ22HDHI.js.map +0 -1
@@ -0,0 +1,638 @@
1
+ import { a as ImageVarEmptyError, c as PromptVar, d as TextVar, f as ToggleVar, h as extractErrorMessage, i as ImageVar, l as SeedVar, n as ChoiceVar, o as IntVar, r as FloatVar, s as LorasVar, u as SizeVar } from "./DefinedWorkflow-gpknV-5f.js";
2
+ import { c as findDefinedWorkflow, i as listDraftsForFile, n as draftKeyForFile, r as draftsDirForFile, u as scanCflowFiles } from "./DraftsSt-DmA0jWGl.js";
3
+ import { pathToFileURL } from "node:url";
4
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, extname, join, resolve } from "pathe";
6
+ import { nanoid } from "nanoid";
7
+ import { createServer } from "node:http";
8
+ //#region src/cli/serve/describeVar.ts
9
+ function rangeText(opts) {
10
+ if (opts.min == null && opts.max == null) return "";
11
+ return ` (${opts.min ?? "-∞"}..${opts.max ?? "∞"})`;
12
+ }
13
+ function describeVar(varDef) {
14
+ const base = {
15
+ kind: varDef.kind,
16
+ label: varDef.label,
17
+ default: varDef.defaultValue
18
+ };
19
+ if (varDef instanceof PromptVar) return {
20
+ ...base,
21
+ payload: "string (\"//\" lines = comments, \"- \" lines = negative)"
22
+ };
23
+ if (varDef instanceof IntVar) return {
24
+ ...base,
25
+ payload: `integer${rangeText(varDef.opts)}`,
26
+ min: varDef.opts.min,
27
+ max: varDef.opts.max
28
+ };
29
+ if (varDef instanceof FloatVar) return {
30
+ ...base,
31
+ payload: `number${rangeText(varDef.opts)}`,
32
+ min: varDef.opts.min,
33
+ max: varDef.opts.max
34
+ };
35
+ if (varDef instanceof SeedVar) return {
36
+ ...base,
37
+ default: {
38
+ mode: varDef.mode,
39
+ value: varDef.defaultValue
40
+ },
41
+ payload: "number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}"
42
+ };
43
+ if (varDef.kind === "toggle") return {
44
+ ...base,
45
+ payload: "true or false"
46
+ };
47
+ if (varDef instanceof ChoiceVar) return {
48
+ ...base,
49
+ payload: `one of: ${varDef.choices.join(" | ")}`,
50
+ choices: varDef.choices
51
+ };
52
+ if (varDef instanceof LorasVar) return {
53
+ ...base,
54
+ payload: "{\"<lora name>\": false | true | strength | [model, clip]}",
55
+ options: varDef.options
56
+ };
57
+ if (varDef instanceof SizeVar) return {
58
+ ...base,
59
+ payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
60
+ presets: varDef.presets
61
+ };
62
+ if (varDef instanceof ImageVar) return {
63
+ ...base,
64
+ payload: "local file path or http(s) url",
65
+ extensions: varDef.extensions
66
+ };
67
+ return {
68
+ ...base,
69
+ payload: "string"
70
+ };
71
+ }
72
+ /** one aligned console line per var (startup print) */
73
+ function renderDescriptorLine(name, d, nameWidth) {
74
+ const def = typeof d.default === "string" ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default);
75
+ return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? "null", 60)}`;
76
+ }
77
+ function truncate(s, n) {
78
+ return s.length <= n ? s : s.slice(0, n - 1) + "…";
79
+ }
80
+ //#endregion
81
+ //#region src/cli/serve/applyVarPayload.ts
82
+ function isFiniteNumber(x) {
83
+ return typeof x === "number" && Number.isFinite(x);
84
+ }
85
+ function isLoraStrength(x) {
86
+ if (typeof x === "boolean") return true;
87
+ if (isFiniteNumber(x)) return true;
88
+ return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1]);
89
+ }
90
+ /** cap long option lists in error messages */
91
+ function listSome(items, cap = 20) {
92
+ if (items.length <= cap) return items.join(", ");
93
+ return `${items.slice(0, cap).join(", ")} … +${items.length - cap} more`;
94
+ }
95
+ function applyVarPayload(varDef, raw) {
96
+ const name = varDef.name ?? varDef.label ?? varDef.kind;
97
+ if (varDef instanceof TextVar || varDef instanceof PromptVar) {
98
+ if (typeof raw !== "string") return `var '${name}' expects a string`;
99
+ varDef.set(raw);
100
+ return null;
101
+ }
102
+ if (varDef instanceof IntVar || varDef instanceof FloatVar) {
103
+ if (isFiniteNumber(raw)) {
104
+ varDef.set(raw);
105
+ return null;
106
+ }
107
+ if (typeof raw === "string" && varDef.parse(raw)) return null;
108
+ const o = varDef.opts;
109
+ return `var '${name}' expects a number${o.min == null && o.max == null ? "" : ` (${o.min ?? "-∞"}..${o.max ?? "∞"})`}`;
110
+ }
111
+ if (varDef instanceof SeedVar) {
112
+ if (isFiniteNumber(raw)) {
113
+ varDef.setMode("=");
114
+ varDef.set(raw);
115
+ return null;
116
+ }
117
+ if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
118
+ const o = raw;
119
+ const mode = o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?" ? o.mode : null;
120
+ if (o.mode !== void 0 && mode == null) return `var '${name}': mode must be one of = + - ?`;
121
+ if (o.value !== void 0 && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`;
122
+ if (mode == null && o.value === void 0) return `var '${name}': give "mode" and/or "value"`;
123
+ if (mode != null) varDef.setMode(mode);
124
+ if (isFiniteNumber(o.value)) varDef.set(o.value);
125
+ return null;
126
+ }
127
+ return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`;
128
+ }
129
+ if (varDef instanceof ToggleVar) {
130
+ if (typeof raw !== "boolean") return `var '${name}' expects true or false`;
131
+ varDef.set(raw);
132
+ return null;
133
+ }
134
+ if (varDef instanceof ChoiceVar) {
135
+ if (typeof raw === "string" && varDef.parse(raw)) return null;
136
+ return `var '${name}' expects one of: ${listSome(varDef.choices)}`;
137
+ }
138
+ if (varDef instanceof LorasVar) {
139
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`;
140
+ const record = raw;
141
+ const known = new Set(varDef.options);
142
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k));
143
+ if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome(varDef.options)}`;
144
+ for (const [k, s] of Object.entries(record)) if (!isLoraStrength(s)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`;
145
+ varDef.set(record);
146
+ return null;
147
+ }
148
+ if (varDef instanceof SizeVar) {
149
+ if (typeof raw === "string" && varDef.parse(raw)) return null;
150
+ if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
151
+ const o = raw;
152
+ if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
153
+ varDef.set({
154
+ width: o.width,
155
+ height: o.height
156
+ });
157
+ return null;
158
+ }
159
+ }
160
+ return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`;
161
+ }
162
+ if (varDef instanceof ImageVar) {
163
+ if (typeof raw !== "string") return `var '${name}' expects a file path or http(s) url string`;
164
+ varDef.set(raw);
165
+ return null;
166
+ }
167
+ return `var '${name}' has unsupported kind '${varDef.kind}'`;
168
+ }
169
+ //#endregion
170
+ //#region src/cli/serve/ServeApp.ts
171
+ /** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex */
172
+ const realStarter = async (mod) => {
173
+ await mod.dw.host.connect();
174
+ return await (await mod.dw.build({ advance: true })).start({});
175
+ };
176
+ const CONTENT_TYPES = {
177
+ ".png": "image/png",
178
+ ".jpg": "image/jpeg",
179
+ ".jpeg": "image/jpeg",
180
+ ".webp": "image/webp",
181
+ ".gif": "image/gif",
182
+ ".mp4": "video/mp4",
183
+ ".webm": "video/webm",
184
+ ".json": "application/json",
185
+ ".txt": "text/plain"
186
+ };
187
+ function json(status, payload) {
188
+ return {
189
+ status,
190
+ contentType: "application/json",
191
+ body: JSON.stringify(payload, null, 2)
192
+ };
193
+ }
194
+ const USAGE = [
195
+ "GET /drafts — every served workflow, its drafts and var descriptors",
196
+ "GET /drafts/<module>/<draft> — one draft with its stored values",
197
+ "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
198
+ "POST /generate/<draft> — unqualified, when unambiguous",
199
+ "GET /outputs/<path> — generated files"
200
+ ];
201
+ var ServeApp = class {
202
+ constructor(modules, opts = {}) {
203
+ this.modules = modules;
204
+ this.opts = opts;
205
+ this.seedState = /* @__PURE__ */ new Map();
206
+ this.chains = /* @__PURE__ */ new Map();
207
+ this.starter = opts.starter ?? realStarter;
208
+ }
209
+ get outputRoot() {
210
+ return this.opts.outputRoot ?? comfyts.outputPath;
211
+ }
212
+ async handle(req) {
213
+ try {
214
+ const path = (req.url.split("?")[0] ?? "/").split("#")[0] ?? "/";
215
+ let segs;
216
+ try {
217
+ segs = path.split("/").filter((s) => s !== "").map(decodeURIComponent);
218
+ } catch {
219
+ return json(400, { error: `bad url encoding: ${path}` });
220
+ }
221
+ if (req.method === "GET") {
222
+ if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return this.replyIndex();
223
+ if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
224
+ if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
225
+ return json(404, {
226
+ error: `no route: GET ${path}`,
227
+ usage: USAGE
228
+ });
229
+ }
230
+ if (req.method === "POST" && segs[0] === "generate") {
231
+ const target = this.resolveDraft(segs.slice(1));
232
+ if ("error" in target) return json(target.status, { error: target.error });
233
+ return await this.generate(target.mod, target.draft, req);
234
+ }
235
+ return json(404, {
236
+ error: `no route: ${req.method} ${path}`,
237
+ usage: USAGE
238
+ });
239
+ } catch (e) {
240
+ console.error("[serve] request crashed:", e);
241
+ return json(500, { error: extractErrorMessage(e) });
242
+ }
243
+ }
244
+ moduleByKey(key) {
245
+ return this.modules.find((m) => m.key === key) ?? null;
246
+ }
247
+ /** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
248
+ draftsFor(mod) {
249
+ return ["default", ...listDraftsForFile(mod.file).filter((n) => n !== "default")];
250
+ }
251
+ draftExists(mod, draft) {
252
+ return draft === "default" || existsSync(join(draftsDirForFile(mod.file), `${draft}.json`));
253
+ }
254
+ resolveDraft(segs) {
255
+ if (segs.length === 2 && segs[0] != null && segs[1] != null) {
256
+ const mod = this.moduleByKey(segs[0]);
257
+ if (mod == null) return {
258
+ status: 404,
259
+ error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(", ")}`
260
+ };
261
+ if (!this.draftExists(mod, segs[1])) return {
262
+ status: 404,
263
+ error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(", ")}`
264
+ };
265
+ return {
266
+ mod,
267
+ draft: segs[1]
268
+ };
269
+ }
270
+ if (segs.length === 1 && segs[0] != null) {
271
+ const draft = segs[0];
272
+ if (this.modules.length === 1 && this.modules[0] != null) {
273
+ const mod = this.modules[0];
274
+ if (!this.draftExists(mod, draft)) return {
275
+ status: 404,
276
+ error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
277
+ };
278
+ return {
279
+ mod,
280
+ draft
281
+ };
282
+ }
283
+ const hits = this.modules.filter((m) => this.draftExists(m, draft));
284
+ if (hits.length === 1 && hits[0] != null) return {
285
+ mod: hits[0],
286
+ draft
287
+ };
288
+ if (hits.length === 0) return {
289
+ status: 404,
290
+ error: `no module has a draft '${draft}'`
291
+ };
292
+ return {
293
+ status: 400,
294
+ error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(" or ")}`
295
+ };
296
+ }
297
+ return {
298
+ status: 400,
299
+ error: "use POST /generate/<module>/<draft> or /generate/<draft>"
300
+ };
301
+ }
302
+ describeModule(mod) {
303
+ const vars = {};
304
+ for (const [name, varDef] of mod.dw.entries()) vars[name] = describeVar(varDef);
305
+ return {
306
+ module: mod.key,
307
+ file: mod.file,
308
+ host: mod.dw.host.data.id,
309
+ drafts: this.draftsFor(mod),
310
+ routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
311
+ vars
312
+ };
313
+ }
314
+ replyIndex() {
315
+ return json(200, {
316
+ server: "comfy-ts serve",
317
+ usage: USAGE,
318
+ workflows: this.modules.map((m) => this.describeModule(m)),
319
+ ...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
320
+ });
321
+ }
322
+ replyDraft(modKey, draft) {
323
+ const mod = this.moduleByKey(modKey);
324
+ if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
325
+ if (!this.draftExists(mod, draft)) return json(404, { error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}` });
326
+ return json(200, {
327
+ ...this.describeModule(mod),
328
+ draft,
329
+ values: this.draftValues(mod, draft)
330
+ });
331
+ }
332
+ /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
333
+ draftValues(mod, draft) {
334
+ const path = join(draftsDirForFile(mod.file), `${draft}.json`);
335
+ if (existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
336
+ const out = {};
337
+ for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default;
338
+ return out;
339
+ }
340
+ replyOutput(segs) {
341
+ const abs = resolve(this.outputRoot, ...segs);
342
+ if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + "/")) return json(400, { error: "path escapes the outputs root" });
343
+ if (!existsSync(abs) || !statSync(abs).isFile()) return json(404, { error: `no such output file: /${segs.join("/")}` });
344
+ return {
345
+ status: 200,
346
+ contentType: CONTENT_TYPES[extname(abs).toLowerCase()] ?? "application/octet-stream",
347
+ body: new Uint8Array(readFileSync(abs))
348
+ };
349
+ }
350
+ outputUrl(absPath) {
351
+ if (!absPath.startsWith(this.outputRoot + "/")) return null;
352
+ return "/outputs/" + absPath.slice(this.outputRoot.length + 1).split("/").map(encodeURIComponent).join("/");
353
+ }
354
+ async generate(mod, draft, req) {
355
+ let payload = {};
356
+ if (req.body != null && req.body.trim() !== "") {
357
+ let parsed;
358
+ try {
359
+ parsed = JSON.parse(req.body);
360
+ } catch (e) {
361
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
362
+ }
363
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
364
+ payload = parsed;
365
+ }
366
+ const t0 = Date.now();
367
+ const seeds = {};
368
+ const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
369
+ if ("error" in started) return json(started.status, { error: started.error });
370
+ const execution = started.execution;
371
+ console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
372
+ await execution.done;
373
+ const durationMs = Date.now() - t0;
374
+ if (execution.status === "Failure") {
375
+ console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`);
376
+ return json(500, {
377
+ ok: false,
378
+ module: mod.key,
379
+ draft,
380
+ promptId: execution.data.id,
381
+ durationMs,
382
+ error: execution.data.error ?? "execution failed"
383
+ });
384
+ }
385
+ console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1e3).toFixed(1)}s · ${execution.images.length} image(s)`);
386
+ const first = execution.images[0];
387
+ if (req.accept?.includes("image/") && first != null) return {
388
+ status: 200,
389
+ contentType: CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? "application/octet-stream",
390
+ body: new Uint8Array(readFileSync(first.absPath))
391
+ };
392
+ return json(200, {
393
+ ok: true,
394
+ module: mod.key,
395
+ draft,
396
+ promptId: execution.data.id,
397
+ durationMs,
398
+ seeds,
399
+ images: execution.images.map((img) => ({
400
+ filename: img.filename,
401
+ url: this.outputUrl(img.absPath),
402
+ absPath: img.absPath
403
+ }))
404
+ });
405
+ }
406
+ /** everything that touches the module's SHARED vars, under the module mutex */
407
+ async prepareAndStart(mod, draft, payload, seeds) {
408
+ for (const [, varDef] of mod.dw.entries()) varDef.reset();
409
+ const draftPath = join(draftsDirForFile(mod.file), `${draft}.json`);
410
+ if (existsSync(draftPath)) try {
411
+ const values = JSON.parse(readFileSync(draftPath, "utf8"));
412
+ for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k]);
413
+ } catch (e) {
414
+ return {
415
+ status: 500,
416
+ error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}`
417
+ };
418
+ }
419
+ const varMap = new Map(mod.dw.entries());
420
+ for (const [k, rawValue] of Object.entries(payload)) {
421
+ const varDef = varMap.get(k);
422
+ if (varDef == null) return {
423
+ status: 400,
424
+ error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(", ")}`
425
+ };
426
+ let value = rawValue;
427
+ if (varDef instanceof ImageVar && typeof rawValue === "string" && /^https?:\/\//.test(rawValue)) try {
428
+ value = await this.downloadInput(rawValue);
429
+ } catch (e) {
430
+ return {
431
+ status: 400,
432
+ error: `var '${k}': ${extractErrorMessage(e)}`
433
+ };
434
+ }
435
+ const err = applyVarPayload(varDef, value);
436
+ if (err != null) return {
437
+ status: 400,
438
+ error: err
439
+ };
440
+ }
441
+ for (const [k, varDef] of varMap) if (varDef instanceof ImageVar && varDef.isSet() && !existsSync(varDef.absPath())) return {
442
+ status: 400,
443
+ error: `image var '${k}': file not found: ${varDef.absPath()}`
444
+ };
445
+ for (const [k, varDef] of varMap) {
446
+ if (!(varDef instanceof SeedVar)) continue;
447
+ const stateKey = `${mod.key}/${draft}/${k}`;
448
+ if (!(k in payload)) {
449
+ if (varDef.mode === "?") varDef.randomize();
450
+ else if (varDef.mode === "+" || varDef.mode === "-") {
451
+ const last = this.seedState.get(stateKey);
452
+ if (last != null) varDef.set(last + (varDef.mode === "+" ? 1 : -1));
453
+ }
454
+ }
455
+ this.seedState.set(stateKey, varDef.value);
456
+ seeds[k] = varDef.value;
457
+ }
458
+ try {
459
+ return { execution: await this.starter(mod) };
460
+ } catch (e) {
461
+ if (e instanceof ImageVarEmptyError) return {
462
+ status: 400,
463
+ error: e.message
464
+ };
465
+ return {
466
+ status: 500,
467
+ error: extractErrorMessage(e)
468
+ };
469
+ }
470
+ }
471
+ /** serialize fn per module key; the stored chain never rejects */
472
+ exclusive(key, fn) {
473
+ const next = (this.chains.get(key) ?? Promise.resolve()).then(fn);
474
+ this.chains.set(key, next.catch(() => {}));
475
+ return next;
476
+ }
477
+ /** payload image urls land as local files under outputs/serve-inputs/ */
478
+ async downloadInput(url) {
479
+ const res = await fetch(url);
480
+ if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`);
481
+ const bytes = new Uint8Array(await res.arrayBuffer());
482
+ const name = basename(new URL(url).pathname) || "input";
483
+ const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${name}`);
484
+ mkdirSync(dirname(abs), { recursive: true });
485
+ writeFileSync(abs, bytes);
486
+ return abs;
487
+ }
488
+ };
489
+ //#endregion
490
+ //#region src/cli/serve/run-serve.ts
491
+ const DEFAULT_PORT = 8288;
492
+ const BODY_CAP = 1e7;
493
+ function parseArgs(args) {
494
+ let target;
495
+ let port = DEFAULT_PORT;
496
+ let bind = "127.0.0.1";
497
+ for (let i = 0; i < args.length; i++) {
498
+ const a = args[i];
499
+ if (a === "--port") {
500
+ const n = Number(args[++i]);
501
+ if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` };
502
+ port = n;
503
+ } else if (a === "--bind") {
504
+ const b = args[++i];
505
+ if (b == null) return { error: "--bind expects an address" };
506
+ bind = b;
507
+ } else if (a != null && a.startsWith("--")) return { error: `unknown flag '${a}'` };
508
+ else if (a != null) {
509
+ if (target != null) return { error: `one target only (got '${target}' and '${a}')` };
510
+ target = a;
511
+ }
512
+ }
513
+ return {
514
+ target,
515
+ port,
516
+ bind
517
+ };
518
+ }
519
+ /** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
520
+ function makeRequestListener(app) {
521
+ return (req, res) => {
522
+ const cors = {
523
+ "access-control-allow-origin": "*",
524
+ "access-control-allow-methods": "GET, POST, OPTIONS",
525
+ "access-control-allow-headers": "content-type, accept"
526
+ };
527
+ const chunks = [];
528
+ let size = 0;
529
+ let overflow = false;
530
+ req.on("error", (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`));
531
+ req.on("data", (c) => {
532
+ if (overflow) return;
533
+ size += c.length;
534
+ if (size > BODY_CAP) {
535
+ overflow = true;
536
+ res.writeHead(413, {
537
+ "content-type": "application/json",
538
+ ...cors
539
+ });
540
+ res.end(JSON.stringify({ error: "payload too large" }), () => req.destroy());
541
+ } else chunks.push(c);
542
+ });
543
+ req.on("end", () => {
544
+ if (overflow) return;
545
+ if (req.method === "OPTIONS") {
546
+ res.writeHead(204, cors);
547
+ res.end();
548
+ return;
549
+ }
550
+ app.handle({
551
+ method: req.method ?? "GET",
552
+ url: req.url ?? "/",
553
+ accept: req.headers.accept,
554
+ body: Buffer.concat(chunks).toString("utf8")
555
+ }).then((reply) => {
556
+ res.writeHead(reply.status, {
557
+ "content-type": reply.contentType,
558
+ ...cors
559
+ });
560
+ res.end(reply.body);
561
+ }).catch((e) => {
562
+ console.error(`[serve] response write failed: ${extractErrorMessage(e)}`);
563
+ res.destroy();
564
+ });
565
+ });
566
+ };
567
+ }
568
+ async function runServe(args) {
569
+ const parsed = parseArgs(args);
570
+ if ("error" in parsed) {
571
+ console.error(`[comfy-ts serve] ${parsed.error}`);
572
+ return 1;
573
+ }
574
+ const target = resolve(parsed.target ?? ".");
575
+ let files;
576
+ try {
577
+ files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target];
578
+ } catch {
579
+ console.error(`[comfy-ts serve] no such file or directory: ${target}`);
580
+ return 1;
581
+ }
582
+ if (files.length === 0) {
583
+ console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`);
584
+ return 1;
585
+ }
586
+ const modules = [];
587
+ const loadErrors = {};
588
+ for (const file of files) try {
589
+ const dw = findDefinedWorkflow(await import(pathToFileURL(file).href));
590
+ if (dw == null) throw new Error("exports no DefinedWorkflow");
591
+ const key = draftKeyForFile(file);
592
+ const clash = modules.find((m) => m.key === key);
593
+ if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`);
594
+ modules.push({
595
+ key,
596
+ file,
597
+ dw
598
+ });
599
+ } catch (e) {
600
+ loadErrors[file] = extractErrorMessage(e);
601
+ console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`);
602
+ }
603
+ if (modules.length === 0) {
604
+ console.error("[comfy-ts serve] every module failed to load — nothing to serve");
605
+ return 1;
606
+ }
607
+ const app = new ServeApp(modules, { loadErrors });
608
+ printStartup(app, parsed.bind, parsed.port);
609
+ const server = createServer(makeRequestListener(app));
610
+ server.on("error", (e) => {
611
+ console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`);
612
+ process.exitCode = 1;
613
+ server.close();
614
+ });
615
+ server.listen(parsed.port, parsed.bind);
616
+ return new Promise((resolveExit) => {
617
+ server.on("close", () => resolveExit(typeof process.exitCode === "number" ? process.exitCode : 0));
618
+ });
619
+ }
620
+ function printStartup(app, bind, port) {
621
+ const base = `http://${bind}:${port}`;
622
+ console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`);
623
+ if (bind !== "127.0.0.1" && bind !== "localhost") console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`);
624
+ for (const mod of app.modules) {
625
+ console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`);
626
+ for (const draft of app.draftsFor(mod)) console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`);
627
+ const entries = mod.dw.entries();
628
+ const nameWidth = Math.max(...entries.map(([n]) => n.length), 4);
629
+ for (const [name, varDef] of entries) console.log(renderDescriptorLine(name, describeVar(varDef), nameWidth));
630
+ }
631
+ const firstMod = app.modules[0];
632
+ if (firstMod != null) console.log(`\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`);
633
+ console.log(`docs: GET ${base}/drafts (json index of everything above)`);
634
+ }
635
+ //#endregion
636
+ export { runServe };
637
+
638
+ //# sourceMappingURL=run-serve-Bn6yIJB0.js.map