comfy-ts 2.11.0 → 2.12.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 (99) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-qtFzOKpu.js → LogsSt-U1H0mP1m.js} +35 -5
  3. package/dist/LogsSt-U1H0mP1m.js.map +1 -0
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +473 -62
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +191 -31
  8. package/dist/index.d.ts +191 -31
  9. package/dist/index.js +469 -63
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-BK7BA2dn.js → run-serve-BeAznay5.js} +461 -43
  12. package/dist/run-serve-BeAznay5.js.map +1 -0
  13. package/dist/{run-tui-CQyvMf0N.js → run-tui-BTGjvnKk.js} +43 -18
  14. package/dist/run-tui-BTGjvnKk.js.map +1 -0
  15. package/dist/{schemaDrift-DjjEtwfx.js → schemaDrift-Cg39vs53.js} +470 -60
  16. package/dist/schemaDrift-Cg39vs53.js.map +1 -0
  17. package/dist/serve-web.js +508 -134
  18. package/dist/{state--wrz0BQc.js → state-C7REnHan.js} +7 -3
  19. package/dist/{state--wrz0BQc.js.map → state-C7REnHan.js.map} +1 -1
  20. package/dist/web.d.ts +191 -31
  21. package/dist/web.js +469 -63
  22. package/dist/web.js.map +1 -1
  23. package/examples/rvion/06-qwen-image-edit.cflow.ts +3 -2
  24. package/examples/rvion/10-anima-t2i.cflow.ts +229 -0
  25. package/extra/README.md +4 -0
  26. package/extra/comfyui-fresh-model-lists/README.md +25 -0
  27. package/extra/comfyui-fresh-model-lists/__init__.py +36 -0
  28. package/extra/comfyui-fresh-model-lists/test_fresh_model_lists.py +97 -0
  29. package/package.json +15 -7
  30. package/src/cli/draftMeta.ts +39 -0
  31. package/src/cli/serve/ServeApp.ts +148 -12
  32. package/src/cli/serve/applyVarPayload.ts +50 -22
  33. package/src/cli/serve/describeVar.ts +42 -6
  34. package/src/cli/serve/llmConfigShape.ts +51 -0
  35. package/src/cli/serve/llmConfigs.ts +52 -0
  36. package/src/cli/serve/tagList.ts +92 -0
  37. package/src/cli/serve/tagSource.ts +69 -0
  38. package/src/cli/serve/web/api.ts +48 -0
  39. package/src/cli/serve/web/components/App.tsx +336 -44
  40. package/src/cli/serve/web/components/Gallery.tsx +105 -28
  41. package/src/cli/serve/web/components/HistoryPicker.tsx +149 -0
  42. package/src/cli/serve/web/components/Icon.tsx +18 -2
  43. package/src/cli/serve/web/components/MenuButton.tsx +53 -0
  44. package/src/cli/serve/web/components/Omnibox.tsx +85 -0
  45. package/src/cli/serve/web/components/PromptEnhancer.tsx +476 -180
  46. package/src/cli/serve/web/components/TooltipLayer.tsx +45 -0
  47. package/src/cli/serve/web/components/VarIcon.tsx +24 -0
  48. package/src/cli/serve/web/components/VarsForm.tsx +341 -188
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +57 -32
  50. package/src/cli/serve/web/components/controls/LorasControl.tsx +644 -317
  51. package/src/cli/serve/web/components/controls/PresetPicker.tsx +1 -1
  52. package/src/cli/serve/web/components/controls/PromptControl.tsx +279 -0
  53. package/src/cli/serve/web/components/controls/PromptEditor.tsx +113 -0
  54. package/src/cli/serve/web/components/controls/SeedControl.tsx +17 -10
  55. package/src/cli/serve/web/components/controls/SizeControl.tsx +111 -18
  56. package/src/cli/serve/web/components/modKey.ts +2 -0
  57. package/src/cli/serve/web/llm.ts +23 -12
  58. package/src/cli/serve/web/promptEditor/promptExtensions.ts +281 -0
  59. package/src/cli/serve/web/state/EnhancerSt.ts +415 -100
  60. package/src/cli/serve/web/state/FormSt.ts +193 -29
  61. package/src/cli/serve/web/state/OmniboxSt.ts +57 -0
  62. package/src/cli/serve/web/state/WebSt.ts +219 -74
  63. package/src/cli/serve/web/state/choiceButtons.ts +61 -0
  64. package/src/cli/serve/web/state/generateButton.ts +16 -0
  65. package/src/cli/serve/web/state/history.ts +54 -0
  66. package/src/cli/serve/web/state/host.ts +5 -2
  67. package/src/cli/serve/web/state/keptLines.ts +53 -0
  68. package/src/cli/serve/web/state/latentMode.ts +20 -0
  69. package/src/cli/serve/web/state/loraSort.ts +18 -0
  70. package/src/cli/serve/web/state/moduleTree.ts +2 -2
  71. package/src/cli/serve/web/state/omnibox.ts +69 -0
  72. package/src/cli/serve/web/state/payload.ts +38 -58
  73. package/src/cli/serve/web/state/shortcuts.ts +54 -0
  74. package/src/cli/serve/web/state/sizeStars.ts +31 -0
  75. package/src/cli/serve/web/state/stableSlots.ts +21 -0
  76. package/src/cli/serve/web/state/varGroups.ts +24 -0
  77. package/src/cli/serve/web/styles.ts +457 -118
  78. package/src/cli/serve/webBundle.ts +54 -10
  79. package/src/cli/tui/components/PickerOverlays.tsx +9 -2
  80. package/src/cli/tui/imagePicker/ImagePickerSt.ts +1 -1
  81. package/src/cli/tui/state/DraftsSt.ts +18 -2
  82. package/src/cli/tui/state/EditorSt.ts +1 -1
  83. package/src/cli/tui/state/LorasSt.ts +1 -1
  84. package/src/cli/tui/state/PickerSt.ts +25 -7
  85. package/src/cli/tui/state/SettingsSt.ts +1 -1
  86. package/src/cli/tui/state/TuiSt.ts +10 -0
  87. package/src/coreExports.ts +20 -0
  88. package/src/host/loraInfoCache.ts +6 -0
  89. package/src/state.ts +5 -0
  90. package/src/vars/ComfyVars.ts +337 -67
  91. package/src/vars/DefinedWorkflow.ts +40 -19
  92. package/src/vars/lanes.ts +238 -0
  93. package/src/vars/loraEntry.ts +101 -0
  94. package/src/vars/promptSyntax.ts +382 -0
  95. package/dist/LogsSt-qtFzOKpu.js.map +0 -1
  96. package/dist/run-serve-BK7BA2dn.js.map +0 -1
  97. package/dist/run-tui-CQyvMf0N.js.map +0 -1
  98. package/dist/schemaDrift-DjjEtwfx.js.map +0 -1
  99. package/src/cli/serve/web/components/Sidebar.tsx +0 -66
@@ -1,11 +1,11 @@
1
- import { A as fetchLoraExampleImages, B as lmSha256, D as writeLoraMirror, E as reloadLoraInfoCache, F as lmFilePath, G as loraPreviewMapFrom, I as lmFileSize, J as stripAnsi, K as ansi, L as lmFolder, M as fetchLoraPreviewBytes, N as lmBaseModel, O as fetchLoraCivitai, P as lmCivitai, S as loraMirrorEntries, T as refreshLoraInfoCacheIfChanged, V as lmTags, W as loraKey, Y as extractErrorMessage, Z as bang, _ as getLoraInfo, b as getLoraTriggers, g as getLoraDisplayName, h as getLoraAddedAt, i as summarizeDrift, it as statelessRegex, j as fetchLoraList, k as fetchLoraDescription, m as buildLoraMirror, o as DEFAULT_IMAGE_EXTENSIONS, q as colorsAvailable, r as driftChanged, u as getLoraKeyword, v as getLoraPreviewUrl, w as recordCivitaiMiss, y as getLoraTriggerWords, z as lmNotes } from "./schemaDrift-DjjEtwfx.js";
2
- import { a as draftsDirForFile, f as scanCflowFiles, i as draftKeyForFile, n as assembleLogChunks, o as listDraftsForFile, u as findDefinedWorkflow } from "./LogsSt-qtFzOKpu.js";
1
+ import { $ as stripAnsi, A as refreshLoraInfoCacheIfChanged, B as lmFilePath, C as getLoraTriggerWords, D as lorasMissingFromMirror, E as loraMirrorEntries, F as fetchLoraExampleImages, G as lmSha256, H as lmFolder, I as fetchLoraList, K as lmTags, L as fetchLoraPreviewBytes, M as writeLoraMirror, N as fetchLoraCivitai, P as fetchLoraDescription, Q as colorsAvailable, R as lmBaseModel, S as getLoraPreviewUrl, V as lmFileSize, W as lmNotes, X as loraPreviewMapFrom, Y as loraKey, Z as ansi, b as getLoraDisplayName, d as isPromptInput, dt as sha1HexOfString, et as extractErrorMessage, f as isLoraStrength, i as summarizeDrift, j as reloadLoraInfoCache, k as recordCivitaiMiss, l as isLoraLanes, lt as statelessRegex, m as getLoraKeyword, nt as bang, o as DEFAULT_IMAGE_EXTENSIONS, r as driftChanged, u as isLorasInput, v as buildLoraMirror, w as getLoraTriggers, x as getLoraInfo, y as getLoraAddedAt, z as lmCivitai } from "./schemaDrift-Cg39vs53.js";
2
+ import { a as draftsDirForFile, c as isDraftMetaKey, f as findDefinedWorkflow, i as draftKeyForFile, m as scanCflowFiles, n as assembleLogChunks, o as listDraftsForFile, s as ENHANCE_KEY } from "./LogsSt-U1H0mP1m.js";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
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";
5
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "pathe";
6
6
  import { nanoid } from "nanoid";
7
7
  import { createServer } from "node:http";
8
- import { networkInterfaces } from "node:os";
8
+ import { homedir, networkInterfaces } from "node:os";
9
9
  //#region src/cli/serve/describeVar.ts
10
10
  /** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
11
11
  function presetsOrUndefined(presets) {
@@ -19,15 +19,21 @@ function describeVar(varDef) {
19
19
  const base = {
20
20
  kind: varDef.kind,
21
21
  label: varDef.label,
22
- default: varDef.defaultValue
22
+ default: varDef.defaultValue,
23
+ ...Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}
23
24
  };
24
25
  switch (varDef.kind) {
25
26
  case "prompt": {
26
27
  const v = varDef;
27
28
  return {
28
29
  ...base,
29
- payload: "string (\"//\" lines = comments, \"- \" lines = negative)",
30
- textPresets: presetsOrUndefined(v.presets)
30
+ payload: "string (\"//\" starts a comment, \"- \" lines = negative)",
31
+ textPresets: presetsOrUndefined(v.presets),
32
+ tags: v.tags == null ? void 0 : {
33
+ underscores: v.tags.underscores === true,
34
+ artistPrefix: v.tags.artistPrefix
35
+ },
36
+ weights: v.promptOpts.weights === false ? false : void 0
31
37
  };
32
38
  }
33
39
  case "text": {
@@ -74,10 +80,13 @@ function describeVar(varDef) {
74
80
  };
75
81
  case "choice": {
76
82
  const v = varDef;
83
+ const list = v.choices.join(" | ");
84
+ const payload = v.select === "many" ? `a list of: ${list}` : v.select === "zero-or-one" ? `null or one of: ${list}` : `one of: ${list}`;
77
85
  return {
78
86
  ...base,
79
- payload: `one of: ${v.choices.join(" | ")}`,
80
- choices: v.choices
87
+ payload,
88
+ choices: v.choices,
89
+ select: v.select
81
90
  };
82
91
  }
83
92
  case "loras": {
@@ -94,7 +103,8 @@ function describeVar(varDef) {
94
103
  return {
95
104
  ...base,
96
105
  payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
97
- presets: v.presets
106
+ presets: v.presets,
107
+ starredPresets: [...v.starred]
98
108
  };
99
109
  }
100
110
  case "image": {
@@ -134,11 +144,6 @@ function truncate(s, n) {
134
144
  function isFiniteNumber(x) {
135
145
  return typeof x === "number" && Number.isFinite(x);
136
146
  }
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
147
  /** cap long option lists in error messages */
143
148
  function listSome(items, cap = 20) {
144
149
  if (items.length <= cap) return items.join(", ");
@@ -151,10 +156,13 @@ function applyVarPayload(varDef, raw, opts = {}) {
151
156
  const name = varDef.name ?? varDef.label ?? varDef.kind;
152
157
  switch (varDef.kind) {
153
158
  case "text":
154
- case "prompt":
155
159
  if (typeof raw !== "string") return `var '${name}' expects a string`;
156
160
  varDef.set(raw);
157
161
  return null;
162
+ case "prompt":
163
+ if (!isPromptInput(raw)) return `var '${name}' expects a string or {"lanes": [{"name": string, "prompt": string, "active": boolean}]}`;
164
+ varDef.set(raw);
165
+ return null;
158
166
  case "int":
159
167
  case "float": {
160
168
  const v = varDef;
@@ -191,18 +199,44 @@ function applyVarPayload(varDef, raw, opts = {}) {
191
199
  return null;
192
200
  case "choice": {
193
201
  const v = varDef;
194
- if (typeof raw === "string" && v.parse(raw)) return null;
202
+ const known = (x) => typeof x === "string" && v.choices.includes(x);
203
+ if (v.select === "many") {
204
+ if (known(raw)) {
205
+ v.set([raw]);
206
+ return null;
207
+ }
208
+ if (Array.isArray(raw) && raw.every(known)) {
209
+ v.set(v.choices.filter((c) => raw.includes(c)));
210
+ return null;
211
+ }
212
+ return `var '${name}' expects a list of: ${listSome(v.choices)}`;
213
+ }
214
+ if (v.select === "zero-or-one") {
215
+ if (raw === null || known(raw)) {
216
+ v.set(raw);
217
+ return null;
218
+ }
219
+ return `var '${name}' expects null or one of: ${listSome(v.choices)}`;
220
+ }
221
+ if (known(raw)) {
222
+ v.set(raw);
223
+ return null;
224
+ }
195
225
  return `var '${name}' expects one of: ${listSome(v.choices)}`;
196
226
  }
197
227
  case "loras": {
198
228
  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;
229
+ const SHAPE = `{"<lora name>": false | true | strength | [model, clip] | {strength, off?, mute?}} or {"lanes": [{"name", "active", "loras": {…}}]}`;
230
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects ${SHAPE}`;
231
+ const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw];
201
232
  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);
233
+ for (const record of records) {
234
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k));
235
+ if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
236
+ for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip] | { strength: [model, clip], off?, mute? }`;
237
+ }
238
+ if (!isLorasInput(raw)) return `var '${name}' expects ${SHAPE}`;
239
+ v.set(raw);
206
240
  return null;
207
241
  }
208
242
  case "size": {
@@ -252,13 +286,13 @@ function validSavePrefix(raw) {
252
286
  }
253
287
  //#endregion
254
288
  //#region src/promptEnhancers.ts
255
- const EXT = ".md";
289
+ const EXT$1 = ".md";
256
290
  function promptEnhancersDir() {
257
291
  return comfyts.resolveFromPromptEnhancers("");
258
292
  }
259
293
  function promptEnhancerPath(name) {
260
294
  const safe = validStoreName(name);
261
- return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
295
+ return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT$1}`);
262
296
  }
263
297
  /** the shipped starting point. It is a FILE from the first read on, so it can be edited
264
298
  * on disk like everything else, the browser ships no copy of this text */
@@ -294,7 +328,7 @@ function readPromptEnhancers() {
294
328
  if (!existsSync(dir)) return [];
295
329
  const out = [];
296
330
  for (const file of readdirSync(dir).sort()) {
297
- if (!file.endsWith(EXT)) continue;
331
+ if (!file.endsWith(EXT$1)) continue;
298
332
  const name = file.slice(0, -3);
299
333
  if (validStoreName(name) == null) continue;
300
334
  try {
@@ -323,6 +357,85 @@ function deletePromptEnhancer(name) {
323
357
  return true;
324
358
  }
325
359
  //#endregion
360
+ //#region src/cli/serve/web/llm.ts
361
+ const OPENROUTER_BASE = "https://openrouter.ai/api/v1";
362
+ const OPENWEBUI_BASE = "http://localhost:3000";
363
+ const OPENAI_COMPAT_BASE = "http://localhost:8080/v1";
364
+ function defaultBaseUrl(provider) {
365
+ if (provider === "openrouter") return OPENROUTER_BASE;
366
+ return provider === "openwebui" ? OPENWEBUI_BASE : OPENAI_COMPAT_BASE;
367
+ }
368
+ //#endregion
369
+ //#region src/cli/serve/llmConfigShape.ts
370
+ function isProvider(raw) {
371
+ return raw === "openrouter" || raw === "openwebui" || raw === "openai";
372
+ }
373
+ function isEffort(raw) {
374
+ return raw === "off" || raw === "low" || raw === "medium" || raw === "high";
375
+ }
376
+ /** explicit model ids, never an alias: behaviour and cost stay reproducible */
377
+ const DEFAULT_MODEL = {
378
+ openrouter: "anthropic/claude-sonnet-5",
379
+ openwebui: "",
380
+ openai: ""
381
+ };
382
+ /** a stored file → a usable config: a half-written or hand-broken field degrades to its
383
+ * default, never breaks the modal */
384
+ function normalizeLlmConfig(raw) {
385
+ const o = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
386
+ const provider = isProvider(o.provider) ? o.provider : "openrouter";
387
+ return {
388
+ provider,
389
+ baseUrl: typeof o.baseUrl === "string" && o.baseUrl.trim() !== "" ? o.baseUrl.trim() : defaultBaseUrl(provider),
390
+ model: typeof o.model === "string" ? o.model : DEFAULT_MODEL[provider],
391
+ effort: isEffort(o.effort) ? o.effort : "medium",
392
+ thinkingOnly: o.thinkingOnly !== false
393
+ };
394
+ }
395
+ //#endregion
396
+ //#region src/cli/serve/llmConfigs.ts
397
+ const EXT = ".json";
398
+ function llmConfigsDir() {
399
+ return comfyts.resolveFromLlmConfigs("");
400
+ }
401
+ function llmConfigPath(name) {
402
+ const safe = validStoreName(name);
403
+ return safe == null ? null : join(llmConfigsDir(), `${safe}${EXT}`);
404
+ }
405
+ function listLlmConfigs() {
406
+ const dir = llmConfigsDir();
407
+ if (!existsSync(dir)) return [];
408
+ const out = [];
409
+ for (const file of readdirSync(dir).sort()) {
410
+ if (!file.endsWith(EXT)) continue;
411
+ const name = file.slice(0, -5);
412
+ if (validStoreName(name) == null) continue;
413
+ try {
414
+ out.push({
415
+ name,
416
+ config: normalizeLlmConfig(JSON.parse(readFileSync(join(dir, file), "utf8")))
417
+ });
418
+ } catch (e) {
419
+ console.error(`[serve] llm config '${name}' unreadable, skipped:`, e);
420
+ }
421
+ }
422
+ return out;
423
+ }
424
+ function writeLlmConfig(name, config) {
425
+ const path = llmConfigPath(name);
426
+ if (path == null) return null;
427
+ mkdirSync(llmConfigsDir(), { recursive: true });
428
+ writeFileSync(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}\n`);
429
+ return path;
430
+ }
431
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
432
+ function deleteLlmConfig(name) {
433
+ const path = llmConfigPath(name);
434
+ if (path == null) return false;
435
+ if (existsSync(path)) rmSync(path);
436
+ return true;
437
+ }
438
+ //#endregion
326
439
  //#region src/cli/serve/managerOnlyLoras.ts
327
440
  /**
328
441
  * `options` is the host enum for this var: it decides both what counts as already-known
@@ -336,6 +449,163 @@ function managerOnlyLoraOptions(p) {
336
449
  return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
337
450
  }
338
451
  //#endregion
452
+ //#region src/cli/serve/tagList.ts
453
+ /** one csv line, double-quoted fields with `""` escapes */
454
+ function csvFields(line) {
455
+ const out = [];
456
+ let cur = "";
457
+ let quoted = false;
458
+ for (let i = 0; i < line.length; i++) {
459
+ const ch = line[i];
460
+ if (quoted) if (ch === "\"" && line[i + 1] === "\"") {
461
+ cur += "\"";
462
+ i++;
463
+ } else if (ch === "\"") quoted = false;
464
+ else cur += ch;
465
+ else if (ch === "\"") quoted = true;
466
+ else if (ch === ",") {
467
+ out.push(cur);
468
+ cur = "";
469
+ } else cur += ch;
470
+ }
471
+ out.push(cur);
472
+ return out;
473
+ }
474
+ const intOrNull = (s) => s != null && /^\d+$/.test(s.trim()) ? Number(s) : null;
475
+ function parseTagList(text) {
476
+ const out = [];
477
+ for (const raw of text.split(/\r?\n/)) {
478
+ const line = raw.trim();
479
+ if (line === "" || line.startsWith("#")) continue;
480
+ const f = csvFields(line);
481
+ const name = (f[0] ?? "").trim();
482
+ if (name === "") continue;
483
+ const twoCols = f.length === 2;
484
+ out.push({
485
+ name,
486
+ category: twoCols ? null : intOrNull(f[1]),
487
+ count: (twoCols ? intOrNull(f[1]) : intOrNull(f[2])) ?? 0,
488
+ aliases: (f[3] ?? "").split(",").map((a) => a.trim()).filter((a) => a !== "")
489
+ });
490
+ }
491
+ return out;
492
+ }
493
+ /** the searchable form: lowercase, spaces as underscores (the lists write `long_hair`) */
494
+ const key = (s) => s.trim().toLowerCase().replace(/\s+/g, "_");
495
+ var TagList = class TagList {
496
+ constructor(entries) {
497
+ this.entries = entries;
498
+ this.rows = entries.map((e) => ({
499
+ e,
500
+ name: key(e.name),
501
+ aliases: e.aliases.map(key)
502
+ }));
503
+ this.rows.sort((a, b) => b.e.count - a.e.count);
504
+ }
505
+ static parse(text) {
506
+ return new TagList(parseTagList(text));
507
+ }
508
+ /** prefix of the name first, then prefix of an alias (answered with the name it points to),
509
+ * then a word inside the name (`hair` finds `long_hair`), each by post count */
510
+ search(query, limit = 20) {
511
+ const q = key(query);
512
+ if (q === "") return [];
513
+ const hits = [];
514
+ const seen = /* @__PURE__ */ new Set();
515
+ const take = (e, alias) => {
516
+ if (seen.has(e.name)) return false;
517
+ seen.add(e.name);
518
+ hits.push(alias == null ? {
519
+ name: e.name,
520
+ category: e.category,
521
+ count: e.count
522
+ } : {
523
+ ...pick(e),
524
+ alias
525
+ });
526
+ return hits.length >= limit;
527
+ };
528
+ for (const r of this.rows) if (r.name.startsWith(q) && take(r.e)) return hits;
529
+ for (const r of this.rows) {
530
+ const a = r.aliases.find((x) => x.startsWith(q));
531
+ if (a != null && take(r.e, a)) return hits;
532
+ }
533
+ for (const r of this.rows) if (r.name.includes(`_${q}`) && take(r.e)) return hits;
534
+ return hits;
535
+ }
536
+ };
537
+ const pick = (e) => ({
538
+ name: e.name,
539
+ category: e.category,
540
+ count: e.count
541
+ });
542
+ //#endregion
543
+ //#region src/cli/serve/tagSource.ts
544
+ /** http(s) stays a url; `file://`, `~/`, absolute and relative (to the workflow file) become a path */
545
+ function resolveTagSource(url, moduleFile) {
546
+ if (/^https?:\/\//i.test(url)) return {
547
+ kind: "http",
548
+ url
549
+ };
550
+ if (url.startsWith("file://")) return {
551
+ kind: "file",
552
+ path: fileURLToPath(url)
553
+ };
554
+ if (url === "~" || url.startsWith("~/")) return {
555
+ kind: "file",
556
+ path: join(homedir(), url.slice(1))
557
+ };
558
+ if (isAbsolute(url)) return {
559
+ kind: "file",
560
+ path: url
561
+ };
562
+ return {
563
+ kind: "file",
564
+ path: resolve(dirname(moduleFile), url)
565
+ };
566
+ }
567
+ var TagSources = class {
568
+ constructor(p) {
569
+ this.p = p;
570
+ this.files = /* @__PURE__ */ new Map();
571
+ this.remote = /* @__PURE__ */ new Map();
572
+ }
573
+ async load(ref) {
574
+ if (ref.kind === "file") return this.loadFile(ref.path);
575
+ const hit = this.remote.get(ref.url);
576
+ if (hit != null) return hit;
577
+ const pending = this.loadRemote(ref.url);
578
+ this.remote.set(ref.url, pending);
579
+ pending.catch(() => this.remote.delete(ref.url));
580
+ return pending;
581
+ }
582
+ loadFile(path) {
583
+ if (!existsSync(path)) throw new Error(`tag list not found: ${path}`);
584
+ const mtimeMs = statSync(path).mtimeMs;
585
+ const cached = this.files.get(path);
586
+ if (cached != null && cached.mtimeMs === mtimeMs) return cached.list;
587
+ const list = TagList.parse(readFileSync(path, "utf8"));
588
+ if (list.entries.length === 0) throw new Error(`tag list is empty: ${path}`);
589
+ this.files.set(path, {
590
+ mtimeMs,
591
+ list
592
+ });
593
+ return list;
594
+ }
595
+ async loadRemote(url) {
596
+ const file = join(this.p.cacheDir(), `${sha1HexOfString(url)}.txt`);
597
+ if (existsSync(file)) return TagList.parse(readFileSync(file, "utf8"));
598
+ console.log(`[serve] fetching tag list ${url}`);
599
+ const text = await this.p.fetchText(url);
600
+ const list = TagList.parse(text);
601
+ if (list.entries.length === 0) throw new Error(`tag list is empty: ${url}`);
602
+ mkdirSync(dirname(file), { recursive: true });
603
+ writeFileSync(file, text);
604
+ console.log(`[serve] tag list ${url}: ${list.entries.length} tags, kept in ${file}`);
605
+ return list;
606
+ }
607
+ };
608
+ //#endregion
339
609
  //#region src/cli/serve/favicon.ts
340
610
  const FAVICON_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAKUklEQVR42u1aaWxU1xW2DWEJZCENNgaK8iNRU5UAAYKBWW1Imw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JySYH3xjrPT9O92OG6Q/yxRiEh6ISE2V49U+mYWlUmrcLkstTtbd1md/ibcwX2EajiEBnrMVBbBDs8vF3oCAyYkBZe6NQqRDj4u6wb9X4FsoQjVsFIA4HrZ8LHY1TUXbiXcUtHHbeWRTpvj7D1XvsO7qspw5NhsH4wVYB3KuwYNmAZw5UvS3bh8brW4gvvRKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII=";
341
611
  //#endregion
@@ -466,6 +736,9 @@ var DownloadRefused = class extends Error {
466
736
  };
467
737
  const INPUT_DOWNLOAD_CAP = 5e7;
468
738
  const INPUT_DOWNLOAD_TIMEOUT_MS = 6e4;
739
+ /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
740
+ const TAG_LIST_CAP = 4e7;
741
+ const TAG_LIST_TIMEOUT_MS = 12e4;
469
742
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
470
743
  * whole body first, so a chunked reply with no content-length could exhaust the process before
471
744
  * anything checked its size, the cap then reported a number nobody survived to read. */
@@ -557,10 +830,12 @@ const USAGE = [
557
830
  "GET /drafts/<module>/<draft> — one draft with its stored values",
558
831
  "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
559
832
  "POST /generate/<draft> — unqualified, when unambiguous",
833
+ "POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run",
560
834
  "PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
561
835
  "DELETE /drafts/<module>/<draft> — delete that draft file",
562
836
  "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
563
837
  "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
838
+ "GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)",
564
839
  "GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)",
565
840
  "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
566
841
  "POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror",
@@ -568,6 +843,8 @@ const USAGE = [
568
843
  "GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
569
844
  "GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
570
845
  "PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
846
+ "GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)",
847
+ "PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>",
571
848
  "GET /settings — { saveToDisk } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory",
572
849
  "GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere",
573
850
  "POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host",
@@ -613,10 +890,20 @@ var ServeApp = class {
613
890
  this.opts = opts;
614
891
  this.seedState = /* @__PURE__ */ new Map();
615
892
  this.chains = /* @__PURE__ */ new Map();
616
- this.webJsCache = null;
617
893
  this.settingsCache = null;
618
894
  this.memoryImages = /* @__PURE__ */ new Map();
619
895
  this.MEMORY_IMAGE_CAP = 60;
896
+ this.tagSources = new TagSources({
897
+ cacheDir: () => join(comfyts.baseFolder, "cache", "tags"),
898
+ fetchText: async (url) => {
899
+ const res = await fetch(url, {
900
+ redirect: "follow",
901
+ signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS)
902
+ });
903
+ if (!res.ok) throw new Error(`tag list download failed (http ${res.status}): ${url}`);
904
+ return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url));
905
+ }
906
+ });
620
907
  this.liveRuns = /* @__PURE__ */ new Map();
621
908
  this.latentPreviews = /* @__PURE__ */ new Map();
622
909
  this.latentSeq = 0;
@@ -639,8 +926,7 @@ var ServeApp = class {
639
926
  }
640
927
  if (req.method === "GET") {
641
928
  if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
642
- this.webJsCache ??= this.opts.webJs();
643
- const js = await this.webJsCache;
929
+ const js = await this.opts.webJs();
644
930
  if (js != null) return {
645
931
  status: 200,
646
932
  contentType: "text/html; charset=utf-8",
@@ -657,6 +943,8 @@ var ServeApp = class {
657
943
  if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
658
944
  if (segs[0] === "lora-about" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraAbout(segs[1], segs[2]);
659
945
  if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
946
+ if (segs[0] === "llm-configs" && segs.length === 1) return this.replyLlmConfigs();
947
+ if (segs[0] === "tags" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyTags(segs[1], segs[2], req.url);
660
948
  if (segs[0] === "settings" && segs.length === 1) return this.replySettings();
661
949
  if (segs[0] === "hosts" && segs.length === 1) return this.replyHosts();
662
950
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs") return await this.replyHostLogs(segs[1]);
@@ -674,6 +962,7 @@ var ServeApp = class {
674
962
  if ("error" in target) return json(target.status, { error: target.error });
675
963
  return await this.generate(target.mod, target.draft, req);
676
964
  }
965
+ if (req.method === "POST" && segs[0] === "preview" && segs.length === 2 && segs[1] != null) return await this.replyPreview(segs[1], req);
677
966
  if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
678
967
  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);
679
968
  if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
@@ -683,6 +972,8 @@ var ServeApp = class {
683
972
  if (req.method === "POST" && segs[0] === "hosts" && segs.length === 4 && segs[1] != null && segs[2] === "lora-civitai" && segs[3] != null) return await this.replyLoraCivitaiFetch(segs[1], segs[3]);
684
973
  if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
685
974
  if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
975
+ if (req.method === "PUT" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replySaveLlmConfig(segs[1], req);
976
+ if (req.method === "DELETE" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replyDeleteLlmConfig(segs[1]);
686
977
  return json(404, {
687
978
  error: `no route: ${req.method} ${path}`,
688
979
  usage: USAGE
@@ -823,7 +1114,8 @@ var ServeApp = class {
823
1114
  host: mod.dw.host.data.id,
824
1115
  drafts: this.draftsFor(mod),
825
1116
  routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
826
- vars
1117
+ vars,
1118
+ previews: Object.keys(mod.dw.spec.previews ?? {})
827
1119
  };
828
1120
  }
829
1121
  replyIndex() {
@@ -844,6 +1136,31 @@ var ServeApp = class {
844
1136
  values: this.draftValues(mod, draft)
845
1137
  });
846
1138
  }
1139
+ /** the workflow's previews for the values the panel holds right now. The vars are SHARED
1140
+ * state (a run reads them), so this runs under the module lock: load the values, compute,
1141
+ * put the old values back. Nothing is queued, nothing is written */
1142
+ async replyPreview(key, req) {
1143
+ const mod = this.moduleByKey(key);
1144
+ if (mod == null) return json(404, { error: `unknown workflow '${key}'` });
1145
+ let values;
1146
+ try {
1147
+ values = JSON.parse(req.body ?? "{}");
1148
+ } catch (e) {
1149
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1150
+ }
1151
+ if (values == null || typeof values !== "object" || Array.isArray(values)) return json(400, { error: "expects { \"<var>\": value, … }" });
1152
+ const incoming = values;
1153
+ return json(200, { previews: await this.exclusive(mod.key, () => {
1154
+ const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()]);
1155
+ try {
1156
+ for (const [k, v] of mod.dw.entries()) if (k in incoming) v.loadJSON(incoming[k]);
1157
+ return Promise.resolve(mod.dw.computePreviews());
1158
+ } finally {
1159
+ const byName = new Map(mod.dw.entries());
1160
+ for (const [k, json] of saved) byName.get(k)?.loadJSON(json);
1161
+ }
1162
+ }) });
1163
+ }
847
1164
  /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
848
1165
  draftValues(mod, draft) {
849
1166
  const path = this.draftPath(mod, draft);
@@ -864,8 +1181,7 @@ var ServeApp = class {
864
1181
  }
865
1182
  async replyWebJs() {
866
1183
  if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
867
- this.webJsCache ??= this.opts.webJs();
868
- const js = await this.webJsCache;
1184
+ const js = await this.opts.webJs();
869
1185
  if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
870
1186
  return {
871
1187
  status: 200,
@@ -911,7 +1227,11 @@ var ServeApp = class {
911
1227
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
912
1228
  const values = parsed;
913
1229
  const known = new Set(mod.dw.entries().map(([k]) => k));
914
- const unknown = Object.keys(values).filter((k) => !known.has(k));
1230
+ if ("$enhance" in values) {
1231
+ const raw = values[ENHANCE_KEY];
1232
+ if (!(raw != null && typeof raw === "object" && !Array.isArray(raw) && Object.values(raw).every((v) => typeof v === "string"))) return json(400, { error: `${ENHANCE_KEY} must be { "<prompt var>": "<intent>" }` });
1233
+ }
1234
+ const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k));
915
1235
  if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
916
1236
  const path = bang(this.draftPath(mod, draft), "draft name validated just above");
917
1237
  await this.exclusive(mod.key, () => {
@@ -996,6 +1316,8 @@ var ServeApp = class {
996
1316
  if (action === "refresh-loras") return await this.refreshLoraMirror(hostId, host);
997
1317
  if (action === "refresh-schema") {
998
1318
  await host.fetchAndUpdateSchema();
1319
+ const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null);
1320
+ const lorasNote = (await this.refreshLoraMirror(hostId, host)).status === 200 ? unmirrored.length > 0 ? `, lora list re-read (${unmirrored.length} new)` : ", lora list re-read" : ", the lora manager list could not be re-read";
999
1321
  const rebound = await this.rebindHostVars(hostId, host);
1000
1322
  const nodes = host.schema.nodes.length;
1001
1323
  const loras = host.schema.getLoras().length;
@@ -1005,7 +1327,7 @@ var ServeApp = class {
1005
1327
  host: hostId,
1006
1328
  action,
1007
1329
  stale: rebound.stale,
1008
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`
1330
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}${lorasNote}`
1009
1331
  });
1010
1332
  }
1011
1333
  if (action === "restart") {
@@ -1317,7 +1639,22 @@ var ServeApp = class {
1317
1639
  effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)]))
1318
1640
  });
1319
1641
  }
1320
- /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
1642
+ async replyTags(modKey, varName, url) {
1643
+ const mod = this.moduleByKey(modKey);
1644
+ if (mod == null) return json(404, { error: `unknown workflow '${modKey}'` });
1645
+ const found = mod.dw.entries().find(([k]) => k === varName)?.[1];
1646
+ if (found == null) return json(404, { error: `workflow '${modKey}' has no var '${varName}'` });
1647
+ const tags = found.kind === "prompt" ? found.tags : null;
1648
+ if (tags == null) return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` });
1649
+ const params = new URLSearchParams(url.split("?")[1] ?? "");
1650
+ const limit = Math.min(100, Math.max(1, Number(params.get("limit") ?? "20") || 20));
1651
+ try {
1652
+ return json(200, { hits: (await this.tagSources.load(resolveTagSource(tags.url, mod.file))).search(params.get("q") ?? "", limit) });
1653
+ } catch (e) {
1654
+ console.error(`[serve] 🔴 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`);
1655
+ return json(502, { error: extractErrorMessage(e) });
1656
+ }
1657
+ }
1321
1658
  replyPromptEnhancers() {
1322
1659
  try {
1323
1660
  return json(200, { enhancers: listPromptEnhancers() });
@@ -1363,6 +1700,49 @@ var ServeApp = class {
1363
1700
  enhancers: listPromptEnhancers()
1364
1701
  });
1365
1702
  }
1703
+ replyLlmConfigs() {
1704
+ try {
1705
+ return json(200, { configs: listLlmConfigs() });
1706
+ } catch (e) {
1707
+ return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` });
1708
+ }
1709
+ }
1710
+ replySaveLlmConfig(rawName, req) {
1711
+ const name = validStoreName(rawName);
1712
+ if (name == null) return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, ". -_"` });
1713
+ let parsed;
1714
+ try {
1715
+ parsed = JSON.parse(req.body ?? "");
1716
+ } catch (e) {
1717
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1718
+ }
1719
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { provider, baseUrl, model, effort, thinkingOnly }" });
1720
+ try {
1721
+ writeLlmConfig(name, normalizeLlmConfig(parsed));
1722
+ } catch (e) {
1723
+ return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` });
1724
+ }
1725
+ return json(200, {
1726
+ ok: true,
1727
+ name,
1728
+ configs: listLlmConfigs()
1729
+ });
1730
+ }
1731
+ replyDeleteLlmConfig(rawName) {
1732
+ const name = validStoreName(rawName);
1733
+ if (name == null) return json(400, { error: `invalid config name '${rawName}'` });
1734
+ try {
1735
+ deleteLlmConfig(name);
1736
+ } catch (e) {
1737
+ return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` });
1738
+ }
1739
+ console.log(`[serve] llm config deleted: ${name}`);
1740
+ return json(200, {
1741
+ ok: true,
1742
+ name,
1743
+ configs: listLlmConfigs()
1744
+ });
1745
+ }
1366
1746
  runningModules() {
1367
1747
  return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
1368
1748
  }
@@ -1837,11 +2217,40 @@ async function buildWebJsText(pkgRoot) {
1837
2217
  if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
1838
2218
  return await result.outputs[0].text();
1839
2219
  }
1840
- /** the runtime resolution chain; every miss logs loud and degrades to api-only */
2220
+ /** changes whenever a file under `dir` is added, removed or rewritten. The web bundle reaches
2221
+ * outside web/ (vars, protocol types), so the whole src/ tree is the input: ~300 stats, a few ms */
2222
+ function sourceSignature(dir) {
2223
+ let count = 0;
2224
+ let newest = 0;
2225
+ let bytes = 0;
2226
+ const walk = (d) => {
2227
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
2228
+ const abs = join(d, entry.name);
2229
+ if (entry.isDirectory()) walk(abs);
2230
+ else if (entry.isFile()) {
2231
+ const st = statSync(abs);
2232
+ count += 1;
2233
+ bytes += st.size;
2234
+ newest = Math.max(newest, st.mtimeMs);
2235
+ }
2236
+ }
2237
+ };
2238
+ walk(dir);
2239
+ return `${count}:${bytes}:${newest}`;
2240
+ }
2241
+ let prebuiltJs = null;
2242
+ let fromSource = null;
2243
+ /** the runtime resolution chain; every miss logs loud and degrades to api-only. Called on every
2244
+ * page load: a prebuilt file is read once, a source build is redone only when src/ changed, so
2245
+ * an edited panel shows on refresh under `bun --watch`, which never sees the bundled files */
1841
2246
  async function loadOrBuildWebJs() {
1842
2247
  const here = dirname(fileURLToPath(import.meta.url));
1843
2248
  const prebuilt = join(here, "serve-web.js");
1844
- if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
2249
+ if (prebuiltJs != null) return prebuiltJs;
2250
+ if (existsSync(prebuilt)) {
2251
+ prebuiltJs = readFileSync(prebuilt, "utf8");
2252
+ return prebuiltJs;
2253
+ }
1845
2254
  if (typeof Bun === "undefined") {
1846
2255
  console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
1847
2256
  return null;
@@ -1851,12 +2260,21 @@ async function loadOrBuildWebJs() {
1851
2260
  console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
1852
2261
  return null;
1853
2262
  }
1854
- try {
1855
- return await buildWebJsText(pkgRoot);
1856
- } catch (e) {
1857
- console.error("[serve] 🔴 web ui bundle failed — api only:", e);
1858
- return null;
2263
+ const signature = sourceSignature(join(pkgRoot, "src"));
2264
+ if (fromSource?.signature !== signature) {
2265
+ const rebuilt = fromSource != null;
2266
+ fromSource = {
2267
+ signature,
2268
+ js: buildWebJsText(pkgRoot).then((js) => {
2269
+ if (rebuilt) console.log("[serve] web ui rebuilt from source");
2270
+ return js;
2271
+ }, (e) => {
2272
+ console.error("[serve] 🔴 web ui bundle failed — api only until the next edit:", e);
2273
+ return null;
2274
+ })
2275
+ };
1859
2276
  }
2277
+ return await fromSource.js;
1860
2278
  }
1861
2279
  //#endregion
1862
2280
  //#region src/cli/serve/run-serve.ts
@@ -2033,4 +2451,4 @@ function printStartup(app, bind, port) {
2033
2451
  //#endregion
2034
2452
  export { runServe };
2035
2453
 
2036
- //# sourceMappingURL=run-serve-BK7BA2dn.js.map
2454
+ //# sourceMappingURL=run-serve-BeAznay5.js.map