comfy-ts 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +66 -0
  2. package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/DraftsSt-DcOTn0QR.js +434 -0
  5. package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +476 -202
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +98 -40
  11. package/dist/index.d.ts +117 -59
  12. package/dist/index.js +468 -193
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-CN0DhrsA.js +638 -0
  15. package/dist/run-serve-CN0DhrsA.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
  17. package/dist/run-tui-bN2hSD5i.js.map +1 -0
  18. package/dist/state-COlKYipO.js +4743 -0
  19. package/dist/state-COlKYipO.js.map +1 -0
  20. package/dist/web.d.ts +17340 -0
  21. package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
  22. package/dist/web.js.map +1 -0
  23. package/examples/web/example.ts +71 -0
  24. package/examples/web/index.html +77 -0
  25. package/examples/web/serve.ts +42 -0
  26. package/examples/web/tsconfig.json +15 -0
  27. package/package.json +10 -3
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/StatusBar.tsx +1 -0
  34. package/src/cli/tui/components/TreePanel.tsx +17 -3
  35. package/src/cli/tui/components/TuiApp.tsx +7 -2
  36. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  37. package/src/cli/tui/imageClipboard.ts +39 -0
  38. package/src/cli/tui/listWindow.ts +36 -0
  39. package/src/cli/tui/state/ExecSt.ts +48 -0
  40. package/src/cli/tui/state/TreeSt.ts +25 -0
  41. package/src/cli/tui/state/TuiSt.ts +34 -0
  42. package/src/coreExports.ts +118 -0
  43. package/src/host/ComfyHost.ts +23 -23
  44. package/src/host/ResilientWebsocket.ts +93 -47
  45. package/src/host/hostUrl.ts +2 -1
  46. package/src/host/loraManagerApi.ts +6 -7
  47. package/src/index.ts +8 -107
  48. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  49. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  50. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  51. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  52. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  53. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  54. package/src/runner/ComfyExecution.ts +32 -12
  55. package/src/runner/MediaImage.ts +18 -30
  56. package/src/runner/outputPath.ts +75 -0
  57. package/src/sdk-generator/ComfySchema.ts +2 -2
  58. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  59. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  60. package/src/state.ts +13 -9
  61. package/src/storage/ComfyStorage.ts +144 -0
  62. package/src/storage/nodeStorage.ts +9 -0
  63. package/src/utils/downloadFile.ts +11 -69
  64. package/src/utils/hashArrayBuffer.ts +3 -4
  65. package/src/utils/lazySharp.ts +25 -0
  66. package/src/utils/sha1.ts +69 -0
  67. package/src/vars/ComfyVars.ts +13 -6
  68. package/src/vars/loraKeywords.ts +6 -6
  69. package/src/web.ts +13 -0
  70. package/dist/run-tui-BAdizWsO.js.map +0 -1
  71. package/dist/state-BYbxDgfr.js.map +0 -1
  72. package/src/utils/writeFile.ts +0 -16
@@ -0,0 +1,737 @@
1
+ import { basename, isAbsolute, join, resolve } from "pathe";
2
+ import { imageMeta } from "image-meta";
3
+ import { action, makeObservable, observable, runInAction } from "mobx";
4
+ //#region src/utils/log.ts
5
+ const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
6
+ const logInfo = (msg) => {
7
+ if (!isQuiet()) console.log(msg);
8
+ };
9
+ const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
10
+ const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
11
+ //#endregion
12
+ //#region src/storage/ComfyStorage.ts
13
+ function dirnameOf(path) {
14
+ const ix = path.lastIndexOf("/");
15
+ return ix <= 0 ? "/" : path.slice(0, ix);
16
+ }
17
+ /** node backend built from INJECTED modules: nodeStorage.ts passes its static
18
+ * imports, the autodetect below passes process.getBuiltinModule results */
19
+ function createNodeStorageFrom(fs, os) {
20
+ return {
21
+ kind: "node",
22
+ readText: (p) => fs.readFileSync(p, "utf8"),
23
+ readTextIfExists: (p) => fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null,
24
+ readBytes: (p) => new Uint8Array(fs.readFileSync(p)),
25
+ writeText: (p, text) => {
26
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
27
+ fs.writeFileSync(p, text);
28
+ },
29
+ writeBytes: (p, bytes) => {
30
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
31
+ fs.writeFileSync(p, bytes);
32
+ },
33
+ exists: (p) => fs.existsSync(p),
34
+ mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
35
+ mtimeMs: (p) => fs.existsSync(p) ? fs.statSync(p).mtimeMs : null,
36
+ homedir: () => os.homedir(),
37
+ cwd: () => process.cwd()
38
+ };
39
+ }
40
+ let installedDefault = null;
41
+ function autodetectNodeStorage() {
42
+ const get = globalThis.process?.getBuiltinModule;
43
+ if (typeof get !== "function") return null;
44
+ const fs = get("node:fs");
45
+ const os = get("node:os");
46
+ if (fs == null || os == null) return null;
47
+ return createNodeStorageFrom(fs, os);
48
+ }
49
+ function resolveComfyStorage(explicit) {
50
+ if (explicit != null) return explicit;
51
+ if (installedDefault != null) return installedDefault;
52
+ const detected = autodetectNodeStorage();
53
+ if (detected != null) {
54
+ installedDefault = detected;
55
+ return detected;
56
+ }
57
+ throw new Error(`no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`);
58
+ }
59
+ /** the ONE accessor call sites use: the instance's storage when the global
60
+ * exists, the resolved default otherwise (vars constructed before create()) */
61
+ function getComfyStorage() {
62
+ return globalThis.comfyts?.storage ?? resolveComfyStorage();
63
+ }
64
+ //#endregion
65
+ //#region src/utils/extractErrorMessage.ts
66
+ /** Extracts an error message from an exception stuff. */
67
+ const extractErrorMessage = (error) => {
68
+ if (error instanceof Error) return error.message;
69
+ if (error === null) return "null";
70
+ if (typeof error === "string") return error;
71
+ if (typeof error === "object") {
72
+ if ("message" in error && typeof error.message === "string") return error.message;
73
+ return JSON.stringify(error);
74
+ }
75
+ return String(error);
76
+ };
77
+ //#endregion
78
+ //#region src/vars/loraKeywords.ts
79
+ /**
80
+ * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
81
+ * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
82
+ * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
83
+ * and must survive a cache wipe). Observable map: overlay rows re-render on
84
+ * assignment. Keys are the RAW lora names (folder/file.safetensors).
85
+ */
86
+ const keywords = observable.map();
87
+ let loaded = false;
88
+ function filePath() {
89
+ return join(comfyts.baseFolder, "lora-keywords.json");
90
+ }
91
+ function loadOnce() {
92
+ if (loaded) return;
93
+ loaded = true;
94
+ const path = filePath();
95
+ const text = getComfyStorage().readTextIfExists(path);
96
+ if (text == null) return;
97
+ try {
98
+ const raw = JSON.parse(text);
99
+ if (raw == null || typeof raw !== "object") return;
100
+ runInAction(() => {
101
+ for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
102
+ });
103
+ } catch (e) {
104
+ logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
105
+ }
106
+ }
107
+ function getLoraKeyword(name) {
108
+ loadOnce();
109
+ return keywords.get(name) ?? "";
110
+ }
111
+ /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
112
+ function setLoraKeyword(name, keyword) {
113
+ loadOnce();
114
+ const trimmed = keyword.trim();
115
+ runInAction(() => {
116
+ if (trimmed === "") keywords.delete(name);
117
+ else keywords.set(name, trimmed);
118
+ });
119
+ const path = filePath();
120
+ try {
121
+ getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
122
+ } catch (e) {
123
+ logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
124
+ }
125
+ }
126
+ //#endregion
127
+ //#region src/vars/ComfyVars.ts
128
+ /**
129
+ * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
130
+ * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
131
+ * the one Out-specialized var (string in, PromptValue out); the split keeps
132
+ * outValue() cast-free.
133
+ */
134
+ var ComfyVarBase = class {
135
+ constructor(defaultValue, label) {
136
+ this.defaultValue = defaultValue;
137
+ this.label = label;
138
+ this.value = defaultValue;
139
+ makeObservable(this, {
140
+ value: observable,
141
+ set: action,
142
+ reset: action,
143
+ parse: action,
144
+ loadJSON: action
145
+ });
146
+ }
147
+ set(value) {
148
+ this.value = value;
149
+ return this;
150
+ }
151
+ /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
152
+ toJSON() {
153
+ return this.value;
154
+ }
155
+ /**
156
+ * restore a value produced by toJSON() (drafts). The cast is sanctioned:
157
+ * drafts are our own round-trip, subclasses re-validate via set().
158
+ */
159
+ loadJSON(value) {
160
+ return this.set(value);
161
+ }
162
+ reset() {
163
+ this.value = this.defaultValue;
164
+ return this;
165
+ }
166
+ /** how the value renders in a var list */
167
+ display() {
168
+ return String(this.value);
169
+ }
170
+ /** the string the inline editor starts from (round-trips through parse) */
171
+ toEditBuffer() {
172
+ return String(this.value);
173
+ }
174
+ /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
175
+ afterRun() {}
176
+ };
177
+ /** the standard var: the graph consumes the stored value AS-IS (Out = T) */
178
+ var ComfyVar = class extends ComfyVarBase {
179
+ outValue() {
180
+ return this.value;
181
+ }
182
+ };
183
+ var TextVar = class extends ComfyVar {
184
+ constructor(..._args) {
185
+ super(..._args);
186
+ this.kind = "text";
187
+ }
188
+ parse(raw) {
189
+ this.set(raw);
190
+ return true;
191
+ }
192
+ };
193
+ const commentLineRe = /^\s*\/\//;
194
+ const negativeLineRe = /^\s*- (.*)$/;
195
+ /**
196
+ * prompt text with editor comforts, all resolved at BUILD time (the editor and
197
+ * drafts keep the raw text):
198
+ * - `//` lines are COMMENTS — stripped
199
+ * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
200
+ * comma-joined into `.negative`
201
+ * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
202
+ * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
203
+ * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
204
+ */
205
+ var PromptVar = class extends ComfyVarBase {
206
+ constructor(defaultValue, promptOpts = {}) {
207
+ super(defaultValue, promptOpts.label);
208
+ this.promptOpts = promptOpts;
209
+ this.kind = "text";
210
+ }
211
+ parse(raw) {
212
+ this.set(raw);
213
+ return true;
214
+ }
215
+ static isCommentLine(line) {
216
+ return commentLineRe.test(line);
217
+ }
218
+ static isNegativeLine(line) {
219
+ return negativeLineRe.test(line);
220
+ }
221
+ /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
222
+ injectedKeywords() {
223
+ const src = this.promptOpts.loraKeywordsFrom;
224
+ if (src == null) return [];
225
+ return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
226
+ }
227
+ outValue() {
228
+ const pos = [];
229
+ const neg = [];
230
+ for (const line of this.value.split("\n")) {
231
+ if (commentLineRe.test(line)) continue;
232
+ const m = negativeLineRe.exec(line);
233
+ if (m != null) {
234
+ const text = (m[1] ?? "").trim();
235
+ if (text !== "") neg.push(text);
236
+ } else pos.push(line);
237
+ }
238
+ const body = pos.join("\n").trim();
239
+ const keywords = this.injectedKeywords();
240
+ return {
241
+ positive: keywords.length === 0 ? body : body === "" ? keywords.join(", ") : `${keywords.join(", ")}, ${body}`,
242
+ negative: neg.join(", ")
243
+ };
244
+ }
245
+ };
246
+ var IntVar = class extends ComfyVar {
247
+ constructor(defaultValue, opts = {}) {
248
+ super(defaultValue, opts.label);
249
+ this.opts = opts;
250
+ this.kind = "int";
251
+ }
252
+ set(value) {
253
+ const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
254
+ return super.set(clamped);
255
+ }
256
+ parse(raw) {
257
+ const n = Number(raw);
258
+ if (Number.isNaN(n)) return false;
259
+ this.set(n);
260
+ return true;
261
+ }
262
+ };
263
+ var FloatVar = class extends ComfyVar {
264
+ constructor(defaultValue, opts = {}) {
265
+ super(defaultValue, opts.label);
266
+ this.opts = opts;
267
+ this.kind = "float";
268
+ }
269
+ set(value) {
270
+ return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
271
+ }
272
+ parse(raw) {
273
+ const n = Number(raw);
274
+ if (Number.isNaN(n)) return false;
275
+ this.set(n);
276
+ return true;
277
+ }
278
+ };
279
+ /**
280
+ * a seed is a MODE + a number. `value` stays a plain number (what the graph
281
+ * consumes); `mode` decides how it advances after each run (afterRun()):
282
+ * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
283
+ * The number shown is always the seed the NEXT run will use.
284
+ */
285
+ var SeedVar = class extends ComfyVar {
286
+ constructor(defaultValue = 0, label) {
287
+ super(defaultValue, label);
288
+ this.kind = "seed";
289
+ this.mode = "=";
290
+ makeObservable(this, {
291
+ mode: observable,
292
+ setMode: action,
293
+ randomize: action,
294
+ advance: action
295
+ });
296
+ }
297
+ setMode(mode) {
298
+ this.mode = mode;
299
+ return this;
300
+ }
301
+ randomize() {
302
+ return this.set(Math.floor(Math.random() * 2 ** 32));
303
+ }
304
+ set(value) {
305
+ return super.set(Math.max(0, Math.floor(value)));
306
+ }
307
+ /** move the seed to what the NEXT run should use, per mode */
308
+ advance() {
309
+ if (this.mode === "+") return this.set(this.value + 1);
310
+ if (this.mode === "-") return this.set(this.value - 1);
311
+ if (this.mode === "?") return this.randomize();
312
+ return this;
313
+ }
314
+ afterRun() {
315
+ this.advance();
316
+ }
317
+ /** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive
318
+ * ('=' is the construction default; drafts restore their own mode via loadJSON) */
319
+ reset() {
320
+ this.setMode("=");
321
+ return super.reset();
322
+ }
323
+ /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
324
+ parse(raw) {
325
+ const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
326
+ if (m == null) return false;
327
+ const modeChar = m[1];
328
+ const numStr = m[2];
329
+ if (modeChar == null && numStr == null) return false;
330
+ this.setMode(modeChar == null ? "=" : modeChar);
331
+ if (numStr != null) this.set(Number(numStr));
332
+ return true;
333
+ }
334
+ display() {
335
+ return `${this.mode} ${this.value}`;
336
+ }
337
+ toEditBuffer() {
338
+ return `${this.mode} ${this.value}`;
339
+ }
340
+ toJSON() {
341
+ return {
342
+ mode: this.mode,
343
+ value: this.value
344
+ };
345
+ }
346
+ loadJSON(value) {
347
+ if (typeof value === "number") return this.set(value);
348
+ if (value != null && typeof value === "object") {
349
+ const o = value;
350
+ if (o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?") this.setMode(o.mode);
351
+ if (typeof o.value === "number") this.set(o.value);
352
+ }
353
+ return this;
354
+ }
355
+ };
356
+ var ToggleVar = class extends ComfyVar {
357
+ constructor(..._args2) {
358
+ super(..._args2);
359
+ this.kind = "toggle";
360
+ }
361
+ toggle() {
362
+ return this.set(!this.value);
363
+ }
364
+ parse(raw) {
365
+ if (raw !== "true" && raw !== "false") return false;
366
+ this.set(raw === "true");
367
+ return true;
368
+ }
369
+ display() {
370
+ return this.value ? "ON" : "OFF";
371
+ }
372
+ };
373
+ var ChoiceVar = class extends ComfyVar {
374
+ constructor(choices, defaultValue, label) {
375
+ super(defaultValue, label);
376
+ this.choices = choices;
377
+ this.kind = "choice";
378
+ }
379
+ next(delta = 1) {
380
+ const nextIx = (this.choices.indexOf(this.value) + delta + this.choices.length) % this.choices.length;
381
+ return this.set(this.choices[nextIx] ?? this.value);
382
+ }
383
+ parse(raw) {
384
+ const hit = this.choices.find((c) => c === raw);
385
+ if (hit == null) return false;
386
+ this.set(hit);
387
+ return true;
388
+ }
389
+ };
390
+ /**
391
+ * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
392
+ * against the host's loras at define time (DefinedWorkflow calls bindHost),
393
+ * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
394
+ * a hardcoded inventory. Selection is empty by default.
395
+ */
396
+ var LorasVar = class LorasVar extends ComfyVar {
397
+ constructor(optionsSource, initial = {}, label) {
398
+ super(initial, label);
399
+ this.optionsSource = optionsSource;
400
+ this.kind = "loras";
401
+ this.prev = {};
402
+ this.resolvedOptions = null;
403
+ }
404
+ get options() {
405
+ if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
406
+ if (this.resolvedOptions == null) throw new Error(`v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`);
407
+ return this.resolvedOptions;
408
+ }
409
+ /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
410
+ * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
411
+ * values of the SAME object_info enum the generated E_LoraName union comes from */
412
+ bindHost(host) {
413
+ if (!(this.optionsSource instanceof RegExp)) return;
414
+ this.resolvedOptions = host.schema.getLoras(this.optionsSource);
415
+ }
416
+ get names() {
417
+ return [...this.options];
418
+ }
419
+ /** loras currently ON (PromptVar keyword prefixing consumes this) */
420
+ activeNames() {
421
+ return this.names.filter((n) => this.isOn(n));
422
+ }
423
+ isOn(name) {
424
+ const s = this.value[name];
425
+ return s != null && s !== false;
426
+ }
427
+ toggleItem(name) {
428
+ const cur = this.value[name];
429
+ if (cur == null || cur === false) return this.set({
430
+ ...this.value,
431
+ [name]: this.prev[name] ?? true
432
+ });
433
+ this.prev[name] = cur;
434
+ return this.set({
435
+ ...this.value,
436
+ [name]: false
437
+ });
438
+ }
439
+ /** step both strengths by delta (true becomes 1 first); no-op when off */
440
+ adjustItem(name, delta) {
441
+ const cur = this.value[name];
442
+ if (cur == null || cur === false) return this;
443
+ const step = (n) => Math.max(0, Math.round((n + delta) * 100) / 100);
444
+ const next = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur);
445
+ return this.set({
446
+ ...this.value,
447
+ [name]: next
448
+ });
449
+ }
450
+ /** compact per-item strength label for lists */
451
+ strengthLabel(name) {
452
+ const s = this.value[name];
453
+ if (s == null || s === false) return "";
454
+ if (s === true) return "1.00";
455
+ if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`;
456
+ return s.toFixed(2);
457
+ }
458
+ parse(raw) {
459
+ try {
460
+ const parsed = JSON.parse(raw);
461
+ if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) return false;
462
+ this.set(parsed);
463
+ return true;
464
+ } catch {
465
+ return false;
466
+ }
467
+ }
468
+ /** short human name: subfolder + extension stripped */
469
+ static shortName(name) {
470
+ return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, "");
471
+ }
472
+ /** tick (true) or untick (false) every lora in `names` (default: all options) */
473
+ setAll(on, names = this.options) {
474
+ const next = { ...this.value };
475
+ for (const name of names) {
476
+ const cur = next[name];
477
+ if (on) {
478
+ if (cur == null || cur === false) next[name] = this.prev[name] ?? true;
479
+ } else {
480
+ if (cur != null && cur !== false) this.prev[name] = cur;
481
+ next[name] = false;
482
+ }
483
+ }
484
+ return this.set(next);
485
+ }
486
+ display() {
487
+ const on = this.activeNames();
488
+ if (on.length === 0) return `(0/${this.options.length}) none`;
489
+ return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(", ")}`;
490
+ }
491
+ };
492
+ /** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
493
+ const DEFAULT_SIZE_PRESETS = [
494
+ {
495
+ label: "1:1 square",
496
+ width: 1024,
497
+ height: 1024
498
+ },
499
+ {
500
+ label: "4:3 landscape",
501
+ width: 1152,
502
+ height: 896
503
+ },
504
+ {
505
+ label: "3:4 portrait",
506
+ width: 896,
507
+ height: 1152
508
+ },
509
+ {
510
+ label: "3:2 landscape",
511
+ width: 1216,
512
+ height: 832
513
+ },
514
+ {
515
+ label: "2:3 portrait",
516
+ width: 832,
517
+ height: 1216
518
+ },
519
+ {
520
+ label: "16:9 widescreen",
521
+ width: 1344,
522
+ height: 768
523
+ },
524
+ {
525
+ label: "9:16 tall",
526
+ width: 768,
527
+ height: 1344
528
+ }
529
+ ];
530
+ /** width/height picker: presets + free `WxH` entry + optionally the LIVE
531
+ * size of a linked image var (his ask 2026-07-30: the widget shows
532
+ * `WxH size of image '<name>'` as a pickable row) */
533
+ var SizeVar = class extends ComfyVar {
534
+ constructor(defaultValue = {
535
+ width: 1024,
536
+ height: 1024
537
+ }, presets = DEFAULT_SIZE_PRESETS, label, imageVar) {
538
+ super(defaultValue, label);
539
+ this.presets = presets;
540
+ this.imageVar = imageVar;
541
+ this.kind = "size";
542
+ }
543
+ /** current dimensions of the linked image var — null when no link, unset
544
+ * path, or an unreadable/undecodable file (those errors belong to the
545
+ * image var itself, the size row simply disappears) */
546
+ imageSize() {
547
+ const iv = this.imageVar;
548
+ if (iv == null || iv.value === "") return null;
549
+ try {
550
+ const abs = iv.absPath();
551
+ const meta = imageMeta(getComfyStorage().readBytes(abs));
552
+ if (meta.width == null || meta.height == null) return null;
553
+ return {
554
+ width: meta.width,
555
+ height: meta.height,
556
+ name: basename(abs)
557
+ };
558
+ } catch {
559
+ return null;
560
+ }
561
+ }
562
+ /** accepts '1024x768' / '1024×768' / a preset label */
563
+ parse(raw) {
564
+ const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/);
565
+ if (m != null) {
566
+ this.set({
567
+ width: Number(m[1]),
568
+ height: Number(m[2])
569
+ });
570
+ return true;
571
+ }
572
+ const preset = this.presets.find((p) => p.label === raw.trim());
573
+ if (preset != null) {
574
+ this.set({
575
+ width: preset.width,
576
+ height: preset.height
577
+ });
578
+ return true;
579
+ }
580
+ return false;
581
+ }
582
+ display() {
583
+ const { width, height } = this.value;
584
+ const hit = this.presets.find((p) => p.width === width && p.height === height);
585
+ return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
586
+ }
587
+ };
588
+ const DEFAULT_IMAGE_EXTENSIONS = [
589
+ "png",
590
+ "jpg",
591
+ "jpeg",
592
+ "webp",
593
+ "gif"
594
+ ];
595
+ /** empty image var consumed at build time — typed so drivers surface it apart from real crashes */
596
+ var ImageVarEmptyError = class extends Error {
597
+ constructor(varName) {
598
+ super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`);
599
+ this.varName = varName;
600
+ }
601
+ };
602
+ /** trim + expand a leading `~/` — every ImageVar write funnels through this */
603
+ function expandUserPath(raw) {
604
+ const trimmed = raw.trim();
605
+ return trimmed.startsWith("~/") ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed;
606
+ }
607
+ /**
608
+ * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
609
+ * drafts persist it verbatim (toJSON = the string), hand-editable in the
610
+ * draft json. Empty = unset: outValue()/absPath() throw ImageVarEmptyError,
611
+ * so a build never runs on a silent placeholder. The TUI opens the image
612
+ * picker overlay for kind 'image'.
613
+ */
614
+ var ImageVar = class extends ComfyVar {
615
+ constructor(defaultValue, opts = {}) {
616
+ super(expandUserPath(defaultValue), opts.label);
617
+ this.opts = opts;
618
+ this.kind = "image";
619
+ }
620
+ /** what the picker lists (lowercase, no dots) */
621
+ get extensions() {
622
+ return this.opts.extensions ?? DEFAULT_IMAGE_EXTENSIONS;
623
+ }
624
+ set(value) {
625
+ return super.set(expandUserPath(value));
626
+ }
627
+ parse(raw) {
628
+ this.set(raw);
629
+ return true;
630
+ }
631
+ isSet() {
632
+ return this.value !== "";
633
+ }
634
+ emptyError() {
635
+ return new ImageVarEmptyError(this.name ?? this.label ?? "image");
636
+ }
637
+ /** the ONE resolution helper: absolute kept as-is, relative resolved against opts.folder, else cwd */
638
+ absPath() {
639
+ if (!this.isSet()) throw this.emptyError();
640
+ if (isAbsolute(this.value)) return this.value;
641
+ return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value);
642
+ }
643
+ /** empty = unset: the build fails LOUD here (varValues calls outValue) */
644
+ outValue() {
645
+ if (!this.isSet()) throw this.emptyError();
646
+ return this.value;
647
+ }
648
+ display() {
649
+ if (!this.isSet()) return "(unset) pick a file";
650
+ const home = getComfyStorage().homedir();
651
+ return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
652
+ }
653
+ };
654
+ /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */
655
+ const v = {
656
+ text: (defaultValue, label) => new TextVar(defaultValue, label),
657
+ prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
658
+ int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
659
+ float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
660
+ seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
661
+ toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
662
+ choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
663
+ loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
664
+ size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label, opts.image),
665
+ image: (defaultValue, opts = {}) => new ImageVar(defaultValue, opts)
666
+ };
667
+ function varValues(vars) {
668
+ const out = {};
669
+ for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue();
670
+ return out;
671
+ }
672
+ //#endregion
673
+ //#region src/vars/DefinedWorkflow.ts
674
+ /** type predicate (not a cast): a VarsSpec is a plain record, never callable */
675
+ function isVarsThunk(vars) {
676
+ return typeof vars === "function";
677
+ }
678
+ /**
679
+ * a re-runnable workflow definition: `build` re-executes per run with the
680
+ * current var values, so every run gets a fresh, deterministic graph.
681
+ */
682
+ var DefinedWorkflow = class {
683
+ constructor(host, spec) {
684
+ this.host = host;
685
+ this.spec = spec;
686
+ this.lastWorkflow = null;
687
+ this.lastExecution = null;
688
+ this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
689
+ for (const [key, varDef] of this.entries()) {
690
+ varDef.name = key;
691
+ varDef.bindHost?.(this.host);
692
+ }
693
+ }
694
+ /** [name, var] pairs, for drivers that enumerate the knobs */
695
+ entries() {
696
+ return Object.entries(this.vars);
697
+ }
698
+ /**
699
+ * build a fresh graph from the CURRENT var values (no send). `p.advance`
700
+ * (set by run()) fires each var's afterRun() right after snapshotting the
701
+ * values — atomically, before any await — so the graph uses this run's seed
702
+ * while the var moves to the next (queued runs get distinct seeds; a bare
703
+ * build() for copy/export never advances). `p.host` substitutes the host
704
+ * the graph is built against (TUI host override): node/model availability
705
+ * there surfaces as workflow.problems / server validation, by design.
706
+ */
707
+ async build(p = {}) {
708
+ const wf = (p.host ?? this.host).workflow({ id: this.spec.id });
709
+ const values = varValues(this.vars);
710
+ if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun();
711
+ await this.spec.build(wf.builder, values, wf);
712
+ this.lastWorkflow = wf;
713
+ return wf;
714
+ }
715
+ /** build a fresh graph from the current var values, send it, wait for outputs.
716
+ * connects first (idempotent) — modules can import offline from the schema cache.
717
+ * `settings.host` runs against THAT host instead of the defining one. */
718
+ async run(settings = {}) {
719
+ const host = settings.host ?? this.host;
720
+ await host.connect();
721
+ const execution = await (await this.build({
722
+ advance: true,
723
+ host
724
+ })).run({
725
+ saveFormat: settings.saveFormat,
726
+ idMode: settings.idMode,
727
+ log: settings.log,
728
+ onProgress: settings.onProgress
729
+ });
730
+ this.lastExecution = execution;
731
+ return execution;
732
+ }
733
+ };
734
+ //#endregion
735
+ export { resolveComfyStorage as _, ImageVarEmptyError as a, logInfo as b, PromptVar as c, TextVar as d, ToggleVar as f, getComfyStorage as g, extractErrorMessage as h, ImageVar as i, SeedVar as l, setLoraKeyword as m, ChoiceVar as n, IntVar as o, getLoraKeyword as p, FloatVar as r, LorasVar as s, DefinedWorkflow as t, SizeVar as u, isQuiet as v, logSuccess as x, logError as y };
736
+
737
+ //# sourceMappingURL=DefinedWorkflow-C_QAxKr3.js.map