comfy-ts 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +26 -0
  2. package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-C_QAxKr3.js} +64 -13
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-DcOTn0QR.js} +2 -2
  5. package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-DcOTn0QR.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +346 -183
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +93 -40
  10. package/dist/index.d.ts +94 -41
  11. package/dist/index.js +338 -174
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-Bn6yIJB0.js → run-serve-CN0DhrsA.js} +3 -3
  14. package/dist/{run-serve-Bn6yIJB0.js.map → run-serve-CN0DhrsA.js.map} +1 -1
  15. package/dist/{run-tui-BtjaOXRh.js → run-tui-bN2hSD5i.js} +10 -11
  16. package/dist/{run-tui-BtjaOXRh.js.map → run-tui-bN2hSD5i.js.map} +1 -1
  17. package/dist/{state-DKCPy105.js → state-COlKYipO.js} +199 -146
  18. package/dist/state-COlKYipO.js.map +1 -0
  19. package/dist/web.d.ts +17340 -0
  20. package/dist/web.js +5569 -0
  21. package/dist/web.js.map +1 -0
  22. package/examples/web/example.ts +71 -0
  23. package/examples/web/index.html +77 -0
  24. package/examples/web/serve.ts +42 -0
  25. package/examples/web/tsconfig.json +15 -0
  26. package/package.json +8 -2
  27. package/src/coreExports.ts +118 -0
  28. package/src/host/ComfyHost.ts +23 -23
  29. package/src/host/ResilientWebsocket.ts +93 -47
  30. package/src/host/hostUrl.ts +2 -1
  31. package/src/host/loraManagerApi.ts +6 -7
  32. package/src/index.ts +8 -107
  33. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  34. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  35. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  36. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  37. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  38. package/src/runner/ComfyExecution.ts +14 -11
  39. package/src/runner/MediaImage.ts +18 -30
  40. package/src/sdk-generator/ComfySchema.ts +2 -2
  41. package/src/state.ts +13 -9
  42. package/src/storage/ComfyStorage.ts +144 -0
  43. package/src/storage/nodeStorage.ts +9 -0
  44. package/src/utils/downloadFile.ts +11 -69
  45. package/src/utils/hashArrayBuffer.ts +3 -4
  46. package/src/utils/lazySharp.ts +25 -0
  47. package/src/utils/sha1.ts +69 -0
  48. package/src/vars/ComfyVars.ts +5 -6
  49. package/src/vars/loraKeywords.ts +6 -6
  50. package/src/web.ts +13 -0
  51. package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
  52. package/dist/state-DKCPy105.js.map +0 -1
  53. package/src/utils/writeFile.ts +0 -16
@@ -0,0 +1,71 @@
1
+ // comfy-ts/web in a real browser page: connect to a ComfyUI host, build a
2
+ // txt2img graph, run it, show the image — no server between the page and
3
+ // Comfy. The host must allow browser origins:
4
+ // python main.py --enable-cors-header '*'
5
+ // (Comfy Cloud sends no CORS headers today — cloud rides `comfy-ts serve`.)
6
+ import { ComfyTS } from 'comfy-ts/web'
7
+
8
+ const comfy = ComfyTS.create()
9
+
10
+ function el<T extends HTMLElement>(id: string): T {
11
+ const hit = document.getElementById(id)
12
+ if (hit == null) throw new Error(`missing #${id}`)
13
+ return hit as T
14
+ }
15
+
16
+ /** a LIVE host has whatever nodes it has — resolve or fail loud by name */
17
+ function node<T>(factory: T | undefined, name: string): T {
18
+ if (factory == null) throw new Error(`this host has no ${name} node`)
19
+ return factory
20
+ }
21
+
22
+ const status = el<HTMLDivElement>('status')
23
+ const output = el<HTMLImageElement>('output')
24
+
25
+ async function generate(): Promise<void> {
26
+ const url = el<HTMLInputElement>('host').value.trim()
27
+ const prompt = el<HTMLTextAreaElement>('prompt').value
28
+ const ckptName = el<HTMLInputElement>('ckpt').value.trim()
29
+ status.textContent = 'connecting…'
30
+ try {
31
+ // one host per url; re-clicking with the same url reuses the connection
32
+ const host = comfy.host({ id: `web-${url}`, url })
33
+ await host.connect()
34
+
35
+ const wf = host.workflow()
36
+ const b = wf.builderBase
37
+ const ckpt = node(b.CheckpointLoaderSimple, 'CheckpointLoaderSimple')({ ckpt_name: ckptName })
38
+ const latent = node(b.EmptyLatentImage, 'EmptyLatentImage')({ width: 512, height: 512, batch_size: 1 })
39
+ const sampled = node(
40
+ b.KSampler,
41
+ 'KSampler',
42
+ )({
43
+ model: ckpt,
44
+ positive: node(b.CLIPTextEncode, 'CLIPTextEncode')({ clip: ckpt, text: prompt }),
45
+ negative: node(b.CLIPTextEncode, 'CLIPTextEncode')({ clip: ckpt, text: 'blurry, low quality' }),
46
+ latent_image: latent,
47
+ sampler_name: 'euler',
48
+ scheduler: 'normal',
49
+ seed: Math.floor(Math.random() * 2 ** 32),
50
+ steps: 20,
51
+ cfg: 7,
52
+ denoise: 1,
53
+ })
54
+ node(b.SaveImage, 'SaveImage')({ images: node(b.VAEDecode, 'VAEDecode')({ samples: sampled, vae: ckpt }) })
55
+
56
+ const execution = await wf.run({
57
+ onProgress: (p) => {
58
+ status.textContent = `${p.percent.toFixed(0)}%${p.nodeName ? ` · ${p.nodeName}` : ''}`
59
+ },
60
+ })
61
+ const img = execution.images[0]
62
+ if (img == null) throw new Error(`no image came back (status: ${execution.status})`)
63
+ output.src = URL.createObjectURL(img.getAsBlob())
64
+ status.textContent = `done · ${img.filename}`
65
+ } catch (e) {
66
+ status.textContent = String(e)
67
+ throw e // loud in the console too
68
+ }
69
+ }
70
+
71
+ el<HTMLButtonElement>('generate').onclick = (): void => void generate()
@@ -0,0 +1,77 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>comfy-ts/web — txt2img in the browser</title>
7
+ <style>
8
+ :root {
9
+ color-scheme: dark;
10
+ }
11
+ body {
12
+ font-family: ui-monospace, monospace;
13
+ max-width: 640px;
14
+ margin: 2rem auto;
15
+ padding: 0 1rem;
16
+ background: #111;
17
+ color: #ddd;
18
+ }
19
+ label {
20
+ display: block;
21
+ margin-top: 0.8rem;
22
+ font-size: 0.8rem;
23
+ opacity: 0.7;
24
+ }
25
+ input,
26
+ textarea {
27
+ width: 100%;
28
+ box-sizing: border-box;
29
+ background: #1a1a1a;
30
+ color: #ddd;
31
+ border: 1px solid #333;
32
+ padding: 0.5rem;
33
+ font: inherit;
34
+ }
35
+ button {
36
+ margin-top: 1rem;
37
+ padding: 0.5rem 1.5rem;
38
+ background: #2a6;
39
+ color: #fff;
40
+ border: 0;
41
+ font: inherit;
42
+ cursor: pointer;
43
+ }
44
+ #status {
45
+ margin-top: 0.8rem;
46
+ min-height: 1.2em;
47
+ opacity: 0.8;
48
+ }
49
+ #output {
50
+ margin-top: 1rem;
51
+ max-width: 100%;
52
+ }
53
+ .note {
54
+ font-size: 0.75rem;
55
+ opacity: 0.5;
56
+ margin-top: 1.5rem;
57
+ }
58
+ </style>
59
+ </head>
60
+ <body>
61
+ <h1>comfy-ts/web</h1>
62
+ <label for="host">ComfyUI host (started with <code>--enable-cors-header '*'</code>)</label>
63
+ <input id="host" value="http://127.0.0.1:8188" />
64
+ <label for="ckpt">checkpoint name (as the host knows it)</label>
65
+ <input id="ckpt" value="v1-5-pruned-emaonly.ckpt" />
66
+ <label for="prompt">prompt</label>
67
+ <textarea id="prompt" rows="3">a lighthouse on a cliff, dramatic sky</textarea>
68
+ <button id="generate">generate</button>
69
+ <div id="status"></div>
70
+ <img id="output" alt="" />
71
+ <p class="note">
72
+ Everything runs in this page: comfy-ts/web talks to the host directly (schema fetch, websocket progress, image
73
+ download). Nothing touches disk — the library writes to an in-memory store.
74
+ </p>
75
+ <script type="module" src="./example.js"></script>
76
+ </body>
77
+ </html>
@@ -0,0 +1,42 @@
1
+ // dev server for the browser example: bundles example.ts with the SAME
2
+ // browser target the guard test enforces, serves it with index.html.
3
+ // bun examples/web/serve.ts → http://127.0.0.1:8290
4
+ import { fileURLToPath } from 'node:url'
5
+ import { dirname, join } from 'pathe'
6
+
7
+ const here = dirname(fileURLToPath(import.meta.url))
8
+ const repoRoot = join(here, '../..')
9
+
10
+ const result = await Bun.build({
11
+ entrypoints: [join(here, 'example.ts')],
12
+ target: 'browser',
13
+ minify: false,
14
+ plugins: [
15
+ {
16
+ name: 'repo-paths',
17
+ setup(build) {
18
+ build.onResolve({ filter: /^comfy-ts\/web$/ }, () => ({ path: join(repoRoot, 'src/web.ts') }))
19
+ build.onResolve({ filter: /^src\// }, (args) => ({ path: join(repoRoot, args.path) }))
20
+ },
21
+ },
22
+ ],
23
+ })
24
+ if (!result.success) {
25
+ console.error(result.logs.join('\n'))
26
+ throw new Error('example bundle failed')
27
+ }
28
+ const first = result.outputs[0]
29
+ if (first == null) throw new Error('no bundle output')
30
+ const bundle = await first.text()
31
+
32
+ const server = Bun.serve({
33
+ port: 8290,
34
+ hostname: '127.0.0.1',
35
+ fetch: (req) => {
36
+ const path = new URL(req.url).pathname
37
+ if (path === '/example.js') return new Response(bundle, { headers: { 'content-type': 'text/javascript' } })
38
+ return new Response(Bun.file(join(here, 'index.html')))
39
+ },
40
+ })
41
+ console.log(`comfy-ts/web example → http://127.0.0.1:${server.port}/`)
42
+ console.log(`point it at a ComfyUI started with: --enable-cors-header '*'`)
@@ -0,0 +1,15 @@
1
+ {
2
+ // the ONE dom-typed corner of the repo: the browser example needs document/
3
+ // URL.createObjectURL. src/ stays dom-free by machine (root + lib configs
4
+ // have no dom lib), so a dom global leaking into the library fails there.
5
+ "extends": "../../tsconfig.json",
6
+ "compilerOptions": {
7
+ "lib": ["ESNext", "DOM", "DOM.Iterable"],
8
+ "paths": {
9
+ "src/*": ["../../src/*"],
10
+ "comfy-ts": ["../../src/index.ts"],
11
+ "comfy-ts/web": ["../../src/web.ts"]
12
+ }
13
+ },
14
+ "include": [".", "../../src"]
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -48,6 +48,12 @@
48
48
  "default": "./dist/index.cjs"
49
49
  }
50
50
  },
51
+ "./web": {
52
+ "import": {
53
+ "types": "./dist/web.d.ts",
54
+ "default": "./dist/web.js"
55
+ }
56
+ },
51
57
  "./src/*": "./src/*"
52
58
  },
53
59
  "files": [
@@ -63,7 +69,7 @@
63
69
  "build:watch": "tsdown --watch",
64
70
  "test": "bun test",
65
71
  "test:watch": "bun test --watch",
66
- "typecheck": "tsc --noEmit",
72
+ "typecheck": "tsc --noEmit && tsc -p examples/web/tsconfig.json",
67
73
  "typecheck:lib": "tsc -p tsconfig.lib.json",
68
74
  "lint": "oxlint src examples scripts tests",
69
75
  "format": "oxfmt src examples scripts tests",
@@ -0,0 +1,118 @@
1
+ // the SHARED export surface of both entries (architecture item 13):
2
+ // everything here must stay web-safe — node-only exports live in index.ts.
3
+
4
+ // global Comfy.* base namespace + per-host sdk registry (side-effectful types)
5
+ export * from 'src/types/comfy-sdk.ts'
6
+
7
+ // entrypoint singleton
8
+ export { ComfyTS } from 'src/state.ts'
9
+
10
+ // host
11
+ export {
12
+ ComfyHost,
13
+ ComfyHostAuthError,
14
+ type ComfyHostData,
15
+ type ComfyHostID,
16
+ type ConnectOptions,
17
+ } from 'src/host/ComfyHost.ts'
18
+ export { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
19
+ export { ComfyManager } from 'src/host/ComfyManager.ts'
20
+ export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
21
+ export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
22
+ export type { Requirements, PluginInstallStatus, PluginSuggestion } from 'src/host/Requirements.ts'
23
+ export { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
24
+
25
+ // runner
26
+ export {
27
+ ComfyWorkflow,
28
+ type ComfyNodeIdMode,
29
+ type ComfyWorkflowData,
30
+ type ComfyWorkflowID,
31
+ type ExecutionSnapshot,
32
+ type ProgressReport,
33
+ type RunSettings,
34
+ } from 'src/runner/ComfyWorkflow.ts'
35
+ export { ComfyExecution, type ComfyExecutionData, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
36
+ export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi.ts'
37
+ export { MediaImage, type MediaImageData } from 'src/runner/MediaImage.ts'
38
+ export type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
39
+ export { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
40
+
41
+ // graph (programmatic node graph)
42
+ export { ComfyNode } from 'src/graph/ComfyNode.ts'
43
+ export { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
44
+ export type { ComfyNodeMetadata, ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
45
+ export { auto, auto_ } from 'src/graph/autoValue.ts'
46
+
47
+ // sdk generator (schema parsing + per-host codegen)
48
+ export { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
49
+ export { codegenSDK, hostIdToNamespace, type CodegenOptions } from 'src/sdk-generator/comfyui-sdk-codegen.ts'
50
+ export type { ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
51
+ export type { ComfyImageName, ComfyUnionValue, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'
52
+ export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
53
+
54
+ // litegraph (ComfyUI saved-workflow JSON format)
55
+ export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
56
+ export { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
57
+ export type {
58
+ CanonicalGroup,
59
+ CanonicalInput,
60
+ CanonicalLink,
61
+ CanonicalNode,
62
+ CanonicalOutput,
63
+ CanonicalWidgetValues,
64
+ CanonicalWorkflow,
65
+ NodeMode,
66
+ } from 'src/litegraph/CanonicalWorkflow.ts'
67
+ export { normalizeWorkflow, parseWorkflowJson, WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'
68
+ export { convertLiteGraphToPrompt, WorkflowConvertError } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
69
+
70
+ // vars + re-runnable workflows
71
+ export {
72
+ v,
73
+ ComfyVarBase,
74
+ ComfyVar,
75
+ TextVar,
76
+ PromptVar,
77
+ IntVar,
78
+ FloatVar,
79
+ SeedVar,
80
+ ToggleVar,
81
+ ChoiceVar,
82
+ LorasVar,
83
+ SizeVar,
84
+ ImageVar,
85
+ ImageVarEmptyError,
86
+ DEFAULT_SIZE_PRESETS,
87
+ DEFAULT_IMAGE_EXTENSIONS,
88
+ activeLoras,
89
+ } from 'src/vars/ComfyVars.ts'
90
+ export type {
91
+ AnyVar,
92
+ VarKind,
93
+ VarsSpec,
94
+ VarValues,
95
+ PromptValue,
96
+ ActiveLoraSource,
97
+ LorasHost,
98
+ LoraStrength,
99
+ ActiveLora,
100
+ SizeValue,
101
+ SizePreset,
102
+ ImageVarOpts,
103
+ } from 'src/vars/ComfyVars.ts'
104
+ export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
105
+ export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
106
+ export { loraTag } from 'src/utils/loraTag.ts'
107
+
108
+ // shared types
109
+ export * from 'src/types/index.ts'
110
+
111
+ // the storage seam (custom backends: ComfyTS.create({ storage }))
112
+ export {
113
+ type ComfyStorage,
114
+ createMemoryStorage,
115
+ getComfyStorage,
116
+ setDefaultComfyStorage,
117
+ } from 'src/storage/ComfyStorage.ts'
118
+ export type { WsLike, WsMessageEvent } from 'src/host/ResilientWebsocket.ts'
@@ -1,6 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
- import type { MessageEvent } from 'ws'
4
3
  import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
5
4
  import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'
6
5
  import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
@@ -28,13 +27,12 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
28
27
  import { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'
29
28
  import { readableStringify } from 'src/utils/stringifyReadable.ts'
30
29
  import { logError as toastError, logInfo } from 'src/utils/log.ts'
31
- import { writeFileAsync } from 'src/utils/writeFile.ts'
32
30
  import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
33
31
  import { ComfyManager } from 'src/host/ComfyManager.ts'
34
32
  import { ComfyUploader } from 'src/host/ComfyUploader.ts'
35
33
  import { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
36
34
  import type { Requirements } from 'src/host/Requirements.ts'
37
- import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
35
+ import { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/ResilientWebsocket.ts'
38
36
  import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
39
37
  import type { VarsSpec } from 'src/vars/ComfyVars.ts'
40
38
 
@@ -65,7 +63,7 @@ export type ComfyHostData = {
65
63
  installType?: ComfyInstallType
66
64
 
67
65
  // misc
68
- onWsMessageAny?: (e: MessageEvent) => void
66
+ onWsMessageAny?: (e: WsMessageEvent) => void
69
67
  onWsMessageArrayBuffer?: (e: ArrayBuffer) => void
70
68
  onWsMessageJSON?: (e: WsMsg) => void
71
69
  }
@@ -122,10 +120,10 @@ export class ComfyHost<ID extends string = string> {
122
120
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
123
121
 
124
122
  // create the folder if it does not exist
125
- const exists = existsSync(this.cacheFolder)
126
- if (!exists) {
123
+ const storage = getComfyStorage()
124
+ if (!storage.exists(this.cacheFolder)) {
127
125
  console.log('🟢 creating folder', this.cacheFolder)
128
- mkdirSync(this.cacheFolder, { recursive: true })
126
+ storage.mkdirp(this.cacheFolder)
129
127
  }
130
128
 
131
129
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)
@@ -435,22 +433,22 @@ export class ComfyHost<ID extends string = string> {
435
433
 
436
434
  private async writeSDKToDisk(): Promise<void> {
437
435
  if (this.data.sdkAutoWrite === false) return
436
+ const storage = getComfyStorage()
438
437
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
439
438
  // skip the 4MB write when nothing changed (fast re-connects)
440
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return
441
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, 'utf-8')
439
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return
440
+ storage.writeText(this.sdkDTSPath, comfySchemaTs)
442
441
  }
443
442
 
444
443
  private shouldUseSchemaCache(): boolean {
445
444
  if (this._schemaStrategy === 'refresh') return false
446
- const exists = existsSync(this.comfyJSONPath)
445
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath)
447
446
  if (this._schemaStrategy === 'cache') {
448
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
447
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
449
448
  return true
450
449
  }
451
- if (!exists) return false
452
- const ageMs = Date.now() - statSync(this.comfyJSONPath).mtimeMs
453
- return ageMs < this._schemaMaxAgeMs
450
+ if (mtimeMs == null) return false
451
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs
454
452
  }
455
453
 
456
454
  // WEBSCKET -----------------------------------------------------------------------------
@@ -501,10 +499,12 @@ export class ComfyHost<ID extends string = string> {
501
499
  await this.waitForSession()
502
500
  this.markReady()
503
501
  },
504
- onMessage: (e: MessageEvent): void => this.onMessage(e),
502
+ onMessage: (e: WsMessageEvent): void => this.onMessage(e),
505
503
  url: () => this.getWSUrl(),
506
- // auth rides the upgrade HEADERS, never the query string
504
+ // auth rides the upgrade headers; headerless transports (browser)
505
+ // remap X-API-Key to ?token= inside the ws client
507
506
  headers: () => this.authHeaders(),
507
+ onTransportDead: (e): void => this.markFailed(e),
508
508
  onClose: (): void => {
509
509
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
510
510
  },
@@ -531,7 +531,7 @@ export class ComfyHost<ID extends string = string> {
531
531
  * examples must still open in the TUI; run() fetches the real schema through
532
532
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
533
533
  loadSchemaFromCache(): Promise<void> {
534
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
534
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
535
535
  toastError(
536
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
537
  )
@@ -546,7 +546,7 @@ export class ComfyHost<ID extends string = string> {
546
546
  this.schema.RUN_BASIC_CHECKS()
547
547
 
548
548
  // the on-disk sdk was generated from this same cache — only write when missing
549
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk()
549
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk()
550
550
  })().catch((e: unknown) => {
551
551
  this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)
552
552
  throw e
@@ -626,7 +626,7 @@ export class ComfyHost<ID extends string = string> {
626
626
  // e.g. lora-manager serves HTML at /embeddings)
627
627
  const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')
628
628
  const object_info_str = readableStringify(object_info_json, 4)
629
- void writeFileAsync(this.comfyJSONPath, object_info_str, 'utf-8')
629
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str)
630
630
  // use ark to check if payload match the type, and display errors if not
631
631
  const res = ComfySchemaJSON_ark(object_info_json)
632
632
  if (res instanceof type.errors) {
@@ -638,7 +638,7 @@ export class ComfyHost<ID extends string = string> {
638
638
  const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(
639
639
  () => [] as EmbeddingName[],
640
640
  )
641
- void writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), 'utf-8')
641
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json))
642
642
 
643
643
  // 3 ------------------------------------
644
644
  // update schema
@@ -657,7 +657,7 @@ export class ComfyHost<ID extends string = string> {
657
657
  console.error(error)
658
658
  console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))
659
659
 
660
- const schemaExists = existsSync(this.sdkDTSPath)
660
+ const schemaExists = getComfyStorage().exists(this.sdkDTSPath)
661
661
  if (!schemaExists) await this.writeSDKToDisk()
662
662
  this.markFailed(error)
663
663
  } finally {
@@ -726,7 +726,7 @@ export class ComfyHost<ID extends string = string> {
726
726
  * never revives one) */
727
727
  lastWsMessageAt: number | null = null
728
728
 
729
- onMessage(e: MessageEvent): void {
729
+ onMessage(e: WsMessageEvent): void {
730
730
  this.lastWsMessageAt = Date.now()
731
731
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
732
732
  if (e.data instanceof ArrayBuffer) {