comfy-ts 2.24.0 → 2.25.1

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 (321) hide show
  1. package/dist/chunk-6mgjbrp6.js +579 -0
  2. package/dist/chunk-6mgjbrp6.js.map +17 -0
  3. package/dist/chunk-6tsg7fm5.js +1876 -0
  4. package/dist/chunk-6tsg7fm5.js.map +31 -0
  5. package/dist/chunk-dvxjvwe7.js +2593 -0
  6. package/dist/chunk-dvxjvwe7.js.map +29 -0
  7. package/dist/chunk-dw0t1nye.js +457 -0
  8. package/dist/chunk-dw0t1nye.js.map +16 -0
  9. package/dist/chunk-he70ewwx.js +444 -0
  10. package/dist/chunk-he70ewwx.js.map +13 -0
  11. package/dist/chunk-n22qz0j1.js +6663 -0
  12. package/dist/chunk-n22qz0j1.js.map +95 -0
  13. package/dist/chunk-n35nffm8.js +4777 -0
  14. package/dist/chunk-n35nffm8.js.map +51 -0
  15. package/dist/cli/serve/hostProtocol.d.cts +74 -0
  16. package/dist/cli/serve/hostProtocol.d.ts +74 -0
  17. package/dist/cli/tui-env.d.cts +2 -0
  18. package/dist/cli/tui-env.d.ts +2 -0
  19. package/dist/cli.js +494 -485
  20. package/dist/cli.js.map +16 -1
  21. package/dist/coreExports.d.cts +45 -0
  22. package/dist/coreExports.d.ts +45 -0
  23. package/dist/errors/InvalidPromptError.d.cts +10 -0
  24. package/dist/errors/InvalidPromptError.d.ts +10 -0
  25. package/dist/exampleAssets.d.cts +24 -0
  26. package/dist/exampleAssets.d.ts +24 -0
  27. package/dist/graph/ComfyNode.d.cts +109 -0
  28. package/dist/graph/ComfyNode.d.ts +109 -0
  29. package/dist/graph/ComfyNodeID.d.cts +15 -0
  30. package/dist/graph/ComfyNodeID.d.ts +15 -0
  31. package/dist/graph/ComfyNodeOutput.d.cts +21 -0
  32. package/dist/graph/ComfyNodeOutput.d.ts +21 -0
  33. package/dist/graph/NodeSlotSize.d.cts +4 -0
  34. package/dist/graph/NodeSlotSize.d.ts +4 -0
  35. package/dist/graph/autoValue.d.cts +16 -0
  36. package/dist/graph/autoValue.d.ts +16 -0
  37. package/dist/host/ComfyHost.d.cts +383 -0
  38. package/dist/host/ComfyHost.d.ts +383 -0
  39. package/dist/host/ComfyInstallType.d.cts +11 -0
  40. package/dist/host/ComfyInstallType.d.ts +11 -0
  41. package/dist/host/ComfyManager.d.cts +152 -0
  42. package/dist/host/ComfyManager.d.ts +152 -0
  43. package/dist/host/ComfyUploader.d.cts +42 -0
  44. package/dist/host/ComfyUploader.d.ts +42 -0
  45. package/dist/host/ComfyWorkflowBuilder.d.cts +19 -0
  46. package/dist/host/ComfyWorkflowBuilder.d.ts +19 -0
  47. package/dist/host/Requirements.d.cts +43 -0
  48. package/dist/host/Requirements.d.ts +43 -0
  49. package/dist/host/ResilientWebsocket.d.cts +122 -0
  50. package/dist/host/ResilientWebsocket.d.ts +122 -0
  51. package/dist/host/hostFile.d.cts +23 -0
  52. package/dist/host/hostFile.d.ts +23 -0
  53. package/dist/host/hostUrl.d.cts +22 -0
  54. package/dist/host/hostUrl.d.ts +22 -0
  55. package/dist/host/leastBusy.d.cts +9 -0
  56. package/dist/host/leastBusy.d.ts +9 -0
  57. package/dist/host/loraInfoCache.d.cts +110 -0
  58. package/dist/host/loraInfoCache.d.ts +110 -0
  59. package/dist/host/loraManagerApi.d.cts +106 -0
  60. package/dist/host/loraManagerApi.d.ts +106 -0
  61. package/dist/host/previewMethod.d.cts +5 -0
  62. package/dist/host/previewMethod.d.ts +5 -0
  63. package/dist/host/schemaDrift.d.cts +54 -0
  64. package/dist/host/schemaDrift.d.ts +54 -0
  65. package/dist/image-utils/_getPngMetadata.d.cts +5 -0
  66. package/dist/image-utils/_getPngMetadata.d.ts +5 -0
  67. package/dist/index.cjs +8197 -8509
  68. package/dist/index.cjs.map +124 -1
  69. package/dist/index.d.cts +4 -19116
  70. package/dist/index.d.ts +4 -19116
  71. package/dist/index.js +8129 -8390
  72. package/dist/index.js.map +124 -1
  73. package/dist/litegraph/CanonicalWorkflow.d.cts +75 -0
  74. package/dist/litegraph/CanonicalWorkflow.d.ts +75 -0
  75. package/dist/litegraph/LiteGraphGroup.d.cts +17 -0
  76. package/dist/litegraph/LiteGraphGroup.d.ts +17 -0
  77. package/dist/litegraph/LiteGraphJSON.d.cts +242 -0
  78. package/dist/litegraph/LiteGraphJSON.d.ts +242 -0
  79. package/dist/litegraph/LiteGraphLink.d.cts +48 -0
  80. package/dist/litegraph/LiteGraphLink.d.ts +48 -0
  81. package/dist/litegraph/LiteGraphLinkID.d.cts +6 -0
  82. package/dist/litegraph/LiteGraphLinkID.d.ts +6 -0
  83. package/dist/litegraph/LiteGraphNode.d.cts +76 -0
  84. package/dist/litegraph/LiteGraphNode.d.ts +76 -0
  85. package/dist/litegraph/LiteGraphNodeInput.d.cts +25 -0
  86. package/dist/litegraph/LiteGraphNodeInput.d.ts +25 -0
  87. package/dist/litegraph/LiteGraphNodeOutput.d.cts +20 -0
  88. package/dist/litegraph/LiteGraphNodeOutput.d.ts +20 -0
  89. package/dist/litegraph/LiteGraphSlotIndex.d.cts +6 -0
  90. package/dist/litegraph/LiteGraphSlotIndex.d.ts +6 -0
  91. package/dist/litegraph/LiteGraphSubgraphDef.d.cts +174 -0
  92. package/dist/litegraph/LiteGraphSubgraphDef.d.ts +174 -0
  93. package/dist/litegraph/convertFlowToLiteGraphJSON.d.cts +12 -0
  94. package/dist/litegraph/convertFlowToLiteGraphJSON.d.ts +12 -0
  95. package/dist/litegraph/expandSubgraphs.d.cts +27 -0
  96. package/dist/litegraph/expandSubgraphs.d.ts +27 -0
  97. package/dist/litegraph/normalizeWorkflow.d.cts +21 -0
  98. package/dist/litegraph/normalizeWorkflow.d.ts +21 -0
  99. package/dist/manager/ComfyRegistry.d.cts +54 -0
  100. package/dist/manager/ComfyRegistry.d.ts +54 -0
  101. package/dist/manager/generated/KnownComfyCustomNodeName.d.cts +1 -0
  102. package/dist/manager/generated/KnownComfyCustomNodeName.d.ts +1 -0
  103. package/dist/manager/generated/KnownComfyPluginTitle.d.cts +12109 -0
  104. package/dist/manager/generated/KnownComfyPluginTitle.d.ts +12109 -0
  105. package/dist/manager/generated/KnownComfyPluginURL.d.cts +1 -0
  106. package/dist/manager/generated/KnownComfyPluginURL.d.ts +1 -0
  107. package/dist/manager/generated/KnownModel_Base.d.cts +2 -0
  108. package/dist/manager/generated/KnownModel_Base.d.ts +2 -0
  109. package/dist/manager/generated/KnownModel_Name.d.cts +2842 -0
  110. package/dist/manager/generated/KnownModel_Name.d.ts +2842 -0
  111. package/dist/manager/generated/KnownModel_SavePath.d.cts +2 -0
  112. package/dist/manager/generated/KnownModel_SavePath.d.ts +2 -0
  113. package/dist/manager/generated/KnownModel_Type.d.cts +2 -0
  114. package/dist/manager/generated/KnownModel_Type.d.ts +2 -0
  115. package/dist/manager/installedView.d.cts +65 -0
  116. package/dist/manager/installedView.d.ts +65 -0
  117. package/dist/manager/json/custom-node-list.extra.d.cts +2 -0
  118. package/dist/manager/json/custom-node-list.extra.d.ts +2 -0
  119. package/dist/manager/json/model-list.extra.d.cts +2 -0
  120. package/dist/manager/json/model-list.extra.d.ts +2 -0
  121. package/dist/manager/loaders/parseReport.d.cts +24 -0
  122. package/dist/manager/loaders/parseReport.d.ts +24 -0
  123. package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.cts +1 -0
  124. package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.ts +1 -0
  125. package/dist/manager/loaders/step2_custom-node-list-loader.d.cts +2 -0
  126. package/dist/manager/loaders/step2_custom-node-list-loader.d.ts +2 -0
  127. package/dist/manager/loaders/step3_extension-node-map-loader.d.cts +2 -0
  128. package/dist/manager/loaders/step3_extension-node-map-loader.d.ts +2 -0
  129. package/dist/manager/loaders/step4_model-list-loader.d.cts +2 -0
  130. package/dist/manager/loaders/step4_model-list-loader.d.ts +2 -0
  131. package/dist/manager/loaders/step5_alter-list-loader.d.cts +2 -0
  132. package/dist/manager/loaders/step5_alter-list-loader.d.ts +2 -0
  133. package/dist/manager/loaders/step6_github-stats-loader.d.cts +2 -0
  134. package/dist/manager/loaders/step6_github-stats-loader.d.ts +2 -0
  135. package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.cts +7 -0
  136. package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.ts +7 -0
  137. package/dist/manager/types/ComfyManagerAPIModelList.d.cts +10 -0
  138. package/dist/manager/types/ComfyManagerAPIModelList.d.ts +10 -0
  139. package/dist/manager/types/ComfyManagerAPIPluginList.d.cts +33 -0
  140. package/dist/manager/types/ComfyManagerAPIPluginList.d.ts +33 -0
  141. package/dist/manager/types/ComfyManagerAlterInfo.d.cts +12 -0
  142. package/dist/manager/types/ComfyManagerAlterInfo.d.ts +12 -0
  143. package/dist/manager/types/ComfyManagerFileModelInfo.d.cts +10 -0
  144. package/dist/manager/types/ComfyManagerFileModelInfo.d.ts +10 -0
  145. package/dist/manager/types/ComfyManagerFilePluginContent.d.cts +11 -0
  146. package/dist/manager/types/ComfyManagerFilePluginContent.d.ts +11 -0
  147. package/dist/manager/types/ComfyManagerFilePluginList.d.cts +5 -0
  148. package/dist/manager/types/ComfyManagerFilePluginList.d.ts +5 -0
  149. package/dist/manager/types/ComfyManagerGithubStats.d.cts +7 -0
  150. package/dist/manager/types/ComfyManagerGithubStats.d.ts +7 -0
  151. package/dist/manager/types/ComfyManagerModelInfo.d.cts +12 -0
  152. package/dist/manager/types/ComfyManagerModelInfo.d.ts +12 -0
  153. package/dist/manager/types/ComfyManagerPluginContentMetadata.d.cts +10 -0
  154. package/dist/manager/types/ComfyManagerPluginContentMetadata.d.ts +10 -0
  155. package/dist/manager/types/ComfyManagerPluginEnums.d.cts +5 -0
  156. package/dist/manager/types/ComfyManagerPluginEnums.d.ts +5 -0
  157. package/dist/manager/types/ComfyManagerPluginInfo.d.cts +54 -0
  158. package/dist/manager/types/ComfyManagerPluginInfo.d.ts +54 -0
  159. package/dist/promptEnhancers.d.cts +22 -0
  160. package/dist/promptEnhancers.d.ts +22 -0
  161. package/dist/runner/ComfyExecution.d.cts +230 -0
  162. package/dist/runner/ComfyExecution.d.ts +230 -0
  163. package/dist/runner/ComfyExecutionStatus.d.cts +1 -0
  164. package/dist/runner/ComfyExecutionStatus.d.ts +1 -0
  165. package/dist/runner/ComfyWorkflow.d.cts +141 -0
  166. package/dist/runner/ComfyWorkflow.d.ts +141 -0
  167. package/dist/runner/ComfyWorkflowLayout.d.cts +17 -0
  168. package/dist/runner/ComfyWorkflowLayout.d.ts +17 -0
  169. package/dist/runner/ComfyWsApi.d.cts +2174 -0
  170. package/dist/runner/ComfyWsApi.d.ts +2174 -0
  171. package/dist/runner/MediaImage.d.cts +127 -0
  172. package/dist/runner/MediaImage.d.ts +127 -0
  173. package/dist/runner/comfyOrgApiKey.d.cts +21 -0
  174. package/dist/runner/comfyOrgApiKey.d.ts +21 -0
  175. package/dist/runner/describePromptRejection.d.cts +1 -0
  176. package/dist/runner/describePromptRejection.d.ts +1 -0
  177. package/dist/runner/ephemeral.d.cts +10 -0
  178. package/dist/runner/ephemeral.d.ts +10 -0
  179. package/dist/runner/historyReplay.d.cts +13 -0
  180. package/dist/runner/historyReplay.d.ts +13 -0
  181. package/dist/runner/mediaKinds.d.cts +7 -0
  182. package/dist/runner/mediaKinds.d.ts +7 -0
  183. package/dist/runner/outputPath.d.cts +40 -0
  184. package/dist/runner/outputPath.d.ts +40 -0
  185. package/dist/runner/outputs3d.d.cts +3 -0
  186. package/dist/runner/outputs3d.d.ts +3 -0
  187. package/dist/runner/wsBinaryFrame.d.cts +25 -0
  188. package/dist/runner/wsBinaryFrame.d.ts +25 -0
  189. package/dist/sdk-generator/ComfyNodeSchema.d.cts +25 -0
  190. package/dist/sdk-generator/ComfyNodeSchema.d.ts +25 -0
  191. package/dist/sdk-generator/ComfySchema.d.cts +74 -0
  192. package/dist/sdk-generator/ComfySchema.d.ts +74 -0
  193. package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.cts +3072 -0
  194. package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.ts +3072 -0
  195. package/dist/sdk-generator/Primitives.d.cts +12 -0
  196. package/dist/sdk-generator/Primitives.d.ts +12 -0
  197. package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.cts +2 -0
  198. package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.ts +2 -0
  199. package/dist/sdk-generator/_pythonModuleToNamespace.d.cts +1 -0
  200. package/dist/sdk-generator/_pythonModuleToNamespace.d.ts +1 -0
  201. package/dist/sdk-generator/_toQualifiedNodeKey.d.cts +1 -0
  202. package/dist/sdk-generator/_toQualifiedNodeKey.d.ts +1 -0
  203. package/dist/sdk-generator/comfy-api-json.d.cts +16 -0
  204. package/dist/sdk-generator/comfy-api-json.d.ts +16 -0
  205. package/dist/sdk-generator/comfyui-sdk-codegen.d.cts +23 -0
  206. package/dist/sdk-generator/comfyui-sdk-codegen.d.ts +23 -0
  207. package/dist/sdk-generator/comfyui-types.d.cts +55 -0
  208. package/dist/sdk-generator/comfyui-types.d.ts +55 -0
  209. package/dist/sdk-generator/inputWidgetKind.d.cts +80 -0
  210. package/dist/sdk-generator/inputWidgetKind.d.ts +80 -0
  211. package/dist/sdk-generator/litegraphToApiRequestPayload.d.cts +41 -0
  212. package/dist/sdk-generator/litegraphToApiRequestPayload.d.ts +41 -0
  213. package/dist/serve-web.js +51 -51
  214. package/dist/ssh-host-manager/ssh-config-manager.d.cts +17 -0
  215. package/dist/ssh-host-manager/ssh-config-manager.d.ts +17 -0
  216. package/dist/state.d.cts +80 -0
  217. package/dist/state.d.ts +80 -0
  218. package/dist/storage/ComfyStorage.d.cts +55 -0
  219. package/dist/storage/ComfyStorage.d.ts +55 -0
  220. package/dist/storage/nodeStorage.d.cts +2 -0
  221. package/dist/storage/nodeStorage.d.ts +2 -0
  222. package/dist/types/comfy-sdk.d.cts +85 -0
  223. package/dist/types/comfy-sdk.d.ts +85 -0
  224. package/dist/types/index.d.cts +65 -0
  225. package/dist/types/index.d.ts +65 -0
  226. package/dist/utils/CodeBuffer.d.cts +20 -0
  227. package/dist/utils/CodeBuffer.d.ts +20 -0
  228. package/dist/utils/ComfyColors.d.cts +14 -0
  229. package/dist/utils/ComfyColors.d.ts +14 -0
  230. package/dist/utils/ansi.d.cts +22 -0
  231. package/dist/utils/ansi.d.ts +22 -0
  232. package/dist/utils/bang.d.cts +9 -0
  233. package/dist/utils/bang.d.ts +9 -0
  234. package/dist/utils/deepCopyNaive.d.cts +1 -0
  235. package/dist/utils/deepCopyNaive.d.ts +1 -0
  236. package/dist/utils/downloadFile.d.cts +2 -0
  237. package/dist/utils/downloadFile.d.ts +2 -0
  238. package/dist/utils/escapeJSKey.d.cts +2 -0
  239. package/dist/utils/escapeJSKey.d.ts +2 -0
  240. package/dist/utils/exhaust.d.cts +1 -0
  241. package/dist/utils/exhaust.d.ts +1 -0
  242. package/dist/utils/extractErrorMessage.d.cts +2 -0
  243. package/dist/utils/extractErrorMessage.d.ts +2 -0
  244. package/dist/utils/githubRegexes.d.cts +2 -0
  245. package/dist/utils/githubRegexes.d.ts +2 -0
  246. package/dist/utils/hashArrayBuffer.d.cts +1 -0
  247. package/dist/utils/hashArrayBuffer.d.ts +1 -0
  248. package/dist/utils/isRecord.d.cts +2 -0
  249. package/dist/utils/isRecord.d.ts +2 -0
  250. package/dist/utils/lazySharp.d.cts +3 -0
  251. package/dist/utils/lazySharp.d.ts +3 -0
  252. package/dist/utils/log.d.cts +4 -0
  253. package/dist/utils/log.d.ts +4 -0
  254. package/dist/utils/loraTag.d.cts +8 -0
  255. package/dist/utils/loraTag.d.ts +8 -0
  256. package/dist/utils/matchesRegex.d.cts +2 -0
  257. package/dist/utils/matchesRegex.d.ts +2 -0
  258. package/dist/utils/printArkResultInConsole.d.cts +2 -0
  259. package/dist/utils/printArkResultInConsole.d.ts +2 -0
  260. package/dist/utils/safeName.d.cts +6 -0
  261. package/dist/utils/safeName.d.ts +6 -0
  262. package/dist/utils/sha1.d.cts +2 -0
  263. package/dist/utils/sha1.d.ts +2 -0
  264. package/dist/utils/softValidate.d.cts +2 -0
  265. package/dist/utils/softValidate.d.ts +2 -0
  266. package/dist/utils/stringifyReadable.d.cts +1 -0
  267. package/dist/utils/stringifyReadable.d.ts +1 -0
  268. package/dist/utils/toposort.d.cts +3 -0
  269. package/dist/utils/toposort.d.ts +3 -0
  270. package/dist/vars/ComfyVars.d.cts +607 -0
  271. package/dist/vars/ComfyVars.d.ts +607 -0
  272. package/dist/vars/DefinedWorkflow.d.cts +104 -0
  273. package/dist/vars/DefinedWorkflow.d.ts +104 -0
  274. package/dist/vars/lanes.d.cts +81 -0
  275. package/dist/vars/lanes.d.ts +81 -0
  276. package/dist/vars/loraEntry.d.cts +26 -0
  277. package/dist/vars/loraEntry.d.ts +26 -0
  278. package/dist/vars/loraKeywords.d.cts +19 -0
  279. package/dist/vars/loraKeywords.d.ts +19 -0
  280. package/dist/vars/outputWidgets.d.cts +33 -0
  281. package/dist/vars/outputWidgets.d.ts +33 -0
  282. package/dist/vars/presets.d.cts +9 -0
  283. package/dist/vars/presets.d.ts +9 -0
  284. package/dist/vars/promptSyntax.d.cts +98 -0
  285. package/dist/vars/promptSyntax.d.ts +98 -0
  286. package/dist/web.d.cts +2 -0
  287. package/dist/web.d.ts +2 -19160
  288. package/dist/web.js +8040 -8292
  289. package/dist/web.js.map +119 -1
  290. package/examples/depth-explorer/web/tsconfig.json +1 -2
  291. package/examples/upscale-explorer/web/tsconfig.json +1 -2
  292. package/examples/web/tsconfig.json +1 -4
  293. package/examples/world-explorer/web/tsconfig.json +1 -2
  294. package/package.json +27 -32
  295. package/src/cli/serve/web/components/SideMenu.tsx +1 -1
  296. package/src/cli/serve/web/components/controls/LorasControl.tsx +2 -0
  297. package/src/cli/serve/web/components/controls/RichSelect.tsx +1 -0
  298. package/src/cli/serve/web/state/RunSt.poll.test.ts +2 -1
  299. package/src/cli/serve/web/tsconfig.json +1 -2
  300. package/src/cli/serve/web/widgets/RelightWidget.tsx +1 -0
  301. package/src/cli/tui/state/HostSt.ts +1 -1
  302. package/src/host/loraManagerApi.ts +8 -3
  303. package/src/runner/ComfyExecution.ts +3 -1
  304. package/src/runner/ComfyWsApi.ts +2 -1
  305. package/src/storage/ComfyStorage.ts +5 -4
  306. package/src/types/comfy-sdk.ts +1 -0
  307. package/src/utils/ansi.ts +1 -0
  308. package/dist/ServeApp-fsHtW5zG.js +0 -2689
  309. package/dist/ServeApp-fsHtW5zG.js.map +0 -1
  310. package/dist/exampleAssets-DZynSkZm.js +0 -6674
  311. package/dist/exampleAssets-DZynSkZm.js.map +0 -1
  312. package/dist/findDefinedWorkflow-qyqFea7q.js +0 -625
  313. package/dist/findDefinedWorkflow-qyqFea7q.js.map +0 -1
  314. package/dist/run-run-Cn2JzKlE.js +0 -449
  315. package/dist/run-run-Cn2JzKlE.js.map +0 -1
  316. package/dist/run-serve-BhGegaCI.js +0 -464
  317. package/dist/run-serve-BhGegaCI.js.map +0 -1
  318. package/dist/run-tui-CrM4ijkH.js +0 -4569
  319. package/dist/run-tui-CrM4ijkH.js.map +0 -1
  320. package/dist/schemaDrift-BGYJZGMD.js +0 -2225
  321. package/dist/schemaDrift-BGYJZGMD.js.map +0 -1
@@ -1,2689 +0,0 @@
1
- import { $ as MODEL_3D_MIMES, A as reloadLoraInfoCache, B as lmFileSize, C as getLoraTriggers, E as lorasMissingFromMirror, F as fetchLoraList, G as lmTags, I as fetchLoraPreviewBytes, J as loraKey, L as lmBaseModel, M as fetchLoraCivitai, N as fetchLoraDescription, O as recordCivitaiMiss, P as fetchLoraExampleImages, R as lmCivitai, S as getLoraTriggerWords, T as loraMirrorEntries, U as lmNotes, V as lmFolder, W as lmSha256, X as ansi, Y as loraPreviewMapFrom, _ as buildLoraMirror, _t as sha1HexOfString, b as getLoraInfo, c as isLoraLanes, d as isLoraStrength, gt as statelessRegex, i as summarizeDrift, j as writeLoraMirror, k as refreshLoraInfoCacheIfChanged, l as isLorasInput, lt as bang, nt as MEDIA_KINDS, p as getLoraKeyword, r as driftChanged, st as importSharp, tt as DEFAULT_MEDIA_EXTENSIONS, u as isPromptInput, v as getLoraAddedAt, vt as extractErrorMessage, x as getLoraPreviewUrl, y as getLoraDisplayName, z as lmFilePath } from "./schemaDrift-BGYJZGMD.js";
2
- import { d as isDraftMetaKey, l as assembleLogChunks, o as draftsDirForFile, s as listDraftsForFile, u as ENHANCE_KEY } from "./findDefinedWorkflow-qyqFea7q.js";
3
- import { homedir } from "node:os";
4
- import { fileURLToPath } from "node:url";
5
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
6
- import { basename, dirname, extname, isAbsolute, join, resolve } from "pathe";
7
- import { nanoid } from "nanoid";
8
- import { createHash } from "node:crypto";
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
- ...Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}
24
- };
25
- switch (varDef.kind) {
26
- case "prompt": {
27
- const v = varDef;
28
- return {
29
- ...base,
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
37
- };
38
- }
39
- case "text": {
40
- const v = varDef;
41
- return {
42
- ...base,
43
- payload: "string",
44
- multiline: v.opts.multiline,
45
- textPresets: presetsOrUndefined(v.presets)
46
- };
47
- }
48
- case "int": {
49
- const v = varDef;
50
- return {
51
- ...base,
52
- payload: `integer${rangeText(v.opts)}`,
53
- min: v.opts.min,
54
- max: v.opts.max
55
- };
56
- }
57
- case "float": {
58
- const v = varDef;
59
- return {
60
- ...base,
61
- payload: `number${rangeText(v.opts)}`,
62
- min: v.opts.min,
63
- max: v.opts.max
64
- };
65
- }
66
- case "seed": {
67
- const v = varDef;
68
- return {
69
- ...base,
70
- default: {
71
- mode: v.defaultMode,
72
- value: v.defaultValue
73
- },
74
- payload: "number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}"
75
- };
76
- }
77
- case "toggle": return {
78
- ...base,
79
- payload: "true or false"
80
- };
81
- case "choice": {
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}`;
85
- return {
86
- ...base,
87
- payload,
88
- choices: v.choices,
89
- select: v.select
90
- };
91
- }
92
- case "loras": {
93
- const v = varDef;
94
- return {
95
- ...base,
96
- payload: "{\"<lora name>\": false | true | strength | [model, clip]}",
97
- options: v.options,
98
- optionsFilter: v.optionsFilter == null ? void 0 : String(v.optionsFilter)
99
- };
100
- }
101
- case "size": {
102
- const v = varDef;
103
- return {
104
- ...base,
105
- payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
106
- presets: v.presets,
107
- starredPresets: [...v.starred]
108
- };
109
- }
110
- case "image":
111
- case "audio":
112
- case "video": {
113
- const v = varDef;
114
- const presets = v.presets;
115
- return {
116
- ...base,
117
- payload: "local file path or http(s) url",
118
- extensions: v.extensions,
119
- ...presets.length > 0 ? { mediaPresets: presets } : {}
120
- };
121
- }
122
- default: {
123
- const unknownKind = varDef.kind;
124
- return {
125
- ...base,
126
- payload: `string (unrecognised kind '${String(unknownKind)}')`
127
- };
128
- }
129
- }
130
- }
131
- /** one aligned console line per var (startup print). Padding happens on the PLAIN text: colors are wrapped around the
132
- * already-padded cells, so a colored and an uncolored print line up identically */
133
- function renderDescriptorLine(name, d, nameWidth, color = false) {
134
- const def = typeof d.default === "string" ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default);
135
- const cells = {
136
- name: name.padEnd(nameWidth),
137
- kind: d.kind.padEnd(6),
138
- value: truncate(def ?? "null", 60)
139
- };
140
- if (!color) return ` ${cells.name} ${cells.kind} ${d.payload} · default: ${cells.value}`;
141
- return ` ${ansi.bold(cells.name)} ${ansi.yellow(cells.kind)} ${ansi.gray(d.payload)} ${ansi.gray("· default:")} ${cells.value}`;
142
- }
143
- function truncate(s, n) {
144
- return s.length <= n ? s : s.slice(0, n - 1) + "…";
145
- }
146
- //#endregion
147
- //#region src/cli/serve/thumbs.ts
148
- const isHttpUrl = (s) => /^https?:\/\//i.test(s);
149
- /** the url the page loads for a local image's preview */
150
- function thumbUrl(abs, width = 160) {
151
- return `/thumb?src=${encodeURIComponent(abs)}&w=${width}`;
152
- }
153
- /** Bun's own image pipeline when the server runs on Bun, sharp only under Node (the cli runs on
154
- * both). Both read the EXIF orientation */
155
- async function webpThumb(path, width) {
156
- if (typeof Bun !== "undefined") return new Bun.Image(path).resize(width, width, {
157
- fit: "inside",
158
- withoutEnlargement: true
159
- }).webp({ quality: 78 }).bytes();
160
- const sharp = await importSharp("a thumbnail");
161
- return new Uint8Array(await sharp(path).rotate().resize({
162
- width,
163
- height: width,
164
- fit: "inside",
165
- withoutEnlargement: true
166
- }).webp({ quality: 78 }).toBuffer());
167
- }
168
- const MAX_WIDTH = 640;
169
- const MAX_CACHED = 400;
170
- var ThumbStore = class {
171
- constructor() {
172
- this.allowed = /* @__PURE__ */ new Set();
173
- this.roots = /* @__PURE__ */ new Set();
174
- this.cache = /* @__PURE__ */ new Map();
175
- }
176
- /** one file a served module declared */
177
- allow(abs) {
178
- this.allowed.add(resolve(abs));
179
- }
180
- /** every image under this folder */
181
- allowRoot(dir) {
182
- this.roots.add(resolve(dir));
183
- }
184
- isAllowed(abs) {
185
- const p = resolve(abs);
186
- if (this.allowed.has(p)) return true;
187
- for (const root of this.roots) if (p.startsWith(`${root}/`)) return true;
188
- return false;
189
- }
190
- /** a webp at most `width` wide, or why not: 'forbidden' (not declared, not under a root),
191
- * 'missing' (not on this machine) */
192
- async render(abs, width) {
193
- if (!this.isAllowed(abs)) return "forbidden";
194
- const p = resolve(abs);
195
- if (!existsSync(p)) return "missing";
196
- const w = Math.max(16, Math.min(MAX_WIDTH, Math.round(width)));
197
- const key = `${p}|${statSync(p).mtimeMs}|${w}`;
198
- const hit = this.cache.get(key);
199
- if (hit != null) return hit;
200
- const bytes = await webpThumb(p, w);
201
- if (this.cache.size >= MAX_CACHED) {
202
- const oldest = this.cache.keys().next().value;
203
- if (oldest != null) this.cache.delete(oldest);
204
- }
205
- this.cache.set(key, bytes);
206
- return bytes;
207
- }
208
- };
209
- //#endregion
210
- //#region src/cli/serve/applyVarPayload.ts
211
- function isFiniteNumber(x) {
212
- return typeof x === "number" && Number.isFinite(x);
213
- }
214
- /** cap long option lists in error messages */
215
- function listSome(items, cap = 20) {
216
- if (items.length <= cap) return items.join(", ");
217
- return `${items.slice(0, cap).join(", ")} … +${items.length - cap} more`;
218
- }
219
- /** `extraLoraOptions`: names the lora-manager mirror knows that ComfyUI's enum does not.
220
- * they are accepted like any option, the file is on disk, so the run usually works, but
221
- * ONLY those: an arbitrary name still fails, so a typo cannot reach the host */
222
- function applyVarPayload(varDef, raw, opts = {}) {
223
- const name = varDef.name ?? varDef.label ?? varDef.kind;
224
- switch (varDef.kind) {
225
- case "text":
226
- if (typeof raw !== "string") return `var '${name}' expects a string`;
227
- varDef.set(raw);
228
- return null;
229
- case "prompt":
230
- if (!isPromptInput(raw)) return `var '${name}' expects a string or {"lanes": [{"name": string, "prompt": string, "active": boolean}]}`;
231
- varDef.set(raw);
232
- return null;
233
- case "int":
234
- case "float": {
235
- const v = varDef;
236
- if (isFiniteNumber(raw)) {
237
- v.set(raw);
238
- return null;
239
- }
240
- if (typeof raw === "string" && v.parse(raw)) return null;
241
- const o = v.opts;
242
- return `var '${name}' expects a number${o.min == null && o.max == null ? "" : ` (${o.min ?? "-∞"}..${o.max ?? "∞"})`}`;
243
- }
244
- case "seed": {
245
- const v = varDef;
246
- if (isFiniteNumber(raw)) {
247
- v.setMode("=");
248
- v.set(raw);
249
- return null;
250
- }
251
- if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
252
- const o = raw;
253
- const mode = o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?" ? o.mode : null;
254
- if (o.mode !== void 0 && mode == null) return `var '${name}': mode must be one of = + - ?`;
255
- if (o.value !== void 0 && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`;
256
- if (mode == null && o.value === void 0) return `var '${name}': give "mode" and/or "value"`;
257
- if (mode != null) v.setMode(mode);
258
- if (isFiniteNumber(o.value)) v.set(o.value);
259
- return null;
260
- }
261
- return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`;
262
- }
263
- case "toggle":
264
- if (typeof raw !== "boolean") return `var '${name}' expects true or false`;
265
- varDef.set(raw);
266
- return null;
267
- case "choice": {
268
- const v = varDef;
269
- const known = (x) => typeof x === "string" && v.choices.includes(x);
270
- if (v.select === "many") {
271
- if (known(raw)) {
272
- v.set([raw]);
273
- return null;
274
- }
275
- if (Array.isArray(raw) && raw.every(known)) {
276
- v.set(v.choices.filter((c) => raw.includes(c)));
277
- return null;
278
- }
279
- return `var '${name}' expects a list of: ${listSome(v.choices)}`;
280
- }
281
- if (v.select === "zero-or-one") {
282
- if (raw === null || known(raw)) {
283
- v.set(raw);
284
- return null;
285
- }
286
- return `var '${name}' expects null or one of: ${listSome(v.choices)}`;
287
- }
288
- if (known(raw)) {
289
- v.set(raw);
290
- return null;
291
- }
292
- return `var '${name}' expects one of: ${listSome(v.choices)}`;
293
- }
294
- case "loras": {
295
- const v = varDef;
296
- const SHAPE = `{"<lora name>": false | true | strength | [model, clip] | {strength, off?, mute?}} or {"lanes": [{"name", "active", "loras": {…}}]}`;
297
- if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects ${SHAPE}`;
298
- const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw];
299
- const known = /* @__PURE__ */ new Set([...v.options, ...opts.extraLoraOptions ?? []]);
300
- for (const record of records) {
301
- const unknownNames = Object.keys(record).filter((k) => !known.has(k));
302
- if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
303
- 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? }`;
304
- }
305
- if (!isLorasInput(raw)) return `var '${name}' expects ${SHAPE}`;
306
- v.set(raw);
307
- return null;
308
- }
309
- case "size": {
310
- const v = varDef;
311
- if (typeof raw === "string" && v.parse(raw)) return null;
312
- if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
313
- const o = raw;
314
- if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
315
- v.set({
316
- width: o.width,
317
- height: o.height
318
- });
319
- return null;
320
- }
321
- }
322
- return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`;
323
- }
324
- case "image":
325
- case "audio":
326
- case "video":
327
- if (typeof raw !== "string") return `var '${name}' expects a file path or http(s) url string`;
328
- varDef.set(raw);
329
- return null;
330
- default: {
331
- const unknownKind = varDef.kind;
332
- return `var '${name}' has unsupported kind '${String(unknownKind)}'`;
333
- }
334
- }
335
- }
336
- //#endregion
337
- //#region src/utils/safeName.ts
338
- /** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
339
- function validStoreName(raw) {
340
- const name = raw.trim();
341
- if (name.length > 100) return null;
342
- return /^[\w][\w .-]*$/.test(name) ? name : null;
343
- }
344
- /** a save prefix becomes a PATH under outputs/, so every segment goes through the same gate:
345
- * it cannot climb out, and it cannot be absolute. Lives here, not on ServeApp, because the
346
- * settings READER validates it too, a hand-written settings file never met the PUT route. */
347
- function validSavePrefix(raw) {
348
- const clean = raw.trim().replaceAll("\\", "/");
349
- if (clean === "") return "";
350
- if (clean.startsWith("/") || /^[a-z]:/i.test(clean)) return null;
351
- if (clean.length > 200) return null;
352
- const segments = clean.split("/").filter((s) => s !== "");
353
- if (segments.length === 0 || segments.some((s) => validStoreName(s) == null)) return null;
354
- return segments.join("/");
355
- }
356
- //#endregion
357
- //#region src/promptEnhancers.ts
358
- const EXT$1 = ".md";
359
- function promptEnhancersDir() {
360
- return comfyts.resolveFromPromptEnhancers("");
361
- }
362
- function promptEnhancerPath(name) {
363
- const safe = validStoreName(name);
364
- return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT$1}`);
365
- }
366
- /** the shipped starting point. It is a FILE from the first read on, so it can be edited
367
- * on disk like everything else, the browser ships no copy of this text */
368
- const SEED = {
369
- name: "refine-krea2-prompt",
370
- 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.
371
-
372
- Rewrite it into ONE paragraph a reader could picture with their eyes closed:
373
-
374
- - 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.
375
- - 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).
376
- - 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.
377
- - 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.
378
- - an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.
379
- - 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.
380
- - text that must appear inside the image is spelled out in "quotes", exactly as it should be rendered.
381
- - roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.
382
- - never write a negative ("- ...") line or a comment ("// ...") line: the panel keeps the user's own and adds them back after your prompt.
383
-
384
- Answer with the rewritten prompt and nothing else: no preamble, no explanation.
385
- `
386
- };
387
- /** seeds ONCE, on an absent folder, then lists. An emptied folder stays empty: the seed is a
388
- * starting point, not a file the store keeps restoring */
389
- function listPromptEnhancers() {
390
- if (!existsSync(promptEnhancersDir())) writePromptEnhancer(SEED.name, SEED.text);
391
- return readPromptEnhancers();
392
- }
393
- /** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing
394
- * a module must never create files in someone's project */
395
- function readPromptEnhancers() {
396
- const dir = promptEnhancersDir();
397
- if (!existsSync(dir)) return [];
398
- const out = [];
399
- for (const file of readdirSync(dir).sort()) {
400
- if (!file.endsWith(EXT$1)) continue;
401
- const name = file.slice(0, -3);
402
- if (validStoreName(name) == null) continue;
403
- try {
404
- out.push({
405
- name,
406
- text: readFileSync(join(dir, file), "utf8")
407
- });
408
- } catch (e) {
409
- console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e);
410
- }
411
- }
412
- return out;
413
- }
414
- function writePromptEnhancer(name, text) {
415
- const path = promptEnhancerPath(name);
416
- if (path == null) return null;
417
- mkdirSync(promptEnhancersDir(), { recursive: true });
418
- writeFileSync(path, text);
419
- return path;
420
- }
421
- /** a missing file is still a success: the caller asked for it to be gone, and it is */
422
- function deletePromptEnhancer(name) {
423
- const path = promptEnhancerPath(name);
424
- if (path == null) return false;
425
- if (existsSync(path)) rmSync(path);
426
- return true;
427
- }
428
- //#endregion
429
- //#region src/cli/serve/web/llm.ts
430
- const OPENROUTER_BASE = "https://openrouter.ai/api/v1";
431
- const OPENWEBUI_BASE = "http://localhost:3000";
432
- const OPENAI_COMPAT_BASE = "http://localhost:8080/v1";
433
- function defaultBaseUrl(provider) {
434
- if (provider === "openrouter") return OPENROUTER_BASE;
435
- return provider === "openwebui" ? OPENWEBUI_BASE : OPENAI_COMPAT_BASE;
436
- }
437
- //#endregion
438
- //#region src/cli/serve/llmConfigShape.ts
439
- function isProvider(raw) {
440
- return raw === "openrouter" || raw === "openwebui" || raw === "openai";
441
- }
442
- function isEffort(raw) {
443
- return raw === "off" || raw === "low" || raw === "medium" || raw === "high";
444
- }
445
- /** explicit model ids, never an alias: behaviour and cost stay reproducible */
446
- const DEFAULT_MODEL = {
447
- openrouter: "anthropic/claude-sonnet-5",
448
- openwebui: "",
449
- openai: ""
450
- };
451
- /** a stored file → a usable config: a half-written or hand-broken field degrades to its
452
- * default, never breaks the modal */
453
- function normalizeLlmConfig(raw) {
454
- const o = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
455
- const provider = isProvider(o.provider) ? o.provider : "openrouter";
456
- return {
457
- provider,
458
- baseUrl: typeof o.baseUrl === "string" && o.baseUrl.trim() !== "" ? o.baseUrl.trim() : defaultBaseUrl(provider),
459
- model: typeof o.model === "string" ? o.model : DEFAULT_MODEL[provider],
460
- effort: isEffort(o.effort) ? o.effort : "medium",
461
- thinkingOnly: o.thinkingOnly !== false
462
- };
463
- }
464
- //#endregion
465
- //#region src/cli/serve/llmConfigs.ts
466
- const EXT = ".json";
467
- function llmConfigsDir() {
468
- return comfyts.resolveFromLlmConfigs("");
469
- }
470
- function llmConfigPath(name) {
471
- const safe = validStoreName(name);
472
- return safe == null ? null : join(llmConfigsDir(), `${safe}${EXT}`);
473
- }
474
- function listLlmConfigs() {
475
- const dir = llmConfigsDir();
476
- if (!existsSync(dir)) return [];
477
- const out = [];
478
- for (const file of readdirSync(dir).sort()) {
479
- if (!file.endsWith(EXT)) continue;
480
- const name = file.slice(0, -5);
481
- if (validStoreName(name) == null) continue;
482
- try {
483
- out.push({
484
- name,
485
- config: normalizeLlmConfig(JSON.parse(readFileSync(join(dir, file), "utf8")))
486
- });
487
- } catch (e) {
488
- console.error(`[serve] llm config '${name}' unreadable, skipped:`, e);
489
- }
490
- }
491
- return out;
492
- }
493
- function writeLlmConfig(name, config) {
494
- const path = llmConfigPath(name);
495
- if (path == null) return null;
496
- mkdirSync(llmConfigsDir(), { recursive: true });
497
- writeFileSync(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}\n`);
498
- return path;
499
- }
500
- /** a missing file is still a success: the caller asked for it to be gone, and it is */
501
- function deleteLlmConfig(name) {
502
- const path = llmConfigPath(name);
503
- if (path == null) return false;
504
- if (existsSync(path)) rmSync(path);
505
- return true;
506
- }
507
- //#endregion
508
- //#region src/cli/serve/managerOnlyLoras.ts
509
- /**
510
- * `options` is the host enum for this var: it decides both what counts as already-known
511
- * (compared by normalized key, never raw, the enum keeps case, extension and separators)
512
- * and which separator the rebuilt names must use.
513
- */
514
- function managerOnlyLoraOptions(p) {
515
- const filter = p.filter == null ? null : statelessRegex(p.filter);
516
- const known = new Set(p.options.map((o) => loraKey(o)));
517
- const separator = p.options.some((o) => o.includes("\\")) ? "\\" : "/";
518
- return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
519
- }
520
- //#endregion
521
- //#region src/cli/serve/tagList.ts
522
- /** one csv line, double-quoted fields with `""` escapes */
523
- function csvFields(line) {
524
- const out = [];
525
- let cur = "";
526
- let quoted = false;
527
- for (let i = 0; i < line.length; i++) {
528
- const ch = line[i];
529
- if (quoted) if (ch === "\"" && line[i + 1] === "\"") {
530
- cur += "\"";
531
- i++;
532
- } else if (ch === "\"") quoted = false;
533
- else cur += ch;
534
- else if (ch === "\"") quoted = true;
535
- else if (ch === ",") {
536
- out.push(cur);
537
- cur = "";
538
- } else cur += ch;
539
- }
540
- out.push(cur);
541
- return out;
542
- }
543
- const intOrNull = (s) => s != null && /^\d+$/.test(s.trim()) ? Number(s) : null;
544
- function parseTagList(text) {
545
- const out = [];
546
- for (const raw of text.split(/\r?\n/)) {
547
- const line = raw.trim();
548
- if (line === "" || line.startsWith("#")) continue;
549
- const f = csvFields(line);
550
- const name = (f[0] ?? "").trim();
551
- if (name === "") continue;
552
- const twoCols = f.length === 2;
553
- out.push({
554
- name,
555
- category: twoCols ? null : intOrNull(f[1]),
556
- count: (twoCols ? intOrNull(f[1]) : intOrNull(f[2])) ?? 0,
557
- aliases: (f[3] ?? "").split(",").map((a) => a.trim()).filter((a) => a !== "")
558
- });
559
- }
560
- return out;
561
- }
562
- /** the searchable form: lowercase, spaces as underscores (the lists write `long_hair`) */
563
- const key = (s) => s.trim().toLowerCase().replace(/\s+/g, "_");
564
- var TagList = class TagList {
565
- constructor(entries) {
566
- this.entries = entries;
567
- this.rows = entries.map((e) => ({
568
- e,
569
- name: key(e.name),
570
- aliases: e.aliases.map(key)
571
- }));
572
- this.rows.sort((a, b) => b.e.count - a.e.count);
573
- }
574
- static parse(text) {
575
- return new TagList(parseTagList(text));
576
- }
577
- /** prefix of the name first, then prefix of an alias (answered with the name it points to),
578
- * then a word inside the name (`hair` finds `long_hair`), each by post count */
579
- search(query, limit = 20) {
580
- const q = key(query);
581
- if (q === "") return [];
582
- const hits = [];
583
- const seen = /* @__PURE__ */ new Set();
584
- const take = (e, alias) => {
585
- if (seen.has(e.name)) return false;
586
- seen.add(e.name);
587
- hits.push(alias == null ? {
588
- name: e.name,
589
- category: e.category,
590
- count: e.count
591
- } : {
592
- ...pick(e),
593
- alias
594
- });
595
- return hits.length >= limit;
596
- };
597
- for (const r of this.rows) if (r.name.startsWith(q) && take(r.e)) return hits;
598
- for (const r of this.rows) {
599
- const a = r.aliases.find((x) => x.startsWith(q));
600
- if (a != null && take(r.e, a)) return hits;
601
- }
602
- for (const r of this.rows) if (r.name.includes(`_${q}`) && take(r.e)) return hits;
603
- return hits;
604
- }
605
- };
606
- const pick = (e) => ({
607
- name: e.name,
608
- category: e.category,
609
- count: e.count
610
- });
611
- //#endregion
612
- //#region src/cli/serve/tagSource.ts
613
- /** http(s) stays a url; `file://`, `~/`, absolute and relative (to the workflow file) become a path */
614
- function resolveTagSource(url, moduleFile) {
615
- if (/^https?:\/\//i.test(url)) return {
616
- kind: "http",
617
- url
618
- };
619
- if (url.startsWith("file://")) return {
620
- kind: "file",
621
- path: fileURLToPath(url)
622
- };
623
- if (url === "~" || url.startsWith("~/")) return {
624
- kind: "file",
625
- path: join(homedir(), url.slice(1))
626
- };
627
- if (isAbsolute(url)) return {
628
- kind: "file",
629
- path: url
630
- };
631
- return {
632
- kind: "file",
633
- path: resolve(dirname(moduleFile), url)
634
- };
635
- }
636
- var TagSources = class {
637
- constructor(p) {
638
- this.p = p;
639
- this.files = /* @__PURE__ */ new Map();
640
- this.remote = /* @__PURE__ */ new Map();
641
- }
642
- async load(ref) {
643
- if (ref.kind === "file") return this.loadFile(ref.path);
644
- const hit = this.remote.get(ref.url);
645
- if (hit != null) return hit;
646
- const pending = this.loadRemote(ref.url);
647
- this.remote.set(ref.url, pending);
648
- pending.catch(() => this.remote.delete(ref.url));
649
- return pending;
650
- }
651
- loadFile(path) {
652
- if (!existsSync(path)) throw new Error(`tag list not found: ${path}`);
653
- const mtimeMs = statSync(path).mtimeMs;
654
- const cached = this.files.get(path);
655
- if (cached != null && cached.mtimeMs === mtimeMs) return cached.list;
656
- const list = TagList.parse(readFileSync(path, "utf8"));
657
- if (list.entries.length === 0) throw new Error(`tag list is empty: ${path}`);
658
- this.files.set(path, {
659
- mtimeMs,
660
- list
661
- });
662
- return list;
663
- }
664
- async loadRemote(url) {
665
- const file = join(this.p.cacheDir(), `${sha1HexOfString(url)}.txt`);
666
- if (existsSync(file)) return TagList.parse(readFileSync(file, "utf8"));
667
- console.log(`[serve] fetching tag list ${url}`);
668
- const text = await this.p.fetchText(url);
669
- const list = TagList.parse(text);
670
- if (list.entries.length === 0) throw new Error(`tag list is empty: ${url}`);
671
- mkdirSync(dirname(file), { recursive: true });
672
- writeFileSync(file, text);
673
- console.log(`[serve] tag list ${url}: ${list.entries.length} tags, kept in ${file}`);
674
- return list;
675
- }
676
- };
677
- //#endregion
678
- //#region src/cli/serve/favicon.ts
679
- const FAVICON_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAKUklEQVR42u1aaWxU1xW2DWEJZCENNgaK8iNRU5UAAYKBWW1ImwbaoqiuQkrUVlRdlDZSGpqAcTKrFyAoJRCRKmpRidKA98Sm0MQhRClOs7CIggiTtniZN4sZe8AeL/Puvef23LeMnwePQdWwhTnS9XvP8zzvft/5znfPfXJWViYykYlMZCITmchEJjKRiUxc4eCcj8ExFkfOzQg+23huvL5pwFNKf8wYexmvZ2m/H6cpQlHFV5IYIXvtaMEh4+CM83/hIS9ZGSOUSvYNnXUNyC3iGgA2KuAZ7+NqvI3jZ6iKp3GsIYQsw+sZOmFJZIy5Ec0uRzufhOMHjMGnGnAUAAdtJALUqxgwOIYs7UBCViFptycTekNkXcv4eMzsL/Hap2Pkw0MQQbTBkj/UbvDjj514ukQvh+uWCOPE8LgUpX7UAJxpY7QAzqh6b1+rzPslZuANvZMdIoR/3/CMMdfNcqqBVyZDOV+P53FV1kCNwCEFbi5uA/U2GjoI5MBsYJFPlTIBRqnxTxnAYTws056bc83VoAP3+XzjMUu7E8AZYRyIBkwreQDDuQBNlHMl7SwO5IvtIFdNAHr8GfUmhb9hJaOTKb71L7FYLN+40lwz8HicgODrtMmRlMkeIf2MxoH53wF6sAjI3vFA6/OA9ZwWAEFXRbI1aMoSdXFWlmXzNSFBb1q09bpGmxvRpU7P7AB6ZhvQ7qPA+kPA5Bhw0seY3Ass1g48/D6jp7wgN5sw65M5rbqNk6o7gDRbFVJUIUFq4phGAhfLKvmeNqexV63dNmR/hyZQYqx01lbNSP00kGvuBLnxXhhs+ibI+7/F5H3fALlhFpDaO4FU3QK0ZgqXa/G+uumM7EH5tzyh1QiDodUxlWsmlBAzKCFHm2B21pVqpAxO/Bt1AsOLVa9r2tsK5O8Pgbx3IsRr7gJScwcSMgXB5qLU84E2TMcjgq+9m+CR0KpJwA7/kCeMgolMj06CwRf+PSizXTJhf8Y/fQavc1N1munK/DwcF0YyeDV1qiDohdNAGu8TIBF4PiN1uaiMPAQ/DUhdHo6pEK/LpagWSpAcXAE4i0eHqUCQcEkvGZqDQsjeT/qPZi0+eVdCDene2OBTmgxLHb+IAM0SxJH4/ohynwRC6ghakKCBz0NScNTnIQE48DO55lYgrbvVr6CyAoxdhqnKuO7sOx6TPQ3R+GN/CA+aKy9w89Yem5hrcXHVmHRL/1GNarhUb6PcF+8C8rfZoGQYVYCAgdRPVbKvkFGfSxUS6vIJegaT92Mf0O/XyoCMaoh6C3m8dZDP39gOD6yXqGXTILe4g589/OzxSdrMs9OafTzWpcr+iFYlVHD4cYjvmYgZn0bluqlMrs0FMUh9Po+jF8j1+YzWTSNy/XRKqicD/fBRYINdWj+QmmeqOcDuf/TAvBI/FJWFwOwO1Fk2fvn1tMrfkP0ZCLx71OYuyaMUQ/zs17jOTxSARbZZvBalL4yxejKX944DuXq8MElGUAGk+nagb2YB3Xc/0NC7cKlHIQmw9vVOusgZ4csrAs8qsq8S800f+BwDASsuT/7DZUo/XoNgbwPSMFMtBQRNm+4B0rIa2KlNQFvfACY1qqPtLWA+7CE++SnQd+cCC7+n9pAouEQvCUPZP3hqkC0sDXKrR6JFXmm+mKfN8cHYtIB3OBy66+fh7u53uOae0vb17HLkr3phL7r7IrHmoxlOwPN5CHA7sL6AbnDDBhjNlA7g6OPDfgdDtR8bYPDEq520wBXhVm/wy4e3pLHu9SUP9+bfppQFjaiMk0iNX7UIFj7E4lWTUd63AzuxAWhimdPMTdkzEG1/oA1GeIpWWJW99uxtB87DnBK/XLSlVxDwmpq0NHSBuuHtbI7MiBMmac+ND8iMnuwYhM4LijsrE4GLcm7Y4QoYLY9TWj2JUalhaH2nRNn+jtblqJ8Nf3cCBuNrPjkABS9KYHJ2gMUT5uay0LK0LXs6i8srw+Z1ewd5eVOMr3urGx7bFmL4UPajV0LstBTXNuuqGgCSpyoSOQD0n08yFnpflbuyrDEY6a1Qyn7CEEQDf6JDhqKKECxxSsReHuUWT+QQTleXfXq7v7nPt5fPWe+Pzi/xxxe7OpnVE2AFpQFm9wbY20d62dBbi5RloTY06guP5DFi5kdShp75L4IEVmzthAJHAMRcrN5z3OYJP5LWpic5ntru/9qTlSdn2T2db1g39eIDA7LJJcGDJX72+z1drO2czBKvfy7yB9CrNjGM5qe1uhcN/TuMjn/k7CB8d0sYFqH0Le4AsW/u59ay0C5VtldqByi+WFsNbI72e23l0U5LWYSb3BKzugMwfyM2IOUB9sqBKAS6yTAnFxMXylCzOqyoRx3iXtz4c0L1P+PQdKwf1Sdh5hG8J0gs3m5u84Z9RWX/yUt7zz+CK2Yv+MXnyituuye41o4qMLkDFLsuZvMGweQKwtwNHbCsMsDKG6PsWBu+4UkycUGEAESTMs5GaHXVclIJO9/PwNsQhQWlaHhuAd5PLe4wWMvO9Vsc/7VeUeknh/4gm0tyFiIJZk+ImjEbZiQAywKWuPwwDxWx2CnBT14Lw58+7IGT/kGQaQqZM5UQNnLNw/4T/cJ44cGN6PQI3uTyM3wes1Vg9j3S6qGu7yqGTkKhq3WdvaKbmcu7uXDjpS6JCV+we0NgcQVgYWkA5pZICimrXw1DxTtRaDwaA18wDtjAsCQlGI0PPjozwH7++jnMekBZ6qweobIANXk6qb0iys3O1t9eE/AJErQH2zz+5ejAPmFGZndQEEBMeMTdmDApEOWBZaKAmLtBggUvIBi8XrklwNYiwOf3RMBV2wU73zsPcTLU8D21qxPuX9cGdqx5QSZ+JzF7z4HVG6EWl/9XaW13/09TyNZJWFHRNsXqkjZbPKE+++YYt3g7ccIBQQQ1aUQIEnDJQkLw3BmEpQ4/PFTqR2n7YfZz7XjeAYGonNDAX1su4ArTgWQpqiK2ivPY6ESiZkf7qusAvFEKSIK2/FjdHfcVYjuKkz5vq8SlUkwagSMAWRAiDNPsEhmVQBwFIVbF1ERtS9Di60+URPOpPrbwhQ6KpLJCQaoz8LnV3f7ANZX9qMtk8dD20+bwzbS7pOfMLv8RYVjWTQgAuzU0TI51jCRgD+EOyiYPkuLCFxi4muAKQkUp6AQ0Hu2nC51daHTBHqsr8OJKh3Tr9Qk+qX0uLh6aoDBLe3lHgd3d4UEgLWaPFLOWR3jhSwNclIoNX1tZUSXWcjyWdfECp8T2fNyDBknJ02/G+JySYH3xjrPT9O92OG6Q/yxRiEh6ISE2V49U+mYWlUmrcLkstTtbd1md/ibcwX2EajiEBnrMVBbBDs8vF3oCAyYkBZe6NQqRDj4u6wb9X4FsoQjVsFIA4HrZ8LHY1TUXbiXcUtHHbeWRTpvj7D1XvsO7qspw5NhsH4wVYB3KuwYNmAZw5UvS3bh8brW4gvvRKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII=";
680
- //#endregion
681
- //#region src/cli/serve/workflowTags.ts
682
- /** display order: what the workflow makes first, then how it works, then free tags */
683
- const MEDIA_BY_TYPE = {
684
- IMAGE: "image",
685
- AUDIO: "audio",
686
- VIDEO: "video",
687
- STRING: "text"
688
- };
689
- const MEDIA_ORDER = [
690
- "image",
691
- "audio",
692
- "video",
693
- "text"
694
- ];
695
- function workflowTags(p) {
696
- const byId = new Map(p.nodes.map((n) => [n.id, n]));
697
- const media = /* @__PURE__ */ new Set();
698
- for (const node of p.nodes) {
699
- if (!node.outputNode) continue;
700
- for (const [producerId, ix] of node.links) {
701
- const type = byId.get(producerId)?.outputTypes[ix];
702
- const tag = type == null ? void 0 : MEDIA_BY_TYPE[type];
703
- if (tag != null) media.add(tag);
704
- }
705
- }
706
- const out = MEDIA_ORDER.filter((t) => media.has(t));
707
- if (p.nodes.some((n) => /textgenerate/i.test(n.classType))) out.push("llm");
708
- if (p.varKinds.includes("image")) out.push("edit");
709
- for (const tag of p.extra ?? []) {
710
- const t = tag.trim().toLowerCase();
711
- if (t !== "" && !out.includes(t)) out.push(t);
712
- }
713
- return out;
714
- }
715
- //#endregion
716
- //#region src/cli/serve/workspaceLabels.ts
717
- function tilde(path, home) {
718
- if (home === "" || home === "/") return path;
719
- if (path === home) return "~";
720
- return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
721
- }
722
- function workspaceLabels(p) {
723
- const ws = p.workspace.replace(/\/+$/, "");
724
- const root = p.root.replace(/\/+$/, "");
725
- const rootLabel = root === ws ? "." : root.startsWith(`${ws}/`) ? root.slice(ws.length + 1) : tilde(root, p.home);
726
- return {
727
- workspace: {
728
- path: ws,
729
- label: tilde(ws, p.home)
730
- },
731
- root: {
732
- path: root,
733
- label: rootLabel
734
- }
735
- };
736
- }
737
- //#endregion
738
- //#region src/utils/stringMap.ts
739
- function stringMap(raw) {
740
- const out = {};
741
- if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
742
- for (const [k, v] of Object.entries(raw)) if (typeof v === "string") out[k] = v;
743
- }
744
- return out;
745
- }
746
- var ResultHistory = class {
747
- constructor(budgetBytes) {
748
- this.budgetBytes = budgetBytes;
749
- this.runs = [];
750
- this.blobs = /* @__PURE__ */ new Map();
751
- this.used = 0;
752
- }
753
- add(p) {
754
- this.remove(p.record.promptId);
755
- for (const b of p.blobs) {
756
- this.blobs.set(b.key, {
757
- bytes: b.bytes,
758
- contentType: b.contentType
759
- });
760
- this.used += b.bytes.byteLength;
761
- }
762
- const kept = {
763
- record: p.record,
764
- imageKeys: p.imageKeys,
765
- audioKeys: p.audioKeys,
766
- videoKeys: p.videoKeys ?? [],
767
- model3dKeys: p.model3dKeys ?? []
768
- };
769
- this.runs = [kept, ...this.runs];
770
- for (const dropped of this.runs.slice(50)) this.freeRun(dropped);
771
- this.runs = this.runs.slice(0, 50);
772
- this.evict();
773
- }
774
- blob(key) {
775
- return this.blobs.get(key) ?? null;
776
- }
777
- /** an output whose bytes were evicted lists with url null: the panel says it is gone */
778
- list() {
779
- return this.runs.map((k) => ({
780
- ...k.record,
781
- images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),
782
- audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),
783
- videos: (k.record.videos ?? []).map((a, ix) => this.withLiveUrl(a, k.videoKeys[ix])),
784
- models3d: (k.record.models3d ?? []).map((a, ix) => this.withLiveUrl(a, k.model3dKeys[ix]))
785
- }));
786
- }
787
- remove(promptId) {
788
- const hit = this.runs.find((k) => k.record.promptId === promptId);
789
- if (hit == null) return;
790
- this.freeRun(hit);
791
- this.runs = this.runs.filter((k) => k !== hit);
792
- }
793
- clear() {
794
- this.runs = [];
795
- this.blobs.clear();
796
- this.used = 0;
797
- }
798
- setBudget(bytes) {
799
- this.budgetBytes = bytes;
800
- this.evict();
801
- }
802
- usage() {
803
- return {
804
- usedBytes: this.used,
805
- budgetBytes: this.budgetBytes,
806
- outputs: this.blobs.size,
807
- runs: this.runs.length
808
- };
809
- }
810
- withLiveUrl(out, key) {
811
- if (key == null || this.blobs.has(key)) return out;
812
- return {
813
- ...out,
814
- url: null
815
- };
816
- }
817
- freeRun(k) {
818
- for (const key of [
819
- ...k.imageKeys,
820
- ...k.audioKeys,
821
- ...k.videoKeys,
822
- ...k.model3dKeys
823
- ]) {
824
- if (key == null) continue;
825
- const b = this.blobs.get(key);
826
- if (b == null) continue;
827
- this.used -= b.bytes.byteLength;
828
- this.blobs.delete(key);
829
- }
830
- }
831
- /** the NEWEST output always stays, even alone over budget: the run that just finished must
832
- * not reply with a url that already 404s */
833
- evict() {
834
- while (this.used > this.budgetBytes && this.blobs.size > 1) {
835
- const oldest = this.blobs.entries().next();
836
- if (oldest.done === true) break;
837
- this.used -= oldest.value[1].bytes.byteLength;
838
- this.blobs.delete(oldest.value[0]);
839
- }
840
- this.runs = this.runs.filter((k) => {
841
- const live = (keys) => keys.some((key) => key == null || this.blobs.has(key));
842
- const hasText = k.record.texts.length > 0;
843
- const hasNothing = k.record.images.length === 0 && k.record.audios.length === 0 && (k.record.videos ?? []).length === 0 && (k.record.models3d ?? []).length === 0;
844
- return hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys) || live(k.model3dKeys);
845
- });
846
- }
847
- };
848
- //#endregion
849
- //#region src/cli/serve/serveSettings.ts
850
- const DEFAULT_SERVE_SETTINGS = {
851
- saveToDisk: true,
852
- hostOverride: {},
853
- savePrefix: {},
854
- memoryBudgetMb: 100
855
- };
856
- /** null = not a budget. A hand-written file goes through the same gate as PUT /settings */
857
- function validMemoryBudgetMb(raw) {
858
- if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
859
- if (raw < 1 || raw > 1e5) return null;
860
- return Math.round(raw);
861
- }
862
- /** null when no comfyts is registered yet: a ServeApp can be constructed before the global
863
- * exists (tests do), and reading a setting must degrade to defaults, never throw */
864
- function settingsPath() {
865
- const path = globalThis.comfyts?.settingsPath;
866
- return typeof path === "string" ? path : null;
867
- }
868
- /** `readable: false` says the file EXISTS but could not be parsed — the one case where a write
869
- * must refuse. Merging onto `{}` there would rewrite the file from nothing and take the TUI's
870
- * keys with it, and these files are documented as hand-editable, so the user would lose the
871
- * chance to repair it. */
872
- function readBlob() {
873
- const path = settingsPath();
874
- if (path == null || !existsSync(path)) return {
875
- blob: {},
876
- readable: true
877
- };
878
- try {
879
- const parsed = JSON.parse(readFileSync(path, "utf8"));
880
- const ok = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
881
- if (!ok) console.error(`[serve] settings is not an object (${path}), using defaults`);
882
- return {
883
- blob: ok ? parsed : {},
884
- readable: ok
885
- };
886
- } catch (e) {
887
- console.error(`[serve] settings unreadable (${path}), using defaults:`, e);
888
- return {
889
- blob: {},
890
- readable: false
891
- };
892
- }
893
- }
894
- /** keeps the CLEANED value, not the raw one: storing the raw form let the same input mean two
895
- * different directories depending on whether it arrived by PUT or by hand */
896
- function cleanValues(map, clean) {
897
- const out = {};
898
- for (const [k, v] of Object.entries(map)) {
899
- const ok = clean(v);
900
- if (ok != null) out[k] = ok;
901
- }
902
- return out;
903
- }
904
- function readServeSettings() {
905
- const serve = readBlob().blob.serve;
906
- const o = typeof serve === "object" && serve !== null ? serve : {};
907
- return {
908
- saveToDisk: typeof o.saveToDisk === "boolean" ? o.saveToDisk : DEFAULT_SERVE_SETTINGS.saveToDisk,
909
- hostOverride: stringMap(o.hostOverride),
910
- savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix),
911
- memoryBudgetMb: validMemoryBudgetMb(o.memoryBudgetMb) ?? DEFAULT_SERVE_SETTINGS.memoryBudgetMb
912
- };
913
- }
914
- function writeServeSettings(next) {
915
- const path = settingsPath();
916
- if (path == null) throw new Error("no comfyts instance registered — cannot persist serve settings");
917
- const current = readBlob();
918
- 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`);
919
- mkdirSync(dirname(path), { recursive: true });
920
- writeFileSync(path, JSON.stringify({
921
- ...current.blob,
922
- serve: next
923
- }, null, 2));
924
- }
925
- //#endregion
926
- //#region src/cli/serve/runError.ts
927
- function describeRunError(error) {
928
- if (error == null) return "execution failed";
929
- if (typeof error === "string") return error;
930
- if (error instanceof Error) return error.message;
931
- if (typeof error === "object") {
932
- const data = error.data;
933
- if (typeof data === "object" && data !== null) {
934
- const d = data;
935
- if (typeof d.exception_message === "string") return `${typeof d.node_type === "string" ? `${d.node_type} (node ${String(d.node_id)}): ` : ""}${typeof d.exception_type === "string" && d.exception_type !== "" ? `${d.exception_type}: ` : ""}${d.exception_message.trim()}`;
936
- }
937
- }
938
- try {
939
- return JSON.stringify(error);
940
- } catch {
941
- return String(error);
942
- }
943
- }
944
- //#endregion
945
- //#region src/cli/serve/web/state/draftTabs.ts
946
- /** where the serve process keeps them, under .comfy-ts/: draft names are private, so this file
947
- * must stay gitignored (tests/serve-tabs.test.ts runs git check-ignore on it) */
948
- const SERVE_TABS_FILE = "serve-tabs.json";
949
- const same = (a, b) => a.module === b.module && a.draft === b.draft;
950
- /** a stored list, shape-checked, keeping only drafts that still exist */
951
- function readTabs(raw, modules) {
952
- if (!Array.isArray(raw)) return [];
953
- const out = [];
954
- for (const x of raw) {
955
- if (x == null || typeof x !== "object") continue;
956
- const o = x;
957
- if (typeof o.module !== "string" || typeof o.draft !== "string") continue;
958
- const t = {
959
- module: o.module,
960
- draft: o.draft
961
- };
962
- if (!modules.some((m) => m.module === t.module && m.drafts.includes(t.draft))) continue;
963
- if (!out.some((y) => same(y, t))) out.push(t);
964
- }
965
- return out;
966
- }
967
- //#endregion
968
- //#region src/cli/serve/ServeApp.ts
969
- /** what serve will read off the disk and upload, per medium. Wider than the picker defaults:
970
- * ComfyUI's LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
971
- const SERVE_MEDIA_FLOOR = {
972
- image: /* @__PURE__ */ new Set([
973
- ...DEFAULT_MEDIA_EXTENSIONS.image,
974
- "bmp",
975
- "tif",
976
- "tiff",
977
- "avif"
978
- ]),
979
- audio: /* @__PURE__ */ new Set([...DEFAULT_MEDIA_EXTENSIONS.audio, "aac"]),
980
- video: /* @__PURE__ */ new Set([...DEFAULT_MEDIA_EXTENSIONS.video, "avi"])
981
- };
982
- /** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops
983
- * a .png that holds a key or a script from being read and uploaded to the host.
984
- * HONEST LIMIT: this is checked before the run, and the file is read again when the graph
985
- * builds, so a local writer who can swap the path in between still wins. Closing that needs
986
- * the upload to hold an fd, which is a bigger change than this gate. */
987
- function looksLikeMedia(kind, path) {
988
- let fd = null;
989
- try {
990
- fd = openSync(path, "r");
991
- const head = /* @__PURE__ */ new Uint8Array(16);
992
- const n = readSync(fd, head, 0, 16, 0);
993
- return isMediaMagic(kind, head.subarray(0, n));
994
- } catch {
995
- return false;
996
- } finally {
997
- if (fd != null) closeSync(fd);
998
- }
999
- }
1000
- /** what `POST /generate` will read off this machine and upload to a ComfyUI host. A var's own
1001
- * `extensions` is documented as a PICKER filter that never affects the value, so it cannot be
1002
- * the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able
1003
- * to widen what an unauthenticated request can make the server read. The var may narrow this
1004
- * floor, never leave it. */
1005
- function serveAcceptsMediaExt(kind, declared, ext) {
1006
- const floor = SERVE_MEDIA_FLOOR[kind];
1007
- if (ext === "") return false;
1008
- if (!floor.has(ext)) return false;
1009
- const narrowed = declared.map((e) => e.toLowerCase().replace(/^\./, "")).filter((e) => floor.has(e));
1010
- return narrowed.length === 0 || narrowed.includes(ext);
1011
- }
1012
- /** an image var pointing at a url downloads it: capped, because the inbound BODY cap does not
1013
- * apply to what serve fetches on your behalf, and one url at a big file would OOM the process */
1014
- var DownloadRefused = class extends Error {
1015
- constructor(url) {
1016
- super(`could not fetch ${url}`);
1017
- this.name = "DownloadRefused";
1018
- }
1019
- };
1020
- const INPUT_DOWNLOAD_CAP = 5e7;
1021
- const INPUT_DOWNLOAD_TIMEOUT_MS = 6e4;
1022
- /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
1023
- const TAG_LIST_CAP = 4e7;
1024
- const TAG_LIST_TIMEOUT_MS = 12e4;
1025
- const MB = 1024 * 1024;
1026
- /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
1027
- * whole body first, so a chunked reply with no content-length could exhaust the process before
1028
- * anything checked its size, the cap then reported a number nobody survived to read. */
1029
- async function readCapped(res, cap, what) {
1030
- const body = res.body;
1031
- if (body == null) return /* @__PURE__ */ new Uint8Array(0);
1032
- const reader = body.getReader();
1033
- const chunks = [];
1034
- let total = 0;
1035
- try {
1036
- for (;;) {
1037
- const step = await reader.read();
1038
- if (step.done) break;
1039
- total += step.value.length;
1040
- if (total > cap) {
1041
- await reader.cancel();
1042
- throw new Error(`download too large (over ${cap} bytes): ${what}`);
1043
- }
1044
- chunks.push(step.value);
1045
- }
1046
- } finally {
1047
- reader.releaseLock();
1048
- }
1049
- const out = new Uint8Array(total);
1050
- let at = 0;
1051
- for (const c of chunks) {
1052
- out.set(c, at);
1053
- at += c.length;
1054
- }
1055
- return out;
1056
- }
1057
- /** the panel is REBUILT per serve process, so a cached copy is always the wrong one. With no
1058
- * cache header at all a browser applies heuristic freshness and reuses app.js across reloads,
1059
- * which makes every fix look like it never landed */
1060
- const NO_STORE = { "cache-control": "no-store, must-revalidate" };
1061
- /** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.
1062
- * serve OPTS INTO local saving (library default is memory-only, architecture.md
1063
- * item 14): the /outputs/ routes serve files, grouped per module */
1064
- const realStarter = async (mod, opts) => {
1065
- const host = opts.host ?? mod.dw.host;
1066
- await host.connect();
1067
- return await (await mod.dw.build({
1068
- advance: true,
1069
- host
1070
- })).start({
1071
- save: opts.saveToDisk ? { prefix: opts.savePrefix } : false,
1072
- onPreview: opts.onPreview
1073
- });
1074
- };
1075
- const CONTENT_TYPES = {
1076
- ".png": "image/png",
1077
- ".jpg": "image/jpeg",
1078
- ".jpeg": "image/jpeg",
1079
- ".webp": "image/webp",
1080
- ".gif": "image/gif",
1081
- ".mp4": "video/mp4",
1082
- ".webm": "video/webm",
1083
- ".m4v": "video/mp4",
1084
- ".mov": "video/quicktime",
1085
- ".mkv": "video/x-matroska",
1086
- ".avi": "video/x-msvideo",
1087
- ".aac": "audio/aac",
1088
- ".flac": "audio/flac",
1089
- ".mp3": "audio/mpeg",
1090
- ".opus": "audio/ogg",
1091
- ".ogg": "audio/ogg",
1092
- ".wav": "audio/wav",
1093
- ".m4a": "audio/mp4",
1094
- ".json": "application/json",
1095
- ".txt": "text/plain",
1096
- ...Object.fromEntries(Object.entries(MODEL_3D_MIMES).map(([ext, mime]) => [`.${ext}`, mime]))
1097
- };
1098
- /** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
1099
- function sniffImageContentType(bytes) {
1100
- if (bytes[0] === 137 && bytes[1] === 80) return "image/png";
1101
- if (bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
1102
- if (bytes[0] === 71 && bytes[1] === 73) return "image/gif";
1103
- if (bytes[0] === 82 && bytes[1] === 73) return "image/webp";
1104
- return "application/octet-stream";
1105
- }
1106
- /** the FULL signature, not the first two bytes: `RI` alone matched a wav renamed .webp, and a
1107
- * two-byte file matched png. bmp/tiff/avif are here because the floor accepts them */
1108
- function isImageMagic(b) {
1109
- const at = (i, ...want) => want.every((w, k) => b[i + k] === w);
1110
- if (at(0, 137, 80, 78, 71, 13, 10, 26, 10)) return true;
1111
- if (at(0, 255, 216, 255)) return true;
1112
- if (at(0, 71, 73, 70, 56)) return true;
1113
- if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return true;
1114
- if (at(0, 66, 77)) return true;
1115
- if (at(0, 73, 73, 42, 0) || at(0, 77, 77, 0, 42)) return true;
1116
- if (at(4, 102, 116, 121, 112)) return true;
1117
- return false;
1118
- }
1119
- /** the same full-signature sniff for every medium: a var of one kind never reads a file of
1120
- * another. mp4, mov and m4a share the isobmff `ftyp` box, the extension floor tells them apart */
1121
- function isMediaMagic(kind, b) {
1122
- const at = (i, ...want) => want.every((w, k) => b[i + k] === w);
1123
- const isobmff = at(4, 102, 116, 121, 112);
1124
- if (kind === "image") return isImageMagic(b);
1125
- if (kind === "audio") {
1126
- if (at(0, 82, 73, 70, 70) && at(8, 87, 65, 86, 69)) return true;
1127
- if (at(0, 102, 76, 97, 67)) return true;
1128
- if (at(0, 79, 103, 103, 83)) return true;
1129
- if (at(0, 73, 68, 51)) return true;
1130
- const b0 = b[0];
1131
- const b1 = b[1];
1132
- const b2 = b[2];
1133
- if (b0 === 255 && b1 != null && b1 !== 254 && b2 != null && (b1 & 224) === 224 && (b1 & 24) !== 8 && (b1 & 6) !== 0 && b2 >> 4 !== 15 && (b2 >> 2 & 3) !== 3) return true;
1134
- if (b0 === 255 && b1 != null && (b1 & 246) === 240) return true;
1135
- return isobmff;
1136
- }
1137
- if (at(0, 26, 69, 223, 163)) return true;
1138
- if (at(0, 82, 73, 70, 70) && at(8, 65, 86, 73, 32)) return true;
1139
- return isobmff;
1140
- }
1141
- function isMediaKind(kind) {
1142
- return MEDIA_KINDS.includes(kind);
1143
- }
1144
- function json(status, payload) {
1145
- return {
1146
- status,
1147
- contentType: "application/json",
1148
- body: JSON.stringify(payload, null, 2)
1149
- };
1150
- }
1151
- const USAGE = [
1152
- "GET / in a browser — web control panel (every var as a form control)",
1153
- "GET /drafts — every served workflow, its drafts and var descriptors",
1154
- "GET /drafts/<module>/<draft> — one draft with its stored values",
1155
- "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
1156
- "POST /generate/<draft> — unqualified, when unambiguous",
1157
- "POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run",
1158
- "PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
1159
- "DELETE /drafts/<module>/<draft> — delete that draft file",
1160
- "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
1161
- "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image, audio or video var",
1162
- "GET /images|audio|video|model3d/<promptId>/<ix> — an output kept in memory (saving off)",
1163
- "GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)",
1164
- "GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)",
1165
- "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
1166
- "POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror",
1167
- "GET /lora-preview/<hostId>/<lora> — preview image bytes",
1168
- "GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
1169
- "GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
1170
- "PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
1171
- "GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)",
1172
- "PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>",
1173
- "GET /settings — { saveToDisk, memoryBudgetMb } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory; {\"memoryBudgetMb\"} caps what memory keeps",
1174
- "GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere",
1175
- "POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host",
1176
- "GET /hosts/<hostId>/ping — is that host answering right now (restart watch)",
1177
- "GET /hosts/<hostId>/logs — the last lines of that host console",
1178
- "GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives",
1179
- "GET /audio/<promptId>/<ix> — the same for an in-memory audio output",
1180
- "GET /results — the last runs this process kept, for a reload · DELETE /results[/<promptId>] — forget them, freeing their memory",
1181
- "GET /outputs/<path> — generated files"
1182
- ];
1183
- /** content hash of the bundle, so the script URL CHANGES whenever the code does. no-store
1184
- * alone does not help a browser that already has app.js cached under a plain url, and a panel
1185
- * running stale javascript is indistinguishable from a broken fix */
1186
- function buildId(js) {
1187
- let h = 5381;
1188
- for (let i = 0; i < js.length; i++) h = (h << 5) + h + js.charCodeAt(i) | 0;
1189
- return (h >>> 0).toString(36);
1190
- }
1191
- /** the html shell; the app itself is ONE bundle at /web/app.js */
1192
- const WEB_SHELL = `<!doctype html>
1193
- <html lang="en">
1194
- <head>
1195
- <meta charset="utf-8">
1196
- <meta name="viewport" content="width=device-width, initial-scale=1">
1197
- <title>comfy-ts serve</title>
1198
- <link rel="icon" type="image/png" href="${FAVICON_DATA_URI}">
1199
- <style>html{background:#101217;color:#e8eaf0}</style>
1200
- </head>
1201
- <body>
1202
- <div id="root"></div>
1203
- <script type="module" src="/web/app.js?v=__BUILD__"><\/script>
1204
- </body>
1205
- </html>
1206
- `;
1207
- var ServeApp = class {
1208
- get settings() {
1209
- this.settingsCache ??= readServeSettings();
1210
- return this.settingsCache;
1211
- }
1212
- set settings(next) {
1213
- this.settingsCache = next;
1214
- }
1215
- get kept() {
1216
- this.keptCache ??= new ResultHistory(this.settings.memoryBudgetMb * MB);
1217
- return this.keptCache;
1218
- }
1219
- constructor(modules, opts = {}) {
1220
- this.modules = modules;
1221
- this.opts = opts;
1222
- this.seedState = /* @__PURE__ */ new Map();
1223
- this.chains = /* @__PURE__ */ new Map();
1224
- this.settingsCache = null;
1225
- this.keptCache = null;
1226
- this.tagsByModule = /* @__PURE__ */ new Map();
1227
- this.thumbs = new ThumbStore();
1228
- this.tabs = null;
1229
- this.tagSources = new TagSources({
1230
- cacheDir: () => join(comfyts.baseFolder, "cache", "tags"),
1231
- fetchText: async (url) => {
1232
- const res = await fetch(url, {
1233
- redirect: "follow",
1234
- signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS)
1235
- });
1236
- if (!res.ok) throw new Error(`tag list download failed (http ${res.status}): ${url}`);
1237
- return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url));
1238
- }
1239
- });
1240
- this.liveRuns = /* @__PURE__ */ new Map();
1241
- this.latentPreviews = /* @__PURE__ */ new Map();
1242
- this.latentSeq = 0;
1243
- this.previewSweeps = /* @__PURE__ */ new Map();
1244
- this.starter = opts.starter ?? realStarter;
1245
- }
1246
- get outputRoot() {
1247
- return this.opts.outputRoot ?? comfyts.outputPath;
1248
- }
1249
- async handle(req) {
1250
- try {
1251
- const path = (req.url.split("?")[0] ?? "/").split("#")[0] ?? "/";
1252
- let segs;
1253
- try {
1254
- segs = path.split("/").filter((s) => s !== "").map(decodeURIComponent);
1255
- } catch {
1256
- return json(400, { error: `bad url encoding: ${path}` });
1257
- }
1258
- if (req.method === "GET") {
1259
- if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
1260
- const js = await this.opts.webJs();
1261
- if (js != null) return {
1262
- status: 200,
1263
- contentType: "text/html; charset=utf-8",
1264
- body: WEB_SHELL.replace("__BUILD__", buildId(js)),
1265
- headers: NO_STORE
1266
- };
1267
- }
1268
- if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return await this.replyIndex();
1269
- if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2) return await this.replyWebJs();
1270
- if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
1271
- if (segs[0] === "run" && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1]);
1272
- if (segs[0] === "run" && segs.length === 3 && segs[1] != null && segs[2] === "preview") return this.replyRunPreview(segs[1]);
1273
- if (segs[0] === "lora-info" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyLoraInfo(segs[1], segs[2]);
1274
- if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
1275
- if (segs[0] === "lora-about" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraAbout(segs[1], segs[2]);
1276
- if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
1277
- if (segs[0] === "llm-configs" && segs.length === 1) return this.replyLlmConfigs();
1278
- if (segs[0] === "tags" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyTags(segs[1], segs[2], req.url);
1279
- if (segs[0] === "settings" && segs.length === 1) return this.replySettings();
1280
- if (segs[0] === "thumb" && segs.length === 1) return await this.replyThumb(req.url);
1281
- if (segs[0] === "tabs" && segs.length === 1) return this.replyTabs();
1282
- if (segs[0] === "hosts" && segs.length === 1) return this.replyHosts();
1283
- if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs") return await this.replyHostLogs(segs[1]);
1284
- if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "ping") return await this.replyHostPing(segs[1]);
1285
- if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "drift") return await this.replyHostDrift(segs[1], req.url.includes("full=1"));
1286
- if (segs[0] === "images" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`${segs[1]}/${segs[2]}`);
1287
- if (segs[0] === "audio" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`);
1288
- if (segs[0] === "video" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`video/${segs[1]}/${segs[2]}`);
1289
- if (segs[0] === "model3d" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`model3d/${segs[1]}/${segs[2]}`);
1290
- if (segs[0] === "results" && segs.length === 1) return json(200, {
1291
- runs: this.kept.list(),
1292
- memory: this.kept.usage()
1293
- });
1294
- if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
1295
- return json(404, {
1296
- error: `no route: GET ${path}`,
1297
- usage: USAGE
1298
- });
1299
- }
1300
- if (req.method === "POST" && segs[0] === "generate") {
1301
- const target = this.resolveDraft(segs.slice(1));
1302
- if ("error" in target) return json(target.status, { error: target.error });
1303
- return await this.generate(target.mod, target.draft, req);
1304
- }
1305
- if (req.method === "POST" && segs[0] === "preview" && segs.length === 2 && segs[1] != null) return await this.replyPreview(segs[1], req);
1306
- if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
1307
- 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);
1308
- if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
1309
- if (req.method === "PUT" && segs[0] === "settings" && segs.length === 1) return this.replySaveSettings(req);
1310
- if (req.method === "DELETE" && segs[0] === "results" && segs.length <= 2) {
1311
- if (segs[1] == null) this.kept.clear();
1312
- else this.kept.remove(segs[1]);
1313
- return json(200, { memory: this.kept.usage() });
1314
- }
1315
- if (req.method === "PUT" && segs[0] === "tabs" && segs.length === 1) return this.replySaveTabs(req);
1316
- if (req.method === "PUT" && segs[0] === "hosts" && segs.length === 2 && segs[1] != null) return this.replySetHost(segs[1], req);
1317
- if (req.method === "POST" && segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyHostAction(segs[1], segs[2]);
1318
- 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]);
1319
- if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
1320
- if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
1321
- if (req.method === "PUT" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replySaveLlmConfig(segs[1], req);
1322
- if (req.method === "DELETE" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replyDeleteLlmConfig(segs[1]);
1323
- return json(404, {
1324
- error: `no route: ${req.method} ${path}`,
1325
- usage: USAGE
1326
- });
1327
- } catch (e) {
1328
- console.error("[serve] request crashed:", e);
1329
- return json(500, { error: extractErrorMessage(e) });
1330
- }
1331
- }
1332
- moduleByKey(key) {
1333
- return this.modules.find((m) => m.key === key) ?? null;
1334
- }
1335
- /** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
1336
- draftsFor(mod) {
1337
- return ["default", ...listDraftsForFile(mod.file).filter((n) => n !== "default")];
1338
- }
1339
- /** THE draft-name gate, shared by every route that turns a url segment into a path
1340
- * (safeName.ts owns the rule, the prompt-enhancer routes call the same function) */
1341
- validDraftName(raw) {
1342
- return validStoreName(raw);
1343
- }
1344
- /** absolute path of a draft file, or null when the name is not one we accept */
1345
- draftPath(mod, draft) {
1346
- const name = this.validDraftName(draft);
1347
- return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`);
1348
- }
1349
- draftExists(mod, draft) {
1350
- const path = this.draftPath(mod, draft);
1351
- if (path == null) return false;
1352
- return draft === "default" || existsSync(path);
1353
- }
1354
- resolveDraft(segs) {
1355
- if (segs.length === 2 && segs[0] != null && segs[1] != null) {
1356
- const mod = this.moduleByKey(segs[0]);
1357
- if (mod == null) return {
1358
- status: 404,
1359
- error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(", ")}`
1360
- };
1361
- if (!this.draftExists(mod, segs[1])) return {
1362
- status: 404,
1363
- error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(", ")}`
1364
- };
1365
- return {
1366
- mod,
1367
- draft: segs[1]
1368
- };
1369
- }
1370
- if (segs.length === 1 && segs[0] != null) {
1371
- const draft = segs[0];
1372
- if (this.modules.length === 1 && this.modules[0] != null) {
1373
- const mod = this.modules[0];
1374
- if (!this.draftExists(mod, draft)) return {
1375
- status: 404,
1376
- error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
1377
- };
1378
- return {
1379
- mod,
1380
- draft
1381
- };
1382
- }
1383
- const hits = this.modules.filter((m) => this.draftExists(m, draft));
1384
- if (hits.length === 1 && hits[0] != null) return {
1385
- mod: hits[0],
1386
- draft
1387
- };
1388
- if (hits.length === 0) return {
1389
- status: 404,
1390
- error: `no module has a draft '${draft}'`
1391
- };
1392
- return {
1393
- status: 400,
1394
- error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(" or ")}`
1395
- };
1396
- }
1397
- return {
1398
- status: 400,
1399
- error: "use POST /generate/<module>/<draft> or /generate/<draft>"
1400
- };
1401
- }
1402
- /** the pictures of a descriptor made concrete for the page: a local thumb or preset becomes a
1403
- * /thumb url the store allows, a local preset not on this machine is flagged missing, a url
1404
- * stays as it is. Relative paths are relative to the workflow file */
1405
- decorateLooks(desc, mod) {
1406
- const dir = dirname(mod.file);
1407
- this.thumbs.allowRoot(dir);
1408
- this.thumbs.allowRoot(this.outputRoot);
1409
- const local = (p) => isAbsolute(p) ? p : resolve(dir, p);
1410
- const options = desc.ui?.options;
1411
- if (desc.ui != null && options != null) {
1412
- const looks = {};
1413
- for (const [value, look] of Object.entries(options)) {
1414
- if (look.thumb == null || isHttpUrl(look.thumb)) {
1415
- looks[value] = look;
1416
- continue;
1417
- }
1418
- const abs = local(look.thumb);
1419
- this.thumbs.allow(abs);
1420
- looks[value] = {
1421
- ...look,
1422
- thumb: thumbUrl(abs, 128)
1423
- };
1424
- }
1425
- desc.ui = {
1426
- ...desc.ui,
1427
- options: looks
1428
- };
1429
- }
1430
- if (desc.mediaPresets != null) desc.mediaPresets = desc.mediaPresets.map((preset) => {
1431
- if (isHttpUrl(preset.value)) {
1432
- const cached = this.urlInputPath(preset.value, basename(new URL(preset.value).pathname));
1433
- return {
1434
- ...preset,
1435
- thumb: existsSync(cached) ? thumbUrl(cached, 160) : preset.value
1436
- };
1437
- }
1438
- const abs = local(preset.value);
1439
- this.thumbs.allow(abs);
1440
- return existsSync(abs) ? {
1441
- ...preset,
1442
- value: abs,
1443
- thumb: thumbUrl(abs, 160)
1444
- } : {
1445
- ...preset,
1446
- value: abs,
1447
- missing: true
1448
- };
1449
- });
1450
- if (MEDIA_KINDS.includes(desc.kind) && typeof desc.default === "string" && desc.default !== "") {
1451
- if (!isHttpUrl(desc.default)) this.thumbs.allow(local(desc.default));
1452
- }
1453
- }
1454
- async replyThumb(url) {
1455
- const q = new URLSearchParams(url.split("?")[1] ?? "");
1456
- const src = q.get("src");
1457
- if (src == null || src === "") return json(400, { error: "thumb needs ?src=<local path>" });
1458
- const out = await this.thumbs.render(src, Number(q.get("w") ?? 160) || 160);
1459
- if (out === "forbidden") return json(403, { error: "not a picture a served workflow declared, nor under its folder or the outputs" });
1460
- if (out === "missing") return json(404, { error: "not on this machine" });
1461
- return {
1462
- status: 200,
1463
- contentType: "image/webp",
1464
- body: out,
1465
- headers: { "cache-control": "max-age=300" }
1466
- };
1467
- }
1468
- describeModule(mod) {
1469
- refreshLoraInfoCacheIfChanged();
1470
- const hostId = mod.dw.host.data.id;
1471
- const vars = {};
1472
- for (const [name, varDef] of mod.dw.entries()) {
1473
- const desc = describeVar(varDef);
1474
- this.decorateLooks(desc, mod);
1475
- if (desc.kind === "loras" && desc.options != null) {
1476
- const labels = {};
1477
- for (const option of desc.options) {
1478
- const label = getLoraDisplayName(option, hostId);
1479
- if (label !== option) labels[option] = label;
1480
- }
1481
- if (Object.keys(labels).length > 0) desc.optionLabels = labels;
1482
- const extras = managerOnlyLoraOptions({
1483
- hostId,
1484
- options: desc.options,
1485
- filter: varDef.optionsFilter
1486
- });
1487
- if (extras.length > 0) {
1488
- desc.managerOnlyOptions = extras;
1489
- desc.options = [...desc.options, ...extras];
1490
- for (const extra of extras) {
1491
- const label = getLoraDisplayName(extra, hostId);
1492
- if (label !== extra) (desc.optionLabels ??= {})[extra] = label;
1493
- }
1494
- }
1495
- const keywords = {};
1496
- for (const option of desc.options) {
1497
- const kw = getLoraKeyword(option, hostId);
1498
- if (kw !== "") keywords[option] = kw;
1499
- }
1500
- if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords;
1501
- const addedAt = {};
1502
- for (const option of desc.options) {
1503
- const t = getLoraAddedAt(option, hostId);
1504
- if (t != null) addedAt[option] = t;
1505
- }
1506
- if (Object.keys(addedAt).length > 0) desc.optionAddedAt = addedAt;
1507
- const triggers = {};
1508
- for (const option of desc.options) {
1509
- const t = getLoraTriggers(option, hostId);
1510
- if (t != null) triggers[option] = t;
1511
- }
1512
- if (Object.keys(triggers).length > 0) desc.optionTriggers = triggers;
1513
- }
1514
- vars[name] = desc;
1515
- }
1516
- for (const [name, varDef] of mod.dw.entries()) {
1517
- if (varDef.kind !== "prompt") continue;
1518
- const source = varDef.promptOpts.loraKeywordsFrom;
1519
- if (source == null) continue;
1520
- const sourceName = mod.dw.entries().find(([, other]) => other === source)?.[0];
1521
- const desc = vars[name];
1522
- if (sourceName != null && desc != null) desc.keywordsFrom = sourceName;
1523
- }
1524
- return {
1525
- module: mod.key,
1526
- file: mod.file,
1527
- host: mod.dw.host.data.id,
1528
- drafts: this.draftsFor(mod),
1529
- routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
1530
- vars,
1531
- previews: Object.keys(mod.dw.spec.previews ?? {}),
1532
- tags: this.tagsByModule.get(mod.key) ?? mod.dw.spec.tags ?? []
1533
- };
1534
- }
1535
- async tagsFor(mod) {
1536
- const known = this.tagsByModule.get(mod.key);
1537
- if (known != null) return known;
1538
- const extra = mod.dw.spec.tags ?? [];
1539
- const varKinds = mod.dw.entries().map(([, varDef]) => varDef.kind);
1540
- let tags;
1541
- try {
1542
- tags = workflowTags({
1543
- nodes: (await mod.dw.build({ dry: true })).nodes.map((n) => ({
1544
- id: n.uid,
1545
- classType: n.json.class_type,
1546
- outputNode: n.$schema.raw.output_node,
1547
- outputTypes: n.$schema.outputs.map((o) => o.typeName),
1548
- links: Object.values(n.json.inputs).flatMap((v) => Array.isArray(v) && v.length === 2 && typeof v[1] === "number" ? [[String(v[0]), v[1]]] : [])
1549
- })),
1550
- varKinds,
1551
- extra
1552
- });
1553
- } catch (e) {
1554
- console.error(`[serve] 🔴 tags for ${mod.key}: dry build failed, spec tags only: ${extractErrorMessage(e)}`);
1555
- tags = workflowTags({
1556
- nodes: [],
1557
- varKinds,
1558
- extra
1559
- });
1560
- }
1561
- this.tagsByModule.set(mod.key, tags);
1562
- return tags;
1563
- }
1564
- async replyIndex() {
1565
- for (const m of this.modules) await this.tagsFor(m);
1566
- return json(200, {
1567
- server: "comfy-ts serve",
1568
- usage: USAGE,
1569
- workflows: this.modules.map((m) => this.describeModule(m)),
1570
- ...this.opts.workspace == null ? {} : workspaceLabels({
1571
- workspace: this.opts.workspace,
1572
- root: this.opts.root ?? this.opts.workspace,
1573
- home: process.env.HOME ?? ""
1574
- }),
1575
- ...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
1576
- });
1577
- }
1578
- replyDraft(modKey, draft) {
1579
- const mod = this.moduleByKey(modKey);
1580
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
1581
- if (!this.draftExists(mod, draft)) return json(404, { error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}` });
1582
- return json(200, {
1583
- ...this.describeModule(mod),
1584
- draft,
1585
- values: this.draftValues(mod, draft)
1586
- });
1587
- }
1588
- /** the workflow's previews for the values the panel holds right now. The vars are SHARED
1589
- * state (a run reads them), so this runs under the module lock: load the values, compute,
1590
- * put the old values back. Nothing is queued, nothing is written */
1591
- async replyPreview(key, req) {
1592
- const mod = this.moduleByKey(key);
1593
- if (mod == null) return json(404, { error: `unknown workflow '${key}'` });
1594
- let values;
1595
- try {
1596
- values = JSON.parse(req.body ?? "{}");
1597
- } catch (e) {
1598
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1599
- }
1600
- if (values == null || typeof values !== "object" || Array.isArray(values)) return json(400, { error: "expects { \"<var>\": value, … }" });
1601
- const incoming = values;
1602
- return json(200, { previews: await this.exclusive(mod.key, () => {
1603
- const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()]);
1604
- try {
1605
- for (const [k, v] of mod.dw.entries()) if (k in incoming) v.loadJSON(incoming[k]);
1606
- return Promise.resolve(mod.dw.computePreviews());
1607
- } finally {
1608
- const byName = new Map(mod.dw.entries());
1609
- for (const [k, json] of saved) byName.get(k)?.loadJSON(json);
1610
- }
1611
- }) });
1612
- }
1613
- /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
1614
- draftValues(mod, draft) {
1615
- const path = this.draftPath(mod, draft);
1616
- if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
1617
- const out = {};
1618
- for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default;
1619
- return out;
1620
- }
1621
- replyOutput(segs) {
1622
- const abs = resolve(this.outputRoot, ...segs);
1623
- if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + "/")) return json(400, { error: "path escapes the outputs root" });
1624
- if (!existsSync(abs) || !statSync(abs).isFile()) return json(404, { error: `no such output file: /${segs.join("/")}` });
1625
- return {
1626
- status: 200,
1627
- contentType: CONTENT_TYPES[extname(abs).toLowerCase()] ?? "application/octet-stream",
1628
- body: new Uint8Array(readFileSync(abs))
1629
- };
1630
- }
1631
- async replyWebJs() {
1632
- if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
1633
- const js = await this.opts.webJs();
1634
- if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
1635
- return {
1636
- status: 200,
1637
- contentType: "text/javascript; charset=utf-8",
1638
- body: js,
1639
- headers: NO_STORE
1640
- };
1641
- }
1642
- /** browser file → local file a media var can point at (downloadInput family) */
1643
- replyUpload(req) {
1644
- let parsed;
1645
- try {
1646
- parsed = JSON.parse(req.body ?? "");
1647
- } catch (e) {
1648
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1649
- }
1650
- const o = parsed ?? {};
1651
- if (typeof o.name !== "string" || o.name === "" || typeof o.dataBase64 !== "string" || o.dataBase64 === "") return json(400, { error: "upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}" });
1652
- const bytes = Buffer.from(o.dataBase64, "base64");
1653
- if (bytes.length === 0) return json(400, { error: "dataBase64 decoded to zero bytes" });
1654
- const safe = (basename(o.name).replace(/[^\w.-]+/g, "_") || "upload").slice(0, 100);
1655
- const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${safe}`);
1656
- mkdirSync(dirname(abs), { recursive: true });
1657
- writeFileSync(abs, bytes);
1658
- console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`);
1659
- return json(200, {
1660
- ok: true,
1661
- path: abs,
1662
- url: this.outputUrl(abs)
1663
- });
1664
- }
1665
- async replySaveDraft(modKey, rawDraft, req) {
1666
- const mod = this.moduleByKey(modKey);
1667
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
1668
- const draft = this.validDraftName(rawDraft);
1669
- if (draft == null) return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` });
1670
- let parsed;
1671
- try {
1672
- parsed = JSON.parse(req.body ?? "");
1673
- } catch (e) {
1674
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1675
- }
1676
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
1677
- const values = parsed;
1678
- const known = new Set(mod.dw.entries().map(([k]) => k));
1679
- if ("$enhance" in values) {
1680
- const raw = values[ENHANCE_KEY];
1681
- 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>" }` });
1682
- }
1683
- const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k));
1684
- if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
1685
- const path = bang(this.draftPath(mod, draft), "draft name validated just above");
1686
- await this.exclusive(mod.key, () => {
1687
- mkdirSync(dirname(path), { recursive: true });
1688
- writeFileSync(path, JSON.stringify(values, null, 2));
1689
- return Promise.resolve();
1690
- });
1691
- return json(200, {
1692
- ok: true,
1693
- module: mod.key,
1694
- draft,
1695
- drafts: this.draftsFor(mod)
1696
- });
1697
- }
1698
- /** delete the draft FILE. `default` is deletable like any other: the implicit `default`
1699
- * draft (spec values, no file) survives it, which is exactly the reset. Missing file is
1700
- * still a 200, the caller asked for it to be gone, and it is */
1701
- async replyDeleteDraft(modKey, rawDraft) {
1702
- const mod = this.moduleByKey(modKey);
1703
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
1704
- const path = this.draftPath(mod, rawDraft);
1705
- if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` });
1706
- await this.exclusive(mod.key, () => {
1707
- if (existsSync(path)) rmSync(path);
1708
- return Promise.resolve();
1709
- });
1710
- console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`);
1711
- return json(200, {
1712
- ok: true,
1713
- module: mod.key,
1714
- draft: rawDraft.trim(),
1715
- drafts: this.draftsFor(mod)
1716
- });
1717
- }
1718
- /** every host this process registered: the modules' own, plus anything they created */
1719
- knownHosts() {
1720
- const byId = /* @__PURE__ */ new Map();
1721
- for (const [id, host] of comfyts.hosts) byId.set(id, {
1722
- id,
1723
- url: host.addressLabel,
1724
- httpUrl: host.noAddress == null ? host.getServerHostHTTP() : null,
1725
- modules: []
1726
- });
1727
- for (const mod of this.modules) {
1728
- const entry = byId.get(mod.dw.host.data.id);
1729
- if (entry != null) entry.modules.push(mod.key);
1730
- }
1731
- return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id));
1732
- }
1733
- /** the host a run goes to: the override if it still exists, else the module's own.
1734
- * A stale override (a host id that is gone) must never silently swallow the run */
1735
- runHostFor(mod) {
1736
- const wanted = this.settings.hostOverride[mod.key];
1737
- if (wanted == null || wanted === mod.dw.host.data.id) return null;
1738
- return comfyts.hosts.get(wanted) ?? null;
1739
- }
1740
- /** the host actions the TUI's host panel has, minus re-codegen: regenerating the sdk
1741
- * rewrites a .d.ts for your EDITOR, while the running modules keep the builder they were
1742
- * imported with, a button that changes nothing in this process would be a lie */
1743
- async replyHostAction(hostId, action) {
1744
- const host = comfyts.hosts.get(hostId);
1745
- if (host == null) return json(404, { error: `unknown host '${hostId}' — known: ${[...comfyts.hosts.keys()].join(", ")}` });
1746
- try {
1747
- if (action === "interrupt") {
1748
- await host.interrupt();
1749
- return json(200, {
1750
- ok: true,
1751
- host: hostId,
1752
- action,
1753
- note: "interrupt requested"
1754
- });
1755
- }
1756
- if (action === "clear-queue") {
1757
- await host.clearQueue();
1758
- return json(200, {
1759
- ok: true,
1760
- host: hostId,
1761
- action,
1762
- note: "pending prompts dropped"
1763
- });
1764
- }
1765
- if (action === "refresh-loras") return await this.refreshLoraMirror(hostId, host);
1766
- if (action === "refresh-schema") {
1767
- await host.fetchAndUpdateSchema();
1768
- const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null);
1769
- 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";
1770
- const rebound = await this.rebindHostVars(hostId, host);
1771
- const nodes = host.schema.nodes.length;
1772
- const loras = host.schema.getLoras().length;
1773
- const dropped = rebound.stale.length === 0 ? "" : `. ${rebound.stale.length} selection(s) this host no longer lists (a lora is dropped, a model stays picked)`;
1774
- return json(200, {
1775
- ok: true,
1776
- host: hostId,
1777
- action,
1778
- stale: rebound.stale,
1779
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora or model var(s) changed${dropped}${lorasNote}`
1780
- });
1781
- }
1782
- if (action === "restart") {
1783
- await host.manager.restartComfyUI();
1784
- return json(200, {
1785
- ok: true,
1786
- host: hostId,
1787
- action,
1788
- note: "reboot requested — it reconnects when back"
1789
- });
1790
- }
1791
- return json(400, { error: `unknown host action '${action}' — interrupt | clear-queue | restart | refresh-loras | refresh-schema` });
1792
- } catch (e) {
1793
- return json(502, { error: `host '${hostId}' refused '${action}': ${extractErrorMessage(e)}` });
1794
- }
1795
- }
1796
- /** re-sweep ComfyUI-Lora-Manager and rewrite the mirror — what `comfy-ts loras` does, with
1797
- * its refusals kept: a partial or unreachable sweep NEVER overwrites, because writing it
1798
- * would delete loras from the mirror that are alive on the host */
1799
- /** re-resolve the host-bound lora vars of the modules DEFINED on this host: LorasVar only
1800
- * resolves its RegExp inside bindHost, so nothing else picks up a widened enum.
1801
- *
1802
- * the defining host, not the override: rebinding an overridden module against another box
1803
- * rewrites its options AND its hostId (which picks the metadata mirror) with no way back,
1804
- * since dropping the override cannot un-resolve them.
1805
- *
1806
- * runs under each module's mutex, so it cannot swap the options out from under a generate
1807
- * that already validated its payload against the old list. */
1808
- async rebindHostVars(hostId, host) {
1809
- let widened = 0;
1810
- const stale = [];
1811
- for (const mod of this.modules) {
1812
- if (mod.dw.host.data.id !== hostId) continue;
1813
- await this.exclusive(mod.key, () => {
1814
- for (const [name, varDef] of mod.dw.entries()) {
1815
- if (varDef.kind === "choice") {
1816
- const choice = varDef;
1817
- if (choice.hostSlot == null) continue;
1818
- const before = choice.choices.length;
1819
- choice.bindHost(host);
1820
- if (choice.choices.length !== before) widened++;
1821
- if (choice.value != null && !choice.choices.includes(choice.value)) stale.push(`${mod.key}/${name}: ${choice.value}`);
1822
- continue;
1823
- }
1824
- if (varDef.kind !== "loras") continue;
1825
- const lorasVar = varDef;
1826
- if (lorasVar.optionsFilter == null) continue;
1827
- const before = lorasVar.options.length;
1828
- lorasVar.bindHost(host);
1829
- if (lorasVar.options.length !== before) widened++;
1830
- const known = new Set(lorasVar.options);
1831
- const value = lorasVar.value;
1832
- for (const picked of Object.keys(value)) {
1833
- if (known.has(picked)) continue;
1834
- stale.push(`${mod.key}/${name}: ${picked}`);
1835
- delete value[picked];
1836
- }
1837
- }
1838
- return Promise.resolve();
1839
- });
1840
- }
1841
- return {
1842
- widened,
1843
- stale
1844
- };
1845
- }
1846
- async refreshLoraMirror(hostId, host) {
1847
- const sweep = await fetchLoraList(host);
1848
- if (sweep.status === "absent") return json(400, { error: `${hostId} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.` });
1849
- if (sweep.status === "unreachable") return json(502, { error: `${hostId} unreachable — ${sweep.reason}. Mirror left untouched.` });
1850
- 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.` });
1851
- const mirror = buildLoraMirror({
1852
- hostId,
1853
- hostUrl: host.getServerHostHTTP(),
1854
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
1855
- items: sweep.items
1856
- });
1857
- writeLoraMirror(mirror);
1858
- reloadLoraInfoCache();
1859
- console.log(`[serve] lora mirror refreshed for ${hostId}: ${mirror.count} loras`);
1860
- return json(200, {
1861
- ok: true,
1862
- host: hostId,
1863
- action: "refresh-loras",
1864
- count: mirror.count,
1865
- note: `${mirror.count} loras synced`
1866
- });
1867
- }
1868
- /** fetch ONE lora's civitai metadata through the lora manager, then re-sync the mirror so its
1869
- * trigger words reach every surface. The extension keys the request by the file path ON THE
1870
- * HOST, which only the mirror knows, so a lora outside the mirror needs a sync first */
1871
- async replyLoraCivitaiFetch(hostId, lora) {
1872
- const host = comfyts.hosts.get(hostId);
1873
- if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1874
- const info = getLoraInfo(lora, hostId);
1875
- const filePath = info == null ? null : lmFilePath(info);
1876
- if (filePath == null) return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` });
1877
- const fetched = await fetchLoraCivitai(host, filePath);
1878
- const sha256 = info == null ? null : lmSha256(info);
1879
- if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {
1880
- recordCivitaiMiss({
1881
- hostId,
1882
- sha256,
1883
- miss: true
1884
- });
1885
- return json(200, {
1886
- ok: true,
1887
- host: hostId,
1888
- lora,
1889
- triggers: { state: "not-on-civitai" },
1890
- note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`
1891
- });
1892
- }
1893
- if (!fetched.ok) return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` });
1894
- if (sha256 != null) recordCivitaiMiss({
1895
- hostId,
1896
- sha256,
1897
- miss: false
1898
- });
1899
- const synced = await this.refreshLoraMirror(hostId, host);
1900
- if (synced.status !== 200) return synced;
1901
- const t = getLoraTriggers(lora, hostId);
1902
- return json(200, {
1903
- ok: true,
1904
- host: hostId,
1905
- lora,
1906
- triggers: t,
1907
- note: t?.state === "words" ? `trigger words: ${t.words.join(", ")}` : t?.state === "none" ? `civitai lists no trigger words for '${lora}'` : `civitai has no metadata for '${lora}'`
1908
- });
1909
- }
1910
- /** has the host changed since this process loaded its schema: new or removed model files (and
1911
- * node types on a full check). A host whose catalog is COMMITTED rather than live-synced
1912
- * (sdkAutoWrite: false, the cloud catalog) is not compared: its live list moves on purpose */
1913
- async replyHostDrift(hostId, full) {
1914
- const host = comfyts.hosts.get(hostId);
1915
- if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1916
- if (host.data.sdkAutoWrite === false) return json(200, {
1917
- host: hostId,
1918
- checked: false,
1919
- changed: false,
1920
- summary: ""
1921
- });
1922
- try {
1923
- const drift = await host.checkSchemaDrift({ full });
1924
- return json(200, {
1925
- host: hostId,
1926
- checked: true,
1927
- full,
1928
- changed: driftChanged(drift),
1929
- summary: summarizeDrift(drift),
1930
- drift
1931
- });
1932
- } catch (e) {
1933
- return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` });
1934
- }
1935
- }
1936
- /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so
1937
- * "restarting…" ends on a fact rather than on a guess */
1938
- async replyHostPing(hostId) {
1939
- const host = comfyts.hosts.get(hostId);
1940
- if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1941
- try {
1942
- const res = await host.fetch("/system_stats", {});
1943
- return json(200, {
1944
- host: hostId,
1945
- up: res.ok,
1946
- status: res.status
1947
- });
1948
- } catch (e) {
1949
- return json(200, {
1950
- host: hostId,
1951
- up: false,
1952
- reason: extractErrorMessage(e)
1953
- });
1954
- }
1955
- }
1956
- /** the ComfyUI console, the TUI's logs panel over http — through the SAME assembly the TUI
1957
- * uses (assembleLogChunks): entries are write CHUNKS, so lines are folded there, ANSI is
1958
- * stripped, tqdm redraws collapse to their last state, and the cp1252 mojibake a windows
1959
- * host emits is repaired. Re-implementing any of that here would drift from the TUI */
1960
- async replyHostLogs(hostId) {
1961
- const host = comfyts.hosts.get(hostId);
1962
- if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1963
- try {
1964
- const raw = await host.fetchRawLogs();
1965
- const lines = [];
1966
- const partial = assembleLogChunks({
1967
- lines,
1968
- partial: "",
1969
- entries: raw.entries
1970
- });
1971
- if (partial.trim() !== "") lines.push(partial);
1972
- return json(200, {
1973
- host: hostId,
1974
- lines: lines.slice(-200)
1975
- });
1976
- } catch (e) {
1977
- return json(502, { error: `could not read the logs of '${hostId}': ${extractErrorMessage(e)}` });
1978
- }
1979
- }
1980
- replyHosts() {
1981
- return json(200, {
1982
- hosts: this.knownHosts(),
1983
- defaults: Object.fromEntries(this.modules.map((m) => [m.key, m.dw.host.data.id])),
1984
- overrides: this.settings.hostOverride
1985
- });
1986
- }
1987
- replySetHost(modKey, req) {
1988
- const mod = this.moduleByKey(modKey);
1989
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
1990
- let parsed;
1991
- try {
1992
- parsed = JSON.parse(req.body ?? "");
1993
- } catch (e) {
1994
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1995
- }
1996
- const wanted = parsed != null && typeof parsed === "object" ? parsed.host : null;
1997
- if (wanted != null && typeof wanted !== "string") return json(400, { error: "body must be { \"host\": \"<host id>\" } or { \"host\": null } to reset" });
1998
- const next = { ...this.settings.hostOverride };
1999
- if (wanted == null || wanted === mod.dw.host.data.id) delete next[mod.key];
2000
- else {
2001
- if (!comfyts.hosts.has(wanted)) return json(400, { error: `unknown host '${wanted}' — known: ${[...comfyts.hosts.keys()].join(", ")}` });
2002
- next[mod.key] = wanted;
2003
- }
2004
- this.settings = {
2005
- ...this.settings,
2006
- hostOverride: next
2007
- };
2008
- try {
2009
- writeServeSettings(this.settings);
2010
- } catch (e) {
2011
- return json(500, { error: `host applied for this session but not saved: ${extractErrorMessage(e)}` });
2012
- }
2013
- const target = next[mod.key] ?? mod.dw.host.data.id;
2014
- console.log(`[serve] ${mod.key} runs on ${target}${next[mod.key] != null ? " (override)" : ""}`);
2015
- return json(200, {
2016
- ok: true,
2017
- module: mod.key,
2018
- host: target,
2019
- overrides: this.settings.hostOverride
2020
- });
2021
- }
2022
- memoryBlob(key, bytes, filename) {
2023
- return {
2024
- key,
2025
- bytes,
2026
- contentType: CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes)
2027
- };
2028
- }
2029
- replyMemoryImage(key) {
2030
- const hit = this.kept.blob(key);
2031
- if (hit == null) return json(404, { error: `no in-memory output '${key}' — it was deleted, dropped past the ${this.settings.memoryBudgetMb} MB memory budget, or the server restarted. Turn saving on to keep outputs.` });
2032
- return {
2033
- status: 200,
2034
- contentType: hit.contentType,
2035
- body: hit.bytes
2036
- };
2037
- }
2038
- /** the subfolder under outputs/ a module's images land in. Falls back to the module key,
2039
- * which is what every serve run used before the prefix was choosable */
2040
- savePrefixFor(modKey) {
2041
- const stored = this.settings.savePrefix[modKey]?.trim() ?? "";
2042
- return stored === "" ? modKey : stored;
2043
- }
2044
- replySaveSettings(req) {
2045
- let parsed;
2046
- try {
2047
- parsed = JSON.parse(req.body ?? "");
2048
- } catch (e) {
2049
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
2050
- }
2051
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { \"saveToDisk\"?: true | false, \"savePrefix\"?: { \"<module>\": \"path\" }, \"memoryBudgetMb\"?: number }" });
2052
- const wanted = parsed;
2053
- let next = this.settings;
2054
- if (wanted.saveToDisk != null) {
2055
- if (typeof wanted.saveToDisk !== "boolean") return json(400, { error: "\"saveToDisk\" must be true or false" });
2056
- next = {
2057
- ...next,
2058
- saveToDisk: wanted.saveToDisk
2059
- };
2060
- }
2061
- if (wanted.savePrefix != null) {
2062
- if (typeof wanted.savePrefix !== "object" || Array.isArray(wanted.savePrefix)) return json(400, { error: "\"savePrefix\" must be { \"<module>\": \"path\" }" });
2063
- const prefixes = { ...next.savePrefix };
2064
- for (const [modKey, raw] of Object.entries(wanted.savePrefix)) {
2065
- if (this.moduleByKey(modKey) == null) return json(404, { error: `unknown module '${modKey}'` });
2066
- if (typeof raw !== "string") return json(400, { error: `prefix for '${modKey}' must be a string` });
2067
- const clean = validSavePrefix(raw);
2068
- if (clean == null) return json(400, { error: `invalid prefix '${raw}' — folder names only, "a/b" allowed, no ".." and no absolute path` });
2069
- if (clean === "") delete prefixes[modKey];
2070
- else prefixes[modKey] = clean;
2071
- }
2072
- next = {
2073
- ...next,
2074
- savePrefix: prefixes
2075
- };
2076
- }
2077
- if (wanted.memoryBudgetMb != null) {
2078
- const mb = validMemoryBudgetMb(wanted.memoryBudgetMb);
2079
- if (mb == null) return json(400, { error: "\"memoryBudgetMb\" must be a number of MB, 1 to 100000" });
2080
- next = {
2081
- ...next,
2082
- memoryBudgetMb: mb
2083
- };
2084
- }
2085
- const saveToDisk = next.saveToDisk;
2086
- this.settings = next;
2087
- this.kept.setBudget(next.memoryBudgetMb * MB);
2088
- try {
2089
- writeServeSettings(this.settings);
2090
- } catch (e) {
2091
- return json(500, { error: `setting applied for this session but not saved: ${extractErrorMessage(e)}` });
2092
- }
2093
- console.log(`[serve] outputs ${saveToDisk ? "SAVE to disk" : "stay in MEMORY"}`);
2094
- return this.replySettings();
2095
- }
2096
- /** the stored settings PLUS the prefix each module actually uses, so the ui can show the
2097
- * effective folder without re-deriving the fallback rule */
2098
- replySettings() {
2099
- return json(200, {
2100
- ...this.settings,
2101
- effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)]))
2102
- });
2103
- }
2104
- tabsFile() {
2105
- return join(comfyts.baseFolder, SERVE_TABS_FILE);
2106
- }
2107
- /** only drafts that still exist: a tab whose file was deleted elsewhere is dropped on read */
2108
- liveTabs(raw) {
2109
- return readTabs(raw, this.modules.map((m) => ({
2110
- module: m.key,
2111
- drafts: this.draftsFor(m)
2112
- })));
2113
- }
2114
- replyTabs() {
2115
- if (this.tabs == null) {
2116
- const path = this.tabsFile();
2117
- let raw = [];
2118
- try {
2119
- if (existsSync(path)) raw = JSON.parse(readFileSync(path, "utf8"));
2120
- } catch (e) {
2121
- console.error(`[serve] 🔴 open tabs unreadable (${path}), starting with none:`, e);
2122
- }
2123
- this.tabs = this.liveTabs(raw);
2124
- }
2125
- this.tabs = this.liveTabs(this.tabs);
2126
- return json(200, { tabs: this.tabs });
2127
- }
2128
- replySaveTabs(req) {
2129
- let parsed;
2130
- try {
2131
- parsed = JSON.parse(req.body ?? "");
2132
- } catch (e) {
2133
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
2134
- }
2135
- const raw = parsed != null && typeof parsed === "object" ? parsed.tabs : void 0;
2136
- if (!Array.isArray(raw) || raw.length > 100) return json(400, { error: "expects { \"tabs\": [{ \"module\", \"draft\" }, …] }" });
2137
- this.tabs = this.liveTabs(raw);
2138
- try {
2139
- mkdirSync(comfyts.baseFolder, { recursive: true });
2140
- writeFileSync(this.tabsFile(), JSON.stringify(this.tabs, null, 2));
2141
- } catch (e) {
2142
- console.error(`[serve] 🔴 open tabs not saved to ${this.tabsFile()}:`, e);
2143
- return json(200, {
2144
- tabs: this.tabs,
2145
- warning: `not saved: ${extractErrorMessage(e)}`
2146
- });
2147
- }
2148
- return json(200, { tabs: this.tabs });
2149
- }
2150
- async replyTags(modKey, varName, url) {
2151
- const mod = this.moduleByKey(modKey);
2152
- if (mod == null) return json(404, { error: `unknown workflow '${modKey}'` });
2153
- const found = mod.dw.entries().find(([k]) => k === varName)?.[1];
2154
- if (found == null) return json(404, { error: `workflow '${modKey}' has no var '${varName}'` });
2155
- const tags = found.kind === "prompt" ? found.tags : null;
2156
- if (tags == null) return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` });
2157
- const params = new URLSearchParams(url.split("?")[1] ?? "");
2158
- const limit = Math.min(100, Math.max(1, Number(params.get("limit") ?? "20") || 20));
2159
- try {
2160
- return json(200, { hits: (await this.tagSources.load(resolveTagSource(tags.url, mod.file))).search(params.get("q") ?? "", limit) });
2161
- } catch (e) {
2162
- console.error(`[serve] 🔴 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`);
2163
- return json(502, { error: extractErrorMessage(e) });
2164
- }
2165
- }
2166
- replyPromptEnhancers() {
2167
- try {
2168
- return json(200, { enhancers: listPromptEnhancers() });
2169
- } catch (e) {
2170
- return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` });
2171
- }
2172
- }
2173
- replySavePromptEnhancer(rawName, req) {
2174
- const name = validStoreName(rawName);
2175
- if (name == null) return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, ". -_"` });
2176
- let parsed;
2177
- try {
2178
- parsed = JSON.parse(req.body ?? "");
2179
- } catch (e) {
2180
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
2181
- }
2182
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
2183
- const text = parsed.text;
2184
- if (typeof text !== "string") return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
2185
- try {
2186
- writePromptEnhancer(name, text);
2187
- } catch (e) {
2188
- return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` });
2189
- }
2190
- return json(200, {
2191
- ok: true,
2192
- name,
2193
- enhancers: listPromptEnhancers()
2194
- });
2195
- }
2196
- replyDeletePromptEnhancer(rawName) {
2197
- const name = validStoreName(rawName);
2198
- if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` });
2199
- try {
2200
- deletePromptEnhancer(name);
2201
- } catch (e) {
2202
- return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` });
2203
- }
2204
- console.log(`[serve] prompt enhancer deleted: ${name}`);
2205
- return json(200, {
2206
- ok: true,
2207
- name,
2208
- enhancers: listPromptEnhancers()
2209
- });
2210
- }
2211
- replyLlmConfigs() {
2212
- try {
2213
- return json(200, { configs: listLlmConfigs() });
2214
- } catch (e) {
2215
- return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` });
2216
- }
2217
- }
2218
- replySaveLlmConfig(rawName, req) {
2219
- const name = validStoreName(rawName);
2220
- if (name == null) return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, ". -_"` });
2221
- let parsed;
2222
- try {
2223
- parsed = JSON.parse(req.body ?? "");
2224
- } catch (e) {
2225
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
2226
- }
2227
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { provider, baseUrl, model, effort, thinkingOnly }" });
2228
- try {
2229
- writeLlmConfig(name, normalizeLlmConfig(parsed));
2230
- } catch (e) {
2231
- return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` });
2232
- }
2233
- return json(200, {
2234
- ok: true,
2235
- name,
2236
- configs: listLlmConfigs()
2237
- });
2238
- }
2239
- replyDeleteLlmConfig(rawName) {
2240
- const name = validStoreName(rawName);
2241
- if (name == null) return json(400, { error: `invalid config name '${rawName}'` });
2242
- try {
2243
- deleteLlmConfig(name);
2244
- } catch (e) {
2245
- return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` });
2246
- }
2247
- console.log(`[serve] llm config deleted: ${name}`);
2248
- return json(200, {
2249
- ok: true,
2250
- name,
2251
- configs: listLlmConfigs()
2252
- });
2253
- }
2254
- replyRunStatus(modKey) {
2255
- const mod = this.moduleByKey(modKey);
2256
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
2257
- const exec = this.liveRuns.get(mod.key);
2258
- const running = exec != null && exec.status !== "Success" && exec.status !== "Failure";
2259
- return json(200, {
2260
- running,
2261
- status: exec?.status ?? "idle",
2262
- percent: running ? exec.progressGlobal?.percent ?? null : null,
2263
- node: running ? exec.progress?.nodeName ?? null : null,
2264
- nodeProgress: running && exec.progress?.nodeProgress != null ? {
2265
- value: exec.progress.nodeProgress.value,
2266
- max: exec.progress.nodeProgress.max
2267
- } : null,
2268
- progressText: running ? exec.progress?.progressText ?? null : null,
2269
- hasPreview: this.latentPreviews.has(mod.key),
2270
- previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null
2271
- });
2272
- }
2273
- replyRunPreview(modKey) {
2274
- const mod = this.moduleByKey(modKey);
2275
- if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
2276
- const preview = this.latentPreviews.get(mod.key);
2277
- if (preview == null) return json(404, { error: "no latent preview yet" });
2278
- return {
2279
- status: 200,
2280
- contentType: preview.mime !== "" ? preview.mime : sniffImageContentType(preview.bytes),
2281
- body: preview.bytes
2282
- };
2283
- }
2284
- hostById(hostId) {
2285
- return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null;
2286
- }
2287
- hostIds() {
2288
- return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(", ");
2289
- }
2290
- /** mirror-backed text for the hover pane, no network */
2291
- replyLoraInfo(hostId, lora) {
2292
- if (this.hostById(hostId) == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
2293
- refreshLoraInfoCacheIfChanged();
2294
- const item = getLoraInfo(lora, hostId);
2295
- const civitai = item == null ? null : lmCivitai(item);
2296
- return json(200, {
2297
- name: lora,
2298
- displayName: getLoraDisplayName(lora, hostId),
2299
- triggerWords: getLoraTriggerWords(lora, hostId),
2300
- known: item != null,
2301
- baseModel: item == null ? null : lmBaseModel(item),
2302
- folder: item == null ? null : lmFolder(item),
2303
- filePath: item == null ? null : lmFilePath(item),
2304
- fileSize: item == null ? null : lmFileSize(item),
2305
- tags: item == null ? [] : lmTags(item),
2306
- notes: item == null ? "" : lmNotes(item),
2307
- civitaiUrl: civitai?.modelId == null ? null : `https://civitai.com/models/${civitai.modelId}`,
2308
- civitaiVersion: civitai?.name ?? null
2309
- });
2310
- }
2311
- /** what the mirror does NOT hold: civitai's description and the example images, both live
2312
- * from the extension. A SEPARATE route from /lora-info on purpose, that one is mirror-only
2313
- * and instant, this one talks to the host and is fetched when a details panel opens */
2314
- async replyLoraAbout(hostId, lora) {
2315
- const host = this.hostById(hostId);
2316
- if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
2317
- refreshLoraInfoCacheIfChanged();
2318
- const item = getLoraInfo(lora, hostId);
2319
- if (item == null) return json(200, {
2320
- known: false,
2321
- description: null,
2322
- examples: [],
2323
- examplesReason: null
2324
- });
2325
- const filePath = lmFilePath(item);
2326
- const sha = lmSha256(item);
2327
- const [description, examples] = await Promise.all([filePath == null ? Promise.resolve(null) : fetchLoraDescription(host, filePath), sha == null ? Promise.resolve({
2328
- files: [],
2329
- reason: null
2330
- }) : fetchLoraExampleImages(host, sha)]);
2331
- return json(200, {
2332
- known: true,
2333
- description,
2334
- examples: examples.files,
2335
- examplesReason: examples.reason
2336
- });
2337
- }
2338
- async replyLoraPreview(hostId, lora) {
2339
- const host = this.hostById(hostId);
2340
- if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
2341
- refreshLoraInfoCacheIfChanged();
2342
- let url = getLoraPreviewUrl(lora, hostId);
2343
- if (url == null) {
2344
- let sweep = this.previewSweeps.get(hostId);
2345
- if (sweep == null) {
2346
- sweep = fetchLoraList(host).then((r) => {
2347
- if (r.status === "unreachable") {
2348
- this.previewSweeps.delete(hostId);
2349
- return {
2350
- status: r.status,
2351
- map: null
2352
- };
2353
- }
2354
- return {
2355
- status: r.status,
2356
- map: r.status === "absent" ? null : loraPreviewMapFrom(r.items)
2357
- };
2358
- });
2359
- this.previewSweeps.set(hostId, sweep);
2360
- }
2361
- const swept = await sweep;
2362
- url = swept.map?.get(loraKey(lora)) ?? null;
2363
- if (url == null && swept.status === "unreachable") return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` });
2364
- if (url == null && swept.status === "absent") return json(404, { error: `lora-manager extension not detected on '${hostId}'` });
2365
- }
2366
- if (url == null) return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` });
2367
- const bytes = await fetchLoraPreviewBytes(host, url);
2368
- if (bytes == null) return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` });
2369
- return {
2370
- status: 200,
2371
- contentType: sniffImageContentType(bytes),
2372
- body: bytes
2373
- };
2374
- }
2375
- outputUrl(absPath) {
2376
- if (!absPath.startsWith(this.outputRoot + "/")) return null;
2377
- return "/outputs/" + absPath.slice(this.outputRoot.length + 1).split("/").map(encodeURIComponent).join("/");
2378
- }
2379
- async generate(mod, draft, req) {
2380
- let payload = {};
2381
- if (req.body != null && req.body.trim() !== "") {
2382
- let parsed;
2383
- try {
2384
- parsed = JSON.parse(req.body);
2385
- } catch (e) {
2386
- return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
2387
- }
2388
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
2389
- payload = parsed;
2390
- }
2391
- const t0 = Date.now();
2392
- const seeds = {};
2393
- const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
2394
- if ("error" in started) return json(started.status, { error: started.error });
2395
- const execution = started.execution;
2396
- this.liveRuns.set(mod.key, execution);
2397
- console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
2398
- await execution.done;
2399
- const durationMs = Date.now() - t0;
2400
- if (execution.status === "Failure") {
2401
- const error = describeRunError(execution.data.error);
2402
- console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms: ${error}`);
2403
- return json(500, {
2404
- ok: false,
2405
- module: mod.key,
2406
- draft,
2407
- promptId: execution.data.id,
2408
- durationMs,
2409
- error
2410
- });
2411
- }
2412
- const produced = [`${execution.images.length} image(s)`];
2413
- const audios = execution.audios ?? [];
2414
- if (audios.length > 0) produced.push(`${audios.length} audio(s)`);
2415
- const videos = execution.videos ?? [];
2416
- if (videos.length > 0) produced.push(`${videos.length} video(s)`);
2417
- const models3d = execution.models3d ?? [];
2418
- if (models3d.length > 0) produced.push(`${models3d.length} 3d model(s)`);
2419
- if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`);
2420
- console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1e3).toFixed(1)}s · ${produced.join(" · ")}`);
2421
- const blobs = [];
2422
- const imageKeys = execution.images.map((img, ix) => {
2423
- if (img.absPath != null || img.buffer == null) return null;
2424
- const key = `${execution.data.id}/${ix}`;
2425
- blobs.push(this.memoryBlob(key, img.buffer, img.filename));
2426
- return key;
2427
- });
2428
- const audioKeys = audios.map((a, ix) => {
2429
- if (a.absPath != null) return null;
2430
- const key = `audio/${execution.data.id}/${ix}`;
2431
- blobs.push(this.memoryBlob(key, a.bytes, a.filename));
2432
- return key;
2433
- });
2434
- const videoKeys = videos.map((a, ix) => {
2435
- if (a.absPath != null) return null;
2436
- const key = `video/${execution.data.id}/${ix}`;
2437
- blobs.push(this.memoryBlob(key, a.bytes, a.filename));
2438
- return key;
2439
- });
2440
- const model3dKeys = models3d.map((m, ix) => {
2441
- if (m.absPath != null) return null;
2442
- const key = `model3d/${execution.data.id}/${ix}`;
2443
- blobs.push(this.memoryBlob(key, m.bytes, m.filename));
2444
- return key;
2445
- });
2446
- const memoryUrl = (route, key) => `/${route}/${key.split("/").slice(route === "images" ? 0 : 1).map((seg) => encodeURIComponent(seg)).join("/")}`;
2447
- const record = {
2448
- ok: true,
2449
- module: mod.key,
2450
- draft,
2451
- promptId: execution.data.id,
2452
- durationMs,
2453
- finishedAt: Date.now(),
2454
- seeds,
2455
- savedToDisk: this.settings.saveToDisk,
2456
- texts: (execution.texts ?? []).map((t) => ({
2457
- nodeKey: t.nodeKey,
2458
- text: t.text
2459
- })),
2460
- images: execution.images.map((img, ix) => {
2461
- const key = imageKeys[ix];
2462
- return {
2463
- filename: img.filename,
2464
- url: img.absPath != null ? this.outputUrl(img.absPath) : key != null ? memoryUrl("images", key) : null,
2465
- absPath: img.absPath,
2466
- ...img.tags != null && img.tags.length > 0 ? { tags: [...img.tags] } : {}
2467
- };
2468
- }),
2469
- audios: audios.map((a, ix) => {
2470
- const key = audioKeys[ix];
2471
- return {
2472
- filename: a.filename,
2473
- mime: a.mime,
2474
- url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl("audio", key) : null,
2475
- absPath: a.absPath
2476
- };
2477
- }),
2478
- videos: videos.map((a, ix) => {
2479
- const key = videoKeys[ix];
2480
- return {
2481
- filename: a.filename,
2482
- mime: a.mime,
2483
- url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl("video", key) : null,
2484
- absPath: a.absPath
2485
- };
2486
- }),
2487
- models3d: models3d.map((m, ix) => {
2488
- const key = model3dKeys[ix];
2489
- return {
2490
- filename: m.filename,
2491
- mime: m.mime,
2492
- format: m.format,
2493
- size: m.bytes.byteLength,
2494
- url: m.absPath != null ? this.outputUrl(m.absPath) : key != null ? memoryUrl("model3d", key) : null,
2495
- absPath: m.absPath
2496
- };
2497
- }),
2498
- ...mod.dw.spec.widgets != null && mod.dw.spec.widgets.length > 0 ? { widgets: mod.dw.spec.widgets } : {}
2499
- };
2500
- this.kept.add({
2501
- record,
2502
- imageKeys,
2503
- audioKeys,
2504
- videoKeys,
2505
- model3dKeys,
2506
- blobs
2507
- });
2508
- const first = execution.images[0];
2509
- if (req.accept?.includes("image/") && first != null) {
2510
- if (first.absPath != null) return {
2511
- status: 200,
2512
- contentType: CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? "application/octet-stream",
2513
- body: new Uint8Array(readFileSync(first.absPath))
2514
- };
2515
- const inMemory = this.kept.blob(imageKeys[0] ?? "");
2516
- if (inMemory != null) return {
2517
- status: 200,
2518
- contentType: inMemory.contentType,
2519
- body: inMemory.bytes
2520
- };
2521
- }
2522
- return json(200, record);
2523
- }
2524
- /** everything that touches the module's SHARED vars, under the module mutex */
2525
- async prepareAndStart(mod, draft, payload, seeds) {
2526
- for (const [, varDef] of mod.dw.entries()) varDef.reset();
2527
- const draftPath = this.draftPath(mod, draft);
2528
- if (draftPath == null) return {
2529
- status: 404,
2530
- error: `no draft '${draft}'`
2531
- };
2532
- if (existsSync(draftPath)) try {
2533
- const values = JSON.parse(readFileSync(draftPath, "utf8"));
2534
- for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k]);
2535
- } catch (e) {
2536
- return {
2537
- status: 500,
2538
- error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}`
2539
- };
2540
- }
2541
- const draftSeedValues = /* @__PURE__ */ new Map();
2542
- for (const [k, varDef] of mod.dw.entries()) if (varDef.kind === "seed") draftSeedValues.set(k, varDef.value);
2543
- const varMap = new Map(mod.dw.entries());
2544
- for (const [k, rawValue] of Object.entries(payload)) {
2545
- const varDef = varMap.get(k);
2546
- if (varDef == null) return {
2547
- status: 400,
2548
- error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(", ")}`
2549
- };
2550
- let value = rawValue;
2551
- if (isMediaKind(varDef.kind) && typeof rawValue === "string" && /^https?:\/\//.test(rawValue)) try {
2552
- value = await this.downloadInput(rawValue);
2553
- } catch (e) {
2554
- return {
2555
- status: 400,
2556
- error: `var '${k}': ${extractErrorMessage(e)}`
2557
- };
2558
- }
2559
- const err = applyVarPayload(varDef, value, { extraLoraOptions: varDef.kind === "loras" ? managerOnlyLoraOptions({
2560
- hostId: mod.dw.host.data.id,
2561
- options: varDef.options,
2562
- filter: varDef.optionsFilter
2563
- }) : void 0 });
2564
- if (err != null) return {
2565
- status: 400,
2566
- error: err
2567
- };
2568
- }
2569
- for (const [k, varDef] of varMap) {
2570
- const kind = varDef.kind;
2571
- if (!isMediaKind(kind)) continue;
2572
- const media = varDef;
2573
- if (!media.isSet()) continue;
2574
- const abs = media.absPath();
2575
- const refuse = {
2576
- status: 400,
2577
- error: `${kind} var '${k}': not a usable ${kind} file`
2578
- };
2579
- if (!existsSync(abs)) return refuse;
2580
- let real;
2581
- try {
2582
- real = realpathSync(abs);
2583
- } catch {
2584
- return refuse;
2585
- }
2586
- try {
2587
- if (!statSync(real).isFile()) return refuse;
2588
- } catch {
2589
- return refuse;
2590
- }
2591
- if (!serveAcceptsMediaExt(kind, media.extensions, extname(real).toLowerCase().replace(/^\./, ""))) return refuse;
2592
- if (!looksLikeMedia(kind, real)) return refuse;
2593
- }
2594
- for (const [k, varDef] of varMap) {
2595
- if (varDef.kind !== "seed") continue;
2596
- const seedVar = varDef;
2597
- const stateKey = `${mod.key}/${draft}/${k}`;
2598
- const draftValue = draftSeedValues.get(k) ?? seedVar.value;
2599
- const prev = this.seedState.get(stateKey);
2600
- const continues = !(k in payload) && (seedVar.mode === "+" || seedVar.mode === "-") && prev != null && (prev.draftBase === draftValue || prev.served.includes(draftValue));
2601
- if (!(k in payload) && seedVar.mode === "?") seedVar.randomize();
2602
- if (continues) {
2603
- seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
2604
- const served = [...prev.served, seedVar.value].slice(-256);
2605
- this.seedState.set(stateKey, {
2606
- last: seedVar.value,
2607
- draftBase: prev.draftBase,
2608
- served
2609
- });
2610
- } else this.seedState.set(stateKey, {
2611
- last: seedVar.value,
2612
- draftBase: draftValue,
2613
- served: [seedVar.value]
2614
- });
2615
- seeds[k] = seedVar.value;
2616
- }
2617
- this.latentPreviews.delete(mod.key);
2618
- const runHost = this.runHostFor(mod);
2619
- try {
2620
- return { execution: await this.starter(mod, {
2621
- saveToDisk: this.settings.saveToDisk,
2622
- savePrefix: this.savePrefixFor(mod.key),
2623
- host: runHost ?? void 0,
2624
- onPreview: (p) => this.latentPreviews.set(mod.key, {
2625
- bytes: p.bytes,
2626
- mime: p.mime,
2627
- seq: ++this.latentSeq
2628
- })
2629
- }) };
2630
- } catch (e) {
2631
- if (e instanceof Error && (e.name === "MediaVarEmptyError" || e.name === "ImageVarEmptyError")) return {
2632
- status: 400,
2633
- error: e.message
2634
- };
2635
- if (e instanceof Error && e.name === "ComfyHostUnreachableError") return {
2636
- status: 502,
2637
- error: e.message
2638
- };
2639
- return {
2640
- status: 500,
2641
- error: extractErrorMessage(e)
2642
- };
2643
- }
2644
- }
2645
- /** serialize fn per module key; the stored chain never rejects */
2646
- exclusive(key, fn) {
2647
- const next = (this.chains.get(key) ?? Promise.resolve()).then(fn);
2648
- this.chains.set(key, next.catch(() => {}));
2649
- return next;
2650
- }
2651
- /** one file per url: a preset or a pasted url downloads once per output root, not per run */
2652
- urlInputPath(url, name) {
2653
- const hash = createHash("sha1").update(url).digest("hex").slice(0, 16);
2654
- return join(this.outputRoot, "serve-inputs", `url-${hash}${extname(name)}`);
2655
- }
2656
- /** payload image urls land as local files under outputs/serve-inputs/ */
2657
- async downloadInput(url) {
2658
- const cached = this.urlInputPath(url, basename(new URL(url).pathname));
2659
- if (existsSync(cached)) return cached;
2660
- try {
2661
- return await this.fetchInput(url);
2662
- } catch (e) {
2663
- if (!(e instanceof DownloadRefused)) console.error(`[serve] input download failed: ${url}:`, e);
2664
- throw new DownloadRefused(url);
2665
- }
2666
- }
2667
- async fetchInput(url) {
2668
- const res = await fetch(url, {
2669
- redirect: "follow",
2670
- signal: AbortSignal.timeout(INPUT_DOWNLOAD_TIMEOUT_MS)
2671
- });
2672
- if (!res.ok) {
2673
- console.error(`[serve] input download failed (http ${res.status}): ${url}`);
2674
- throw new DownloadRefused(url);
2675
- }
2676
- const declared = Number(res.headers.get("content-length") ?? "0");
2677
- if (declared > INPUT_DOWNLOAD_CAP) throw new Error(`download too large (${declared} bytes): ${url}`);
2678
- const bytes = await readCapped(res, INPUT_DOWNLOAD_CAP, url);
2679
- const name = basename(new URL(url).pathname) || "input";
2680
- const abs = this.urlInputPath(url, name);
2681
- mkdirSync(dirname(abs), { recursive: true });
2682
- writeFileSync(abs, bytes);
2683
- return abs;
2684
- }
2685
- };
2686
- //#endregion
2687
- export { describeVar as n, renderDescriptorLine as r, ServeApp as t };
2688
-
2689
- //# sourceMappingURL=ServeApp-fsHtW5zG.js.map