comfy-ts 2.7.0 → 2.9.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.
- package/README.md +20 -13
- package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
- package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
- package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
- package/dist/LogsSt-DFxzQfDc.js.map +1 -0
- package/dist/cli.js +7 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +284 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +125 -7
- package/dist/index.d.ts +125 -7
- package/dist/index.js +282 -37
- package/dist/index.js.map +1 -1
- package/dist/run-serve-_nrvJYyt.js +1948 -0
- package/dist/run-serve-_nrvJYyt.js.map +1 -0
- package/dist/{run-tui-JxlEbb_f.js → run-tui-BLEdTsOX.js} +106 -157
- package/dist/run-tui-BLEdTsOX.js.map +1 -0
- package/dist/serve-web.js +441 -72
- package/dist/{state-CaHeDL-0.js → state-BbgJeCe6.js} +180 -45
- package/dist/state-BbgJeCe6.js.map +1 -0
- package/dist/web.d.ts +185 -7
- package/dist/web.js +235 -36
- package/dist/web.js.map +1 -1
- package/examples/README.md +1 -0
- package/examples/comfy-cloud/sdk.d.ts +4066 -321
- package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
- package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
- package/examples/web/tsconfig.json +3 -0
- package/extra/README.md +32 -0
- package/extra/comfyui-textgen-stream/README.md +35 -0
- package/extra/comfyui-textgen-stream/__init__.py +166 -0
- package/extra/scripts/fetch_text_encoder.py +137 -0
- package/package.json +6 -3
- package/src/cli/comfy-ts-cli.ts +3 -1
- package/src/cli/serve/ServeApp.ts +754 -40
- package/src/cli/serve/applyVarPayload.ts +10 -3
- package/src/cli/serve/describeVar.ts +47 -7
- package/src/cli/serve/hostProtocol.ts +68 -0
- package/src/cli/serve/managerOnlyLoras.ts +27 -0
- package/src/cli/serve/run-serve.ts +35 -38
- package/src/cli/serve/serveSettings.ts +86 -0
- package/src/cli/serve/startupPrint.ts +111 -0
- package/src/cli/serve/web/api.ts +97 -1
- package/src/cli/serve/web/components/App.tsx +61 -22
- package/src/cli/serve/web/components/Gallery.tsx +306 -41
- package/src/cli/serve/web/components/Icon.tsx +160 -0
- package/src/cli/serve/web/components/PromptEnhancer.tsx +12 -9
- package/src/cli/serve/web/components/Sidebar.tsx +43 -19
- package/src/cli/serve/web/components/VarsForm.tsx +440 -91
- package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
- package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
- package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
- package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
- package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
- package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
- package/src/cli/serve/web/llm.ts +1 -1
- package/src/cli/serve/web/logWeb.ts +6 -0
- package/src/cli/serve/web/state/EnhancerSt.ts +8 -15
- package/src/cli/serve/web/state/FormSt.ts +74 -18
- package/src/cli/serve/web/state/RunSt.ts +22 -1
- package/src/cli/serve/web/state/WebSt.ts +814 -22
- package/src/cli/serve/web/state/host.ts +206 -0
- package/src/cli/serve/web/state/lightbox.ts +44 -0
- package/src/cli/serve/web/state/moduleTree.ts +52 -0
- package/src/cli/serve/web/state/payload.ts +44 -2
- package/src/cli/serve/web/state/urlSelection.ts +53 -0
- package/src/cli/serve/web/styles.ts +422 -57
- package/src/cli/serve/web/tsconfig.json +4 -0
- package/src/cli/tui/components/PickerOverlays.tsx +37 -0
- package/src/cli/tui/components/StatusBar.tsx +14 -1
- package/src/cli/tui/components/TuiApp.tsx +5 -2
- package/src/cli/tui/state/HostSt.ts +3 -2
- package/src/cli/tui/state/PickerSt.ts +48 -2
- package/src/cli/tui/state/TreeSt.ts +1 -1
- package/src/cli/tui/state/TuiSt.ts +2 -1
- package/src/coreExports.ts +8 -1
- package/src/graph/ComfyNode.ts +58 -1
- package/src/host/ComfyHost.ts +13 -2
- package/src/host/ComfyManager.ts +31 -13
- package/src/host/loraInfoCache.ts +35 -1
- package/src/host/loraManagerApi.ts +94 -0
- package/src/index.ts +2 -0
- package/src/promptEnhancers.ts +102 -0
- package/src/runner/ComfyExecution.ts +61 -6
- package/src/runner/ComfyWorkflow.ts +18 -4
- package/src/runner/ComfyWsApi.ts +3 -0
- package/src/runner/describePromptRejection.ts +34 -0
- package/src/sdk-generator/ComfySchema.ts +17 -4
- package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
- package/src/utils/ansi.ts +13 -0
- package/src/utils/matchesRegex.ts +13 -0
- package/src/utils/safeName.ts +29 -0
- package/src/utils/stringMap.ts +9 -0
- package/src/vars/ComfyVars.ts +61 -10
- package/src/vars/presets.ts +17 -0
- package/src/web.ts +12 -0
- package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
- package/dist/DraftsSt-dizp3VcC.js.map +0 -1
- package/dist/run-serve-D1Tsuru9.js +0 -1162
- package/dist/run-serve-D1Tsuru9.js.map +0 -1
- package/dist/run-tui-JxlEbb_f.js.map +0 -1
- package/dist/state-CaHeDL-0.js.map +0 -1
- package/src/cli/serve/promptEnhancers.ts +0 -69
- package/src/cli/serve/safeName.ts +0 -12
|
@@ -0,0 +1,1948 @@
|
|
|
1
|
+
import { B as stripAnsi, C as fetchLoraList, D as lmFilePath, E as lmCivitai, I as loraKey, L as loraPreviewMapFrom, M as lmSha256, N as lmTags, O as lmFileSize, R as ansi, S as fetchLoraExampleImages, T as lmBaseModel, U as bang, V as extractErrorMessage, X as statelessRegex, b as writeLoraMirror, d as getLoraDisplayName, f as getLoraInfo, g as loraMirrorEntries, j as lmNotes, k as lmFolder, m as getLoraTriggerWords, n as DEFAULT_IMAGE_EXTENSIONS, o as getLoraKeyword, p as getLoraPreviewUrl, u as buildLoraMirror, v as refreshLoraInfoCacheIfChanged, w as fetchLoraPreviewBytes, x as fetchLoraDescription, y as reloadLoraInfoCache, z as colorsAvailable } from "./DefinedWorkflow-BatWaZO1.js";
|
|
2
|
+
import { a as draftsDirForFile, f as scanCflowFiles, i as draftKeyForFile, n as assembleLogChunks, o as listDraftsForFile, u as findDefinedWorkflow } from "./LogsSt-DFxzQfDc.js";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, 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
|
+
import { networkInterfaces } from "node:os";
|
|
9
|
+
//#region src/cli/serve/describeVar.ts
|
|
10
|
+
/** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
|
|
11
|
+
function presetsOrUndefined(presets) {
|
|
12
|
+
return presets.length === 0 ? void 0 : presets;
|
|
13
|
+
}
|
|
14
|
+
function rangeText(opts) {
|
|
15
|
+
if (opts.min == null && opts.max == null) return "";
|
|
16
|
+
return ` (${opts.min ?? "-∞"}..${opts.max ?? "∞"})`;
|
|
17
|
+
}
|
|
18
|
+
function describeVar(varDef) {
|
|
19
|
+
const base = {
|
|
20
|
+
kind: varDef.kind,
|
|
21
|
+
label: varDef.label,
|
|
22
|
+
default: varDef.defaultValue
|
|
23
|
+
};
|
|
24
|
+
switch (varDef.kind) {
|
|
25
|
+
case "prompt": {
|
|
26
|
+
const v = varDef;
|
|
27
|
+
return {
|
|
28
|
+
...base,
|
|
29
|
+
payload: "string (\"//\" lines = comments, \"- \" lines = negative)",
|
|
30
|
+
textPresets: presetsOrUndefined(v.presets)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
case "text": {
|
|
34
|
+
const v = varDef;
|
|
35
|
+
return {
|
|
36
|
+
...base,
|
|
37
|
+
payload: "string",
|
|
38
|
+
multiline: v.opts.multiline,
|
|
39
|
+
textPresets: presetsOrUndefined(v.presets)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
case "int": {
|
|
43
|
+
const v = varDef;
|
|
44
|
+
return {
|
|
45
|
+
...base,
|
|
46
|
+
payload: `integer${rangeText(v.opts)}`,
|
|
47
|
+
min: v.opts.min,
|
|
48
|
+
max: v.opts.max
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
case "float": {
|
|
52
|
+
const v = varDef;
|
|
53
|
+
return {
|
|
54
|
+
...base,
|
|
55
|
+
payload: `number${rangeText(v.opts)}`,
|
|
56
|
+
min: v.opts.min,
|
|
57
|
+
max: v.opts.max
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
case "seed": {
|
|
61
|
+
const v = varDef;
|
|
62
|
+
return {
|
|
63
|
+
...base,
|
|
64
|
+
default: {
|
|
65
|
+
mode: v.defaultMode,
|
|
66
|
+
value: v.defaultValue
|
|
67
|
+
},
|
|
68
|
+
payload: "number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}"
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
case "toggle": return {
|
|
72
|
+
...base,
|
|
73
|
+
payload: "true or false"
|
|
74
|
+
};
|
|
75
|
+
case "choice": {
|
|
76
|
+
const v = varDef;
|
|
77
|
+
return {
|
|
78
|
+
...base,
|
|
79
|
+
payload: `one of: ${v.choices.join(" | ")}`,
|
|
80
|
+
choices: v.choices
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
case "loras": {
|
|
84
|
+
const v = varDef;
|
|
85
|
+
return {
|
|
86
|
+
...base,
|
|
87
|
+
payload: "{\"<lora name>\": false | true | strength | [model, clip]}",
|
|
88
|
+
options: v.options,
|
|
89
|
+
optionsFilter: v.optionsFilter == null ? void 0 : String(v.optionsFilter)
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
case "size": {
|
|
93
|
+
const v = varDef;
|
|
94
|
+
return {
|
|
95
|
+
...base,
|
|
96
|
+
payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
|
|
97
|
+
presets: v.presets
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
case "image": {
|
|
101
|
+
const v = varDef;
|
|
102
|
+
return {
|
|
103
|
+
...base,
|
|
104
|
+
payload: "local file path or http(s) url",
|
|
105
|
+
extensions: v.extensions
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
default: {
|
|
109
|
+
const unknownKind = varDef.kind;
|
|
110
|
+
return {
|
|
111
|
+
...base,
|
|
112
|
+
payload: `string (unrecognised kind '${String(unknownKind)}')`
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** one aligned console line per var (startup print). Padding happens on the PLAIN text: colors are wrapped around the
|
|
118
|
+
* already-padded cells, so a colored and an uncolored print line up identically */
|
|
119
|
+
function renderDescriptorLine(name, d, nameWidth, color = false) {
|
|
120
|
+
const def = typeof d.default === "string" ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default);
|
|
121
|
+
const cells = {
|
|
122
|
+
name: name.padEnd(nameWidth),
|
|
123
|
+
kind: d.kind.padEnd(6),
|
|
124
|
+
value: truncate(def ?? "null", 60)
|
|
125
|
+
};
|
|
126
|
+
if (!color) return ` ${cells.name} ${cells.kind} ${d.payload} · default: ${cells.value}`;
|
|
127
|
+
return ` ${ansi.bold(cells.name)} ${ansi.yellow(cells.kind)} ${ansi.gray(d.payload)} ${ansi.gray("· default:")} ${cells.value}`;
|
|
128
|
+
}
|
|
129
|
+
function truncate(s, n) {
|
|
130
|
+
return s.length <= n ? s : s.slice(0, n - 1) + "…";
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/cli/serve/applyVarPayload.ts
|
|
134
|
+
function isFiniteNumber(x) {
|
|
135
|
+
return typeof x === "number" && Number.isFinite(x);
|
|
136
|
+
}
|
|
137
|
+
function isLoraStrength(x) {
|
|
138
|
+
if (typeof x === "boolean") return true;
|
|
139
|
+
if (isFiniteNumber(x)) return true;
|
|
140
|
+
return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1]);
|
|
141
|
+
}
|
|
142
|
+
/** cap long option lists in error messages */
|
|
143
|
+
function listSome(items, cap = 20) {
|
|
144
|
+
if (items.length <= cap) return items.join(", ");
|
|
145
|
+
return `${items.slice(0, cap).join(", ")} … +${items.length - cap} more`;
|
|
146
|
+
}
|
|
147
|
+
/** `extraLoraOptions`: names the lora-manager mirror knows that ComfyUI's enum does not.
|
|
148
|
+
* they are accepted like any option, the file is on disk, so the run usually works, but
|
|
149
|
+
* ONLY those: an arbitrary name still fails, so a typo cannot reach the host */
|
|
150
|
+
function applyVarPayload(varDef, raw, opts = {}) {
|
|
151
|
+
const name = varDef.name ?? varDef.label ?? varDef.kind;
|
|
152
|
+
switch (varDef.kind) {
|
|
153
|
+
case "text":
|
|
154
|
+
case "prompt":
|
|
155
|
+
if (typeof raw !== "string") return `var '${name}' expects a string`;
|
|
156
|
+
varDef.set(raw);
|
|
157
|
+
return null;
|
|
158
|
+
case "int":
|
|
159
|
+
case "float": {
|
|
160
|
+
const v = varDef;
|
|
161
|
+
if (isFiniteNumber(raw)) {
|
|
162
|
+
v.set(raw);
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
if (typeof raw === "string" && v.parse(raw)) return null;
|
|
166
|
+
const o = v.opts;
|
|
167
|
+
return `var '${name}' expects a number${o.min == null && o.max == null ? "" : ` (${o.min ?? "-∞"}..${o.max ?? "∞"})`}`;
|
|
168
|
+
}
|
|
169
|
+
case "seed": {
|
|
170
|
+
const v = varDef;
|
|
171
|
+
if (isFiniteNumber(raw)) {
|
|
172
|
+
v.setMode("=");
|
|
173
|
+
v.set(raw);
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
177
|
+
const o = raw;
|
|
178
|
+
const mode = o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?" ? o.mode : null;
|
|
179
|
+
if (o.mode !== void 0 && mode == null) return `var '${name}': mode must be one of = + - ?`;
|
|
180
|
+
if (o.value !== void 0 && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`;
|
|
181
|
+
if (mode == null && o.value === void 0) return `var '${name}': give "mode" and/or "value"`;
|
|
182
|
+
if (mode != null) v.setMode(mode);
|
|
183
|
+
if (isFiniteNumber(o.value)) v.set(o.value);
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`;
|
|
187
|
+
}
|
|
188
|
+
case "toggle":
|
|
189
|
+
if (typeof raw !== "boolean") return `var '${name}' expects true or false`;
|
|
190
|
+
varDef.set(raw);
|
|
191
|
+
return null;
|
|
192
|
+
case "choice": {
|
|
193
|
+
const v = varDef;
|
|
194
|
+
if (typeof raw === "string" && v.parse(raw)) return null;
|
|
195
|
+
return `var '${name}' expects one of: ${listSome(v.choices)}`;
|
|
196
|
+
}
|
|
197
|
+
case "loras": {
|
|
198
|
+
const v = varDef;
|
|
199
|
+
if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`;
|
|
200
|
+
const record = raw;
|
|
201
|
+
const known = /* @__PURE__ */ new Set([...v.options, ...opts.extraLoraOptions ?? []]);
|
|
202
|
+
const unknownNames = Object.keys(record).filter((k) => !known.has(k));
|
|
203
|
+
if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
|
|
204
|
+
for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`;
|
|
205
|
+
v.set(record);
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
case "size": {
|
|
209
|
+
const v = varDef;
|
|
210
|
+
if (typeof raw === "string" && v.parse(raw)) return null;
|
|
211
|
+
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
212
|
+
const o = raw;
|
|
213
|
+
if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
|
|
214
|
+
v.set({
|
|
215
|
+
width: o.width,
|
|
216
|
+
height: o.height
|
|
217
|
+
});
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`;
|
|
222
|
+
}
|
|
223
|
+
case "image":
|
|
224
|
+
if (typeof raw !== "string") return `var '${name}' expects a file path or http(s) url string`;
|
|
225
|
+
varDef.set(raw);
|
|
226
|
+
return null;
|
|
227
|
+
default: {
|
|
228
|
+
const unknownKind = varDef.kind;
|
|
229
|
+
return `var '${name}' has unsupported kind '${String(unknownKind)}'`;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
//#endregion
|
|
234
|
+
//#region src/utils/safeName.ts
|
|
235
|
+
/** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
|
|
236
|
+
function validStoreName(raw) {
|
|
237
|
+
const name = raw.trim();
|
|
238
|
+
if (name.length > 100) return null;
|
|
239
|
+
return /^[\w][\w .-]*$/.test(name) ? name : null;
|
|
240
|
+
}
|
|
241
|
+
/** a save prefix becomes a PATH under outputs/, so every segment goes through the same gate:
|
|
242
|
+
* it cannot climb out, and it cannot be absolute. Lives here, not on ServeApp, because the
|
|
243
|
+
* settings READER validates it too, a hand-written settings file never met the PUT route. */
|
|
244
|
+
function validSavePrefix(raw) {
|
|
245
|
+
const clean = raw.trim().replaceAll("\\", "/");
|
|
246
|
+
if (clean === "") return "";
|
|
247
|
+
if (clean.startsWith("/") || /^[a-z]:/i.test(clean)) return null;
|
|
248
|
+
if (clean.length > 200) return null;
|
|
249
|
+
const segments = clean.split("/").filter((s) => s !== "");
|
|
250
|
+
if (segments.length === 0 || segments.some((s) => validStoreName(s) == null)) return null;
|
|
251
|
+
return segments.join("/");
|
|
252
|
+
}
|
|
253
|
+
//#endregion
|
|
254
|
+
//#region src/promptEnhancers.ts
|
|
255
|
+
const EXT = ".md";
|
|
256
|
+
function promptEnhancersDir() {
|
|
257
|
+
return comfyts.resolveFromPromptEnhancers("");
|
|
258
|
+
}
|
|
259
|
+
function promptEnhancerPath(name) {
|
|
260
|
+
const safe = validStoreName(name);
|
|
261
|
+
return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
|
|
262
|
+
}
|
|
263
|
+
/** the shipped starting point. It is a FILE from the first read on, so it can be edited
|
|
264
|
+
* on disk like everything else, the browser ships no copy of this text */
|
|
265
|
+
const SEED = {
|
|
266
|
+
name: "refine-krea2-prompt",
|
|
267
|
+
text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language. Long detailed prompts give it the best images. Your job is to serve the VISION behind the user's line: take what they wrote and expand it into the picture they were already imagining but did not type.
|
|
268
|
+
|
|
269
|
+
Rewrite it into ONE paragraph a reader could picture with their eyes closed:
|
|
270
|
+
|
|
271
|
+
- every subject, action, color and spatial relation the user wrote survives, in their own words wherever those words already work. Nothing is dropped, nothing is swapped for something easier.
|
|
272
|
+
- expand the vision, never replace it. Add the visual facts a camera would have to resolve anyway: what each subject looks like, lighting, palette, material and texture, camera angle and distance, framing and composition, background, depth of field, mood, and the signature of the medium itself (visible brushstrokes, film grain, cel shading, stippling, halftone, airbrush gradients, paper texture).
|
|
273
|
+
- choose the style before you write, and keep the choosing invisible. Weigh two or three mediums and lighting setups, pick the one that best serves the input, then write only the result. If they named a medium (photo of, illustration of, 3D render of, painting of, sketch of), that medium is fixed.
|
|
274
|
+
- attach every attribute to its own subject, so nothing bleeds: one clause per figure carrying its features, clothes, pose and action. Spatial words stay grounded: left foreground, upper center, behind, resting on, knee deep in.
|
|
275
|
+
- an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.
|
|
276
|
+
- plain descriptive english. Flowing sentences and comma separated descriptive clauses both read well; disconnected keyword soup does not. No praise words, never "masterpiece", "8k", "highly detailed", "award winning", "trending on". The model is steered by what you name, not by what you forbid.
|
|
277
|
+
- text that must appear inside the image is spelled out in "quotes", exactly as it should be rendered.
|
|
278
|
+
- roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.
|
|
279
|
+
- keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line.
|
|
280
|
+
|
|
281
|
+
Answer with the rewritten prompt and nothing else: no preamble, no explanation.
|
|
282
|
+
`
|
|
283
|
+
};
|
|
284
|
+
/** seeds ONCE, on an absent folder, then lists. An emptied folder stays empty: the seed is a
|
|
285
|
+
* starting point, not a file the store keeps restoring */
|
|
286
|
+
function listPromptEnhancers() {
|
|
287
|
+
if (!existsSync(promptEnhancersDir())) writePromptEnhancer(SEED.name, SEED.text);
|
|
288
|
+
return readPromptEnhancers();
|
|
289
|
+
}
|
|
290
|
+
/** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing
|
|
291
|
+
* a module must never create files in someone's project */
|
|
292
|
+
function readPromptEnhancers() {
|
|
293
|
+
const dir = promptEnhancersDir();
|
|
294
|
+
if (!existsSync(dir)) return [];
|
|
295
|
+
const out = [];
|
|
296
|
+
for (const file of readdirSync(dir).sort()) {
|
|
297
|
+
if (!file.endsWith(EXT)) continue;
|
|
298
|
+
const name = file.slice(0, -3);
|
|
299
|
+
if (validStoreName(name) == null) continue;
|
|
300
|
+
try {
|
|
301
|
+
out.push({
|
|
302
|
+
name,
|
|
303
|
+
text: readFileSync(join(dir, file), "utf8")
|
|
304
|
+
});
|
|
305
|
+
} catch (e) {
|
|
306
|
+
console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
311
|
+
function writePromptEnhancer(name, text) {
|
|
312
|
+
const path = promptEnhancerPath(name);
|
|
313
|
+
if (path == null) return null;
|
|
314
|
+
mkdirSync(promptEnhancersDir(), { recursive: true });
|
|
315
|
+
writeFileSync(path, text);
|
|
316
|
+
return path;
|
|
317
|
+
}
|
|
318
|
+
/** a missing file is still a success: the caller asked for it to be gone, and it is */
|
|
319
|
+
function deletePromptEnhancer(name) {
|
|
320
|
+
const path = promptEnhancerPath(name);
|
|
321
|
+
if (path == null) return false;
|
|
322
|
+
if (existsSync(path)) rmSync(path);
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/cli/serve/managerOnlyLoras.ts
|
|
327
|
+
/**
|
|
328
|
+
* `options` is the host enum for this var: it decides both what counts as already-known
|
|
329
|
+
* (compared by normalized key, never raw, the enum keeps case, extension and separators)
|
|
330
|
+
* and which separator the rebuilt names must use.
|
|
331
|
+
*/
|
|
332
|
+
function managerOnlyLoraOptions(p) {
|
|
333
|
+
const filter = p.filter == null ? null : statelessRegex(p.filter);
|
|
334
|
+
const known = new Set(p.options.map((o) => loraKey(o)));
|
|
335
|
+
const separator = p.options.some((o) => o.includes("\\")) ? "\\" : "/";
|
|
336
|
+
return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region src/utils/stringMap.ts
|
|
340
|
+
function stringMap(raw) {
|
|
341
|
+
const out = {};
|
|
342
|
+
if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
|
|
343
|
+
for (const [k, v] of Object.entries(raw)) if (typeof v === "string") out[k] = v;
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
346
|
+
}
|
|
347
|
+
//#endregion
|
|
348
|
+
//#region src/cli/serve/serveSettings.ts
|
|
349
|
+
const DEFAULT_SERVE_SETTINGS = {
|
|
350
|
+
saveToDisk: true,
|
|
351
|
+
hostOverride: {},
|
|
352
|
+
savePrefix: {}
|
|
353
|
+
};
|
|
354
|
+
/** null when no comfyts is registered yet: a ServeApp can be constructed before the global
|
|
355
|
+
* exists (tests do), and reading a setting must degrade to defaults, never throw */
|
|
356
|
+
function settingsPath() {
|
|
357
|
+
const path = globalThis.comfyts?.settingsPath;
|
|
358
|
+
return typeof path === "string" ? path : null;
|
|
359
|
+
}
|
|
360
|
+
/** `readable: false` says the file EXISTS but could not be parsed — the one case where a write
|
|
361
|
+
* must refuse. Merging onto `{}` there would rewrite the file from nothing and take the TUI's
|
|
362
|
+
* keys with it, and these files are documented as hand-editable, so the user would lose the
|
|
363
|
+
* chance to repair it. */
|
|
364
|
+
function readBlob() {
|
|
365
|
+
const path = settingsPath();
|
|
366
|
+
if (path == null || !existsSync(path)) return {
|
|
367
|
+
blob: {},
|
|
368
|
+
readable: true
|
|
369
|
+
};
|
|
370
|
+
try {
|
|
371
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
372
|
+
const ok = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
|
|
373
|
+
if (!ok) console.error(`[serve] settings is not an object (${path}), using defaults`);
|
|
374
|
+
return {
|
|
375
|
+
blob: ok ? parsed : {},
|
|
376
|
+
readable: ok
|
|
377
|
+
};
|
|
378
|
+
} catch (e) {
|
|
379
|
+
console.error(`[serve] settings unreadable (${path}), using defaults:`, e);
|
|
380
|
+
return {
|
|
381
|
+
blob: {},
|
|
382
|
+
readable: false
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/** keeps the CLEANED value, not the raw one: storing the raw form let the same input mean two
|
|
387
|
+
* different directories depending on whether it arrived by PUT or by hand */
|
|
388
|
+
function cleanValues(map, clean) {
|
|
389
|
+
const out = {};
|
|
390
|
+
for (const [k, v] of Object.entries(map)) {
|
|
391
|
+
const ok = clean(v);
|
|
392
|
+
if (ok != null) out[k] = ok;
|
|
393
|
+
}
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
function readServeSettings() {
|
|
397
|
+
const serve = readBlob().blob.serve;
|
|
398
|
+
const o = typeof serve === "object" && serve !== null ? serve : {};
|
|
399
|
+
return {
|
|
400
|
+
saveToDisk: typeof o.saveToDisk === "boolean" ? o.saveToDisk : DEFAULT_SERVE_SETTINGS.saveToDisk,
|
|
401
|
+
hostOverride: stringMap(o.hostOverride),
|
|
402
|
+
savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix)
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
function writeServeSettings(next) {
|
|
406
|
+
const path = settingsPath();
|
|
407
|
+
if (path == null) throw new Error("no comfyts instance registered — cannot persist serve settings");
|
|
408
|
+
const current = readBlob();
|
|
409
|
+
if (!current.readable) throw new Error(`serve settings not saved: ${path} is not readable json. Fix or delete it — overwriting would drop the keys it still holds`);
|
|
410
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
411
|
+
writeFileSync(path, JSON.stringify({
|
|
412
|
+
...current.blob,
|
|
413
|
+
serve: next
|
|
414
|
+
}, null, 2));
|
|
415
|
+
}
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/cli/serve/ServeApp.ts
|
|
418
|
+
/** what serve will read off the disk and upload. Wider than the picker default: ComfyUI's
|
|
419
|
+
* LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
|
|
420
|
+
const SERVE_IMAGE_FLOOR = /* @__PURE__ */ new Set([
|
|
421
|
+
...DEFAULT_IMAGE_EXTENSIONS.map((e) => e.toLowerCase()),
|
|
422
|
+
"bmp",
|
|
423
|
+
"tif",
|
|
424
|
+
"tiff",
|
|
425
|
+
"avif"
|
|
426
|
+
]);
|
|
427
|
+
/** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops
|
|
428
|
+
* a .png that holds a key or a script from being read and uploaded to the host.
|
|
429
|
+
* HONEST LIMIT: this is checked before the run, and the file is read again when the graph
|
|
430
|
+
* builds, so a local writer who can swap the path in between still wins. Closing that needs
|
|
431
|
+
* the upload to hold an fd, which is a bigger change than this gate. */
|
|
432
|
+
function looksLikeImage(path) {
|
|
433
|
+
let fd = null;
|
|
434
|
+
try {
|
|
435
|
+
fd = openSync(path, "r");
|
|
436
|
+
const head = /* @__PURE__ */ new Uint8Array(16);
|
|
437
|
+
const n = readSync(fd, head, 0, 16, 0);
|
|
438
|
+
return isImageMagic(head.subarray(0, n));
|
|
439
|
+
} catch {
|
|
440
|
+
return false;
|
|
441
|
+
} finally {
|
|
442
|
+
if (fd != null) closeSync(fd);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** what `POST /generate` will read off this machine and upload to a ComfyUI host. A var's own
|
|
446
|
+
* `extensions` is documented as a PICKER filter that never affects the value, so it cannot be
|
|
447
|
+
* the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able
|
|
448
|
+
* to widen what an unauthenticated request can make the server read. The var may narrow this
|
|
449
|
+
* floor, never leave it. */
|
|
450
|
+
function serveAcceptsImageExt(declared, ext) {
|
|
451
|
+
if (ext === "") return false;
|
|
452
|
+
if (!SERVE_IMAGE_FLOOR.has(ext)) return false;
|
|
453
|
+
const narrowed = declared.map((e) => e.toLowerCase().replace(/^\./, "")).filter((e) => SERVE_IMAGE_FLOOR.has(e));
|
|
454
|
+
return narrowed.length === 0 || narrowed.includes(ext);
|
|
455
|
+
}
|
|
456
|
+
/** an image var pointing at a url downloads it: capped, because the inbound BODY cap does not
|
|
457
|
+
* apply to what serve fetches on your behalf, and one url at a big file would OOM the process */
|
|
458
|
+
var DownloadRefused = class extends Error {
|
|
459
|
+
constructor(url) {
|
|
460
|
+
super(`could not fetch ${url}`);
|
|
461
|
+
this.name = "DownloadRefused";
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
const INPUT_DOWNLOAD_CAP = 5e7;
|
|
465
|
+
const INPUT_DOWNLOAD_TIMEOUT_MS = 6e4;
|
|
466
|
+
/** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
|
|
467
|
+
* whole body first, so a chunked reply with no content-length could exhaust the process before
|
|
468
|
+
* anything checked its size, the cap then reported a number nobody survived to read. */
|
|
469
|
+
async function readCapped(res, cap, what) {
|
|
470
|
+
const body = res.body;
|
|
471
|
+
if (body == null) return /* @__PURE__ */ new Uint8Array(0);
|
|
472
|
+
const reader = body.getReader();
|
|
473
|
+
const chunks = [];
|
|
474
|
+
let total = 0;
|
|
475
|
+
try {
|
|
476
|
+
for (;;) {
|
|
477
|
+
const step = await reader.read();
|
|
478
|
+
if (step.done) break;
|
|
479
|
+
total += step.value.length;
|
|
480
|
+
if (total > cap) {
|
|
481
|
+
await reader.cancel();
|
|
482
|
+
throw new Error(`download too large (over ${cap} bytes): ${what}`);
|
|
483
|
+
}
|
|
484
|
+
chunks.push(step.value);
|
|
485
|
+
}
|
|
486
|
+
} finally {
|
|
487
|
+
reader.releaseLock();
|
|
488
|
+
}
|
|
489
|
+
const out = new Uint8Array(total);
|
|
490
|
+
let at = 0;
|
|
491
|
+
for (const c of chunks) {
|
|
492
|
+
out.set(c, at);
|
|
493
|
+
at += c.length;
|
|
494
|
+
}
|
|
495
|
+
return out;
|
|
496
|
+
}
|
|
497
|
+
/** the panel is REBUILT per serve process, so a cached copy is always the wrong one. With no
|
|
498
|
+
* cache header at all a browser applies heuristic freshness and reuses app.js across reloads,
|
|
499
|
+
* which makes every fix look like it never landed */
|
|
500
|
+
const NO_STORE = { "cache-control": "no-store, must-revalidate" };
|
|
501
|
+
/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.
|
|
502
|
+
* serve OPTS INTO local saving (library default is memory-only, architecture.md
|
|
503
|
+
* item 14): the /outputs/ routes serve files, grouped per module */
|
|
504
|
+
const realStarter = async (mod, opts) => {
|
|
505
|
+
const host = opts.host ?? mod.dw.host;
|
|
506
|
+
await host.connect();
|
|
507
|
+
return await (await mod.dw.build({
|
|
508
|
+
advance: true,
|
|
509
|
+
host
|
|
510
|
+
})).start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false });
|
|
511
|
+
};
|
|
512
|
+
const CONTENT_TYPES = {
|
|
513
|
+
".png": "image/png",
|
|
514
|
+
".jpg": "image/jpeg",
|
|
515
|
+
".jpeg": "image/jpeg",
|
|
516
|
+
".webp": "image/webp",
|
|
517
|
+
".gif": "image/gif",
|
|
518
|
+
".mp4": "video/mp4",
|
|
519
|
+
".webm": "video/webm",
|
|
520
|
+
".json": "application/json",
|
|
521
|
+
".txt": "text/plain"
|
|
522
|
+
};
|
|
523
|
+
/** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
|
|
524
|
+
function sniffImageContentType(bytes) {
|
|
525
|
+
if (bytes[0] === 137 && bytes[1] === 80) return "image/png";
|
|
526
|
+
if (bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
|
|
527
|
+
if (bytes[0] === 71 && bytes[1] === 73) return "image/gif";
|
|
528
|
+
if (bytes[0] === 82 && bytes[1] === 73) return "image/webp";
|
|
529
|
+
return "application/octet-stream";
|
|
530
|
+
}
|
|
531
|
+
/** the FULL signature, not the first two bytes: `RI` alone matched a wav renamed .webp, and a
|
|
532
|
+
* two-byte file matched png. bmp/tiff/avif are here because the floor accepts them */
|
|
533
|
+
function isImageMagic(b) {
|
|
534
|
+
const at = (i, ...want) => want.every((w, k) => b[i + k] === w);
|
|
535
|
+
if (at(0, 137, 80, 78, 71, 13, 10, 26, 10)) return true;
|
|
536
|
+
if (at(0, 255, 216, 255)) return true;
|
|
537
|
+
if (at(0, 71, 73, 70, 56)) return true;
|
|
538
|
+
if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return true;
|
|
539
|
+
if (at(0, 66, 77)) return true;
|
|
540
|
+
if (at(0, 73, 73, 42, 0) || at(0, 77, 77, 0, 42)) return true;
|
|
541
|
+
if (at(4, 102, 116, 121, 112)) return true;
|
|
542
|
+
return false;
|
|
543
|
+
}
|
|
544
|
+
function json(status, payload) {
|
|
545
|
+
return {
|
|
546
|
+
status,
|
|
547
|
+
contentType: "application/json",
|
|
548
|
+
body: JSON.stringify(payload, null, 2)
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
const USAGE = [
|
|
552
|
+
"GET / in a browser — web control panel (every var as a form control)",
|
|
553
|
+
"GET /drafts — every served workflow, its drafts and var descriptors",
|
|
554
|
+
"GET /drafts/<module>/<draft> — one draft with its stored values",
|
|
555
|
+
"POST /generate/<module>/<draft> with { ...vars } — run, blocking",
|
|
556
|
+
"POST /generate/<draft> — unqualified, when unambiguous",
|
|
557
|
+
"PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
|
|
558
|
+
"DELETE /drafts/<module>/<draft> — delete that draft file",
|
|
559
|
+
"GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
|
|
560
|
+
"POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
|
|
561
|
+
"GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
|
|
562
|
+
"GET /lora-preview/<hostId>/<lora> — preview image bytes",
|
|
563
|
+
"GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
|
|
564
|
+
"GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
|
|
565
|
+
"PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
|
|
566
|
+
"GET /settings — { saveToDisk } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory",
|
|
567
|
+
"GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere",
|
|
568
|
+
"POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host",
|
|
569
|
+
"GET /hosts/<hostId>/ping — is that host answering right now (restart watch)",
|
|
570
|
+
"GET /hosts/<hostId>/logs — the last lines of that host console",
|
|
571
|
+
"GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives",
|
|
572
|
+
"GET /outputs/<path> — generated files"
|
|
573
|
+
];
|
|
574
|
+
/** content hash of the bundle, so the script URL CHANGES whenever the code does. no-store
|
|
575
|
+
* alone does not help a browser that already has app.js cached under a plain url, and a panel
|
|
576
|
+
* running stale javascript is indistinguishable from a broken fix */
|
|
577
|
+
function buildId(js) {
|
|
578
|
+
let h = 5381;
|
|
579
|
+
for (let i = 0; i < js.length; i++) h = (h << 5) + h + js.charCodeAt(i) | 0;
|
|
580
|
+
return (h >>> 0).toString(36);
|
|
581
|
+
}
|
|
582
|
+
/** the html shell; the app itself is ONE bundle at /web/app.js */
|
|
583
|
+
const WEB_SHELL = `<!doctype html>
|
|
584
|
+
<html lang="en">
|
|
585
|
+
<head>
|
|
586
|
+
<meta charset="utf-8">
|
|
587
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
588
|
+
<title>comfy-ts serve</title>
|
|
589
|
+
<style>html{background:#101217;color:#e8eaf0}</style>
|
|
590
|
+
</head>
|
|
591
|
+
<body>
|
|
592
|
+
<div id="root"></div>
|
|
593
|
+
<script type="module" src="/web/app.js?v=__BUILD__"><\/script>
|
|
594
|
+
</body>
|
|
595
|
+
</html>
|
|
596
|
+
`;
|
|
597
|
+
var ServeApp = class {
|
|
598
|
+
get settings() {
|
|
599
|
+
this.settingsCache ??= readServeSettings();
|
|
600
|
+
return this.settingsCache;
|
|
601
|
+
}
|
|
602
|
+
set settings(next) {
|
|
603
|
+
this.settingsCache = next;
|
|
604
|
+
}
|
|
605
|
+
constructor(modules, opts = {}) {
|
|
606
|
+
this.modules = modules;
|
|
607
|
+
this.opts = opts;
|
|
608
|
+
this.seedState = /* @__PURE__ */ new Map();
|
|
609
|
+
this.chains = /* @__PURE__ */ new Map();
|
|
610
|
+
this.webJsCache = null;
|
|
611
|
+
this.settingsCache = null;
|
|
612
|
+
this.memoryImages = /* @__PURE__ */ new Map();
|
|
613
|
+
this.MEMORY_IMAGE_CAP = 60;
|
|
614
|
+
this.liveRuns = /* @__PURE__ */ new Map();
|
|
615
|
+
this.latentPreviews = /* @__PURE__ */ new Map();
|
|
616
|
+
this.latentSeq = 0;
|
|
617
|
+
this.promptOwner = /* @__PURE__ */ new Map();
|
|
618
|
+
this.latentHosts = /* @__PURE__ */ new Set();
|
|
619
|
+
this.previewSweeps = /* @__PURE__ */ new Map();
|
|
620
|
+
this.starter = opts.starter ?? realStarter;
|
|
621
|
+
}
|
|
622
|
+
get outputRoot() {
|
|
623
|
+
return this.opts.outputRoot ?? comfyts.outputPath;
|
|
624
|
+
}
|
|
625
|
+
async handle(req) {
|
|
626
|
+
try {
|
|
627
|
+
const path = (req.url.split("?")[0] ?? "/").split("#")[0] ?? "/";
|
|
628
|
+
let segs;
|
|
629
|
+
try {
|
|
630
|
+
segs = path.split("/").filter((s) => s !== "").map(decodeURIComponent);
|
|
631
|
+
} catch {
|
|
632
|
+
return json(400, { error: `bad url encoding: ${path}` });
|
|
633
|
+
}
|
|
634
|
+
if (req.method === "GET") {
|
|
635
|
+
if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
|
|
636
|
+
this.webJsCache ??= this.opts.webJs();
|
|
637
|
+
const js = await this.webJsCache;
|
|
638
|
+
if (js != null) return {
|
|
639
|
+
status: 200,
|
|
640
|
+
contentType: "text/html; charset=utf-8",
|
|
641
|
+
body: WEB_SHELL.replace("__BUILD__", buildId(js)),
|
|
642
|
+
headers: NO_STORE
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return this.replyIndex();
|
|
646
|
+
if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2) return await this.replyWebJs();
|
|
647
|
+
if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
|
|
648
|
+
if (segs[0] === "run" && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1]);
|
|
649
|
+
if (segs[0] === "run" && segs.length === 3 && segs[1] != null && segs[2] === "preview") return this.replyRunPreview(segs[1]);
|
|
650
|
+
if (segs[0] === "lora-info" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyLoraInfo(segs[1], segs[2]);
|
|
651
|
+
if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
|
|
652
|
+
if (segs[0] === "lora-about" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraAbout(segs[1], segs[2]);
|
|
653
|
+
if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
|
|
654
|
+
if (segs[0] === "settings" && segs.length === 1) return this.replySettings();
|
|
655
|
+
if (segs[0] === "hosts" && segs.length === 1) return this.replyHosts();
|
|
656
|
+
if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs") return await this.replyHostLogs(segs[1]);
|
|
657
|
+
if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "ping") return await this.replyHostPing(segs[1]);
|
|
658
|
+
if (segs[0] === "images" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`${segs[1]}/${segs[2]}`);
|
|
659
|
+
if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
|
|
660
|
+
return json(404, {
|
|
661
|
+
error: `no route: GET ${path}`,
|
|
662
|
+
usage: USAGE
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
if (req.method === "POST" && segs[0] === "generate") {
|
|
666
|
+
const target = this.resolveDraft(segs.slice(1));
|
|
667
|
+
if ("error" in target) return json(target.status, { error: target.error });
|
|
668
|
+
return await this.generate(target.mod, target.draft, req);
|
|
669
|
+
}
|
|
670
|
+
if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
|
|
671
|
+
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);
|
|
672
|
+
if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
|
|
673
|
+
if (req.method === "PUT" && segs[0] === "settings" && segs.length === 1) return this.replySaveSettings(req);
|
|
674
|
+
if (req.method === "PUT" && segs[0] === "hosts" && segs.length === 2 && segs[1] != null) return this.replySetHost(segs[1], req);
|
|
675
|
+
if (req.method === "POST" && segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyHostAction(segs[1], segs[2]);
|
|
676
|
+
if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
|
|
677
|
+
if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
|
|
678
|
+
return json(404, {
|
|
679
|
+
error: `no route: ${req.method} ${path}`,
|
|
680
|
+
usage: USAGE
|
|
681
|
+
});
|
|
682
|
+
} catch (e) {
|
|
683
|
+
console.error("[serve] request crashed:", e);
|
|
684
|
+
return json(500, { error: extractErrorMessage(e) });
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
moduleByKey(key) {
|
|
688
|
+
return this.modules.find((m) => m.key === key) ?? null;
|
|
689
|
+
}
|
|
690
|
+
/** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
|
|
691
|
+
draftsFor(mod) {
|
|
692
|
+
return ["default", ...listDraftsForFile(mod.file).filter((n) => n !== "default")];
|
|
693
|
+
}
|
|
694
|
+
/** THE draft-name gate, shared by every route that turns a url segment into a path
|
|
695
|
+
* (safeName.ts owns the rule, the prompt-enhancer routes call the same function) */
|
|
696
|
+
validDraftName(raw) {
|
|
697
|
+
return validStoreName(raw);
|
|
698
|
+
}
|
|
699
|
+
/** absolute path of a draft file, or null when the name is not one we accept */
|
|
700
|
+
draftPath(mod, draft) {
|
|
701
|
+
const name = this.validDraftName(draft);
|
|
702
|
+
return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`);
|
|
703
|
+
}
|
|
704
|
+
draftExists(mod, draft) {
|
|
705
|
+
const path = this.draftPath(mod, draft);
|
|
706
|
+
if (path == null) return false;
|
|
707
|
+
return draft === "default" || existsSync(path);
|
|
708
|
+
}
|
|
709
|
+
resolveDraft(segs) {
|
|
710
|
+
if (segs.length === 2 && segs[0] != null && segs[1] != null) {
|
|
711
|
+
const mod = this.moduleByKey(segs[0]);
|
|
712
|
+
if (mod == null) return {
|
|
713
|
+
status: 404,
|
|
714
|
+
error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(", ")}`
|
|
715
|
+
};
|
|
716
|
+
if (!this.draftExists(mod, segs[1])) return {
|
|
717
|
+
status: 404,
|
|
718
|
+
error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
719
|
+
};
|
|
720
|
+
return {
|
|
721
|
+
mod,
|
|
722
|
+
draft: segs[1]
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
if (segs.length === 1 && segs[0] != null) {
|
|
726
|
+
const draft = segs[0];
|
|
727
|
+
if (this.modules.length === 1 && this.modules[0] != null) {
|
|
728
|
+
const mod = this.modules[0];
|
|
729
|
+
if (!this.draftExists(mod, draft)) return {
|
|
730
|
+
status: 404,
|
|
731
|
+
error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
732
|
+
};
|
|
733
|
+
return {
|
|
734
|
+
mod,
|
|
735
|
+
draft
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
const hits = this.modules.filter((m) => this.draftExists(m, draft));
|
|
739
|
+
if (hits.length === 1 && hits[0] != null) return {
|
|
740
|
+
mod: hits[0],
|
|
741
|
+
draft
|
|
742
|
+
};
|
|
743
|
+
if (hits.length === 0) return {
|
|
744
|
+
status: 404,
|
|
745
|
+
error: `no module has a draft '${draft}'`
|
|
746
|
+
};
|
|
747
|
+
return {
|
|
748
|
+
status: 400,
|
|
749
|
+
error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(" or ")}`
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
return {
|
|
753
|
+
status: 400,
|
|
754
|
+
error: "use POST /generate/<module>/<draft> or /generate/<draft>"
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
describeModule(mod) {
|
|
758
|
+
refreshLoraInfoCacheIfChanged();
|
|
759
|
+
const hostId = mod.dw.host.data.id;
|
|
760
|
+
const vars = {};
|
|
761
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
762
|
+
const desc = describeVar(varDef);
|
|
763
|
+
if (desc.kind === "loras" && desc.options != null) {
|
|
764
|
+
const labels = {};
|
|
765
|
+
for (const option of desc.options) {
|
|
766
|
+
const label = getLoraDisplayName(option, hostId);
|
|
767
|
+
if (label !== option) labels[option] = label;
|
|
768
|
+
}
|
|
769
|
+
if (Object.keys(labels).length > 0) desc.optionLabels = labels;
|
|
770
|
+
const extras = managerOnlyLoraOptions({
|
|
771
|
+
hostId,
|
|
772
|
+
options: desc.options,
|
|
773
|
+
filter: varDef.optionsFilter
|
|
774
|
+
});
|
|
775
|
+
if (extras.length > 0) {
|
|
776
|
+
desc.managerOnlyOptions = extras;
|
|
777
|
+
desc.options = [...desc.options, ...extras];
|
|
778
|
+
for (const extra of extras) {
|
|
779
|
+
const label = getLoraDisplayName(extra, hostId);
|
|
780
|
+
if (label !== extra) (desc.optionLabels ??= {})[extra] = label;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const keywords = {};
|
|
784
|
+
for (const option of desc.options) {
|
|
785
|
+
const kw = getLoraKeyword(option, hostId);
|
|
786
|
+
if (kw !== "") keywords[option] = kw;
|
|
787
|
+
}
|
|
788
|
+
if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords;
|
|
789
|
+
}
|
|
790
|
+
vars[name] = desc;
|
|
791
|
+
}
|
|
792
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
793
|
+
if (varDef.kind !== "prompt") continue;
|
|
794
|
+
const source = varDef.promptOpts.loraKeywordsFrom;
|
|
795
|
+
if (source == null) continue;
|
|
796
|
+
const sourceName = mod.dw.entries().find(([, other]) => other === source)?.[0];
|
|
797
|
+
const desc = vars[name];
|
|
798
|
+
if (sourceName != null && desc != null) desc.keywordsFrom = sourceName;
|
|
799
|
+
}
|
|
800
|
+
return {
|
|
801
|
+
module: mod.key,
|
|
802
|
+
file: mod.file,
|
|
803
|
+
host: mod.dw.host.data.id,
|
|
804
|
+
drafts: this.draftsFor(mod),
|
|
805
|
+
routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
|
|
806
|
+
vars
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
replyIndex() {
|
|
810
|
+
return json(200, {
|
|
811
|
+
server: "comfy-ts serve",
|
|
812
|
+
usage: USAGE,
|
|
813
|
+
workflows: this.modules.map((m) => this.describeModule(m)),
|
|
814
|
+
...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
replyDraft(modKey, draft) {
|
|
818
|
+
const mod = this.moduleByKey(modKey);
|
|
819
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
820
|
+
if (!this.draftExists(mod, draft)) return json(404, { error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}` });
|
|
821
|
+
return json(200, {
|
|
822
|
+
...this.describeModule(mod),
|
|
823
|
+
draft,
|
|
824
|
+
values: this.draftValues(mod, draft)
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
/** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
|
|
828
|
+
draftValues(mod, draft) {
|
|
829
|
+
const path = this.draftPath(mod, draft);
|
|
830
|
+
if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
|
|
831
|
+
const out = {};
|
|
832
|
+
for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default;
|
|
833
|
+
return out;
|
|
834
|
+
}
|
|
835
|
+
replyOutput(segs) {
|
|
836
|
+
const abs = resolve(this.outputRoot, ...segs);
|
|
837
|
+
if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + "/")) return json(400, { error: "path escapes the outputs root" });
|
|
838
|
+
if (!existsSync(abs) || !statSync(abs).isFile()) return json(404, { error: `no such output file: /${segs.join("/")}` });
|
|
839
|
+
return {
|
|
840
|
+
status: 200,
|
|
841
|
+
contentType: CONTENT_TYPES[extname(abs).toLowerCase()] ?? "application/octet-stream",
|
|
842
|
+
body: new Uint8Array(readFileSync(abs))
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
async replyWebJs() {
|
|
846
|
+
if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
|
|
847
|
+
this.webJsCache ??= this.opts.webJs();
|
|
848
|
+
const js = await this.webJsCache;
|
|
849
|
+
if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
|
|
850
|
+
return {
|
|
851
|
+
status: 200,
|
|
852
|
+
contentType: "text/javascript; charset=utf-8",
|
|
853
|
+
body: js,
|
|
854
|
+
headers: NO_STORE
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
/** browser file → local file an image var can point at (downloadInput family) */
|
|
858
|
+
replyUpload(req) {
|
|
859
|
+
let parsed;
|
|
860
|
+
try {
|
|
861
|
+
parsed = JSON.parse(req.body ?? "");
|
|
862
|
+
} catch (e) {
|
|
863
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
864
|
+
}
|
|
865
|
+
const o = parsed ?? {};
|
|
866
|
+
if (typeof o.name !== "string" || o.name === "" || typeof o.dataBase64 !== "string" || o.dataBase64 === "") return json(400, { error: "upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}" });
|
|
867
|
+
const bytes = Buffer.from(o.dataBase64, "base64");
|
|
868
|
+
if (bytes.length === 0) return json(400, { error: "dataBase64 decoded to zero bytes" });
|
|
869
|
+
const safe = (basename(o.name).replace(/[^\w.-]+/g, "_") || "upload").slice(0, 100);
|
|
870
|
+
const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${safe}`);
|
|
871
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
872
|
+
writeFileSync(abs, bytes);
|
|
873
|
+
console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`);
|
|
874
|
+
return json(200, {
|
|
875
|
+
ok: true,
|
|
876
|
+
path: abs,
|
|
877
|
+
url: this.outputUrl(abs)
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
async replySaveDraft(modKey, rawDraft, req) {
|
|
881
|
+
const mod = this.moduleByKey(modKey);
|
|
882
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
883
|
+
const draft = this.validDraftName(rawDraft);
|
|
884
|
+
if (draft == null) return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` });
|
|
885
|
+
let parsed;
|
|
886
|
+
try {
|
|
887
|
+
parsed = JSON.parse(req.body ?? "");
|
|
888
|
+
} catch (e) {
|
|
889
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
890
|
+
}
|
|
891
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
|
|
892
|
+
const values = parsed;
|
|
893
|
+
const known = new Set(mod.dw.entries().map(([k]) => k));
|
|
894
|
+
const unknown = Object.keys(values).filter((k) => !known.has(k));
|
|
895
|
+
if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
|
|
896
|
+
const path = bang(this.draftPath(mod, draft), "draft name validated just above");
|
|
897
|
+
await this.exclusive(mod.key, () => {
|
|
898
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
899
|
+
writeFileSync(path, JSON.stringify(values, null, 2));
|
|
900
|
+
return Promise.resolve();
|
|
901
|
+
});
|
|
902
|
+
return json(200, {
|
|
903
|
+
ok: true,
|
|
904
|
+
module: mod.key,
|
|
905
|
+
draft,
|
|
906
|
+
drafts: this.draftsFor(mod)
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
/** delete the draft FILE. `default` is deletable like any other: the implicit `default`
|
|
910
|
+
* draft (spec values, no file) survives it, which is exactly the reset. Missing file is
|
|
911
|
+
* still a 200, the caller asked for it to be gone, and it is */
|
|
912
|
+
async replyDeleteDraft(modKey, rawDraft) {
|
|
913
|
+
const mod = this.moduleByKey(modKey);
|
|
914
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
915
|
+
const path = this.draftPath(mod, rawDraft);
|
|
916
|
+
if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` });
|
|
917
|
+
await this.exclusive(mod.key, () => {
|
|
918
|
+
if (existsSync(path)) rmSync(path);
|
|
919
|
+
return Promise.resolve();
|
|
920
|
+
});
|
|
921
|
+
console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`);
|
|
922
|
+
return json(200, {
|
|
923
|
+
ok: true,
|
|
924
|
+
module: mod.key,
|
|
925
|
+
draft: rawDraft.trim(),
|
|
926
|
+
drafts: this.draftsFor(mod)
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
/** every host this process registered: the modules' own, plus anything they created */
|
|
930
|
+
knownHosts() {
|
|
931
|
+
const byId = /* @__PURE__ */ new Map();
|
|
932
|
+
for (const [id, host] of comfyts.hosts) byId.set(id, {
|
|
933
|
+
id,
|
|
934
|
+
url: `${host.base.host}:${host.base.port}`,
|
|
935
|
+
httpUrl: host.getServerHostHTTP(),
|
|
936
|
+
modules: []
|
|
937
|
+
});
|
|
938
|
+
for (const mod of this.modules) {
|
|
939
|
+
const entry = byId.get(mod.dw.host.data.id);
|
|
940
|
+
if (entry != null) entry.modules.push(mod.key);
|
|
941
|
+
}
|
|
942
|
+
return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id));
|
|
943
|
+
}
|
|
944
|
+
/** the host a run goes to: the override if it still exists, else the module's own.
|
|
945
|
+
* A stale override (a host id that is gone) must never silently swallow the run */
|
|
946
|
+
runHostFor(mod) {
|
|
947
|
+
const wanted = this.settings.hostOverride[mod.key];
|
|
948
|
+
if (wanted == null || wanted === mod.dw.host.data.id) return null;
|
|
949
|
+
return comfyts.hosts.get(wanted) ?? null;
|
|
950
|
+
}
|
|
951
|
+
/** the host actions the TUI's host panel has, minus re-codegen: regenerating the sdk
|
|
952
|
+
* rewrites a .d.ts for your EDITOR, while the running modules keep the builder they were
|
|
953
|
+
* imported with, a button that changes nothing in this process would be a lie */
|
|
954
|
+
async replyHostAction(hostId, action) {
|
|
955
|
+
const host = comfyts.hosts.get(hostId);
|
|
956
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}' — known: ${[...comfyts.hosts.keys()].join(", ")}` });
|
|
957
|
+
try {
|
|
958
|
+
if (action === "interrupt") {
|
|
959
|
+
await host.interrupt();
|
|
960
|
+
return json(200, {
|
|
961
|
+
ok: true,
|
|
962
|
+
host: hostId,
|
|
963
|
+
action,
|
|
964
|
+
note: "interrupt requested"
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
if (action === "clear-queue") {
|
|
968
|
+
await host.clearQueue();
|
|
969
|
+
return json(200, {
|
|
970
|
+
ok: true,
|
|
971
|
+
host: hostId,
|
|
972
|
+
action,
|
|
973
|
+
note: "pending prompts dropped"
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
if (action === "refresh-loras") return await this.refreshLoraMirror(hostId, host);
|
|
977
|
+
if (action === "refresh-schema") {
|
|
978
|
+
await host.fetchAndUpdateSchema();
|
|
979
|
+
const rebound = await this.rebindHostVars(hostId, host);
|
|
980
|
+
const nodes = host.schema.nodes.length;
|
|
981
|
+
const loras = host.schema.getLoras().length;
|
|
982
|
+
const dropped = rebound.stale.length === 0 ? "" : `. dropped ${rebound.stale.length} selection(s) this host no longer lists`;
|
|
983
|
+
return json(200, {
|
|
984
|
+
ok: true,
|
|
985
|
+
host: hostId,
|
|
986
|
+
action,
|
|
987
|
+
stale: rebound.stale,
|
|
988
|
+
note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
if (action === "restart") {
|
|
992
|
+
await host.manager.restartComfyUI();
|
|
993
|
+
return json(200, {
|
|
994
|
+
ok: true,
|
|
995
|
+
host: hostId,
|
|
996
|
+
action,
|
|
997
|
+
note: "reboot requested — it reconnects when back"
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
return json(400, { error: `unknown host action '${action}' — interrupt | clear-queue | restart | refresh-loras | refresh-schema` });
|
|
1001
|
+
} catch (e) {
|
|
1002
|
+
return json(502, { error: `host '${hostId}' refused '${action}': ${extractErrorMessage(e)}` });
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/** re-sweep ComfyUI-Lora-Manager and rewrite the mirror — what `comfy-ts loras` does, with
|
|
1006
|
+
* its refusals kept: a partial or unreachable sweep NEVER overwrites, because writing it
|
|
1007
|
+
* would delete loras from the mirror that are alive on the host */
|
|
1008
|
+
/** re-resolve the host-bound lora vars of the modules DEFINED on this host: LorasVar only
|
|
1009
|
+
* resolves its RegExp inside bindHost, so nothing else picks up a widened enum.
|
|
1010
|
+
*
|
|
1011
|
+
* the defining host, not the override: rebinding an overridden module against another box
|
|
1012
|
+
* rewrites its options AND its hostId (which picks the metadata mirror) with no way back,
|
|
1013
|
+
* since dropping the override cannot un-resolve them.
|
|
1014
|
+
*
|
|
1015
|
+
* runs under each module's mutex, so it cannot swap the options out from under a generate
|
|
1016
|
+
* that already validated its payload against the old list. */
|
|
1017
|
+
async rebindHostVars(hostId, host) {
|
|
1018
|
+
let widened = 0;
|
|
1019
|
+
const stale = [];
|
|
1020
|
+
for (const mod of this.modules) {
|
|
1021
|
+
if (mod.dw.host.data.id !== hostId) continue;
|
|
1022
|
+
await this.exclusive(mod.key, () => {
|
|
1023
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
1024
|
+
if (varDef.kind !== "loras") continue;
|
|
1025
|
+
const lorasVar = varDef;
|
|
1026
|
+
if (lorasVar.optionsFilter == null) continue;
|
|
1027
|
+
const before = lorasVar.options.length;
|
|
1028
|
+
lorasVar.bindHost(host);
|
|
1029
|
+
if (lorasVar.options.length !== before) widened++;
|
|
1030
|
+
const known = new Set(lorasVar.options);
|
|
1031
|
+
const value = lorasVar.value;
|
|
1032
|
+
for (const picked of Object.keys(value)) {
|
|
1033
|
+
if (known.has(picked)) continue;
|
|
1034
|
+
stale.push(`${mod.key}/${name}: ${picked}`);
|
|
1035
|
+
delete value[picked];
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return Promise.resolve();
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
return {
|
|
1042
|
+
widened,
|
|
1043
|
+
stale
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
async refreshLoraMirror(hostId, host) {
|
|
1047
|
+
const sweep = await fetchLoraList(host);
|
|
1048
|
+
if (sweep.status === "absent") return json(400, { error: `${hostId} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.` });
|
|
1049
|
+
if (sweep.status === "unreachable") return json(502, { error: `${hostId} unreachable — ${sweep.reason}. Mirror left untouched.` });
|
|
1050
|
+
if (sweep.status === "partial") return json(502, { error: `the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched.` });
|
|
1051
|
+
const mirror = buildLoraMirror({
|
|
1052
|
+
hostId,
|
|
1053
|
+
hostUrl: host.getServerHostHTTP(),
|
|
1054
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1055
|
+
items: sweep.items
|
|
1056
|
+
});
|
|
1057
|
+
writeLoraMirror(mirror);
|
|
1058
|
+
reloadLoraInfoCache();
|
|
1059
|
+
console.log(`[serve] lora mirror refreshed for ${hostId}: ${mirror.count} loras`);
|
|
1060
|
+
return json(200, {
|
|
1061
|
+
ok: true,
|
|
1062
|
+
host: hostId,
|
|
1063
|
+
action: "refresh-loras",
|
|
1064
|
+
count: mirror.count,
|
|
1065
|
+
note: `${mirror.count} loras synced`
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
/** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so
|
|
1069
|
+
* "restarting…" ends on a fact rather than on a guess */
|
|
1070
|
+
async replyHostPing(hostId) {
|
|
1071
|
+
const host = comfyts.hosts.get(hostId);
|
|
1072
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}'` });
|
|
1073
|
+
try {
|
|
1074
|
+
const res = await host.fetch("/system_stats", {});
|
|
1075
|
+
return json(200, {
|
|
1076
|
+
host: hostId,
|
|
1077
|
+
up: res.ok,
|
|
1078
|
+
status: res.status
|
|
1079
|
+
});
|
|
1080
|
+
} catch (e) {
|
|
1081
|
+
return json(200, {
|
|
1082
|
+
host: hostId,
|
|
1083
|
+
up: false,
|
|
1084
|
+
reason: extractErrorMessage(e)
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
/** the ComfyUI console, the TUI's logs panel over http — through the SAME assembly the TUI
|
|
1089
|
+
* uses (assembleLogChunks): entries are write CHUNKS, so lines are folded there, ANSI is
|
|
1090
|
+
* stripped, tqdm redraws collapse to their last state, and the cp1252 mojibake a windows
|
|
1091
|
+
* host emits is repaired. Re-implementing any of that here would drift from the TUI */
|
|
1092
|
+
async replyHostLogs(hostId) {
|
|
1093
|
+
const host = comfyts.hosts.get(hostId);
|
|
1094
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}'` });
|
|
1095
|
+
try {
|
|
1096
|
+
const raw = await host.fetchRawLogs();
|
|
1097
|
+
const lines = [];
|
|
1098
|
+
const partial = assembleLogChunks({
|
|
1099
|
+
lines,
|
|
1100
|
+
partial: "",
|
|
1101
|
+
entries: raw.entries
|
|
1102
|
+
});
|
|
1103
|
+
if (partial.trim() !== "") lines.push(partial);
|
|
1104
|
+
return json(200, {
|
|
1105
|
+
host: hostId,
|
|
1106
|
+
lines: lines.slice(-200)
|
|
1107
|
+
});
|
|
1108
|
+
} catch (e) {
|
|
1109
|
+
return json(502, { error: `could not read the logs of '${hostId}': ${extractErrorMessage(e)}` });
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
replyHosts() {
|
|
1113
|
+
return json(200, {
|
|
1114
|
+
hosts: this.knownHosts(),
|
|
1115
|
+
defaults: Object.fromEntries(this.modules.map((m) => [m.key, m.dw.host.data.id])),
|
|
1116
|
+
overrides: this.settings.hostOverride
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
replySetHost(modKey, req) {
|
|
1120
|
+
const mod = this.moduleByKey(modKey);
|
|
1121
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
1122
|
+
let parsed;
|
|
1123
|
+
try {
|
|
1124
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1125
|
+
} catch (e) {
|
|
1126
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1127
|
+
}
|
|
1128
|
+
const wanted = parsed != null && typeof parsed === "object" ? parsed.host : null;
|
|
1129
|
+
if (wanted != null && typeof wanted !== "string") return json(400, { error: "body must be { \"host\": \"<host id>\" } or { \"host\": null } to reset" });
|
|
1130
|
+
const next = { ...this.settings.hostOverride };
|
|
1131
|
+
if (wanted == null || wanted === mod.dw.host.data.id) delete next[mod.key];
|
|
1132
|
+
else {
|
|
1133
|
+
if (!comfyts.hosts.has(wanted)) return json(400, { error: `unknown host '${wanted}' — known: ${[...comfyts.hosts.keys()].join(", ")}` });
|
|
1134
|
+
next[mod.key] = wanted;
|
|
1135
|
+
}
|
|
1136
|
+
this.settings = {
|
|
1137
|
+
...this.settings,
|
|
1138
|
+
hostOverride: next
|
|
1139
|
+
};
|
|
1140
|
+
try {
|
|
1141
|
+
writeServeSettings(this.settings);
|
|
1142
|
+
} catch (e) {
|
|
1143
|
+
return json(500, { error: `host applied for this session but not saved: ${extractErrorMessage(e)}` });
|
|
1144
|
+
}
|
|
1145
|
+
const target = next[mod.key] ?? mod.dw.host.data.id;
|
|
1146
|
+
console.log(`[serve] ${mod.key} runs on ${target}${next[mod.key] != null ? " (override)" : ""}`);
|
|
1147
|
+
return json(200, {
|
|
1148
|
+
ok: true,
|
|
1149
|
+
module: mod.key,
|
|
1150
|
+
host: target,
|
|
1151
|
+
overrides: this.settings.hostOverride
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
rememberMemoryImage(key, bytes, filename) {
|
|
1155
|
+
const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes);
|
|
1156
|
+
this.memoryImages.set(key, {
|
|
1157
|
+
bytes,
|
|
1158
|
+
contentType
|
|
1159
|
+
});
|
|
1160
|
+
while (this.memoryImages.size > this.MEMORY_IMAGE_CAP) {
|
|
1161
|
+
const oldest = this.memoryImages.keys().next();
|
|
1162
|
+
if (oldest.done === true) break;
|
|
1163
|
+
this.memoryImages.delete(oldest.value);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
replyMemoryImage(key) {
|
|
1167
|
+
const hit = this.memoryImages.get(key);
|
|
1168
|
+
if (hit == null) return json(404, { error: `no in-memory image '${key}' — it expired (only the last ${this.MEMORY_IMAGE_CAP} are kept) or the server restarted. Turn saving on to keep outputs.` });
|
|
1169
|
+
return {
|
|
1170
|
+
status: 200,
|
|
1171
|
+
contentType: hit.contentType,
|
|
1172
|
+
body: hit.bytes
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
/** the subfolder under outputs/ a module's images land in. Falls back to the module key,
|
|
1176
|
+
* which is what every serve run used before the prefix was choosable */
|
|
1177
|
+
savePrefixFor(modKey) {
|
|
1178
|
+
const stored = this.settings.savePrefix[modKey]?.trim() ?? "";
|
|
1179
|
+
return stored === "" ? modKey : stored;
|
|
1180
|
+
}
|
|
1181
|
+
replySaveSettings(req) {
|
|
1182
|
+
let parsed;
|
|
1183
|
+
try {
|
|
1184
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1185
|
+
} catch (e) {
|
|
1186
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1187
|
+
}
|
|
1188
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { \"saveToDisk\"?: true | false, \"savePrefix\"?: { \"<module>\": \"path\" } }" });
|
|
1189
|
+
const wanted = parsed;
|
|
1190
|
+
let next = this.settings;
|
|
1191
|
+
if (wanted.saveToDisk != null) {
|
|
1192
|
+
if (typeof wanted.saveToDisk !== "boolean") return json(400, { error: "\"saveToDisk\" must be true or false" });
|
|
1193
|
+
next = {
|
|
1194
|
+
...next,
|
|
1195
|
+
saveToDisk: wanted.saveToDisk
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
if (wanted.savePrefix != null) {
|
|
1199
|
+
if (typeof wanted.savePrefix !== "object" || Array.isArray(wanted.savePrefix)) return json(400, { error: "\"savePrefix\" must be { \"<module>\": \"path\" }" });
|
|
1200
|
+
const prefixes = { ...next.savePrefix };
|
|
1201
|
+
for (const [modKey, raw] of Object.entries(wanted.savePrefix)) {
|
|
1202
|
+
if (this.moduleByKey(modKey) == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
1203
|
+
if (typeof raw !== "string") return json(400, { error: `prefix for '${modKey}' must be a string` });
|
|
1204
|
+
const clean = validSavePrefix(raw);
|
|
1205
|
+
if (clean == null) return json(400, { error: `invalid prefix '${raw}' — folder names only, "a/b" allowed, no ".." and no absolute path` });
|
|
1206
|
+
if (clean === "") delete prefixes[modKey];
|
|
1207
|
+
else prefixes[modKey] = clean;
|
|
1208
|
+
}
|
|
1209
|
+
next = {
|
|
1210
|
+
...next,
|
|
1211
|
+
savePrefix: prefixes
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
const saveToDisk = next.saveToDisk;
|
|
1215
|
+
this.settings = next;
|
|
1216
|
+
try {
|
|
1217
|
+
writeServeSettings(this.settings);
|
|
1218
|
+
} catch (e) {
|
|
1219
|
+
return json(500, { error: `setting applied for this session but not saved: ${extractErrorMessage(e)}` });
|
|
1220
|
+
}
|
|
1221
|
+
console.log(`[serve] outputs ${saveToDisk ? "SAVE to disk" : "stay in MEMORY"}`);
|
|
1222
|
+
return this.replySettings();
|
|
1223
|
+
}
|
|
1224
|
+
/** the stored settings PLUS the prefix each module actually uses, so the ui can show the
|
|
1225
|
+
* effective folder without re-deriving the fallback rule */
|
|
1226
|
+
replySettings() {
|
|
1227
|
+
return json(200, {
|
|
1228
|
+
...this.settings,
|
|
1229
|
+
effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)]))
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
/** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
|
|
1233
|
+
replyPromptEnhancers() {
|
|
1234
|
+
try {
|
|
1235
|
+
return json(200, { enhancers: listPromptEnhancers() });
|
|
1236
|
+
} catch (e) {
|
|
1237
|
+
return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` });
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
replySavePromptEnhancer(rawName, req) {
|
|
1241
|
+
const name = validStoreName(rawName);
|
|
1242
|
+
if (name == null) return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, ". -_"` });
|
|
1243
|
+
let parsed;
|
|
1244
|
+
try {
|
|
1245
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1246
|
+
} catch (e) {
|
|
1247
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1248
|
+
}
|
|
1249
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
|
|
1250
|
+
const text = parsed.text;
|
|
1251
|
+
if (typeof text !== "string") return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
|
|
1252
|
+
try {
|
|
1253
|
+
writePromptEnhancer(name, text);
|
|
1254
|
+
} catch (e) {
|
|
1255
|
+
return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` });
|
|
1256
|
+
}
|
|
1257
|
+
return json(200, {
|
|
1258
|
+
ok: true,
|
|
1259
|
+
name,
|
|
1260
|
+
enhancers: listPromptEnhancers()
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
replyDeletePromptEnhancer(rawName) {
|
|
1264
|
+
const name = validStoreName(rawName);
|
|
1265
|
+
if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` });
|
|
1266
|
+
try {
|
|
1267
|
+
deletePromptEnhancer(name);
|
|
1268
|
+
} catch (e) {
|
|
1269
|
+
return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` });
|
|
1270
|
+
}
|
|
1271
|
+
console.log(`[serve] prompt enhancer deleted: ${name}`);
|
|
1272
|
+
return json(200, {
|
|
1273
|
+
ok: true,
|
|
1274
|
+
name,
|
|
1275
|
+
enhancers: listPromptEnhancers()
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
runningModules() {
|
|
1279
|
+
return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
|
|
1280
|
+
}
|
|
1281
|
+
/** one dispatcher per host, installed once and left in place (idempotent) */
|
|
1282
|
+
wireLatents(host) {
|
|
1283
|
+
if (this.latentHosts.has(host)) return;
|
|
1284
|
+
this.latentHosts.add(host);
|
|
1285
|
+
host.onLatentPreview = (p) => {
|
|
1286
|
+
const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : void 0;
|
|
1287
|
+
const running = this.runningModules();
|
|
1288
|
+
const key = owner ?? (running.length === 1 ? running[0] : void 0);
|
|
1289
|
+
if (key == null) return;
|
|
1290
|
+
this.latentPreviews.set(key, {
|
|
1291
|
+
bytes: p.bytes,
|
|
1292
|
+
mime: p.mime,
|
|
1293
|
+
seq: ++this.latentSeq
|
|
1294
|
+
});
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
replyRunStatus(modKey) {
|
|
1298
|
+
const mod = this.moduleByKey(modKey);
|
|
1299
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
1300
|
+
const exec = this.liveRuns.get(mod.key);
|
|
1301
|
+
const running = exec != null && exec.status !== "Success" && exec.status !== "Failure";
|
|
1302
|
+
return json(200, {
|
|
1303
|
+
running,
|
|
1304
|
+
status: exec?.status ?? "idle",
|
|
1305
|
+
percent: running ? exec.progressGlobal?.percent ?? null : null,
|
|
1306
|
+
node: running ? exec.progress?.nodeName ?? null : null,
|
|
1307
|
+
nodeProgress: running && exec.progress?.nodeProgress != null ? {
|
|
1308
|
+
value: exec.progress.nodeProgress.value,
|
|
1309
|
+
max: exec.progress.nodeProgress.max
|
|
1310
|
+
} : null,
|
|
1311
|
+
progressText: running ? exec.progress?.progressText ?? null : null,
|
|
1312
|
+
hasPreview: this.latentPreviews.has(mod.key),
|
|
1313
|
+
previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
replyRunPreview(modKey) {
|
|
1317
|
+
const mod = this.moduleByKey(modKey);
|
|
1318
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
1319
|
+
const preview = this.latentPreviews.get(mod.key);
|
|
1320
|
+
if (preview == null) return json(404, { error: "no latent preview yet" });
|
|
1321
|
+
return {
|
|
1322
|
+
status: 200,
|
|
1323
|
+
contentType: preview.mime !== "" ? preview.mime : sniffImageContentType(preview.bytes),
|
|
1324
|
+
body: preview.bytes
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
hostById(hostId) {
|
|
1328
|
+
return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null;
|
|
1329
|
+
}
|
|
1330
|
+
hostIds() {
|
|
1331
|
+
return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(", ");
|
|
1332
|
+
}
|
|
1333
|
+
/** mirror-backed text for the hover pane, no network */
|
|
1334
|
+
replyLoraInfo(hostId, lora) {
|
|
1335
|
+
if (this.hostById(hostId) == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
1336
|
+
refreshLoraInfoCacheIfChanged();
|
|
1337
|
+
const item = getLoraInfo(lora, hostId);
|
|
1338
|
+
const civitai = item == null ? null : lmCivitai(item);
|
|
1339
|
+
return json(200, {
|
|
1340
|
+
name: lora,
|
|
1341
|
+
displayName: getLoraDisplayName(lora, hostId),
|
|
1342
|
+
triggerWords: getLoraTriggerWords(lora, hostId),
|
|
1343
|
+
known: item != null,
|
|
1344
|
+
baseModel: item == null ? null : lmBaseModel(item),
|
|
1345
|
+
folder: item == null ? null : lmFolder(item),
|
|
1346
|
+
filePath: item == null ? null : lmFilePath(item),
|
|
1347
|
+
fileSize: item == null ? null : lmFileSize(item),
|
|
1348
|
+
tags: item == null ? [] : lmTags(item),
|
|
1349
|
+
notes: item == null ? "" : lmNotes(item),
|
|
1350
|
+
civitaiUrl: civitai?.modelId == null ? null : `https://civitai.com/models/${civitai.modelId}`,
|
|
1351
|
+
civitaiVersion: civitai?.name ?? null
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
/** what the mirror does NOT hold: civitai's description and the example images, both live
|
|
1355
|
+
* from the extension. A SEPARATE route from /lora-info on purpose, that one is mirror-only
|
|
1356
|
+
* and instant, this one talks to the host and is fetched when a details panel opens */
|
|
1357
|
+
async replyLoraAbout(hostId, lora) {
|
|
1358
|
+
const host = this.hostById(hostId);
|
|
1359
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
1360
|
+
refreshLoraInfoCacheIfChanged();
|
|
1361
|
+
const item = getLoraInfo(lora, hostId);
|
|
1362
|
+
if (item == null) return json(200, {
|
|
1363
|
+
known: false,
|
|
1364
|
+
description: null,
|
|
1365
|
+
examples: [],
|
|
1366
|
+
examplesReason: null
|
|
1367
|
+
});
|
|
1368
|
+
const filePath = lmFilePath(item);
|
|
1369
|
+
const sha = lmSha256(item);
|
|
1370
|
+
const [description, examples] = await Promise.all([filePath == null ? Promise.resolve(null) : fetchLoraDescription(host, filePath), sha == null ? Promise.resolve({
|
|
1371
|
+
files: [],
|
|
1372
|
+
reason: null
|
|
1373
|
+
}) : fetchLoraExampleImages(host, sha)]);
|
|
1374
|
+
return json(200, {
|
|
1375
|
+
known: true,
|
|
1376
|
+
description,
|
|
1377
|
+
examples: examples.files,
|
|
1378
|
+
examplesReason: examples.reason
|
|
1379
|
+
});
|
|
1380
|
+
}
|
|
1381
|
+
async replyLoraPreview(hostId, lora) {
|
|
1382
|
+
const host = this.hostById(hostId);
|
|
1383
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
1384
|
+
refreshLoraInfoCacheIfChanged();
|
|
1385
|
+
let url = getLoraPreviewUrl(lora, hostId);
|
|
1386
|
+
if (url == null) {
|
|
1387
|
+
let sweep = this.previewSweeps.get(hostId);
|
|
1388
|
+
if (sweep == null) {
|
|
1389
|
+
sweep = fetchLoraList(host).then((r) => {
|
|
1390
|
+
if (r.status === "unreachable") {
|
|
1391
|
+
this.previewSweeps.delete(hostId);
|
|
1392
|
+
return {
|
|
1393
|
+
status: r.status,
|
|
1394
|
+
map: null
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
return {
|
|
1398
|
+
status: r.status,
|
|
1399
|
+
map: r.status === "absent" ? null : loraPreviewMapFrom(r.items)
|
|
1400
|
+
};
|
|
1401
|
+
});
|
|
1402
|
+
this.previewSweeps.set(hostId, sweep);
|
|
1403
|
+
}
|
|
1404
|
+
const swept = await sweep;
|
|
1405
|
+
url = swept.map?.get(loraKey(lora)) ?? null;
|
|
1406
|
+
if (url == null && swept.status === "unreachable") return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` });
|
|
1407
|
+
if (url == null && swept.status === "absent") return json(404, { error: `lora-manager extension not detected on '${hostId}'` });
|
|
1408
|
+
}
|
|
1409
|
+
if (url == null) return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` });
|
|
1410
|
+
const bytes = await fetchLoraPreviewBytes(host, url);
|
|
1411
|
+
if (bytes == null) return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` });
|
|
1412
|
+
return {
|
|
1413
|
+
status: 200,
|
|
1414
|
+
contentType: sniffImageContentType(bytes),
|
|
1415
|
+
body: bytes
|
|
1416
|
+
};
|
|
1417
|
+
}
|
|
1418
|
+
outputUrl(absPath) {
|
|
1419
|
+
if (!absPath.startsWith(this.outputRoot + "/")) return null;
|
|
1420
|
+
return "/outputs/" + absPath.slice(this.outputRoot.length + 1).split("/").map(encodeURIComponent).join("/");
|
|
1421
|
+
}
|
|
1422
|
+
async generate(mod, draft, req) {
|
|
1423
|
+
let payload = {};
|
|
1424
|
+
if (req.body != null && req.body.trim() !== "") {
|
|
1425
|
+
let parsed;
|
|
1426
|
+
try {
|
|
1427
|
+
parsed = JSON.parse(req.body);
|
|
1428
|
+
} catch (e) {
|
|
1429
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1430
|
+
}
|
|
1431
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
|
|
1432
|
+
payload = parsed;
|
|
1433
|
+
}
|
|
1434
|
+
const t0 = Date.now();
|
|
1435
|
+
const seeds = {};
|
|
1436
|
+
const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
|
|
1437
|
+
if ("error" in started) return json(started.status, { error: started.error });
|
|
1438
|
+
const execution = started.execution;
|
|
1439
|
+
this.liveRuns.set(mod.key, execution);
|
|
1440
|
+
this.promptOwner.set(execution.data.id, mod.key);
|
|
1441
|
+
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
|
|
1442
|
+
try {
|
|
1443
|
+
await execution.done;
|
|
1444
|
+
} finally {
|
|
1445
|
+
this.promptOwner.delete(execution.data.id);
|
|
1446
|
+
}
|
|
1447
|
+
const durationMs = Date.now() - t0;
|
|
1448
|
+
if (execution.status === "Failure") {
|
|
1449
|
+
console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`);
|
|
1450
|
+
return json(500, {
|
|
1451
|
+
ok: false,
|
|
1452
|
+
module: mod.key,
|
|
1453
|
+
draft,
|
|
1454
|
+
promptId: execution.data.id,
|
|
1455
|
+
durationMs,
|
|
1456
|
+
error: execution.data.error ?? "execution failed"
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
const produced = [`${execution.images.length} image(s)`];
|
|
1460
|
+
if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`);
|
|
1461
|
+
console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1e3).toFixed(1)}s · ${produced.join(" · ")}`);
|
|
1462
|
+
const memoryKeys = /* @__PURE__ */ new Map();
|
|
1463
|
+
for (const [ix, img] of execution.images.entries()) {
|
|
1464
|
+
if (img.absPath != null || img.buffer == null) continue;
|
|
1465
|
+
const key = `${execution.data.id}/${ix}`;
|
|
1466
|
+
this.rememberMemoryImage(key, img.buffer, img.filename);
|
|
1467
|
+
memoryKeys.set(ix, key);
|
|
1468
|
+
}
|
|
1469
|
+
const first = execution.images[0];
|
|
1470
|
+
if (req.accept?.includes("image/") && first != null) {
|
|
1471
|
+
if (first.absPath != null) return {
|
|
1472
|
+
status: 200,
|
|
1473
|
+
contentType: CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? "application/octet-stream",
|
|
1474
|
+
body: new Uint8Array(readFileSync(first.absPath))
|
|
1475
|
+
};
|
|
1476
|
+
const inMemory = this.memoryImages.get(memoryKeys.get(0) ?? "");
|
|
1477
|
+
if (inMemory != null) return {
|
|
1478
|
+
status: 200,
|
|
1479
|
+
contentType: inMemory.contentType,
|
|
1480
|
+
body: inMemory.bytes
|
|
1481
|
+
};
|
|
1482
|
+
}
|
|
1483
|
+
return json(200, {
|
|
1484
|
+
ok: true,
|
|
1485
|
+
module: mod.key,
|
|
1486
|
+
draft,
|
|
1487
|
+
promptId: execution.data.id,
|
|
1488
|
+
durationMs,
|
|
1489
|
+
seeds,
|
|
1490
|
+
savedToDisk: this.settings.saveToDisk,
|
|
1491
|
+
texts: (execution.texts ?? []).map((t) => ({
|
|
1492
|
+
nodeKey: t.nodeKey,
|
|
1493
|
+
text: t.text
|
|
1494
|
+
})),
|
|
1495
|
+
images: execution.images.map((img, ix) => ({
|
|
1496
|
+
filename: img.filename,
|
|
1497
|
+
url: img.absPath != null ? this.outputUrl(img.absPath) : memoryKeys.has(ix) ? `/images/${(memoryKeys.get(ix) ?? "").split("/").map((seg) => encodeURIComponent(seg)).join("/")}` : null,
|
|
1498
|
+
absPath: img.absPath
|
|
1499
|
+
}))
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
/** everything that touches the module's SHARED vars, under the module mutex */
|
|
1503
|
+
async prepareAndStart(mod, draft, payload, seeds) {
|
|
1504
|
+
for (const [, varDef] of mod.dw.entries()) varDef.reset();
|
|
1505
|
+
const draftPath = this.draftPath(mod, draft);
|
|
1506
|
+
if (draftPath == null) return {
|
|
1507
|
+
status: 404,
|
|
1508
|
+
error: `no draft '${draft}'`
|
|
1509
|
+
};
|
|
1510
|
+
if (existsSync(draftPath)) try {
|
|
1511
|
+
const values = JSON.parse(readFileSync(draftPath, "utf8"));
|
|
1512
|
+
for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k]);
|
|
1513
|
+
} catch (e) {
|
|
1514
|
+
return {
|
|
1515
|
+
status: 500,
|
|
1516
|
+
error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}`
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
const draftSeedValues = /* @__PURE__ */ new Map();
|
|
1520
|
+
for (const [k, varDef] of mod.dw.entries()) if (varDef.kind === "seed") draftSeedValues.set(k, varDef.value);
|
|
1521
|
+
const varMap = new Map(mod.dw.entries());
|
|
1522
|
+
for (const [k, rawValue] of Object.entries(payload)) {
|
|
1523
|
+
const varDef = varMap.get(k);
|
|
1524
|
+
if (varDef == null) return {
|
|
1525
|
+
status: 400,
|
|
1526
|
+
error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(", ")}`
|
|
1527
|
+
};
|
|
1528
|
+
let value = rawValue;
|
|
1529
|
+
if (varDef.kind === "image" && typeof rawValue === "string" && /^https?:\/\//.test(rawValue)) try {
|
|
1530
|
+
value = await this.downloadInput(rawValue);
|
|
1531
|
+
} catch (e) {
|
|
1532
|
+
return {
|
|
1533
|
+
status: 400,
|
|
1534
|
+
error: `var '${k}': ${extractErrorMessage(e)}`
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
const err = applyVarPayload(varDef, value, { extraLoraOptions: varDef.kind === "loras" ? managerOnlyLoraOptions({
|
|
1538
|
+
hostId: mod.dw.host.data.id,
|
|
1539
|
+
options: varDef.options,
|
|
1540
|
+
filter: varDef.optionsFilter
|
|
1541
|
+
}) : void 0 });
|
|
1542
|
+
if (err != null) return {
|
|
1543
|
+
status: 400,
|
|
1544
|
+
error: err
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
for (const [k, varDef] of varMap) {
|
|
1548
|
+
if (varDef.kind !== "image") continue;
|
|
1549
|
+
const img = varDef;
|
|
1550
|
+
if (!img.isSet()) continue;
|
|
1551
|
+
const abs = img.absPath();
|
|
1552
|
+
const refuse = {
|
|
1553
|
+
status: 400,
|
|
1554
|
+
error: `image var '${k}': not a usable image file`
|
|
1555
|
+
};
|
|
1556
|
+
if (!existsSync(abs)) return refuse;
|
|
1557
|
+
let real;
|
|
1558
|
+
try {
|
|
1559
|
+
real = realpathSync(abs);
|
|
1560
|
+
} catch {
|
|
1561
|
+
return refuse;
|
|
1562
|
+
}
|
|
1563
|
+
try {
|
|
1564
|
+
if (!statSync(real).isFile()) return refuse;
|
|
1565
|
+
} catch {
|
|
1566
|
+
return refuse;
|
|
1567
|
+
}
|
|
1568
|
+
if (!serveAcceptsImageExt(img.extensions, extname(real).toLowerCase().replace(/^\./, ""))) return refuse;
|
|
1569
|
+
if (!looksLikeImage(real)) return refuse;
|
|
1570
|
+
}
|
|
1571
|
+
for (const [k, varDef] of varMap) {
|
|
1572
|
+
if (varDef.kind !== "seed") continue;
|
|
1573
|
+
const seedVar = varDef;
|
|
1574
|
+
const stateKey = `${mod.key}/${draft}/${k}`;
|
|
1575
|
+
const draftValue = draftSeedValues.get(k) ?? seedVar.value;
|
|
1576
|
+
if (!(k in payload)) {
|
|
1577
|
+
if (seedVar.mode === "?") seedVar.randomize();
|
|
1578
|
+
else if (seedVar.mode === "+" || seedVar.mode === "-") {
|
|
1579
|
+
const prev = this.seedState.get(stateKey);
|
|
1580
|
+
const ours = prev != null && (prev.draftBase === draftValue || prev.last === draftValue);
|
|
1581
|
+
if (prev != null && ours) seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
this.seedState.set(stateKey, {
|
|
1585
|
+
last: seedVar.value,
|
|
1586
|
+
draftBase: draftValue
|
|
1587
|
+
});
|
|
1588
|
+
seeds[k] = seedVar.value;
|
|
1589
|
+
}
|
|
1590
|
+
this.latentPreviews.delete(mod.key);
|
|
1591
|
+
const runHost = this.runHostFor(mod);
|
|
1592
|
+
this.wireLatents(runHost ?? mod.dw.host);
|
|
1593
|
+
try {
|
|
1594
|
+
return { execution: await this.starter(mod, {
|
|
1595
|
+
saveToDisk: this.settings.saveToDisk,
|
|
1596
|
+
savePrefix: this.savePrefixFor(mod.key),
|
|
1597
|
+
host: runHost ?? void 0
|
|
1598
|
+
}) };
|
|
1599
|
+
} catch (e) {
|
|
1600
|
+
if (e instanceof Error && e.name === "ImageVarEmptyError") return {
|
|
1601
|
+
status: 400,
|
|
1602
|
+
error: e.message
|
|
1603
|
+
};
|
|
1604
|
+
if (e instanceof Error && e.name === "ComfyHostUnreachableError") return {
|
|
1605
|
+
status: 502,
|
|
1606
|
+
error: e.message
|
|
1607
|
+
};
|
|
1608
|
+
return {
|
|
1609
|
+
status: 500,
|
|
1610
|
+
error: extractErrorMessage(e)
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
/** serialize fn per module key; the stored chain never rejects */
|
|
1615
|
+
exclusive(key, fn) {
|
|
1616
|
+
const next = (this.chains.get(key) ?? Promise.resolve()).then(fn);
|
|
1617
|
+
this.chains.set(key, next.catch(() => {}));
|
|
1618
|
+
return next;
|
|
1619
|
+
}
|
|
1620
|
+
/** payload image urls land as local files under outputs/serve-inputs/ */
|
|
1621
|
+
async downloadInput(url) {
|
|
1622
|
+
try {
|
|
1623
|
+
return await this.fetchInput(url);
|
|
1624
|
+
} catch (e) {
|
|
1625
|
+
if (!(e instanceof DownloadRefused)) console.error(`[serve] input download failed: ${url}:`, e);
|
|
1626
|
+
throw new DownloadRefused(url);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
async fetchInput(url) {
|
|
1630
|
+
const res = await fetch(url, {
|
|
1631
|
+
redirect: "follow",
|
|
1632
|
+
signal: AbortSignal.timeout(INPUT_DOWNLOAD_TIMEOUT_MS)
|
|
1633
|
+
});
|
|
1634
|
+
if (!res.ok) {
|
|
1635
|
+
console.error(`[serve] input download failed (http ${res.status}): ${url}`);
|
|
1636
|
+
throw new DownloadRefused(url);
|
|
1637
|
+
}
|
|
1638
|
+
const declared = Number(res.headers.get("content-length") ?? "0");
|
|
1639
|
+
if (declared > INPUT_DOWNLOAD_CAP) throw new Error(`download too large (${declared} bytes): ${url}`);
|
|
1640
|
+
const bytes = await readCapped(res, INPUT_DOWNLOAD_CAP, url);
|
|
1641
|
+
const name = basename(new URL(url).pathname) || "input";
|
|
1642
|
+
const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${name}`);
|
|
1643
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
1644
|
+
writeFileSync(abs, bytes);
|
|
1645
|
+
return abs;
|
|
1646
|
+
}
|
|
1647
|
+
};
|
|
1648
|
+
//#endregion
|
|
1649
|
+
//#region src/cli/serve/startupPrint.ts
|
|
1650
|
+
const RULE_WIDTH = 64;
|
|
1651
|
+
/** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one
|
|
1652
|
+
* you want when the phone is not on the same wifi */
|
|
1653
|
+
function addressNote(addr) {
|
|
1654
|
+
const octets = addr.split(".").map(Number);
|
|
1655
|
+
const second = octets[1] ?? 0;
|
|
1656
|
+
if (octets[0] === 100 && second >= 64 && second <= 127) return "tailnet";
|
|
1657
|
+
if (addr === "127.0.0.1" || addr === "localhost") return "this machine";
|
|
1658
|
+
return "";
|
|
1659
|
+
}
|
|
1660
|
+
function paint(color) {
|
|
1661
|
+
const id = (s) => s;
|
|
1662
|
+
if (!color) return {
|
|
1663
|
+
title: id,
|
|
1664
|
+
name: id,
|
|
1665
|
+
dim: id,
|
|
1666
|
+
url: id,
|
|
1667
|
+
warn: id
|
|
1668
|
+
};
|
|
1669
|
+
return {
|
|
1670
|
+
title: (s) => ansi.bold(s),
|
|
1671
|
+
name: (s) => ansi.bold.cyan(s),
|
|
1672
|
+
dim: (s) => ansi.gray(s),
|
|
1673
|
+
url: (s) => ansi.green(s),
|
|
1674
|
+
warn: (s) => ansi.yellow(s)
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
/** a box that stays square whatever the colors do: padding measures the VISIBLE text */
|
|
1678
|
+
function boxed(lines, p = { color: false }) {
|
|
1679
|
+
const width = Math.max(...lines.map((l) => stripAnsi(l).length), 0);
|
|
1680
|
+
const edge = (l, r) => `${l}${"─".repeat(width + 2)}${r}`;
|
|
1681
|
+
const border = (s) => p.color ? ansi.gray(s) : s;
|
|
1682
|
+
return [
|
|
1683
|
+
border(edge("┌", "┐")),
|
|
1684
|
+
...lines.map((l) => `${border("│")} ${l}${" ".repeat(width - stripAnsi(l).length)} ${border("│")}`),
|
|
1685
|
+
border(edge("└", "┘"))
|
|
1686
|
+
];
|
|
1687
|
+
}
|
|
1688
|
+
function renderStartupLines(p) {
|
|
1689
|
+
const c = paint(p.color);
|
|
1690
|
+
const loopback = p.bind === "127.0.0.1" || p.bind === "localhost" || p.bind === "::1";
|
|
1691
|
+
const primary = `http://${p.urls[0] ?? p.bind}:${p.port}/`;
|
|
1692
|
+
const out = [];
|
|
1693
|
+
const count = `${p.modules.length} workflow${p.modules.length === 1 ? "" : "s"}`;
|
|
1694
|
+
out.push(c.title(`comfy-ts serve · ${count} · ${primary}`));
|
|
1695
|
+
out.push(c.warn(loopback ? "⚠️ no auth: this API runs workflows, and any page open in your browser can call it" : `⚠️ bound to ${p.bind}, no auth: anyone on this network can run workflows on your ComfyUI host`));
|
|
1696
|
+
for (const mod of p.modules) {
|
|
1697
|
+
out.push("", c.dim("─".repeat(RULE_WIDTH)));
|
|
1698
|
+
out.push(`${c.name(mod.key)} ${c.dim(`host: ${mod.hostId}`)}`);
|
|
1699
|
+
for (const route of mod.routes) out.push(c.dim(` POST ${route}`));
|
|
1700
|
+
out.push(...mod.varLines);
|
|
1701
|
+
}
|
|
1702
|
+
out.push(c.dim("─".repeat(RULE_WIDTH)), "");
|
|
1703
|
+
const box = [`${c.title("web ui")} ${c.url(primary)}`, `${c.dim("json api")} ${c.dim(`${primary}drafts`)}`];
|
|
1704
|
+
if (p.urls.length > 1) {
|
|
1705
|
+
box.push("", c.dim("also reachable at:"));
|
|
1706
|
+
for (const url of p.urls.slice(1)) {
|
|
1707
|
+
const note = addressNote(url);
|
|
1708
|
+
box.push(` ${c.url(`http://${url}:${p.port}/`)}${note === "" ? "" : c.dim(` (${note})`)}`);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
if (loopback) {
|
|
1712
|
+
box.push("", c.dim("to open it from your phone or another machine:"));
|
|
1713
|
+
box.push(c.dim(` comfy-ts serve --host 0.0.0.0 (--bind is the same flag)`));
|
|
1714
|
+
box.push(c.dim(" every reachable url gets printed here, tailnet included"));
|
|
1715
|
+
}
|
|
1716
|
+
out.push(...boxed(box, { color: p.color }));
|
|
1717
|
+
return out;
|
|
1718
|
+
}
|
|
1719
|
+
//#endregion
|
|
1720
|
+
//#region src/cli/serve/webBundle.ts
|
|
1721
|
+
const WEB_ENTRY = "src/cli/serve/web/main.tsx";
|
|
1722
|
+
/** nearest dir upward holding a package.json — the comfy-ts package root, from dist/ and src/ alike */
|
|
1723
|
+
function packageRoot(fromDir) {
|
|
1724
|
+
let dir = fromDir;
|
|
1725
|
+
while (true) {
|
|
1726
|
+
if (existsSync(join(dir, "package.json"))) return dir;
|
|
1727
|
+
const parent = dirname(dir);
|
|
1728
|
+
if (parent === dir) return null;
|
|
1729
|
+
dir = parent;
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
/** bundle the web app to one browser file. Bun.build reads no tsconfig, so the
|
|
1733
|
+
* house 'src/...' absolute imports resolve through the same plugin shape as
|
|
1734
|
+
* tests/web-bundle.test.ts */
|
|
1735
|
+
async function buildWebJsText(pkgRoot) {
|
|
1736
|
+
const result = await Bun.build({
|
|
1737
|
+
entrypoints: [join(pkgRoot, WEB_ENTRY)],
|
|
1738
|
+
target: "browser",
|
|
1739
|
+
minify: true,
|
|
1740
|
+
throw: false,
|
|
1741
|
+
define: { "process.env.NODE_ENV": "\"production\"" },
|
|
1742
|
+
plugins: [{
|
|
1743
|
+
name: "repo-src-paths",
|
|
1744
|
+
setup(build) {
|
|
1745
|
+
build.onResolve({ filter: /^src\// }, (args) => ({ path: join(pkgRoot, args.path) }));
|
|
1746
|
+
}
|
|
1747
|
+
}]
|
|
1748
|
+
});
|
|
1749
|
+
if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
|
|
1750
|
+
return await result.outputs[0].text();
|
|
1751
|
+
}
|
|
1752
|
+
/** the runtime resolution chain; every miss logs loud and degrades to api-only */
|
|
1753
|
+
async function loadOrBuildWebJs() {
|
|
1754
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
1755
|
+
const prebuilt = join(here, "serve-web.js");
|
|
1756
|
+
if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
|
|
1757
|
+
if (typeof Bun === "undefined") {
|
|
1758
|
+
console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
|
|
1759
|
+
return null;
|
|
1760
|
+
}
|
|
1761
|
+
const pkgRoot = packageRoot(here);
|
|
1762
|
+
if (pkgRoot == null || !existsSync(join(pkgRoot, WEB_ENTRY))) {
|
|
1763
|
+
console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
|
|
1764
|
+
return null;
|
|
1765
|
+
}
|
|
1766
|
+
try {
|
|
1767
|
+
return await buildWebJsText(pkgRoot);
|
|
1768
|
+
} catch (e) {
|
|
1769
|
+
console.error("[serve] 🔴 web ui bundle failed — api only:", e);
|
|
1770
|
+
return null;
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
//#endregion
|
|
1774
|
+
//#region src/cli/serve/run-serve.ts
|
|
1775
|
+
const DEFAULT_PORT = 8288;
|
|
1776
|
+
const BODY_CAP = 1e7;
|
|
1777
|
+
function parseArgs(args) {
|
|
1778
|
+
let target;
|
|
1779
|
+
let port = DEFAULT_PORT;
|
|
1780
|
+
let bind = "127.0.0.1";
|
|
1781
|
+
for (let i = 0; i < args.length; i++) {
|
|
1782
|
+
const a = args[i];
|
|
1783
|
+
if (a === "--port") {
|
|
1784
|
+
const n = Number(args[++i]);
|
|
1785
|
+
if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` };
|
|
1786
|
+
port = n;
|
|
1787
|
+
} else if (a === "--host" || a === "--bind") {
|
|
1788
|
+
const b = args[++i];
|
|
1789
|
+
if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` };
|
|
1790
|
+
bind = b;
|
|
1791
|
+
} else if (a != null && a.startsWith("--")) return { error: `unknown flag '${a}'` };
|
|
1792
|
+
else if (a != null) {
|
|
1793
|
+
if (target != null) return { error: `one target only (got '${target}' and '${a}')` };
|
|
1794
|
+
target = a;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
return {
|
|
1798
|
+
target,
|
|
1799
|
+
port,
|
|
1800
|
+
bind
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
/** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
|
|
1804
|
+
/** open CORS, because a browser page IS a first-class client here: the web entry runs the
|
|
1805
|
+
* library in a tab and rides serve as its bridge to hosts that send no CORS headers
|
|
1806
|
+
* (examples/web is on another port by construction). The cost is real and stated at launch:
|
|
1807
|
+
* with no auth, any page you visit can drive this api. That is the same trade as the port
|
|
1808
|
+
* being open at all, so it is said out loud rather than hidden behind a flag. */
|
|
1809
|
+
function makeRequestListener(app) {
|
|
1810
|
+
const cors = {
|
|
1811
|
+
"access-control-allow-origin": "*",
|
|
1812
|
+
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
|
|
1813
|
+
"access-control-allow-headers": "content-type, accept"
|
|
1814
|
+
};
|
|
1815
|
+
return (req, res) => {
|
|
1816
|
+
const chunks = [];
|
|
1817
|
+
let size = 0;
|
|
1818
|
+
let overflow = false;
|
|
1819
|
+
req.on("error", (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`));
|
|
1820
|
+
req.on("data", (c) => {
|
|
1821
|
+
if (overflow) return;
|
|
1822
|
+
size += c.length;
|
|
1823
|
+
if (size > BODY_CAP) {
|
|
1824
|
+
overflow = true;
|
|
1825
|
+
res.writeHead(413, {
|
|
1826
|
+
"content-type": "application/json",
|
|
1827
|
+
...cors
|
|
1828
|
+
});
|
|
1829
|
+
res.end(JSON.stringify({ error: "payload too large" }), () => req.destroy());
|
|
1830
|
+
} else chunks.push(c);
|
|
1831
|
+
});
|
|
1832
|
+
req.on("end", () => {
|
|
1833
|
+
if (overflow) return;
|
|
1834
|
+
if (req.method === "OPTIONS") {
|
|
1835
|
+
res.writeHead(204, cors);
|
|
1836
|
+
res.end();
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
app.handle({
|
|
1840
|
+
method: req.method ?? "GET",
|
|
1841
|
+
url: req.url ?? "/",
|
|
1842
|
+
accept: req.headers.accept,
|
|
1843
|
+
body: Buffer.concat(chunks).toString("utf8")
|
|
1844
|
+
}).then((reply) => {
|
|
1845
|
+
res.writeHead(reply.status, {
|
|
1846
|
+
"content-type": reply.contentType,
|
|
1847
|
+
...reply.headers,
|
|
1848
|
+
...cors
|
|
1849
|
+
});
|
|
1850
|
+
res.end(reply.body);
|
|
1851
|
+
}).catch((e) => {
|
|
1852
|
+
console.error(`[serve] response write failed: ${extractErrorMessage(e)}`);
|
|
1853
|
+
res.destroy();
|
|
1854
|
+
});
|
|
1855
|
+
});
|
|
1856
|
+
};
|
|
1857
|
+
}
|
|
1858
|
+
async function runServe(args) {
|
|
1859
|
+
const parsed = parseArgs(args);
|
|
1860
|
+
if ("error" in parsed) {
|
|
1861
|
+
console.error(`[comfy-ts serve] ${parsed.error}`);
|
|
1862
|
+
return 1;
|
|
1863
|
+
}
|
|
1864
|
+
const target = resolve(parsed.target ?? ".");
|
|
1865
|
+
let files;
|
|
1866
|
+
try {
|
|
1867
|
+
files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target];
|
|
1868
|
+
} catch {
|
|
1869
|
+
console.error(`[comfy-ts serve] no such file or directory: ${target}`);
|
|
1870
|
+
return 1;
|
|
1871
|
+
}
|
|
1872
|
+
if (files.length === 0) {
|
|
1873
|
+
console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`);
|
|
1874
|
+
return 1;
|
|
1875
|
+
}
|
|
1876
|
+
const modules = [];
|
|
1877
|
+
const loadErrors = {};
|
|
1878
|
+
for (const file of files) try {
|
|
1879
|
+
const dw = findDefinedWorkflow(await import(pathToFileURL(file).href));
|
|
1880
|
+
if (dw == null) throw new Error("exports no DefinedWorkflow");
|
|
1881
|
+
const key = draftKeyForFile(file);
|
|
1882
|
+
const clash = modules.find((m) => m.key === key);
|
|
1883
|
+
if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`);
|
|
1884
|
+
modules.push({
|
|
1885
|
+
key,
|
|
1886
|
+
file,
|
|
1887
|
+
dw
|
|
1888
|
+
});
|
|
1889
|
+
} catch (e) {
|
|
1890
|
+
loadErrors[file] = extractErrorMessage(e);
|
|
1891
|
+
console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`);
|
|
1892
|
+
}
|
|
1893
|
+
if (modules.length === 0) {
|
|
1894
|
+
console.error("[comfy-ts serve] every module failed to load — nothing to serve");
|
|
1895
|
+
return 1;
|
|
1896
|
+
}
|
|
1897
|
+
const app = new ServeApp(modules, {
|
|
1898
|
+
loadErrors,
|
|
1899
|
+
webJs: loadOrBuildWebJs
|
|
1900
|
+
});
|
|
1901
|
+
printStartup(app, parsed.bind, parsed.port);
|
|
1902
|
+
const server = createServer(makeRequestListener(app));
|
|
1903
|
+
server.on("error", (e) => {
|
|
1904
|
+
console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`);
|
|
1905
|
+
process.exitCode = 1;
|
|
1906
|
+
server.close();
|
|
1907
|
+
});
|
|
1908
|
+
server.listen(parsed.port, parsed.bind);
|
|
1909
|
+
return new Promise((resolveExit) => {
|
|
1910
|
+
server.on("close", () => resolveExit(typeof process.exitCode === "number" ? process.exitCode : 0));
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
/** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
|
|
1914
|
+
* only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */
|
|
1915
|
+
function reachableAddresses(bind, nics) {
|
|
1916
|
+
if (bind !== "0.0.0.0" && bind !== "::") return [bind];
|
|
1917
|
+
const found = [];
|
|
1918
|
+
for (const list of Object.values(nics)) for (const nic of list ?? []) {
|
|
1919
|
+
if (nic.internal || nic.family !== "IPv4" && nic.family !== 4) continue;
|
|
1920
|
+
found.push(nic.address);
|
|
1921
|
+
}
|
|
1922
|
+
return ["127.0.0.1", ...found];
|
|
1923
|
+
}
|
|
1924
|
+
function printStartup(app, bind, port) {
|
|
1925
|
+
const base = `http://${bind}:${port}`;
|
|
1926
|
+
const color = colorsAvailable();
|
|
1927
|
+
const lines = renderStartupLines({
|
|
1928
|
+
bind,
|
|
1929
|
+
port,
|
|
1930
|
+
urls: reachableAddresses(bind, networkInterfaces()),
|
|
1931
|
+
color,
|
|
1932
|
+
modules: app.modules.map((mod) => {
|
|
1933
|
+
const entries = mod.dw.entries();
|
|
1934
|
+
const nameWidth = Math.max(...entries.map(([n]) => n.length), 4);
|
|
1935
|
+
return {
|
|
1936
|
+
key: mod.key,
|
|
1937
|
+
hostId: mod.dw.host.data.id,
|
|
1938
|
+
routes: app.draftsFor(mod).map((d) => `${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
|
|
1939
|
+
varLines: entries.map(([name, varDef]) => renderDescriptorLine(name, describeVar(varDef), nameWidth, color))
|
|
1940
|
+
};
|
|
1941
|
+
})
|
|
1942
|
+
});
|
|
1943
|
+
for (const line of lines) console.log(line);
|
|
1944
|
+
}
|
|
1945
|
+
//#endregion
|
|
1946
|
+
export { runServe };
|
|
1947
|
+
|
|
1948
|
+
//# sourceMappingURL=run-serve-_nrvJYyt.js.map
|