comfy-ts 2.6.0 → 2.8.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 (101) hide show
  1. package/README.md +22 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +8 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +288 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +128 -7
  11. package/dist/index.d.ts +128 -7
  12. package/dist/index.js +286 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
  17. package/dist/run-tui-BPw-SZYW.js.map +1 -0
  18. package/dist/serve-web.js +434 -81
  19. package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
  20. package/dist/state-B-boDz-Z.js.map +1 -0
  21. package/dist/web.d.ts +112 -7
  22. package/dist/web.js +239 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +7 -1
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +4 -2
  35. package/src/cli/serve/ServeApp.ts +825 -43
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  39. package/src/cli/serve/run-serve.ts +58 -29
  40. package/src/cli/serve/serveSettings.ts +86 -0
  41. package/src/cli/serve/startupPrint.ts +111 -0
  42. package/src/cli/serve/web/api.ts +120 -1
  43. package/src/cli/serve/web/components/App.tsx +61 -22
  44. package/src/cli/serve/web/components/Gallery.tsx +243 -30
  45. package/src/cli/serve/web/components/Icon.tsx +160 -0
  46. package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
  47. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  48. package/src/cli/serve/web/components/VarsForm.tsx +440 -80
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  50. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  51. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  52. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  53. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  54. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  55. package/src/cli/serve/web/llm.ts +254 -0
  56. package/src/cli/serve/web/logWeb.ts +6 -0
  57. package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
  58. package/src/cli/serve/web/state/FormSt.ts +70 -18
  59. package/src/cli/serve/web/state/RunSt.ts +22 -1
  60. package/src/cli/serve/web/state/WebSt.ts +542 -13
  61. package/src/cli/serve/web/state/lightbox.ts +44 -0
  62. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  63. package/src/cli/serve/web/state/payload.ts +44 -2
  64. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  65. package/src/cli/serve/web/styles.ts +415 -57
  66. package/src/cli/serve/web/tsconfig.json +4 -0
  67. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  68. package/src/cli/tui/components/StatusBar.tsx +14 -1
  69. package/src/cli/tui/components/TuiApp.tsx +5 -2
  70. package/src/cli/tui/state/HostSt.ts +3 -2
  71. package/src/cli/tui/state/PickerSt.ts +48 -2
  72. package/src/cli/tui/state/TreeSt.ts +1 -1
  73. package/src/cli/tui/state/TuiSt.ts +2 -1
  74. package/src/coreExports.ts +8 -1
  75. package/src/graph/ComfyNode.ts +58 -1
  76. package/src/host/ComfyHost.ts +13 -2
  77. package/src/host/ComfyManager.ts +31 -13
  78. package/src/host/loraInfoCache.ts +35 -1
  79. package/src/host/loraManagerApi.ts +94 -0
  80. package/src/index.ts +2 -0
  81. package/src/promptEnhancers.ts +102 -0
  82. package/src/runner/ComfyExecution.ts +61 -6
  83. package/src/runner/ComfyWorkflow.ts +18 -4
  84. package/src/runner/ComfyWsApi.ts +3 -0
  85. package/src/runner/describePromptRejection.ts +34 -0
  86. package/src/sdk-generator/ComfySchema.ts +17 -4
  87. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  88. package/src/state.ts +6 -0
  89. package/src/utils/ansi.ts +13 -0
  90. package/src/utils/matchesRegex.ts +13 -0
  91. package/src/utils/safeName.ts +29 -0
  92. package/src/utils/stringMap.ts +9 -0
  93. package/src/vars/ComfyVars.ts +61 -10
  94. package/src/vars/presets.ts +17 -0
  95. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  96. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  97. package/dist/run-serve-CVu39RNd.js +0 -1002
  98. package/dist/run-serve-CVu39RNd.js.map +0 -1
  99. package/dist/run-tui-idFhdO4f.js.map +0 -1
  100. package/dist/state-C90kdjtB.js.map +0 -1
  101. package/src/cli/serve/web/openrouter.ts +0 -142
@@ -1,1002 +0,0 @@
1
- import { C as loraPreviewMapFrom, S as loraKey, T as bang, _ as fetchLoraList, d as getLoraPreviewUrl, f as getLoraTriggerWords, h as refreshLoraInfoCacheIfChanged, u as getLoraDisplayName, v as fetchLoraPreviewBytes, w as extractErrorMessage } from "./DefinedWorkflow-BJgt5t0x.js";
2
- import { c as findDefinedWorkflow, i as listDraftsForFile, n as draftKeyForFile, r as draftsDirForFile, u as scanCflowFiles } from "./DraftsSt-dizp3VcC.js";
3
- import { fileURLToPath, 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
- switch (varDef.kind) {
20
- case "prompt": return {
21
- ...base,
22
- payload: "string (\"//\" lines = comments, \"- \" lines = negative)"
23
- };
24
- case "text": return {
25
- ...base,
26
- payload: "string"
27
- };
28
- case "int": {
29
- const v = varDef;
30
- return {
31
- ...base,
32
- payload: `integer${rangeText(v.opts)}`,
33
- min: v.opts.min,
34
- max: v.opts.max
35
- };
36
- }
37
- case "float": {
38
- const v = varDef;
39
- return {
40
- ...base,
41
- payload: `number${rangeText(v.opts)}`,
42
- min: v.opts.min,
43
- max: v.opts.max
44
- };
45
- }
46
- case "seed": {
47
- const v = varDef;
48
- return {
49
- ...base,
50
- default: {
51
- mode: v.defaultMode,
52
- value: v.defaultValue
53
- },
54
- payload: "number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}"
55
- };
56
- }
57
- case "toggle": return {
58
- ...base,
59
- payload: "true or false"
60
- };
61
- case "choice": {
62
- const v = varDef;
63
- return {
64
- ...base,
65
- payload: `one of: ${v.choices.join(" | ")}`,
66
- choices: v.choices
67
- };
68
- }
69
- case "loras": {
70
- const v = varDef;
71
- return {
72
- ...base,
73
- payload: "{\"<lora name>\": false | true | strength | [model, clip]}",
74
- options: v.options
75
- };
76
- }
77
- case "size": {
78
- const v = varDef;
79
- return {
80
- ...base,
81
- payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
82
- presets: v.presets
83
- };
84
- }
85
- case "image": {
86
- const v = varDef;
87
- return {
88
- ...base,
89
- payload: "local file path or http(s) url",
90
- extensions: v.extensions
91
- };
92
- }
93
- default: {
94
- const unknownKind = varDef.kind;
95
- return {
96
- ...base,
97
- payload: `string (unrecognised kind '${String(unknownKind)}')`
98
- };
99
- }
100
- }
101
- }
102
- /** one aligned console line per var (startup print) */
103
- function renderDescriptorLine(name, d, nameWidth) {
104
- const def = typeof d.default === "string" ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default);
105
- return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? "null", 60)}`;
106
- }
107
- function truncate(s, n) {
108
- return s.length <= n ? s : s.slice(0, n - 1) + "…";
109
- }
110
- //#endregion
111
- //#region src/cli/serve/applyVarPayload.ts
112
- function isFiniteNumber(x) {
113
- return typeof x === "number" && Number.isFinite(x);
114
- }
115
- function isLoraStrength(x) {
116
- if (typeof x === "boolean") return true;
117
- if (isFiniteNumber(x)) return true;
118
- return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1]);
119
- }
120
- /** cap long option lists in error messages */
121
- function listSome(items, cap = 20) {
122
- if (items.length <= cap) return items.join(", ");
123
- return `${items.slice(0, cap).join(", ")} … +${items.length - cap} more`;
124
- }
125
- function applyVarPayload(varDef, raw) {
126
- const name = varDef.name ?? varDef.label ?? varDef.kind;
127
- switch (varDef.kind) {
128
- case "text":
129
- case "prompt":
130
- if (typeof raw !== "string") return `var '${name}' expects a string`;
131
- varDef.set(raw);
132
- return null;
133
- case "int":
134
- case "float": {
135
- const v = varDef;
136
- if (isFiniteNumber(raw)) {
137
- v.set(raw);
138
- return null;
139
- }
140
- if (typeof raw === "string" && v.parse(raw)) return null;
141
- const o = v.opts;
142
- return `var '${name}' expects a number${o.min == null && o.max == null ? "" : ` (${o.min ?? "-∞"}..${o.max ?? "∞"})`}`;
143
- }
144
- case "seed": {
145
- const v = varDef;
146
- if (isFiniteNumber(raw)) {
147
- v.setMode("=");
148
- v.set(raw);
149
- return null;
150
- }
151
- if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
152
- const o = raw;
153
- const mode = o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?" ? o.mode : null;
154
- if (o.mode !== void 0 && mode == null) return `var '${name}': mode must be one of = + - ?`;
155
- if (o.value !== void 0 && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`;
156
- if (mode == null && o.value === void 0) return `var '${name}': give "mode" and/or "value"`;
157
- if (mode != null) v.setMode(mode);
158
- if (isFiniteNumber(o.value)) v.set(o.value);
159
- return null;
160
- }
161
- return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`;
162
- }
163
- case "toggle":
164
- if (typeof raw !== "boolean") return `var '${name}' expects true or false`;
165
- varDef.set(raw);
166
- return null;
167
- case "choice": {
168
- const v = varDef;
169
- if (typeof raw === "string" && v.parse(raw)) return null;
170
- return `var '${name}' expects one of: ${listSome(v.choices)}`;
171
- }
172
- case "loras": {
173
- const v = varDef;
174
- if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`;
175
- const record = raw;
176
- const known = new Set(v.options);
177
- const unknownNames = Object.keys(record).filter((k) => !known.has(k));
178
- if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome(v.options)}`;
179
- for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`;
180
- v.set(record);
181
- return null;
182
- }
183
- case "size": {
184
- const v = varDef;
185
- if (typeof raw === "string" && v.parse(raw)) return null;
186
- if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
187
- const o = raw;
188
- if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
189
- v.set({
190
- width: o.width,
191
- height: o.height
192
- });
193
- return null;
194
- }
195
- }
196
- return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`;
197
- }
198
- case "image":
199
- if (typeof raw !== "string") return `var '${name}' expects a file path or http(s) url string`;
200
- varDef.set(raw);
201
- return null;
202
- default: {
203
- const unknownKind = varDef.kind;
204
- return `var '${name}' has unsupported kind '${String(unknownKind)}'`;
205
- }
206
- }
207
- }
208
- //#endregion
209
- //#region src/cli/serve/ServeApp.ts
210
- /** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.
211
- * serve OPTS INTO local saving (library default is memory-only, architecture.md
212
- * item 14): the /outputs/ routes serve files, grouped per module */
213
- const realStarter = async (mod) => {
214
- await mod.dw.host.connect();
215
- return await (await mod.dw.build({ advance: true })).start({ save: { prefix: mod.key } });
216
- };
217
- const CONTENT_TYPES = {
218
- ".png": "image/png",
219
- ".jpg": "image/jpeg",
220
- ".jpeg": "image/jpeg",
221
- ".webp": "image/webp",
222
- ".gif": "image/gif",
223
- ".mp4": "video/mp4",
224
- ".webm": "video/webm",
225
- ".json": "application/json",
226
- ".txt": "text/plain"
227
- };
228
- /** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
229
- function sniffImageContentType(bytes) {
230
- if (bytes[0] === 137 && bytes[1] === 80) return "image/png";
231
- if (bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
232
- if (bytes[0] === 71 && bytes[1] === 73) return "image/gif";
233
- if (bytes[0] === 82 && bytes[1] === 73) return "image/webp";
234
- return "application/octet-stream";
235
- }
236
- function json(status, payload) {
237
- return {
238
- status,
239
- contentType: "application/json",
240
- body: JSON.stringify(payload, null, 2)
241
- };
242
- }
243
- const USAGE = [
244
- "GET / in a browser — web control panel (every var as a form control)",
245
- "GET /drafts — every served workflow, its drafts and var descriptors",
246
- "GET /drafts/<module>/<draft> — one draft with its stored values",
247
- "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
248
- "POST /generate/<draft> — unqualified, when unambiguous",
249
- "PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
250
- "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
251
- "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
252
- "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
253
- "GET /lora-preview/<hostId>/<lora> — preview image bytes",
254
- "GET /outputs/<path> — generated files"
255
- ];
256
- /** the html shell; the app itself is ONE bundle at /web/app.js */
257
- const WEB_SHELL = `<!doctype html>
258
- <html lang="en">
259
- <head>
260
- <meta charset="utf-8">
261
- <meta name="viewport" content="width=device-width, initial-scale=1">
262
- <title>comfy-ts serve</title>
263
- <style>html{background:#101217;color:#e8eaf0}</style>
264
- </head>
265
- <body>
266
- <div id="root"></div>
267
- <script type="module" src="/web/app.js"><\/script>
268
- </body>
269
- </html>
270
- `;
271
- var ServeApp = class {
272
- constructor(modules, opts = {}) {
273
- this.modules = modules;
274
- this.opts = opts;
275
- this.seedState = /* @__PURE__ */ new Map();
276
- this.chains = /* @__PURE__ */ new Map();
277
- this.webJsCache = null;
278
- this.liveRuns = /* @__PURE__ */ new Map();
279
- this.latentPreviews = /* @__PURE__ */ new Map();
280
- this.latentSeq = 0;
281
- this.promptOwner = /* @__PURE__ */ new Map();
282
- this.latentHosts = /* @__PURE__ */ new Set();
283
- this.previewSweeps = /* @__PURE__ */ new Map();
284
- this.starter = opts.starter ?? realStarter;
285
- }
286
- get outputRoot() {
287
- return this.opts.outputRoot ?? comfyts.outputPath;
288
- }
289
- async handle(req) {
290
- try {
291
- const path = (req.url.split("?")[0] ?? "/").split("#")[0] ?? "/";
292
- let segs;
293
- try {
294
- segs = path.split("/").filter((s) => s !== "").map(decodeURIComponent);
295
- } catch {
296
- return json(400, { error: `bad url encoding: ${path}` });
297
- }
298
- if (req.method === "GET") {
299
- if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
300
- this.webJsCache ??= this.opts.webJs();
301
- if (await this.webJsCache != null) return {
302
- status: 200,
303
- contentType: "text/html; charset=utf-8",
304
- body: WEB_SHELL
305
- };
306
- }
307
- if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return this.replyIndex();
308
- if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2) return await this.replyWebJs();
309
- if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
310
- if (segs[0] === "run" && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1]);
311
- if (segs[0] === "run" && segs.length === 3 && segs[1] != null && segs[2] === "preview") return this.replyRunPreview(segs[1]);
312
- if (segs[0] === "lora-info" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyLoraInfo(segs[1], segs[2]);
313
- if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
314
- if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
315
- return json(404, {
316
- error: `no route: GET ${path}`,
317
- usage: USAGE
318
- });
319
- }
320
- if (req.method === "POST" && segs[0] === "generate") {
321
- const target = this.resolveDraft(segs.slice(1));
322
- if ("error" in target) return json(target.status, { error: target.error });
323
- return await this.generate(target.mod, target.draft, req);
324
- }
325
- if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
326
- if (req.method === "PUT" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replySaveDraft(segs[1], segs[2], req);
327
- return json(404, {
328
- error: `no route: ${req.method} ${path}`,
329
- usage: USAGE
330
- });
331
- } catch (e) {
332
- console.error("[serve] request crashed:", e);
333
- return json(500, { error: extractErrorMessage(e) });
334
- }
335
- }
336
- moduleByKey(key) {
337
- return this.modules.find((m) => m.key === key) ?? null;
338
- }
339
- /** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
340
- draftsFor(mod) {
341
- return ["default", ...listDraftsForFile(mod.file).filter((n) => n !== "default")];
342
- }
343
- /** THE draft-name gate, shared by every route that turns a url segment into a path.
344
- * handle() decodes per segment, so `%2F` reaches here as a real `/` while the segment
345
- * count still looks right — an unguarded reader would read (and RUN) any json on disk */
346
- validDraftName(raw) {
347
- const name = raw.trim();
348
- if (name.length > 100) return null;
349
- return /^[\w][\w .-]*$/.test(name) ? name : null;
350
- }
351
- /** absolute path of a draft file, or null when the name is not one we accept */
352
- draftPath(mod, draft) {
353
- const name = this.validDraftName(draft);
354
- return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`);
355
- }
356
- draftExists(mod, draft) {
357
- const path = this.draftPath(mod, draft);
358
- if (path == null) return false;
359
- return draft === "default" || existsSync(path);
360
- }
361
- resolveDraft(segs) {
362
- if (segs.length === 2 && segs[0] != null && segs[1] != null) {
363
- const mod = this.moduleByKey(segs[0]);
364
- if (mod == null) return {
365
- status: 404,
366
- error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(", ")}`
367
- };
368
- if (!this.draftExists(mod, segs[1])) return {
369
- status: 404,
370
- error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(", ")}`
371
- };
372
- return {
373
- mod,
374
- draft: segs[1]
375
- };
376
- }
377
- if (segs.length === 1 && segs[0] != null) {
378
- const draft = segs[0];
379
- if (this.modules.length === 1 && this.modules[0] != null) {
380
- const mod = this.modules[0];
381
- if (!this.draftExists(mod, draft)) return {
382
- status: 404,
383
- error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
384
- };
385
- return {
386
- mod,
387
- draft
388
- };
389
- }
390
- const hits = this.modules.filter((m) => this.draftExists(m, draft));
391
- if (hits.length === 1 && hits[0] != null) return {
392
- mod: hits[0],
393
- draft
394
- };
395
- if (hits.length === 0) return {
396
- status: 404,
397
- error: `no module has a draft '${draft}'`
398
- };
399
- return {
400
- status: 400,
401
- error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(" or ")}`
402
- };
403
- }
404
- return {
405
- status: 400,
406
- error: "use POST /generate/<module>/<draft> or /generate/<draft>"
407
- };
408
- }
409
- describeModule(mod) {
410
- refreshLoraInfoCacheIfChanged();
411
- const hostId = mod.dw.host.data.id;
412
- const vars = {};
413
- for (const [name, varDef] of mod.dw.entries()) {
414
- const desc = describeVar(varDef);
415
- if (desc.kind === "loras" && desc.options != null) {
416
- const labels = {};
417
- for (const option of desc.options) {
418
- const label = getLoraDisplayName(option, hostId);
419
- if (label !== option) labels[option] = label;
420
- }
421
- if (Object.keys(labels).length > 0) desc.optionLabels = labels;
422
- }
423
- vars[name] = desc;
424
- }
425
- return {
426
- module: mod.key,
427
- file: mod.file,
428
- host: mod.dw.host.data.id,
429
- drafts: this.draftsFor(mod),
430
- routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
431
- vars
432
- };
433
- }
434
- replyIndex() {
435
- return json(200, {
436
- server: "comfy-ts serve",
437
- usage: USAGE,
438
- workflows: this.modules.map((m) => this.describeModule(m)),
439
- ...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
440
- });
441
- }
442
- replyDraft(modKey, draft) {
443
- const mod = this.moduleByKey(modKey);
444
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
445
- if (!this.draftExists(mod, draft)) return json(404, { error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}` });
446
- return json(200, {
447
- ...this.describeModule(mod),
448
- draft,
449
- values: this.draftValues(mod, draft)
450
- });
451
- }
452
- /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
453
- draftValues(mod, draft) {
454
- const path = this.draftPath(mod, draft);
455
- if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
456
- const out = {};
457
- for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default;
458
- return out;
459
- }
460
- replyOutput(segs) {
461
- const abs = resolve(this.outputRoot, ...segs);
462
- if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + "/")) return json(400, { error: "path escapes the outputs root" });
463
- if (!existsSync(abs) || !statSync(abs).isFile()) return json(404, { error: `no such output file: /${segs.join("/")}` });
464
- return {
465
- status: 200,
466
- contentType: CONTENT_TYPES[extname(abs).toLowerCase()] ?? "application/octet-stream",
467
- body: new Uint8Array(readFileSync(abs))
468
- };
469
- }
470
- async replyWebJs() {
471
- if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
472
- this.webJsCache ??= this.opts.webJs();
473
- const js = await this.webJsCache;
474
- if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
475
- return {
476
- status: 200,
477
- contentType: "text/javascript; charset=utf-8",
478
- body: js
479
- };
480
- }
481
- /** browser file → local file an image var can point at (downloadInput family) */
482
- replyUpload(req) {
483
- let parsed;
484
- try {
485
- parsed = JSON.parse(req.body ?? "");
486
- } catch (e) {
487
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
488
- }
489
- const o = parsed ?? {};
490
- if (typeof o.name !== "string" || o.name === "" || typeof o.dataBase64 !== "string" || o.dataBase64 === "") return json(400, { error: "upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}" });
491
- const bytes = Buffer.from(o.dataBase64, "base64");
492
- if (bytes.length === 0) return json(400, { error: "dataBase64 decoded to zero bytes" });
493
- const safe = basename(o.name).replace(/[^\w.-]+/g, "_") || "upload";
494
- const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${safe}`);
495
- mkdirSync(dirname(abs), { recursive: true });
496
- writeFileSync(abs, bytes);
497
- console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`);
498
- return json(200, {
499
- ok: true,
500
- path: abs,
501
- url: this.outputUrl(abs)
502
- });
503
- }
504
- async replySaveDraft(modKey, rawDraft, req) {
505
- const mod = this.moduleByKey(modKey);
506
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
507
- const draft = this.validDraftName(rawDraft);
508
- if (draft == null) return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` });
509
- let parsed;
510
- try {
511
- parsed = JSON.parse(req.body ?? "");
512
- } catch (e) {
513
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
514
- }
515
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
516
- const values = parsed;
517
- const known = new Set(mod.dw.entries().map(([k]) => k));
518
- const unknown = Object.keys(values).filter((k) => !known.has(k));
519
- if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
520
- const path = bang(this.draftPath(mod, draft), "draft name validated just above");
521
- await this.exclusive(mod.key, () => {
522
- mkdirSync(dirname(path), { recursive: true });
523
- writeFileSync(path, JSON.stringify(values, null, 2));
524
- return Promise.resolve();
525
- });
526
- return json(200, {
527
- ok: true,
528
- module: mod.key,
529
- draft,
530
- drafts: this.draftsFor(mod)
531
- });
532
- }
533
- runningModules() {
534
- return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
535
- }
536
- /** one dispatcher per host, installed once and left in place (idempotent) */
537
- wireLatents(host) {
538
- if (this.latentHosts.has(host)) return;
539
- this.latentHosts.add(host);
540
- host.onLatentPreview = (p) => {
541
- const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : void 0;
542
- const running = this.runningModules();
543
- const key = owner ?? (running.length === 1 ? running[0] : void 0);
544
- if (key == null) return;
545
- this.latentPreviews.set(key, {
546
- bytes: p.bytes,
547
- mime: p.mime,
548
- seq: ++this.latentSeq
549
- });
550
- };
551
- }
552
- replyRunStatus(modKey) {
553
- const mod = this.moduleByKey(modKey);
554
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
555
- const exec = this.liveRuns.get(mod.key);
556
- const running = exec != null && exec.status !== "Success" && exec.status !== "Failure";
557
- return json(200, {
558
- running,
559
- status: exec?.status ?? "idle",
560
- percent: running ? exec.progressGlobal?.percent ?? null : null,
561
- hasPreview: this.latentPreviews.has(mod.key),
562
- previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null
563
- });
564
- }
565
- replyRunPreview(modKey) {
566
- const mod = this.moduleByKey(modKey);
567
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
568
- const preview = this.latentPreviews.get(mod.key);
569
- if (preview == null) return json(404, { error: "no latent preview yet" });
570
- return {
571
- status: 200,
572
- contentType: preview.mime !== "" ? preview.mime : sniffImageContentType(preview.bytes),
573
- body: preview.bytes
574
- };
575
- }
576
- hostById(hostId) {
577
- return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null;
578
- }
579
- hostIds() {
580
- return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(", ");
581
- }
582
- /** mirror-backed text for the hover pane, no network */
583
- replyLoraInfo(hostId, lora) {
584
- if (this.hostById(hostId) == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
585
- refreshLoraInfoCacheIfChanged();
586
- return json(200, {
587
- name: lora,
588
- displayName: getLoraDisplayName(lora, hostId),
589
- triggerWords: getLoraTriggerWords(lora, hostId)
590
- });
591
- }
592
- async replyLoraPreview(hostId, lora) {
593
- const host = this.hostById(hostId);
594
- if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
595
- refreshLoraInfoCacheIfChanged();
596
- let url = getLoraPreviewUrl(lora, hostId);
597
- if (url == null) {
598
- let sweep = this.previewSweeps.get(hostId);
599
- if (sweep == null) {
600
- sweep = fetchLoraList(host).then((r) => {
601
- if (r.status === "unreachable") {
602
- this.previewSweeps.delete(hostId);
603
- return {
604
- status: r.status,
605
- map: null
606
- };
607
- }
608
- return {
609
- status: r.status,
610
- map: r.status === "absent" ? null : loraPreviewMapFrom(r.items)
611
- };
612
- });
613
- this.previewSweeps.set(hostId, sweep);
614
- }
615
- const swept = await sweep;
616
- url = swept.map?.get(loraKey(lora)) ?? null;
617
- if (url == null && swept.status === "unreachable") return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` });
618
- if (url == null && swept.status === "absent") return json(404, { error: `lora-manager extension not detected on '${hostId}'` });
619
- }
620
- if (url == null) return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` });
621
- const bytes = await fetchLoraPreviewBytes(host, url);
622
- if (bytes == null) return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` });
623
- return {
624
- status: 200,
625
- contentType: sniffImageContentType(bytes),
626
- body: bytes
627
- };
628
- }
629
- outputUrl(absPath) {
630
- if (!absPath.startsWith(this.outputRoot + "/")) return null;
631
- return "/outputs/" + absPath.slice(this.outputRoot.length + 1).split("/").map(encodeURIComponent).join("/");
632
- }
633
- async generate(mod, draft, req) {
634
- let payload = {};
635
- if (req.body != null && req.body.trim() !== "") {
636
- let parsed;
637
- try {
638
- parsed = JSON.parse(req.body);
639
- } catch (e) {
640
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
641
- }
642
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
643
- payload = parsed;
644
- }
645
- const t0 = Date.now();
646
- const seeds = {};
647
- const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
648
- if ("error" in started) return json(started.status, { error: started.error });
649
- const execution = started.execution;
650
- this.liveRuns.set(mod.key, execution);
651
- this.promptOwner.set(execution.data.id, mod.key);
652
- console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
653
- try {
654
- await execution.done;
655
- } finally {
656
- this.promptOwner.delete(execution.data.id);
657
- }
658
- const durationMs = Date.now() - t0;
659
- if (execution.status === "Failure") {
660
- console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`);
661
- return json(500, {
662
- ok: false,
663
- module: mod.key,
664
- draft,
665
- promptId: execution.data.id,
666
- durationMs,
667
- error: execution.data.error ?? "execution failed"
668
- });
669
- }
670
- console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1e3).toFixed(1)}s · ${execution.images.length} image(s)`);
671
- const first = execution.images[0];
672
- if (req.accept?.includes("image/") && first?.absPath != null) return {
673
- status: 200,
674
- contentType: CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? "application/octet-stream",
675
- body: new Uint8Array(readFileSync(first.absPath))
676
- };
677
- return json(200, {
678
- ok: true,
679
- module: mod.key,
680
- draft,
681
- promptId: execution.data.id,
682
- durationMs,
683
- seeds,
684
- images: execution.images.map((img) => ({
685
- filename: img.filename,
686
- url: img.absPath != null ? this.outputUrl(img.absPath) : null,
687
- absPath: img.absPath
688
- }))
689
- });
690
- }
691
- /** everything that touches the module's SHARED vars, under the module mutex */
692
- async prepareAndStart(mod, draft, payload, seeds) {
693
- for (const [, varDef] of mod.dw.entries()) varDef.reset();
694
- const draftPath = this.draftPath(mod, draft);
695
- if (draftPath == null) return {
696
- status: 404,
697
- error: `no draft '${draft}'`
698
- };
699
- if (existsSync(draftPath)) try {
700
- const values = JSON.parse(readFileSync(draftPath, "utf8"));
701
- for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k]);
702
- } catch (e) {
703
- return {
704
- status: 500,
705
- error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}`
706
- };
707
- }
708
- const draftSeedValues = /* @__PURE__ */ new Map();
709
- for (const [k, varDef] of mod.dw.entries()) if (varDef.kind === "seed") draftSeedValues.set(k, varDef.value);
710
- const varMap = new Map(mod.dw.entries());
711
- for (const [k, rawValue] of Object.entries(payload)) {
712
- const varDef = varMap.get(k);
713
- if (varDef == null) return {
714
- status: 400,
715
- error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(", ")}`
716
- };
717
- let value = rawValue;
718
- if (varDef.kind === "image" && typeof rawValue === "string" && /^https?:\/\//.test(rawValue)) try {
719
- value = await this.downloadInput(rawValue);
720
- } catch (e) {
721
- return {
722
- status: 400,
723
- error: `var '${k}': ${extractErrorMessage(e)}`
724
- };
725
- }
726
- const err = applyVarPayload(varDef, value);
727
- if (err != null) return {
728
- status: 400,
729
- error: err
730
- };
731
- }
732
- for (const [k, varDef] of varMap) {
733
- if (varDef.kind !== "image") continue;
734
- const img = varDef;
735
- if (img.isSet() && !existsSync(img.absPath())) return {
736
- status: 400,
737
- error: `image var '${k}': file not found: ${img.absPath()}`
738
- };
739
- }
740
- for (const [k, varDef] of varMap) {
741
- if (varDef.kind !== "seed") continue;
742
- const seedVar = varDef;
743
- const stateKey = `${mod.key}/${draft}/${k}`;
744
- const draftValue = draftSeedValues.get(k) ?? seedVar.value;
745
- if (!(k in payload)) {
746
- if (seedVar.mode === "?") seedVar.randomize();
747
- else if (seedVar.mode === "+" || seedVar.mode === "-") {
748
- const prev = this.seedState.get(stateKey);
749
- if (prev != null && prev.draftBase === draftValue) seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
750
- }
751
- }
752
- this.seedState.set(stateKey, {
753
- last: seedVar.value,
754
- draftBase: draftValue
755
- });
756
- seeds[k] = seedVar.value;
757
- }
758
- this.latentPreviews.delete(mod.key);
759
- this.wireLatents(mod.dw.host);
760
- try {
761
- return { execution: await this.starter(mod) };
762
- } catch (e) {
763
- if (e instanceof Error && e.name === "ImageVarEmptyError") return {
764
- status: 400,
765
- error: e.message
766
- };
767
- if (e instanceof Error && e.name === "ComfyHostUnreachableError") return {
768
- status: 502,
769
- error: e.message
770
- };
771
- return {
772
- status: 500,
773
- error: extractErrorMessage(e)
774
- };
775
- }
776
- }
777
- /** serialize fn per module key; the stored chain never rejects */
778
- exclusive(key, fn) {
779
- const next = (this.chains.get(key) ?? Promise.resolve()).then(fn);
780
- this.chains.set(key, next.catch(() => {}));
781
- return next;
782
- }
783
- /** payload image urls land as local files under outputs/serve-inputs/ */
784
- async downloadInput(url) {
785
- const res = await fetch(url);
786
- if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`);
787
- const bytes = new Uint8Array(await res.arrayBuffer());
788
- const name = basename(new URL(url).pathname) || "input";
789
- const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${name}`);
790
- mkdirSync(dirname(abs), { recursive: true });
791
- writeFileSync(abs, bytes);
792
- return abs;
793
- }
794
- };
795
- //#endregion
796
- //#region src/cli/serve/webBundle.ts
797
- const WEB_ENTRY = "src/cli/serve/web/main.tsx";
798
- /** nearest dir upward holding a package.json — the comfy-ts package root, from dist/ and src/ alike */
799
- function packageRoot(fromDir) {
800
- let dir = fromDir;
801
- while (true) {
802
- if (existsSync(join(dir, "package.json"))) return dir;
803
- const parent = dirname(dir);
804
- if (parent === dir) return null;
805
- dir = parent;
806
- }
807
- }
808
- /** bundle the web app to one browser file. Bun.build reads no tsconfig, so the
809
- * house 'src/...' absolute imports resolve through the same plugin shape as
810
- * tests/web-bundle.test.ts */
811
- async function buildWebJsText(pkgRoot) {
812
- const result = await Bun.build({
813
- entrypoints: [join(pkgRoot, WEB_ENTRY)],
814
- target: "browser",
815
- minify: true,
816
- throw: false,
817
- define: { "process.env.NODE_ENV": "\"production\"" },
818
- plugins: [{
819
- name: "repo-src-paths",
820
- setup(build) {
821
- build.onResolve({ filter: /^src\// }, (args) => ({ path: join(pkgRoot, args.path) }));
822
- }
823
- }]
824
- });
825
- if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
826
- return await result.outputs[0].text();
827
- }
828
- /** the runtime resolution chain; every miss logs loud and degrades to api-only */
829
- async function loadOrBuildWebJs() {
830
- const here = dirname(fileURLToPath(import.meta.url));
831
- const prebuilt = join(here, "serve-web.js");
832
- if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
833
- if (typeof Bun === "undefined") {
834
- console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
835
- return null;
836
- }
837
- const pkgRoot = packageRoot(here);
838
- if (pkgRoot == null || !existsSync(join(pkgRoot, WEB_ENTRY))) {
839
- console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
840
- return null;
841
- }
842
- try {
843
- return await buildWebJsText(pkgRoot);
844
- } catch (e) {
845
- console.error("[serve] 🔴 web ui bundle failed — api only:", e);
846
- return null;
847
- }
848
- }
849
- //#endregion
850
- //#region src/cli/serve/run-serve.ts
851
- const DEFAULT_PORT = 8288;
852
- const BODY_CAP = 1e7;
853
- function parseArgs(args) {
854
- let target;
855
- let port = DEFAULT_PORT;
856
- let bind = "127.0.0.1";
857
- for (let i = 0; i < args.length; i++) {
858
- const a = args[i];
859
- if (a === "--port") {
860
- const n = Number(args[++i]);
861
- if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` };
862
- port = n;
863
- } else if (a === "--bind") {
864
- const b = args[++i];
865
- if (b == null) return { error: "--bind expects an address" };
866
- bind = b;
867
- } else if (a != null && a.startsWith("--")) return { error: `unknown flag '${a}'` };
868
- else if (a != null) {
869
- if (target != null) return { error: `one target only (got '${target}' and '${a}')` };
870
- target = a;
871
- }
872
- }
873
- return {
874
- target,
875
- port,
876
- bind
877
- };
878
- }
879
- /** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
880
- function makeRequestListener(app) {
881
- return (req, res) => {
882
- const cors = {
883
- "access-control-allow-origin": "*",
884
- "access-control-allow-methods": "GET, POST, PUT, OPTIONS",
885
- "access-control-allow-headers": "content-type, accept"
886
- };
887
- const chunks = [];
888
- let size = 0;
889
- let overflow = false;
890
- req.on("error", (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`));
891
- req.on("data", (c) => {
892
- if (overflow) return;
893
- size += c.length;
894
- if (size > BODY_CAP) {
895
- overflow = true;
896
- res.writeHead(413, {
897
- "content-type": "application/json",
898
- ...cors
899
- });
900
- res.end(JSON.stringify({ error: "payload too large" }), () => req.destroy());
901
- } else chunks.push(c);
902
- });
903
- req.on("end", () => {
904
- if (overflow) return;
905
- if (req.method === "OPTIONS") {
906
- res.writeHead(204, cors);
907
- res.end();
908
- return;
909
- }
910
- app.handle({
911
- method: req.method ?? "GET",
912
- url: req.url ?? "/",
913
- accept: req.headers.accept,
914
- body: Buffer.concat(chunks).toString("utf8")
915
- }).then((reply) => {
916
- res.writeHead(reply.status, {
917
- "content-type": reply.contentType,
918
- ...cors
919
- });
920
- res.end(reply.body);
921
- }).catch((e) => {
922
- console.error(`[serve] response write failed: ${extractErrorMessage(e)}`);
923
- res.destroy();
924
- });
925
- });
926
- };
927
- }
928
- async function runServe(args) {
929
- const parsed = parseArgs(args);
930
- if ("error" in parsed) {
931
- console.error(`[comfy-ts serve] ${parsed.error}`);
932
- return 1;
933
- }
934
- const target = resolve(parsed.target ?? ".");
935
- let files;
936
- try {
937
- files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target];
938
- } catch {
939
- console.error(`[comfy-ts serve] no such file or directory: ${target}`);
940
- return 1;
941
- }
942
- if (files.length === 0) {
943
- console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`);
944
- return 1;
945
- }
946
- const modules = [];
947
- const loadErrors = {};
948
- for (const file of files) try {
949
- const dw = findDefinedWorkflow(await import(pathToFileURL(file).href));
950
- if (dw == null) throw new Error("exports no DefinedWorkflow");
951
- const key = draftKeyForFile(file);
952
- const clash = modules.find((m) => m.key === key);
953
- if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`);
954
- modules.push({
955
- key,
956
- file,
957
- dw
958
- });
959
- } catch (e) {
960
- loadErrors[file] = extractErrorMessage(e);
961
- console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`);
962
- }
963
- if (modules.length === 0) {
964
- console.error("[comfy-ts serve] every module failed to load — nothing to serve");
965
- return 1;
966
- }
967
- const app = new ServeApp(modules, {
968
- loadErrors,
969
- webJs: loadOrBuildWebJs
970
- });
971
- printStartup(app, parsed.bind, parsed.port);
972
- const server = createServer(makeRequestListener(app));
973
- server.on("error", (e) => {
974
- console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`);
975
- process.exitCode = 1;
976
- server.close();
977
- });
978
- server.listen(parsed.port, parsed.bind);
979
- return new Promise((resolveExit) => {
980
- server.on("close", () => resolveExit(typeof process.exitCode === "number" ? process.exitCode : 0));
981
- });
982
- }
983
- function printStartup(app, bind, port) {
984
- const base = `http://${bind}:${port}`;
985
- console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`);
986
- 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`);
987
- for (const mod of app.modules) {
988
- console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`);
989
- for (const draft of app.draftsFor(mod)) console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`);
990
- const entries = mod.dw.entries();
991
- const nameWidth = Math.max(...entries.map(([n]) => n.length), 4);
992
- for (const [name, varDef] of entries) console.log(renderDescriptorLine(name, describeVar(varDef), nameWidth));
993
- }
994
- const firstMod = app.modules[0];
995
- if (firstMod != null) console.log(`\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`);
996
- console.log(`docs: GET ${base}/drafts (json index of everything above)`);
997
- console.log(`ui: open ${base}/ in a browser (every var as a form control)`);
998
- }
999
- //#endregion
1000
- export { runServe };
1001
-
1002
- //# sourceMappingURL=run-serve-CVu39RNd.js.map