comfy-ts 0.4.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +385 -255
  2. package/dist/DefinedWorkflow-BYyu5dK9.js +669 -0
  3. package/dist/DefinedWorkflow-BYyu5dK9.js.map +1 -0
  4. package/dist/cli.js +4106 -152
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1560 -333
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +7826 -467
  9. package/dist/index.d.ts +7808 -449
  10. package/dist/index.js +1550 -333
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-DZ22HDHI.js} +631 -657
  13. package/dist/run-tui-DZ22HDHI.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +55 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +51 -0
  19. package/examples/README.md +30 -0
  20. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +79 -0
  21. package/examples/comfy-cloud/anima-t2i.cflow.ts +57 -0
  22. package/examples/comfy-cloud/boogu-i2i.cflow.ts +76 -0
  23. package/examples/comfy-cloud/capybara-i2i.cflow.ts +85 -0
  24. package/examples/comfy-cloud/capybara-i2v.cflow.ts +90 -0
  25. package/examples/comfy-cloud/capybara-t2i.cflow.ts +67 -0
  26. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +79 -0
  27. package/examples/comfy-cloud/chroma-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/cloudHost.ts +41 -0
  29. package/examples/comfy-cloud/ernie-t2i.cflow.ts +59 -0
  30. package/examples/comfy-cloud/firered-i2i.cflow.ts +74 -0
  31. package/examples/comfy-cloud/flux1-i2i.cflow.ts +76 -0
  32. package/examples/comfy-cloud/flux1-t2i.cflow.ts +63 -0
  33. package/examples/comfy-cloud/flux2-i2i.cflow.ts +80 -0
  34. package/examples/comfy-cloud/flux2-t2i.cflow.ts +57 -0
  35. package/examples/comfy-cloud/hidream-i2i.cflow.ts +89 -0
  36. package/examples/comfy-cloud/hidream-t2i.cflow.ts +65 -0
  37. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +93 -0
  38. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +74 -0
  39. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +80 -0
  40. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +95 -0
  41. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +60 -0
  42. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +78 -0
  43. package/examples/comfy-cloud/krea2-t2i.cflow.ts +59 -0
  44. package/examples/comfy-cloud/lens-t2i.cflow.ts +62 -0
  45. package/examples/comfy-cloud/longcat-i2i.cflow.ts +74 -0
  46. package/examples/comfy-cloud/longcat-t2i.cflow.ts +65 -0
  47. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +92 -0
  48. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +78 -0
  49. package/examples/comfy-cloud/newbie-t2i.cflow.ts +67 -0
  50. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +86 -0
  51. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +62 -0
  52. package/examples/comfy-cloud/ovis-t2i.cflow.ts +56 -0
  53. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +63 -0
  54. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +69 -0
  55. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +55 -0
  56. package/examples/comfy-cloud/sd35-t2i.cflow.ts +48 -0
  57. package/examples/comfy-cloud/sdk.d.ts +123062 -0
  58. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +69 -0
  59. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +53 -0
  60. package/examples/comfy-cloud/svd-i2v.cflow.ts +75 -0
  61. package/examples/comfy-cloud/wan21-i2v.cflow.ts +83 -0
  62. package/examples/comfy-cloud/wan21-t2v.cflow.ts +64 -0
  63. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +69 -0
  64. package/examples/comfy-cloud/wan22-i2v.cflow.ts +107 -0
  65. package/examples/comfy-cloud/wan22-t2v.cflow.ts +98 -0
  66. package/examples/comfy-cloud/z-image-t2i.cflow.ts +62 -0
  67. package/examples/images/README.md +18 -0
  68. package/examples/images/bear_1024x1024.jpg +0 -0
  69. package/examples/images/deer_768x1344.jpg +0 -0
  70. package/examples/images/dog_512x512.jpg +0 -0
  71. package/examples/images/lioness_768x768.jpg +0 -0
  72. package/examples/images/pug_200x300.jpg +0 -0
  73. package/examples/images/walrus_1344x768.jpg +0 -0
  74. package/guide-for-agents.md +172 -0
  75. package/package.json +20 -4
  76. package/src/cli/comfy-ts-cli.ts +19 -2
  77. package/src/cli/gen.ts +21 -12
  78. package/src/cli/tui/components/PreviewPanel.tsx +9 -8
  79. package/src/cli/tui/components/StatusBar.tsx +11 -0
  80. package/src/cli/tui/components/TreePanel.tsx +15 -2
  81. package/src/cli/tui/components/TuiApp.tsx +18 -0
  82. package/src/cli/tui/discoverWorkflows.ts +45 -0
  83. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +72 -0
  84. package/src/cli/tui/imagePicker/ImagePickerSt.ts +288 -0
  85. package/src/cli/tui/imagePicker/fsListing.ts +46 -0
  86. package/src/cli/tui/imagePicker/pickerPrefs.ts +78 -0
  87. package/src/cli/tui/run-tui.tsx +52 -23
  88. package/src/cli/tui/state/HostSt.ts +2 -3
  89. package/src/cli/tui/state/LorasSt.ts +14 -36
  90. package/src/cli/tui/state/PreviewSt.ts +28 -2
  91. package/src/cli/tui/state/TreeSt.ts +30 -6
  92. package/src/cli/tui/state/TuiSt.ts +27 -3
  93. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  94. package/src/exampleAssets.ts +56 -0
  95. package/src/graph/ComfyNode.ts +4 -1
  96. package/src/host/ComfyHost.ts +203 -77
  97. package/src/host/ComfyManager.ts +10 -9
  98. package/src/host/ComfyUploader.ts +1 -2
  99. package/src/host/ResilientWebsocket.ts +3 -1
  100. package/src/host/hostUrl.ts +59 -0
  101. package/src/host/loraManagerApi.ts +5 -4
  102. package/src/index.ts +27 -1
  103. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  104. package/src/litegraph/LiteGraphGroup.ts +9 -7
  105. package/src/litegraph/LiteGraphJSON.ts +34 -13
  106. package/src/litegraph/LiteGraphLink.ts +32 -2
  107. package/src/litegraph/LiteGraphNode.ts +18 -33
  108. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  109. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  110. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  111. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  112. package/src/litegraph/expandSubgraphs.ts +352 -0
  113. package/src/litegraph/normalizeWorkflow.ts +141 -0
  114. package/src/manager/ComfyRegistry.ts +37 -9
  115. package/src/manager/generated/KnownComfyCustomNodeName.ts +23852 -1926
  116. package/src/manager/generated/KnownComfyPluginTitle.ts +6854 -236
  117. package/src/manager/generated/KnownComfyPluginURL.ts +3425 -111
  118. package/src/manager/generated/KnownModel_Base.ts +23 -7
  119. package/src/manager/generated/KnownModel_FileName.ts +421 -0
  120. package/src/manager/generated/KnownModel_Name.ts +421 -0
  121. package/src/manager/generated/KnownModel_SavePath.ts +34 -8
  122. package/src/manager/generated/KnownModel_Type.ts +18 -14
  123. package/src/manager/json/alter-list.json +221 -221
  124. package/src/manager/json/custom-node-list.json +61020 -21946
  125. package/src/manager/json/extension-node-map.json +81077 -31176
  126. package/src/manager/json/github-stats.json +29321 -12601
  127. package/src/manager/json/model-list.json +5935 -4997
  128. package/src/manager/loaders/parseReport.ts +55 -0
  129. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +15 -49
  130. package/src/manager/loaders/step2_custom-node-list-loader.ts +38 -83
  131. package/src/manager/loaders/step3_extension-node-map-loader.ts +36 -142
  132. package/src/manager/loaders/step4_model-list-loader.ts +25 -36
  133. package/src/manager/loaders/step5_alter-list-loader.ts +29 -0
  134. package/src/manager/loaders/step6_github-stats-loader.ts +23 -0
  135. package/src/manager/script-update-manager.bun.ts +9 -1
  136. package/src/manager/types/ComfyManagerAlterInfo.ts +13 -0
  137. package/src/manager/types/ComfyManagerFileModelInfo.ts +7 -3
  138. package/src/manager/types/ComfyManagerFilePluginContent.ts +6 -9
  139. package/src/manager/types/ComfyManagerFilePluginList.ts +3 -3
  140. package/src/manager/types/ComfyManagerGithubStats.ts +9 -0
  141. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +2 -3
  142. package/src/manager/types/ComfyManagerPluginInfo.ts +48 -34
  143. package/src/runner/ComfyExecution.ts +4 -5
  144. package/src/runner/ComfyWorkflow.ts +2 -2
  145. package/src/runner/wsBinaryFrame.ts +48 -0
  146. package/src/sdk-generator/ComfySchema.ts +14 -1
  147. package/src/sdk-generator/Primitives.ts +6 -24
  148. package/src/sdk-generator/comfy-api-json.ts +3 -1
  149. package/src/sdk-generator/comfyui-sdk-codegen.ts +15 -0
  150. package/src/sdk-generator/inputWidgetKind.ts +196 -0
  151. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  152. package/src/state.ts +13 -2
  153. package/src/vars/ComfyVars.ts +82 -2
  154. package/src/vars/DefinedWorkflow.ts +7 -2
  155. package/dist/log-CdfgILde.js +0 -10
  156. package/dist/log-CdfgILde.js.map +0 -1
  157. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
  158. package/src/utils/tryExtracting.ts +0 -41
@@ -6,7 +6,8 @@ import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPlugin
6
6
  import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
7
7
  import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
8
8
  import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
9
- import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
9
+ import { parseWorkflowJson } from 'src/litegraph/normalizeWorkflow.ts'
10
+ import { parseBinaryWsFrame } from 'src/runner/wsBinaryFrame.ts'
10
11
  import { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
11
12
  import { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
12
13
  import {
@@ -31,6 +32,7 @@ import { writeFileAsync } from 'src/utils/writeFile.ts'
31
32
  import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
32
33
  import { ComfyManager } from 'src/host/ComfyManager.ts'
33
34
  import { ComfyUploader } from 'src/host/ComfyUploader.ts'
35
+ import { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
34
36
  import type { Requirements } from 'src/host/Requirements.ts'
35
37
  import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
36
38
  import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
@@ -39,10 +41,26 @@ import type { VarsSpec } from 'src/vars/ComfyVars.ts'
39
41
  export type ComfyHostID = Tagged<string, { HostID: true }>
40
42
  export type ComfyHostData = {
41
43
  id: string
42
- host: string
43
- port: number
44
+
45
+ /** full base url as pasted from a provider (https://cloud.comfy.org,
46
+ * https://xxx.modal.run, http://192.168.1.5:8188/comfy).
47
+ * Exactly ONE of url OR the legacy host+port (+https?) spelling. */
48
+ url?: string
49
+ host?: string
50
+ port?: number
44
51
  https?: boolean
45
52
 
53
+ /** sent as X-API-Key on every request AND the ws upgrade.
54
+ * NEVER persist the value: read it from an env var (e.g. COMFY_CLOUD_API_KEY) */
55
+ apiKey?: string
56
+ /** default true. false = never write sdk.d.ts to .comfy-ts/hosts/<id>/ —
57
+ * schema updates stay in-memory. The comfy-cloud example sets false: its sdk
58
+ * home is the COMMITTED examples/comfy-cloud/sdk.d.ts (gen:sdk:cloud), and a
59
+ * second copy under .comfy-ts/hosts/ would double-declare the globals. */
60
+ sdkAutoWrite?: boolean
61
+ /** extra headers merged into every request + the ws upgrade (Modal-style auth pairs) */
62
+ headers?: Record<string, string>
63
+
46
64
  // for extra features using path manipulation
47
65
  installType?: ComfyInstallType
48
66
 
@@ -68,6 +86,20 @@ type ServerLog = {
68
86
  id: number
69
87
  }
70
88
 
89
+ /** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
90
+ * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
91
+ * (or plain rate limiting on non-cloud hosts). The key value never appears here. */
92
+ export class ComfyHostAuthError extends Error {
93
+ constructor(
94
+ public code: 401 | 402 | 429,
95
+ public hostId: string,
96
+ message: string,
97
+ ) {
98
+ super(message)
99
+ this.name = 'ComfyHostAuthError'
100
+ }
101
+ }
102
+
71
103
  export class ComfyHost<ID extends string = string> {
72
104
  // ----- misc paths where we'll store host-related files -----
73
105
  cacheFolder: AbsolutePath
@@ -80,7 +112,12 @@ export class ComfyHost<ID extends string = string> {
80
112
  schema: ComfySchema
81
113
  uploader = new ComfyUploader(this)
82
114
 
115
+ /** parsed ONCE from data (url-first or legacy host/port/https) — the url ground truth */
116
+ readonly base: ParsedHostBase
117
+
83
118
  constructor(public data: ComfyHostData & { id: ID }) {
119
+ this.base = parseHostBase(this.data)
120
+
84
121
  /** folder where file related to the host config will be cached */
85
122
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
86
123
 
@@ -198,17 +235,106 @@ export class ComfyHost<ID extends string = string> {
198
235
 
199
236
  // URLS -----------------------------------------------------------------------------
200
237
  getServerHostHTTP(): string {
201
- const method = this.data.https ? 'https' : 'http'
202
- const host = this.data.host
203
- const port = this.data.port
204
- return `${method}://${host}:${port}`
238
+ return renderHttpBase(this.base)
205
239
  }
206
240
 
207
241
  getWSUrl = (): string => {
208
- const method = this.data.https ? 'wss' : 'ws'
209
- const host = this.data.host
210
- const port = this.data.port
211
- return `${method}://${host}:${port}/ws`
242
+ return renderWsUrl(this.base)
243
+ }
244
+
245
+ // HTTP -----------------------------------------------------------------------------
246
+ /** extra headers + X-API-Key, for every http request AND the ws upgrade */
247
+ private authHeaders(): Record<string, string> {
248
+ const out: Record<string, string> = {}
249
+ if (this.data.headers != null) Object.assign(out, this.data.headers)
250
+ if (this.data.apiKey != null) out['X-API-Key'] = this.data.apiKey
251
+ return out
252
+ }
253
+
254
+ /** remembered /api-prefix verdict for this host; null until first probed */
255
+ private _apiPrefix: boolean | null = null
256
+
257
+ /**
258
+ * the ONE http path to this host: joins basePath, injects X-API-Key + extra
259
+ * headers, prefers `/api<route>` (required by Comfy Cloud, canonical since
260
+ * custom nodes hijack bare routes) with a bare-route fallback on 404/405 for
261
+ * old local servers (winner memoized; the other spelling is still retried
262
+ * when the memo misses — mixed servers exist, e.g. /internal is bare-only).
263
+ * Auth failures throw a typed ComfyHostAuthError instead of generic noise.
264
+ * `p.apiPrefix: false` opts a route out of the prefix game entirely.
265
+ */
266
+ fetch = async (route: string, init: RequestInit = {}, p: { apiPrefix?: boolean } = {}): Promise<Response> => {
267
+ const base = this.getServerHostHTTP()
268
+ const headers = new Headers(init.headers)
269
+ for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v)
270
+ const send = (prefixed: boolean): Promise<Response> =>
271
+ fetch(`${base}${prefixed ? '/api' : ''}${route}`, { ...init, headers })
272
+ const missed = (res: Response): boolean => res.status === 404 || res.status === 405
273
+
274
+ let res: Response
275
+ if (p.apiPrefix === false) {
276
+ res = await send(false)
277
+ } else if (this._apiPrefix != null) {
278
+ res = await send(this._apiPrefix)
279
+ if (missed(res)) {
280
+ const alt = await send(!this._apiPrefix)
281
+ if (!missed(alt)) res = alt
282
+ }
283
+ } else {
284
+ res = await send(true)
285
+ if (missed(res)) {
286
+ const bare = await send(false)
287
+ if (!missed(bare)) {
288
+ this._apiPrefix = false
289
+ res = bare
290
+ }
291
+ } else {
292
+ this._apiPrefix = true
293
+ }
294
+ }
295
+ this.throwOnAuthError(res, route)
296
+ return res
297
+ }
298
+
299
+ /**
300
+ * binary download path: Comfy Cloud answers `/api/view` with a 302 to a
301
+ * temporary signed URL. fetch only auto-strips Authorization/cookies on
302
+ * cross-origin redirects — a custom X-API-Key WOULD be forwarded to the
303
+ * storage host — so we follow the Location manually with a CLEAN fetch.
304
+ */
305
+ fetchFile = async (route: string): Promise<Response> => {
306
+ const res = await this.fetch(route, { redirect: 'manual' })
307
+ if (res.status >= 300 && res.status < 400) {
308
+ const location = res.headers.get('location')
309
+ if (location == null)
310
+ throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`)
311
+ void res.body?.cancel()
312
+ return fetch(new URL(location, this.getServerHostHTTP()))
313
+ }
314
+ return res
315
+ }
316
+
317
+ private throwOnAuthError(res: Response, route: string): void {
318
+ if (res.status === 401)
319
+ throw new ComfyHostAuthError(
320
+ 401,
321
+ this.data.id,
322
+ this.data.apiKey != null
323
+ ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired`
324
+ : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`,
325
+ )
326
+ if (res.status === 402)
327
+ throw new ComfyHostAuthError(
328
+ 402,
329
+ this.data.id,
330
+ `host '${this.data.id}': 402 on ${route} — insufficient credits`,
331
+ )
332
+ if (res.status === 429)
333
+ throw new ComfyHostAuthError(
334
+ 429,
335
+ this.data.id,
336
+ `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`,
337
+ )
212
338
  }
213
339
 
214
340
  // LOGS -----------------------------------------------------------------------------
@@ -239,9 +365,14 @@ export class ComfyHost<ID extends string = string> {
239
365
  return new DefinedWorkflow(this, spec)
240
366
  }
241
367
 
242
- /** import a workflow.json (litegraph format) as a live, editable workflow */
243
- importWorkflowJson = (json: LiteGraphJSON, p: { id?: string } = {}): ComfyWorkflow<ID> => {
244
- const apiJson = convertLiteGraphToPrompt(this.schema, json)
368
+ /**
369
+ * import a workflow.json (litegraph format) as a live, editable workflow.
370
+ * Accepts unknown: the JSON is ark-validated + normalized (parseWorkflowJson)
371
+ * before conversion — invalid documents throw WorkflowNormalizeError.
372
+ */
373
+ importWorkflowJson = (json: unknown, p: { id?: string } = {}): ComfyWorkflow<ID> => {
374
+ const canonical = parseWorkflowJson(json)
375
+ const apiJson = convertLiteGraphToPrompt(this.schema, canonical)
245
376
  return this.importApiJson(apiJson, p)
246
377
  }
247
378
 
@@ -303,6 +434,7 @@ export class ComfyHost<ID extends string = string> {
303
434
  }
304
435
 
305
436
  private async writeSDKToDisk(): Promise<void> {
437
+ if (this.data.sdkAutoWrite === false) return
306
438
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
307
439
  // skip the 4MB write when nothing changed (fast re-connects)
308
440
  if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return
@@ -371,6 +503,8 @@ export class ComfyHost<ID extends string = string> {
371
503
  },
372
504
  onMessage: (e: MessageEvent): void => this.onMessage(e),
373
505
  url: () => this.getWSUrl(),
506
+ // auth rides the upgrade HEADERS, never the query string
507
+ headers: () => this.authHeaders(),
374
508
  onClose: (): void => {
375
509
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
376
510
  },
@@ -391,8 +525,18 @@ export class ComfyHost<ID extends string = string> {
391
525
  private _schemaFromCache: Promise<void> | null = null
392
526
 
393
527
  /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
394
- * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
528
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once.
529
+ * A MISSING cache degrades LOUDLY to the base types instead of failing the
530
+ * module import (a fresh consumer project has no cache yet — the bundled
531
+ * examples must still open in the TUI; run() fetches the real schema through
532
+ * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
395
533
  loadSchemaFromCache(): Promise<void> {
534
+ if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
535
+ toastError(
536
+ `no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`,
537
+ )
538
+ return Promise.resolve()
539
+ }
396
540
  this._schemaFromCache ??= (async (): Promise<void> => {
397
541
  const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)
398
542
  const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])
@@ -410,18 +554,14 @@ export class ComfyHost<ID extends string = string> {
410
554
  return this._schemaFromCache
411
555
  }
412
556
 
413
- /** POST a JSON route, preferring the /api prefix, falling back to the bare route */
557
+ /** POST a JSON route through host.fetch (/api preferred, bare fallback) */
414
558
  private postJSON_ = async (route: string, body: unknown): Promise<void> => {
415
- const base = this.getServerHostHTTP()
416
- for (const url of [`${base}/api${route}`, `${base}${route}`]) {
417
- const res = await fetch(url, {
418
- method: 'POST',
419
- headers: { 'Content-Type': 'application/json' },
420
- body: JSON.stringify(body),
421
- })
422
- if (res.ok) return
423
- }
424
- throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`)
559
+ const res = await this.fetch(route, {
560
+ method: 'POST',
561
+ headers: { 'Content-Type': 'application/json' },
562
+ body: JSON.stringify(body),
563
+ })
564
+ if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)
425
565
  }
426
566
 
427
567
  /** drop every PENDING prompt from the server queue (the running one keeps going) */
@@ -439,7 +579,7 @@ export class ComfyHost<ID extends string = string> {
439
579
 
440
580
  /** the server's recent console buffer (entries are write CHUNKS, not lines) */
441
581
  fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {
442
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`)
582
+ const res = await this.fetch('/internal/logs/raw', {}, { apiPrefix: false })
443
583
  if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)
444
584
  const json: unknown = await res.json()
445
585
  // wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast
@@ -454,24 +594,27 @@ export class ComfyHost<ID extends string = string> {
454
594
  /** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,
455
595
  * must be re-sent after every reconnect (see onSession) */
456
596
  subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {
457
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {
458
- method: 'PATCH',
459
- headers: { 'Content-Type': 'application/json' },
460
- body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),
461
- })
597
+ const res = await this.fetch(
598
+ '/internal/logs/subscribe',
599
+ {
600
+ method: 'PATCH',
601
+ headers: { 'Content-Type': 'application/json' },
602
+ body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),
603
+ },
604
+ { apiPrefix: false },
605
+ )
462
606
  if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)
463
607
  }
464
608
 
465
- /** GET a JSON route, preferring the /api prefix, falling back to the bare route */
609
+ /** GET a JSON route through host.fetch (/api preferred, bare fallback) */
466
610
  private fetchJSON_ = async <T>(route: string): Promise<T> => {
467
611
  const base = this.getServerHostHTTP()
468
- for (const url of [`${base}/api${route}`, `${base}${route}`]) {
469
- const res = await fetch(url, { method: 'GET' })
470
- if (!res.ok) continue
471
- if (!(res.headers.get('content-type') ?? '').includes('json')) continue
472
- return (await res.json()) as T
473
- }
474
- throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`)
612
+ const res = await this.fetch(route)
613
+ if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`)
614
+ const contentType = res.headers.get('content-type') ?? ''
615
+ if (!contentType.includes('json'))
616
+ throw new Error(`GET ${route} on ${base} answered '${contentType || 'no content-type'}' instead of json`)
617
+ return (await res.json()) as T
475
618
  }
476
619
 
477
620
  /** retrieve the comfy spec from the schema*/
@@ -571,51 +714,34 @@ export class ComfyHost<ID extends string = string> {
571
714
  /** the session assigned to us by the server */
572
715
  comfySessionId: string = 'temp' /** send by ComfyUI server */
573
716
 
717
+ /** binary frame types we already complained about (one log per type, no spam) */
718
+ private _unknownBinaryFrameTypes = new Set<number>()
719
+
574
720
  /** handy to keep around */
575
721
  status: ComfyStatusData['status'] | null = null
576
722
 
577
723
  onMessage(e: MessageEvent): void {
578
724
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
579
725
  if (e.data instanceof ArrayBuffer) {
580
- // 🔴 console.log('[👢] WEBSOCKET: received ArrayBuffer', e.data)
581
- const view = new DataView(e.data)
582
- const eventType = view.getUint32(0)
583
- const buffer = e.data.slice(4)
584
- switch (eventType) {
585
- case 1: {
586
- const view2 = new DataView(e.data)
587
- const imageType = view2.getUint32(4)
588
- let imageMime: string
589
- switch (imageType) {
590
- case 1:
591
- imageMime = 'image/jpeg'
592
- break
593
- case 2:
594
- imageMime = 'image/png'
595
- break
596
- default:
597
- imageMime = 'image/jpeg'
598
- break
599
- }
600
- const imageBytes = buffer.slice(4)
601
- const imageBlob = new Blob([imageBytes], { type: imageMime })
602
- const imagePreview = URL.createObjectURL(imageBlob)
603
- this.latentPreview = {
604
- blob: imageBlob,
605
- url: imagePreview,
606
- receivedAt: Date.now() as number_Timestamp,
607
- promptID: this.activePromptID,
608
- }
609
- this.onLatentPreview?.({
610
- bytes: new Uint8Array(imageBytes),
611
- mime: imageMime,
612
- promptID: this.activePromptID,
613
- })
614
- break
726
+ const frame = parseBinaryWsFrame(e.data)
727
+ if (frame.kind === 'preview') {
728
+ // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook
729
+ const imageBlob = new Blob([frame.bytes], { type: frame.mime })
730
+ this.latentPreview = {
731
+ blob: imageBlob,
732
+ url: URL.createObjectURL(imageBlob),
733
+ receivedAt: Date.now() as number_Timestamp,
734
+ promptID: this.activePromptID,
615
735
  }
616
- default:
617
- throw new Error(`Unknown binary websocket message of type ${eventType}`)
736
+ this.onLatentPreview?.({ bytes: frame.bytes, mime: frame.mime, promptID: this.activePromptID })
737
+ } else if (frame.kind === 'unknown' && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
738
+ // wire tolerance: log once per type, never throw (a throw per sampling
739
+ // step is what the first live cloud run did on type 4)
740
+ this._unknownBinaryFrameTypes.add(frame.eventType)
741
+ console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`)
618
742
  }
743
+ // frame.kind === 'text' (node progress text) is dropped: the json
744
+ // 'progress' messages already carry everything we surface
619
745
  return
620
746
  }
621
747
 
@@ -21,7 +21,12 @@ import { softValidate } from 'src/utils/softValidate.ts'
21
21
  import type { PluginInstallStatus } from 'src/host/Requirements.ts'
22
22
 
23
23
  export class ComfyManager {
24
- constructor(public host: { getServerHostHTTP: () => string }) {
24
+ constructor(
25
+ public host: {
26
+ getServerHostHTTP: () => string
27
+ fetch: (route: string, init?: RequestInit, p?: { apiPrefix?: boolean }) => Promise<Response>
28
+ },
29
+ ) {
25
30
  // void this.updateHostPluginsAndModels()
26
31
  }
27
32
 
@@ -58,11 +63,10 @@ export class ComfyManager {
58
63
  no()
59
64
  }
60
65
  if (abortCtrl) abortCtrl.abort()
61
- const url = this.host.getServerHostHTTP()
62
66
  abortCtrl = new AbortController()
63
67
  try {
64
68
  console.log(` - trying...`)
65
- await fetch(url, { signal: abortCtrl.signal })
69
+ await this.host.fetch('/', { signal: abortCtrl.signal }, { apiPrefix: false })
66
70
  clearInterval(interval)
67
71
  yes(true)
68
72
  } catch {
@@ -200,8 +204,7 @@ export class ComfyManager {
200
204
 
201
205
  // --------------------------------------------------------------
202
206
  private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {
203
- const url = this.host.getServerHostHTTP() + endpoint
204
- const response = await fetch(url, {
207
+ const response = await this.host.fetch(endpoint, {
205
208
  method: 'POST',
206
209
  headers: { 'Content-Type': 'application/json' },
207
210
  body: JSON.stringify(body),
@@ -214,8 +217,7 @@ export class ComfyManager {
214
217
  }
215
218
 
216
219
  private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {
217
- const url = this.host.getServerHostHTTP() + endpoint
218
- const response = await fetch(url)
220
+ const response = await this.host.fetch(endpoint)
219
221
  if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)
220
222
  const jsonResult = await response.json()
221
223
  if (validator) return softValidate(validator, jsonResult)
@@ -224,8 +226,7 @@ export class ComfyManager {
224
226
  }
225
227
 
226
228
  private fetchGetText = async (endopint: string): Promise<string> => {
227
- const url = this.host.getServerHostHTTP() + endopint
228
- const response = await fetch(url)
229
+ const response = await this.host.fetch(endopint)
229
230
  const status = await response.text()
230
231
  return status
231
232
  }
@@ -50,8 +50,7 @@ export class ComfyUploader {
50
50
  if (p.override ?? true) form.set('override', 'true')
51
51
  // const subfolder = p.subfolder ?? 'comfyts-upload'
52
52
  if (p.subfolder) form.set('subfolder', p.subfolder)
53
- const uploadURL = this.host.getServerHostHTTP() + '/upload/image'
54
- const resp = await fetch(uploadURL, { method: 'POST', body: form })
53
+ const resp = await this.host.fetch('/upload/image', { method: 'POST', body: form })
55
54
  const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())
56
55
 
57
56
  // 4. check upload is successfull
@@ -33,6 +33,8 @@ export class ResilientWebSocketClient {
33
33
  constructor(
34
34
  public options: {
35
35
  url: () => string /*protocols?: string | string[]*/
36
+ /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect */
37
+ headers?: () => Record<string, string>
36
38
  onMessage: (event: MessageEvent) => void
37
39
  onConnectOrReconnect: () => void
38
40
  onClose: () => void
@@ -66,7 +68,7 @@ export class ResilientWebSocketClient {
66
68
  this.addInfo('Previous WebSocket discarded')
67
69
  prevWS.close()
68
70
  }
69
- const ws = new WebSocket(this.url)
71
+ const ws = new WebSocket(this.url, { headers: this.options.headers?.() })
70
72
  ws.binaryType = 'arraybuffer'
71
73
 
72
74
  this.currentWS = ws
@@ -0,0 +1,59 @@
1
+ /** pure url layer for ComfyHost: parse once, render everywhere. No comfyts global. */
2
+
3
+ export type ParsedHostBase = {
4
+ scheme: 'http' | 'https'
5
+ host: string
6
+ /** always concrete (defaults 80/443 from the scheme when the url omits it) */
7
+ port: number
8
+ /** '' or '/segment…' with no trailing slash */
9
+ basePath: string
10
+ }
11
+
12
+ /** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
13
+ export function parseHostBase(p: {
14
+ id: string
15
+ url?: string
16
+ host?: string
17
+ port?: number
18
+ https?: boolean
19
+ }): ParsedHostBase {
20
+ const hasLegacy = p.host != null || p.port != null || p.https != null
21
+ if (p.url != null && hasLegacy)
22
+ throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`)
23
+ if (p.url == null) {
24
+ if (p.host == null || p.port == null)
25
+ throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`)
26
+ return { scheme: p.https ? 'https' : 'http', host: p.host, port: p.port, basePath: '' }
27
+ }
28
+
29
+ let parsed: URL
30
+ try {
31
+ parsed = new URL(p.url)
32
+ } catch {
33
+ throw new Error(`host '${p.id}': unparseable url '${p.url}'`)
34
+ }
35
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
36
+ throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`)
37
+ if (parsed.search !== '' || parsed.hash !== '')
38
+ throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`)
39
+ const scheme = parsed.protocol === 'https:' ? 'https' : 'http'
40
+ const port = parsed.port !== '' ? Number(parsed.port) : scheme === 'https' ? 443 : 80
41
+ const basePath = parsed.pathname.replace(/\/+$/, '')
42
+ return { scheme, host: parsed.hostname, port, basePath }
43
+ }
44
+
45
+ /** http(s) base, port omitted when it is the scheme default */
46
+ export function renderHttpBase(p: ParsedHostBase): string {
47
+ return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`
48
+ }
49
+
50
+ /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
51
+ export function renderWsUrl(p: ParsedHostBase): string {
52
+ const scheme = p.scheme === 'https' ? 'wss' : 'ws'
53
+ return `${scheme}://${p.host}${renderPort(p)}${p.basePath}/ws`
54
+ }
55
+
56
+ function renderPort(p: ParsedHostBase): string {
57
+ const schemeDefault = p.scheme === 'https' ? 443 : 80
58
+ return p.port === schemeDefault ? '' : `:${p.port}`
59
+ }
@@ -33,15 +33,15 @@ export function loraPreviewKey(name: string): string {
33
33
  * (server-relative). Returns null when the extension is absent (404/network).
34
34
  */
35
35
  export async function fetchLoraPreviewMap(host: ComfyHost): Promise<Map<string, string> | null> {
36
- const base = host.getServerHostHTTP()
37
36
  const map = new Map<string, string>()
38
37
  const pageSize = 500
39
38
  for (let page = 1; page <= 20; page++) {
40
39
  let res: Response
41
40
  try {
42
- res = await fetch(`${base}/api/lm/loras/list?page=${page}&page_size=${pageSize}`)
41
+ // the extension registers under /api — already prefixed, skip the probe
42
+ res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=${pageSize}`, {}, { apiPrefix: false })
43
43
  } catch {
44
- return null // host unreachable: previews off, not an error
44
+ return null // host unreachable (or auth-refused): previews off, not an error
45
45
  }
46
46
  if (!res.ok) return page === 1 ? null : map // 404 on page 1 = extension absent
47
47
  const json: unknown = await res.json()
@@ -83,7 +83,8 @@ export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string)
83
83
  const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash('sha1').update(previewUrl).digest('hex')}`)
84
84
  if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath))
85
85
  try {
86
- const res = await fetch(`${host.getServerHostHTTP()}${previewUrl}`)
86
+ // preview_url is already a full server-relative path — no /api probing
87
+ const res = await host.fetch(previewUrl, {}, { apiPrefix: false })
87
88
  if (!res.ok) return null
88
89
  const ct = res.headers.get('content-type') ?? ''
89
90
  if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.
package/src/index.ts CHANGED
@@ -10,7 +10,14 @@ export * from 'src/types/comfy-sdk.ts'
10
10
  export { ComfyTS } from 'src/state.ts'
11
11
 
12
12
  // host
13
- export { ComfyHost, type ComfyHostData, type ComfyHostID, type ConnectOptions } from 'src/host/ComfyHost.ts'
13
+ export {
14
+ ComfyHost,
15
+ ComfyHostAuthError,
16
+ type ComfyHostData,
17
+ type ComfyHostID,
18
+ type ConnectOptions,
19
+ } from 'src/host/ComfyHost.ts'
20
+ export { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
14
21
  export { ComfyManager } from 'src/host/ComfyManager.ts'
15
22
  export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
16
23
  export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
@@ -39,6 +46,9 @@ export { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
39
46
  export type { ComfyNodeMetadata, ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
40
47
  export { auto, auto_ } from 'src/graph/autoValue.ts'
41
48
 
49
+ // bundled example assets (ship in the tarball)
50
+ export { exampleImagePath } from 'src/exampleAssets.ts'
51
+
42
52
  // sdk generator (schema parsing + per-host codegen)
43
53
  export { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
44
54
  export { codegenSDK, hostIdToNamespace, type CodegenOptions } from 'src/sdk-generator/comfyui-sdk-codegen.ts'
@@ -49,6 +59,18 @@ export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api
49
59
  // litegraph (ComfyUI saved-workflow JSON format)
50
60
  export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
51
61
  export { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
62
+ export type {
63
+ CanonicalGroup,
64
+ CanonicalInput,
65
+ CanonicalLink,
66
+ CanonicalNode,
67
+ CanonicalOutput,
68
+ CanonicalWidgetValues,
69
+ CanonicalWorkflow,
70
+ NodeMode,
71
+ } from 'src/litegraph/CanonicalWorkflow.ts'
72
+ export { normalizeWorkflow, parseWorkflowJson, WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'
73
+ export { convertLiteGraphToPrompt, WorkflowConvertError } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
52
74
 
53
75
  // vars + re-runnable workflows
54
76
  export {
@@ -64,7 +86,10 @@ export {
64
86
  ChoiceVar,
65
87
  LorasVar,
66
88
  SizeVar,
89
+ ImageVar,
90
+ ImageVarEmptyError,
67
91
  DEFAULT_SIZE_PRESETS,
92
+ DEFAULT_IMAGE_EXTENSIONS,
68
93
  activeLoras,
69
94
  } from 'src/vars/ComfyVars.ts'
70
95
  export type {
@@ -79,6 +104,7 @@ export type {
79
104
  ActiveLora,
80
105
  SizeValue,
81
106
  SizePreset,
107
+ ImageVarOpts,
82
108
  } from 'src/vars/ComfyVars.ts'
83
109
  export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
84
110
  export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'