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
@@ -1,9 +1,51 @@
1
- import WebSocket, { type CloseEvent, type Event, type MessageEvent } from 'ws'
1
+ // transport-agnostic since 2026-07-31 (architecture item 13): node uses the
2
+ // `ws` package (custom upgrade headers work), browsers the native WebSocket.
3
+ // The `ws` import specifier is a VARIABLE so browser bundlers never chase it.
2
4
  import type { Maybe } from 'src/types/index.ts'
3
5
  import { bang } from 'src/utils/bang.ts'
6
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
4
7
  import { logInfo } from 'src/utils/log.ts'
5
8
 
6
- type Message = string | Buffer
9
+ type Message = string | Uint8Array
10
+
11
+ /** structural face of both transports (ws package AND browser WebSocket) */
12
+ export type WsLike = {
13
+ binaryType: string
14
+ onmessage: ((event: WsMessageEvent) => void) | null
15
+ onopen: ((event: unknown) => void) | null
16
+ onclose: ((event: WsCloseEvent) => void) | null
17
+ onerror: ((event: unknown) => void) | null
18
+ send(data: Message): void
19
+ close(): void
20
+ }
21
+
22
+ /** what both transports deliver with binaryType 'arraybuffer': string or ArrayBuffer in `data` */
23
+ export type WsMessageEvent = { data: unknown }
24
+ export type WsCloseEvent = { code: number; reason: string }
25
+
26
+ type WsCtor = new (url: string, opts?: { headers?: Record<string, string> }) => WsLike
27
+
28
+ type WsTransport = { ctor: WsCtor; supportsHeaders: boolean }
29
+
30
+ let transportPromise: Promise<WsTransport> | null = null
31
+
32
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
33
+ function resolveWsTransport(): Promise<WsTransport> {
34
+ transportPromise ??= (async (): Promise<WsTransport> => {
35
+ const specifier = 'ws'
36
+ try {
37
+ // cast: the ws package ctor fits WsCtor structurally; a variable
38
+ // specifier types the import as any, so the shape is stated here
39
+ const mod = (await import(specifier)) as { default: WsCtor }
40
+ return { ctor: mod.default, supportsHeaders: true }
41
+ } catch {
42
+ const native = (globalThis as { WebSocket?: WsCtor }).WebSocket
43
+ if (native != null) return { ctor: native, supportsHeaders: false }
44
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`)
45
+ }
46
+ })()
47
+ return transportPromise
48
+ }
7
49
 
8
50
  type WsDebugMessage = {
9
51
  type: 'info' | 'error'
@@ -12,9 +54,8 @@ type WsDebugMessage = {
12
54
  }
13
55
 
14
56
  export class ResilientWebSocketClient {
15
- // private protocols?: string | string[]
16
57
  private url: string
17
- private currentWS?: Maybe<WebSocket>
58
+ private currentWS?: Maybe<WsLike>
18
59
  private messageBuffer: Message[] = []
19
60
 
20
61
  isOpen: boolean = false
@@ -32,19 +73,24 @@ export class ResilientWebSocketClient {
32
73
 
33
74
  constructor(
34
75
  public options: {
35
- url: () => string /*protocols?: string | string[]*/
36
- /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect */
76
+ url: () => string
77
+ /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect.
78
+ * On a headerless transport (browser) X-API-Key rides `?token=` instead
79
+ * (the probed Comfy Cloud contract); other headers throw loud. */
37
80
  headers?: () => Record<string, string>
38
- onMessage: (event: MessageEvent) => void
81
+ onMessage: (event: WsMessageEvent) => void
39
82
  onConnectOrReconnect: () => void
40
83
  onClose: () => void
84
+ /** transport unrecoverable (no ws package AND no global WebSocket, or ctor threw):
85
+ * reported here ONCE, the client goes permanently closed — never a retry storm */
86
+ onTransportDead?: (error: unknown) => void
41
87
  },
42
88
  ) {
43
89
  this.url = options.url()
44
- this.connect()
90
+ void this.connect()
45
91
  }
46
92
 
47
- private reconnectTimeout?: Maybe<NodeJS.Timeout>
93
+ private reconnectTimeout?: Maybe<ReturnType<typeof setTimeout>>
48
94
  private permanentlyClosed: boolean = false
49
95
 
50
96
  /** close and stop reconnecting (lets a script exit cleanly) */
@@ -56,7 +102,21 @@ export class ResilientWebSocketClient {
56
102
  this.isOpen = false
57
103
  }
58
104
 
59
- private connect(): void {
105
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
106
+ private headerlessUrl(headers: Record<string, string>): string {
107
+ const rest = { ...headers }
108
+ const apiKey = rest['X-API-Key']
109
+ delete rest['X-API-Key']
110
+ const extra = Object.keys(rest)
111
+ if (extra.length > 0)
112
+ throw new Error(
113
+ `custom ws headers (${extra.join(', ')}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`,
114
+ )
115
+ if (apiKey == null) return this.url
116
+ return this.url + (this.url.includes('?') ? '&' : '?') + 'token=' + encodeURIComponent(apiKey)
117
+ }
118
+
119
+ private async connect(): Promise<void> {
60
120
  this.isOpen = false
61
121
  const prevWS = this.currentWS
62
122
 
@@ -68,18 +128,32 @@ export class ResilientWebSocketClient {
68
128
  this.addInfo('Previous WebSocket discarded')
69
129
  prevWS.close()
70
130
  }
71
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() })
131
+
132
+ let ws: WsLike
133
+ try {
134
+ const transport = await resolveWsTransport()
135
+ if (this.permanentlyClosed) return // closed while the transport resolved
136
+ const headers = this.options.headers?.() ?? {}
137
+ ws = transport.supportsHeaders
138
+ ? new transport.ctor(this.url, { headers })
139
+ : new transport.ctor(this.headerlessUrl(headers))
140
+ } catch (e) {
141
+ // connect() runs void'd (ctor + reconnect timer): a rethrow here would be
142
+ // an unhandled rejection, so the failure reports through onTransportDead
143
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`)
144
+ this.permanentlyClosed = true
145
+ this.options.onTransportDead?.(e)
146
+ return
147
+ }
72
148
  ws.binaryType = 'arraybuffer'
73
149
 
74
150
  this.currentWS = ws
75
151
 
76
- if (this.options.onMessage) {
77
- ws.onmessage = (event: MessageEvent): void => {
78
- this.options.onMessage(event)
79
- }
152
+ ws.onmessage = (event: WsMessageEvent): void => {
153
+ this.options.onMessage(event)
80
154
  }
81
155
 
82
- ws.onopen = (_event: Event): void => {
156
+ ws.onopen = (): void => {
83
157
  if (ws !== this.currentWS) return
84
158
  this.addInfo('✅ WebSocket connected to ' + this.url)
85
159
  this.isOpen = true
@@ -87,17 +161,17 @@ export class ResilientWebSocketClient {
87
161
  this.flushMessageBuffer()
88
162
  }
89
163
 
90
- ws.onclose = (event: CloseEvent): void => {
164
+ ws.onclose = (event: WsCloseEvent): void => {
91
165
  if (ws !== this.currentWS) return
92
166
  this.isOpen = false
93
167
  this.options.onClose()
94
168
  if (this.permanentlyClosed) return
95
169
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`)
96
170
  this.addInfo('⏱️ reconnecting in 2 seconds...')
97
- this.reconnectTimeout = setTimeout(() => this.connect(), 2000)
171
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2000)
98
172
  }
99
173
 
100
- ws.onerror = (event: Event): void => {
174
+ ws.onerror = (event: unknown): void => {
101
175
  if (ws !== this.currentWS) return
102
176
  this.addError(`WebSocket ERROR` + JSON.stringify(event))
103
177
  console.error({ event })
@@ -118,32 +192,4 @@ export class ResilientWebSocketClient {
118
192
  this.currentWS?.send(message)
119
193
  }
120
194
  }
121
-
122
- /** forward WebSocket add event listeners to the current WebSocket instance */
123
- public addEventListener<K extends keyof WebSocketEventMap>(
124
- type: K,
125
- listener:
126
- | ((event: WebSocket.WebSocketEventMap[K]) => void)
127
- | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
128
- options?: WebSocket.EventListenerOptions,
129
- ): void {
130
- this.currentWS?.addEventListener(type, listener, options)
131
- }
132
-
133
- /** forward WebSocket remove event listeners to the current WebSocket instance */
134
- public removeEventListener<K extends keyof WebSocketEventMap>(
135
- type: K,
136
- listener:
137
- | ((event: WebSocket.WebSocketEventMap[K]) => void)
138
- | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
139
- ): void {
140
- this.currentWS?.removeEventListener(type, listener)
141
- }
142
- }
143
-
144
- type WebSocketEventMap = {
145
- open: Event
146
- close: CloseEvent
147
- error: Event
148
- message: MessageEvent
149
195
  }
@@ -47,7 +47,8 @@ export function renderHttpBase(p: ParsedHostBase): string {
47
47
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`
48
48
  }
49
49
 
50
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
50
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
51
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
51
52
  export function renderWsUrl(p: ParsedHostBase): string {
52
53
  const scheme = p.scheme === 'https' ? 'wss' : 'ws'
53
54
  return `${scheme}://${p.host}${renderPort(p)}${p.basePath}/ws`
@@ -1,7 +1,6 @@
1
- import { createHash } from 'node:crypto'
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
1
  import { type } from 'arktype'
4
- import { dirname } from 'pathe'
2
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
3
+ import { sha1HexOfString } from 'src/utils/sha1.ts'
5
4
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
6
5
  import { logError } from 'src/utils/log.ts'
7
6
 
@@ -80,8 +79,9 @@ export function looksLikeImage(bytes: Uint8Array): boolean {
80
79
  * a non-image content-type OR non-image magic bytes => no preview, not a crash.
81
80
  */
82
81
  export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string): Promise<Uint8Array | null> {
83
- const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash('sha1').update(previewUrl).digest('hex')}`)
84
- if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath))
82
+ const storage = getComfyStorage()
83
+ const cachePath = comfyts.resolveFromCache(`lora-previews/${sha1HexOfString(previewUrl)}`)
84
+ if (storage.exists(cachePath)) return storage.readBytes(cachePath)
85
85
  try {
86
86
  // preview_url is already a full server-relative path — no /api probing
87
87
  const res = await host.fetch(previewUrl, {}, { apiPrefix: false })
@@ -90,8 +90,7 @@ export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string)
90
90
  if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.
91
91
  const bytes = new Uint8Array(await res.arrayBuffer())
92
92
  if (!looksLikeImage(bytes)) return null
93
- mkdirSync(dirname(cachePath), { recursive: true })
94
- writeFileSync(cachePath, bytes)
93
+ storage.writeBytes(cachePath, bytes)
95
94
  return bytes
96
95
  } catch {
97
96
  return null
package/src/index.ts CHANGED
@@ -1,115 +1,16 @@
1
1
  /**
2
- * comfy-ts — type-safe ComfyUI workflow creation and execution
2
+ * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)
3
3
  * @packageDocumentation
4
4
  */
5
+ import { setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'
6
+ import { createNodeStorage } from 'src/storage/nodeStorage.ts'
5
7
 
6
- // global Comfy.* base namespace + per-host sdk registry (side-effectful types)
7
- export * from 'src/types/comfy-sdk.ts'
8
+ // entry side effect: node 20/21 dist consumers have no getBuiltinModule
9
+ // autodetect, so the node backend installs here (architecture item 13)
10
+ setDefaultComfyStorage(createNodeStorage())
8
11
 
9
- // entrypoint singleton
10
- export { ComfyTS } from 'src/state.ts'
12
+ export * from 'src/coreExports.ts'
11
13
 
12
- // host
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'
21
- export { ComfyManager } from 'src/host/ComfyManager.ts'
22
- export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
23
- export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
24
- export type { Requirements, PluginInstallStatus, PluginSuggestion } from 'src/host/Requirements.ts'
25
- export { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
26
-
27
- // runner
28
- export {
29
- ComfyWorkflow,
30
- type ComfyNodeIdMode,
31
- type ComfyWorkflowData,
32
- type ComfyWorkflowID,
33
- type ExecutionSnapshot,
34
- type ProgressReport,
35
- type RunSettings,
36
- } from 'src/runner/ComfyWorkflow.ts'
37
- export { ComfyExecution, type ComfyExecutionData, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
38
- export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi.ts'
39
- export { MediaImage, type MediaImageData } from 'src/runner/MediaImage.ts'
40
- export type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
41
- export { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
42
-
43
- // graph (programmatic node graph)
44
- export { ComfyNode } from 'src/graph/ComfyNode.ts'
45
- export { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
46
- export type { ComfyNodeMetadata, ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
47
- export { auto, auto_ } from 'src/graph/autoValue.ts'
48
-
49
- // bundled example assets (ship in the tarball)
14
+ // node-only surface: fs-backed example assets + the TUI env contract
50
15
  export { exampleImagePath } from 'src/exampleAssets.ts'
51
-
52
- // sdk generator (schema parsing + per-host codegen)
53
- export { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
54
- export { codegenSDK, hostIdToNamespace, type CodegenOptions } from 'src/sdk-generator/comfyui-sdk-codegen.ts'
55
- export type { ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
56
- export type { ComfyImageName, ComfyUnionValue, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'
57
- export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
58
-
59
- // litegraph (ComfyUI saved-workflow JSON format)
60
- export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
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'
74
-
75
- // vars + re-runnable workflows
76
- export {
77
- v,
78
- ComfyVarBase,
79
- ComfyVar,
80
- TextVar,
81
- PromptVar,
82
- IntVar,
83
- FloatVar,
84
- SeedVar,
85
- ToggleVar,
86
- ChoiceVar,
87
- LorasVar,
88
- SizeVar,
89
- ImageVar,
90
- ImageVarEmptyError,
91
- DEFAULT_SIZE_PRESETS,
92
- DEFAULT_IMAGE_EXTENSIONS,
93
- activeLoras,
94
- } from 'src/vars/ComfyVars.ts'
95
- export type {
96
- AnyVar,
97
- VarKind,
98
- VarsSpec,
99
- VarValues,
100
- PromptValue,
101
- ActiveLoraSource,
102
- LorasHost,
103
- LoraStrength,
104
- ActiveLora,
105
- SizeValue,
106
- SizePreset,
107
- ImageVarOpts,
108
- } from 'src/vars/ComfyVars.ts'
109
- export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
110
- export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
111
16
  export { isTuiActive } from 'src/cli/tui-env.ts'
112
- export { loraTag } from 'src/utils/loraTag.ts'
113
-
114
- // shared types
115
- export * from 'src/types/index.ts'
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import { ansi as chalk } from 'src/utils/ansi.ts'
4
4
  import { githubRegexpV1 } from 'src/utils/githubRegexes.ts'
@@ -17,7 +17,7 @@ export const _getKnownPlugins = (DB: ComfyRegistry): void => {
17
17
  let totalFileSeen = 0
18
18
 
19
19
  // parse rows: loose raw schema per row, skip+report failures, normalize survivors
20
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/custom-node-list.json', 'utf8'))
20
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/custom-node-list.json'))
21
21
  const root = ComfyManagerFilePluginListRoot_ark(raw)
22
22
  if (root instanceof type.errors) throw new ManagerParseError('custom-node-list.json', root.summary)
23
23
 
@@ -68,7 +68,7 @@ export const _getKnownPlugins = (DB: ComfyRegistry): void => {
68
68
  }
69
69
  out1 += '\n'
70
70
  const out1Path = 'src/manager/generated/KnownComfyPluginTitle.ts'
71
- writeFileSync(out1Path, out1 + '\n', 'utf-8')
71
+ getComfyStorage().writeText(out1Path, out1 + '\n')
72
72
  console.log(` > generated: ${chalk.blue.underline(out1Path)}`)
73
73
 
74
74
  // FileType
@@ -79,7 +79,7 @@ export const _getKnownPlugins = (DB: ComfyRegistry): void => {
79
79
  out2 += 'export type KnownComfyPluginURL =\n'
80
80
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`
81
81
  const out2Path = 'src/manager/generated/KnownComfyPluginURL.ts'
82
- writeFileSync(out2Path, out2, 'utf-8')
82
+ getComfyStorage().writeText(out2Path, out2)
83
83
  console.log(` > generated: ${chalk.blue.underline(out2Path)}`)
84
84
  }
85
85
 
@@ -1,4 +1,4 @@
1
- import { writeFileSync, readFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import { ansi as chalk } from 'src/utils/ansi.ts'
4
4
  import { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'
@@ -14,7 +14,7 @@ export const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {
14
14
  const counter = DB.report.file('extension-node-map.json')
15
15
  let totalCustomNodeSeen: number = 0
16
16
 
17
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/extension-node-map.json', 'utf8'))
17
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/extension-node-map.json'))
18
18
  const root = type('Record<string, unknown>')(raw)
19
19
  if (root instanceof type.errors) throw new ManagerParseError('extension-node-map.json', root.summary)
20
20
 
@@ -64,7 +64,7 @@ export const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {
64
64
  out += '\n'
65
65
 
66
66
  const outPath = 'src/manager/generated/KnownComfyCustomNodeName.ts'
67
- writeFileSync(outPath, out + '\n', 'utf-8')
67
+ getComfyStorage().writeText(outPath, out + '\n')
68
68
  console.log(` > generated: ${chalk.blue.underline(outPath)}`)
69
69
  }
70
70
 
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import { ansi as chalk } from 'src/utils/ansi.ts'
4
4
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
@@ -10,7 +10,7 @@ import { type ComfyManagerModelInfo, ComfyManagerModelInfo_ark } from 'src/manag
10
10
  export const _getKnownModels = (DB: ComfyRegistry): void => {
11
11
  const counter = DB.report.file('model-list.json')
12
12
 
13
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/model-list.json', 'utf8'))
13
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/model-list.json'))
14
14
  const root = ComfyManagerFileModelInfoRoot_ark(raw)
15
15
  if (root instanceof type.errors) throw new ManagerParseError('model-list.json', root.summary)
16
16
 
@@ -54,7 +54,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
54
54
  out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`
55
55
  out1 += ']\n'
56
56
  const out1Path = 'src/manager/generated/KnownModel_Type.ts'
57
- writeFileSync(out1Path, out1 + '\n', 'utf-8')
57
+ getComfyStorage().writeText(out1Path, out1 + '\n')
58
58
  console.log(` > generated: ${chalk.blue.underline(out1Path)}`)
59
59
 
60
60
  // #region savepath
@@ -77,7 +77,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
77
77
  out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`
78
78
  out4 += ']\n'
79
79
  const out4Path = 'src/manager/generated/KnownModel_SavePath.ts'
80
- writeFileSync(out4Path, out4 + '\n', 'utf-8')
80
+ getComfyStorage().writeText(out4Path, out4 + '\n')
81
81
  console.log(` > generated: ${chalk.blue.underline(out4Path)}`)
82
82
 
83
83
  // #region base
@@ -101,7 +101,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
101
101
  out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`
102
102
  out2 += ']\n'
103
103
  const out2Path = 'src/manager/generated/KnownModel_Base.ts'
104
- writeFileSync(out2Path, out2 + '\n', 'utf-8')
104
+ getComfyStorage().writeText(out2Path, out2 + '\n')
105
105
  console.log(` > generated: ${chalk.blue.underline(out2Path)}`)
106
106
 
107
107
  // #region KnownModel_Name
@@ -118,7 +118,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
118
118
  }
119
119
  out3 += '\n'
120
120
  const out3Path = 'src/manager/generated/KnownModel_Name.ts'
121
- writeFileSync(out3Path, out3 + '\n', 'utf-8')
121
+ getComfyStorage().writeText(out3Path, out3 + '\n')
122
122
  console.log(` > generated: ${chalk.blue.underline(out3Path)}`)
123
123
 
124
124
  // #region KnownModel_FileName
@@ -134,7 +134,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
134
134
  }
135
135
  out99 += '\n'
136
136
  const out99Path = 'src/manager/generated/KnownModel_FileName.ts'
137
- writeFileSync(out99Path, out99 + '\n', 'utf-8')
137
+ getComfyStorage().writeText(out99Path, out99 + '\n')
138
138
  console.log(` > generated: ${chalk.blue.underline(out99Path)}`)
139
139
  }
140
140
 
@@ -1,4 +1,4 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
4
4
  import { ManagerParseError } from 'src/manager/loaders/parseReport.ts'
@@ -11,7 +11,7 @@ import {
11
11
  export const _getAlterList = (DB: ComfyRegistry): void => {
12
12
  const counter = DB.report.file('alter-list.json')
13
13
 
14
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/alter-list.json', 'utf8'))
14
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/alter-list.json'))
15
15
  const root = ComfyManagerFileAlterListRoot_ark(raw)
16
16
  if (root instanceof type.errors) throw new ManagerParseError('alter-list.json', root.summary)
17
17
 
@@ -1,4 +1,4 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
4
4
  import { ManagerParseError } from 'src/manager/loaders/parseReport.ts'
@@ -7,7 +7,7 @@ import { ComfyManagerGithubStatEntry_ark } from 'src/manager/types/ComfyManagerG
7
7
  export const _getGithubStats = (DB: ComfyRegistry): void => {
8
8
  const counter = DB.report.file('github-stats.json')
9
9
 
10
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/github-stats.json', 'utf8'))
10
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/github-stats.json'))
11
11
  const root = type('Record<string, unknown>')(raw)
12
12
  if (root instanceof type.errors) throw new ManagerParseError('github-stats.json', root.summary)
13
13
 
@@ -1,12 +1,12 @@
1
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
2
- import { dirname } from 'pathe'
3
1
  import { localOutputPath, runTimestamp, uniquifyOutputPath } from 'src/runner/outputPath.ts'
4
2
 
5
3
  /** paths claimed by in-flight retrievals: two same-second runs on a
6
4
  * counter-resetting cloud host compute the same name before either writes */
7
5
  const CLAIMED_OUTPUT_PATHS = new Set<string>()
8
- import sharp, { type FormatEnum } from 'sharp'
6
+ import type { FormatEnum } from 'sharp'
9
7
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
8
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
9
+ import { importSharp } from 'src/utils/lazySharp.ts'
10
10
  import { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'
11
11
  import type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
12
12
  import { asAbsolutePath, type ImageSaveFormat, type Maybe } from 'src/types/index.ts'
@@ -100,7 +100,7 @@ export class ComfyExecution {
100
100
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1000).toFixed(0)}s`
101
101
  if (line === this._lastLoggedLine) return
102
102
  this._lastLoggedLine = line
103
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`)
103
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`)
104
104
  else console.log(line)
105
105
  }
106
106
 
@@ -108,7 +108,7 @@ export class ComfyExecution {
108
108
  if (!this.logProgress) return
109
109
  const p = this.progress
110
110
  const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${this.images.length} image(s)`
111
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
111
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
112
112
  else console.log(line)
113
113
  }
114
114
 
@@ -229,9 +229,8 @@ export class ComfyExecution {
229
229
  }
230
230
  // last-resort uniquifier: bump past files on disk AND paths claimed by
231
231
  // still-downloading retrievals — never overwrite
232
- absPath = uniquifyOutputPath({ path: absPath, exists: existsSync, claimed: CLAIMED_OUTPUT_PATHS })
233
- const dir = dirname(absPath)
234
- mkdirSync(dir, { recursive: true })
232
+ const storage = getComfyStorage()
233
+ absPath = uniquifyOutputPath({ path: absPath, exists: (p) => storage.exists(p), claimed: CLAIMED_OUTPUT_PATHS })
235
234
 
236
235
  // ref
237
236
  let img: MediaImage
@@ -253,15 +252,19 @@ export class ComfyExecution {
253
252
  return 'png'
254
253
  })()
255
254
 
256
- await sharp(buff)
255
+ // node-only branch: re-encoding needs sharp (saveFormat 'raw' is the web path)
256
+ const sharp = await importSharp(`saveFormat '${sf.format}' re-encoding`)
257
+ const encoded = await sharp(buff)
257
258
  .withMetadata()
258
259
  .withExif({ IFD0: textChunk })
259
260
  // sharp expect quality between 1 and 100
260
261
  .toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : undefined)
261
- .toFile(absPath)
262
+ .toBuffer()
263
+ storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded))
262
264
 
263
265
  img = new MediaImage({
264
266
  path: asAbsolutePath(absPath),
267
+ buffer: new Uint8Array(encoded),
265
268
  execution: this,
266
269
  promptNodeID: promptNodeID,
267
270
  comfyUIInfos: {
@@ -276,7 +279,7 @@ export class ComfyExecution {
276
279
  const response = await this.host.fetchFile(imgRoute)
277
280
  const buff = await response.arrayBuffer()
278
281
  const uint8arr = new Uint8Array(buff)
279
- writeFileSync(absPath, uint8arr)
282
+ storage.writeBytes(asAbsolutePath(absPath), uint8arr)
280
283
  img = new MediaImage({
281
284
  path: asAbsolutePath(absPath),
282
285
  buffer: uint8arr,