comfy-ts 1.2.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.
- package/README.md +66 -0
- package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
- package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
- package/dist/DraftsSt-DcOTn0QR.js +434 -0
- package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
- package/dist/cli.js +15 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +476 -202
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +98 -40
- package/dist/index.d.ts +117 -59
- package/dist/index.js +468 -193
- package/dist/index.js.map +1 -1
- package/dist/run-serve-CN0DhrsA.js +638 -0
- package/dist/run-serve-CN0DhrsA.js.map +1 -0
- package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
- package/dist/run-tui-bN2hSD5i.js.map +1 -0
- package/dist/state-COlKYipO.js +4743 -0
- package/dist/state-COlKYipO.js.map +1 -0
- package/dist/web.d.ts +17340 -0
- package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
- package/dist/web.js.map +1 -0
- package/examples/web/example.ts +71 -0
- package/examples/web/index.html +77 -0
- package/examples/web/serve.ts +42 -0
- package/examples/web/tsconfig.json +15 -0
- package/package.json +10 -3
- package/src/cli/comfy-ts-cli.ts +15 -5
- package/src/cli/serve/ServeApp.ts +378 -0
- package/src/cli/serve/applyVarPayload.ts +119 -0
- package/src/cli/serve/describeVar.ts +74 -0
- package/src/cli/serve/run-serve.ts +169 -0
- package/src/cli/tui/components/StatusBar.tsx +1 -0
- package/src/cli/tui/components/TreePanel.tsx +17 -3
- package/src/cli/tui/components/TuiApp.tsx +7 -2
- package/src/cli/tui/components/VarsPanel.tsx +67 -34
- package/src/cli/tui/imageClipboard.ts +39 -0
- package/src/cli/tui/listWindow.ts +36 -0
- package/src/cli/tui/state/ExecSt.ts +48 -0
- package/src/cli/tui/state/TreeSt.ts +25 -0
- package/src/cli/tui/state/TuiSt.ts +34 -0
- package/src/coreExports.ts +118 -0
- package/src/host/ComfyHost.ts +23 -23
- package/src/host/ResilientWebsocket.ts +93 -47
- package/src/host/hostUrl.ts +2 -1
- package/src/host/loraManagerApi.ts +6 -7
- package/src/index.ts +8 -107
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
- package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
- package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
- package/src/manager/loaders/step4_model-list-loader.ts +7 -7
- package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
- package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
- package/src/runner/ComfyExecution.ts +32 -12
- package/src/runner/MediaImage.ts +18 -30
- package/src/runner/outputPath.ts +75 -0
- package/src/sdk-generator/ComfySchema.ts +2 -2
- package/src/sdk-generator/inputWidgetKind.ts +50 -11
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
- package/src/state.ts +13 -9
- package/src/storage/ComfyStorage.ts +144 -0
- package/src/storage/nodeStorage.ts +9 -0
- package/src/utils/downloadFile.ts +11 -69
- package/src/utils/hashArrayBuffer.ts +3 -4
- package/src/utils/lazySharp.ts +25 -0
- package/src/utils/sha1.ts +69 -0
- package/src/vars/ComfyVars.ts +13 -6
- package/src/vars/loraKeywords.ts +6 -6
- package/src/web.ts +13 -0
- package/dist/run-tui-BAdizWsO.js.map +0 -1
- package/dist/state-BYbxDgfr.js.map +0 -1
- package/src/utils/writeFile.ts +0 -16
|
@@ -11,7 +11,20 @@ import { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'
|
|
|
11
11
|
*/
|
|
12
12
|
export type InputWidgetKind =
|
|
13
13
|
| { kind: 'slot' }
|
|
14
|
-
| {
|
|
14
|
+
| {
|
|
15
|
+
kind: 'widget'
|
|
16
|
+
/** total widgets_values entries this input's run occupies: prefix buttons + value + control phantom */
|
|
17
|
+
consumes: number
|
|
18
|
+
strictValues: boolean
|
|
19
|
+
/**
|
|
20
|
+
* serialized values the frontend addWidget()s BEFORE the real value
|
|
21
|
+
* (button widgets, creation order). Import reads the value at
|
|
22
|
+
* `offset + prefixValues.length`; export writes these literals first
|
|
23
|
+
* so a round-trip through the ComfyUI editor keeps positional
|
|
24
|
+
* alignment. Empty for every config-signalled widget.
|
|
25
|
+
*/
|
|
26
|
+
prefixValues: readonly unknown[]
|
|
27
|
+
}
|
|
15
28
|
| { kind: 'dynamic-combo'; options: DynamicComboOption[]; defaultKey: string }
|
|
16
29
|
| { kind: 'dynamic-container'; instanceNames: string[]; requiredCount: number }
|
|
17
30
|
|
|
@@ -110,6 +123,24 @@ export const containerInstanceSlotType = (opts: unknown): string | null => {
|
|
|
110
123
|
return first.type
|
|
111
124
|
}
|
|
112
125
|
|
|
126
|
+
/**
|
|
127
|
+
* frontend-registered widgets whose object_info opts carry NO config signal —
|
|
128
|
+
* the one exception to config-only classification (architecture.md rule 8).
|
|
129
|
+
* Every entry must quote the frontend widget-creation source.
|
|
130
|
+
*
|
|
131
|
+
* LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified
|
|
132
|
+
* 2026-07-31): the LOAD_3D custom widget handler runs
|
|
133
|
+
* node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)
|
|
134
|
+
* node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)
|
|
135
|
+
* node.addWidget('button', 'clear', 'clear', …)
|
|
136
|
+
* THEN creates the scene widget, so the serialized run is
|
|
137
|
+
* [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved
|
|
138
|
+
* files, an {image, mask, normal, camera_info, …} dict at queue time.
|
|
139
|
+
*/
|
|
140
|
+
const EMPTY_CONFIG_FRONTEND_WIDGETS: Record<string, { prefixValues: readonly unknown[] }> = {
|
|
141
|
+
LOAD_3D: { prefixValues: ['upload3dmodel', 'uploadExtraResources', 'clear'] },
|
|
142
|
+
}
|
|
143
|
+
|
|
113
144
|
export const classifyWidgetInput = (p: {
|
|
114
145
|
name: string
|
|
115
146
|
type: string | readonly unknown[]
|
|
@@ -123,14 +154,19 @@ export const classifyWidgetInput = (p: {
|
|
|
123
154
|
// 2. enum arrays / parsed E_ unions are combo widgets
|
|
124
155
|
if (Array.isArray(p.type) || p.isEnumUnion === true) {
|
|
125
156
|
const tn = typeof p.type === 'string' ? p.type : 'COMBO'
|
|
126
|
-
return { kind: 'widget', consumes: controlConsumes(o, tn, p.name), strictValues: true }
|
|
157
|
+
return { kind: 'widget', consumes: controlConsumes(o, tn, p.name), strictValues: true, prefixValues: [] }
|
|
127
158
|
}
|
|
128
159
|
if (typeof p.type !== 'string') return { kind: 'slot' }
|
|
129
160
|
// 3. widgetType names the widget for multi-type unions (frontend: widgets.get(widgetType ?? type))
|
|
130
161
|
const widgetTypeName = typeof o?.['widgetType'] === 'string' ? o['widgetType'] : p.type
|
|
131
162
|
// 4. primitives
|
|
132
163
|
if (ComfyPrimitiveMapping[widgetTypeName] != null)
|
|
133
|
-
return {
|
|
164
|
+
return {
|
|
165
|
+
kind: 'widget',
|
|
166
|
+
consumes: controlConsumes(o, widgetTypeName, p.name),
|
|
167
|
+
strictValues: true,
|
|
168
|
+
prefixValues: [],
|
|
169
|
+
}
|
|
134
170
|
// 5. options array: dynamic {key, inputs} family, else plain combo
|
|
135
171
|
const options = o?.['options']
|
|
136
172
|
if (Array.isArray(options)) {
|
|
@@ -141,7 +177,7 @@ export const classifyWidgetInput = (p: {
|
|
|
141
177
|
const defaultKey = typeof o?.['default'] === 'string' ? o['default'] : first.key
|
|
142
178
|
return { kind: 'dynamic-combo', options: dynOptions, defaultKey }
|
|
143
179
|
}
|
|
144
|
-
return { kind: 'widget', consumes: controlConsumes(o, p.type, p.name), strictValues: true }
|
|
180
|
+
return { kind: 'widget', consumes: controlConsumes(o, p.type, p.name), strictValues: true, prefixValues: [] }
|
|
145
181
|
}
|
|
146
182
|
// 6. template WITH nested input = autogrow container; WITHOUT = matchtype slot typing
|
|
147
183
|
const template = o?.['template']
|
|
@@ -150,7 +186,16 @@ export const classifyWidgetInput = (p: {
|
|
|
150
186
|
return { kind: 'slot' }
|
|
151
187
|
}
|
|
152
188
|
// 7. socketless: a widget that never has a socket (IMAGECOMPARE, COLOR); value domain unknown
|
|
153
|
-
if (o?.['socketless'] === true) return { kind: 'widget', consumes: 1, strictValues: false }
|
|
189
|
+
if (o?.['socketless'] === true) return { kind: 'widget', consumes: 1, strictValues: false, prefixValues: [] }
|
|
190
|
+
// 8. known empty-config frontend widgets (LOAD_3D), the one non-config exception
|
|
191
|
+
const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName]
|
|
192
|
+
if (emptyConfigEntry != null)
|
|
193
|
+
return {
|
|
194
|
+
kind: 'widget',
|
|
195
|
+
consumes: emptyConfigEntry.prefixValues.length + 1,
|
|
196
|
+
strictValues: false,
|
|
197
|
+
prefixValues: emptyConfigEntry.prefixValues,
|
|
198
|
+
}
|
|
154
199
|
return { kind: 'slot' }
|
|
155
200
|
}
|
|
156
201
|
|
|
@@ -162,12 +207,6 @@ export const classifySchemaInput = (input: NodeInputExt): InputWidgetKind =>
|
|
|
162
207
|
isEnumUnion: input.isEnum,
|
|
163
208
|
})
|
|
164
209
|
|
|
165
|
-
/** how many widgets_values entries this schema input consumes (export path + positional walks) */
|
|
166
|
-
export const howManyWidgetValuesForThisSchemaType = (input: NodeInputExt): number => {
|
|
167
|
-
const kind = classifySchemaInput(input)
|
|
168
|
-
return kind.kind === 'widget' ? kind.consumes : 0
|
|
169
|
-
}
|
|
170
|
-
|
|
171
210
|
/**
|
|
172
211
|
* what ComfyUI's frontend gives a widget created with no serialized value
|
|
173
212
|
* (`getWidgetDefaultValue` semantics), used when a positional array is
|
|
@@ -145,15 +145,19 @@ export const convertLiteGraphToPrompt = (
|
|
|
145
145
|
)
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
-
/** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
|
|
149
|
-
const resolveWidgetValue = (p: {
|
|
148
|
+
/** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */
|
|
149
|
+
const resolveWidgetValue = (p: {
|
|
150
|
+
promptName: string
|
|
151
|
+
consumes: number
|
|
152
|
+
prefixLen: number
|
|
153
|
+
}): { value: unknown; filled: boolean } => {
|
|
150
154
|
let value: unknown
|
|
151
155
|
let has = false
|
|
152
156
|
if (Object.hasOwn(named, p.promptName)) {
|
|
153
157
|
value = named[p.promptName]
|
|
154
158
|
has = true
|
|
155
|
-
} else if (offset < positional.length) {
|
|
156
|
-
value = positional[offset]
|
|
159
|
+
} else if (offset + p.prefixLen < positional.length) {
|
|
160
|
+
value = positional[offset + p.prefixLen]
|
|
157
161
|
has = true
|
|
158
162
|
}
|
|
159
163
|
if (positional.length > 0) offset += p.consumes // named-shadow still advances (promotion case)
|
|
@@ -165,11 +169,12 @@ export const convertLiteGraphToPrompt = (
|
|
|
165
169
|
typeName: string
|
|
166
170
|
opts: unknown
|
|
167
171
|
consumes: number
|
|
172
|
+
prefixLen: number
|
|
168
173
|
strict: boolean
|
|
169
174
|
enumValues?: readonly (string | boolean | number)[]
|
|
170
175
|
linkedInput: CanonicalInput | undefined
|
|
171
176
|
}): void => {
|
|
172
|
-
const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes })
|
|
177
|
+
const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes, prefixLen: p.prefixLen })
|
|
173
178
|
const raw = r.filled
|
|
174
179
|
? defaultValueForWidget({
|
|
175
180
|
type: p.typeName,
|
|
@@ -185,7 +190,7 @@ export const convertLiteGraphToPrompt = (
|
|
|
185
190
|
|
|
186
191
|
/** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
|
|
187
192
|
const consumeDynamicCombo = (p: { path: string; options: DynamicComboOption[]; defaultKey: string }): void => {
|
|
188
|
-
const r = resolveWidgetValue({ promptName: p.path, consumes: 1 })
|
|
193
|
+
const r = resolveWidgetValue({ promptName: p.path, consumes: 1, prefixLen: 0 })
|
|
189
194
|
const key = r.filled ? p.defaultKey : r.value
|
|
190
195
|
if (typeof key !== 'string')
|
|
191
196
|
throw new WorkflowConvertError(
|
|
@@ -224,6 +229,7 @@ export const convertLiteGraphToPrompt = (
|
|
|
224
229
|
typeName: typeof sub.type === 'string' ? sub.type : 'COMBO',
|
|
225
230
|
opts: sub.opts,
|
|
226
231
|
consumes: kind.consumes,
|
|
232
|
+
prefixLen: kind.prefixValues.length,
|
|
227
233
|
strict: kind.strictValues,
|
|
228
234
|
enumValues: inlineEnum,
|
|
229
235
|
linkedInput: inputsInNodeJSON.find((i) => i.name === subPath),
|
|
@@ -238,7 +244,7 @@ export const convertLiteGraphToPrompt = (
|
|
|
238
244
|
// proves a widget value was written, so consume per the file's era
|
|
239
245
|
if (kind.kind === 'slot' && input?.widgetName != null) {
|
|
240
246
|
const legacyConsumes = howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)
|
|
241
|
-
kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true }
|
|
247
|
+
kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true, prefixValues: [] }
|
|
242
248
|
}
|
|
243
249
|
|
|
244
250
|
if (kind.kind === 'widget') {
|
|
@@ -247,6 +253,7 @@ export const convertLiteGraphToPrompt = (
|
|
|
247
253
|
typeName: field.typeName,
|
|
248
254
|
opts: field.opts,
|
|
249
255
|
consumes: kind.consumes,
|
|
256
|
+
prefixLen: kind.prefixValues.length,
|
|
250
257
|
strict: kind.strictValues,
|
|
251
258
|
linkedInput: input,
|
|
252
259
|
})
|
package/src/state.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
2
1
|
import { join } from 'pathe'
|
|
3
2
|
import pkgJson from '../package.json' with { type: 'json' }
|
|
4
3
|
import { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'
|
|
5
4
|
import { parseHostBase, renderHttpBase } from 'src/host/hostUrl.ts'
|
|
6
5
|
import { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
|
|
6
|
+
import { type ComfyStorage, resolveComfyStorage } from 'src/storage/ComfyStorage.ts'
|
|
7
7
|
import { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'
|
|
8
8
|
|
|
9
9
|
/** the ONE settings-file location rule — run-tui reads it BEFORE any module
|
|
@@ -16,12 +16,17 @@ export function settingsPathFor(root: string): AbsolutePath {
|
|
|
16
16
|
export class ComfyTS {
|
|
17
17
|
version = pkgJson.version
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
/** the storage seam (architecture item 13): node fs by default, in-memory on web */
|
|
20
|
+
storage: ComfyStorage
|
|
21
|
+
|
|
22
|
+
constructor(p: { rootPath?: string; storage?: ComfyStorage } = {}) {
|
|
20
23
|
// global registration: the rest of the lib resolves paths through `comfyts`
|
|
21
24
|
const globalHack = globalThis as { comfyts?: ComfyTS }
|
|
22
25
|
if (globalHack.comfyts != null) throw new Error('ComfyTS instance already created')
|
|
23
26
|
globalHack.comfyts = this
|
|
24
|
-
|
|
27
|
+
// storage FIRST: the default rootPath comes from it (browser has no process.cwd)
|
|
28
|
+
this.storage = resolveComfyStorage(p.storage)
|
|
29
|
+
this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd())
|
|
25
30
|
this.baseFolder = asAbsolutePath(join(this.rootPath, '.comfy-ts'))
|
|
26
31
|
this.hostsFolder = asAbsolutePath(join(this.baseFolder, 'hosts'))
|
|
27
32
|
this.outputPath = asAbsolutePath(join(this.baseFolder, 'outputs'))
|
|
@@ -32,7 +37,7 @@ export class ComfyTS {
|
|
|
32
37
|
* it. Workflow modules MUST use this (the TUI imports many of them into one
|
|
33
38
|
* process); `new ComfyTS()` still throws on a second instance.
|
|
34
39
|
*/
|
|
35
|
-
static create(p: { rootPath?: string } = {}): ComfyTS {
|
|
40
|
+
static create(p: { rootPath?: string; storage?: ComfyStorage } = {}): ComfyTS {
|
|
36
41
|
const globalHack = globalThis as { comfyts?: ComfyTS }
|
|
37
42
|
const existing = globalHack.comfyts
|
|
38
43
|
if (existing == null) return new ComfyTS(p)
|
|
@@ -82,8 +87,8 @@ export class ComfyTS {
|
|
|
82
87
|
return this._registry
|
|
83
88
|
}
|
|
84
89
|
|
|
85
|
-
/** root path used to resolve things */
|
|
86
|
-
rootPath: AbsolutePath
|
|
90
|
+
/** root path used to resolve things (set in the constructor, storage.cwd() default) */
|
|
91
|
+
rootPath: AbsolutePath
|
|
87
92
|
|
|
88
93
|
/**
|
|
89
94
|
* every repo using comfy-ts gets ONE `.comfy-ts/` folder:
|
|
@@ -126,12 +131,11 @@ export class ComfyTS {
|
|
|
126
131
|
}
|
|
127
132
|
|
|
128
133
|
readJSON_ = <T>(absPath: AbsolutePath, def?: T): T => {
|
|
129
|
-
const
|
|
130
|
-
if (
|
|
134
|
+
const str = this.storage.readTextIfExists(absPath)
|
|
135
|
+
if (str == null) {
|
|
131
136
|
if (def != null) return def
|
|
132
137
|
throw new Error(`file does not exist ${absPath}`)
|
|
133
138
|
}
|
|
134
|
-
const str = readFileSync(absPath, 'utf8')
|
|
135
139
|
const json = JSON.parse(str)
|
|
136
140
|
return json
|
|
137
141
|
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// the storage seam (architecture item 13): ONE sync fs-subset interface the
|
|
2
|
+
// core path talks to. Node gets the real fs, the web entry an in-memory Map.
|
|
3
|
+
// This file must stay browser-safe: no node imports, ever.
|
|
4
|
+
|
|
5
|
+
export type ComfyStorage = {
|
|
6
|
+
/** backend name, for error messages */
|
|
7
|
+
kind: string
|
|
8
|
+
/** throws when missing */
|
|
9
|
+
readText(path: string): string
|
|
10
|
+
readTextIfExists(path: string): string | null
|
|
11
|
+
/** throws when missing */
|
|
12
|
+
readBytes(path: string): Uint8Array
|
|
13
|
+
/** parents are created (mkdirp implied) */
|
|
14
|
+
writeText(path: string, text: string): void
|
|
15
|
+
/** parents are created (mkdirp implied) */
|
|
16
|
+
writeBytes(path: string, bytes: Uint8Array): void
|
|
17
|
+
exists(path: string): boolean
|
|
18
|
+
mkdirp(path: string): void
|
|
19
|
+
/** file mtime in ms; null when missing */
|
|
20
|
+
mtimeMs(path: string): number | null
|
|
21
|
+
homedir(): string
|
|
22
|
+
cwd(): string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** the fs/os surface createNodeStorageFrom needs — structural, so this file
|
|
26
|
+
* never imports node types into the web graph */
|
|
27
|
+
export type NodeFsLike = {
|
|
28
|
+
readFileSync(path: string, encoding?: 'utf8'): string | Uint8Array
|
|
29
|
+
writeFileSync(path: string, data: string | Uint8Array): void
|
|
30
|
+
existsSync(path: string): boolean
|
|
31
|
+
mkdirSync(path: string, opts: { recursive: boolean }): unknown
|
|
32
|
+
statSync(path: string): { mtimeMs: number; isFile(): boolean }
|
|
33
|
+
}
|
|
34
|
+
export type NodeOsLike = { homedir(): string }
|
|
35
|
+
|
|
36
|
+
function dirnameOf(path: string): string {
|
|
37
|
+
const ix = path.lastIndexOf('/')
|
|
38
|
+
return ix <= 0 ? '/' : path.slice(0, ix)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** node backend built from INJECTED modules: nodeStorage.ts passes its static
|
|
42
|
+
* imports, the autodetect below passes process.getBuiltinModule results */
|
|
43
|
+
export function createNodeStorageFrom(fs: NodeFsLike, os: NodeOsLike): ComfyStorage {
|
|
44
|
+
return {
|
|
45
|
+
kind: 'node',
|
|
46
|
+
readText: (p) => fs.readFileSync(p, 'utf8') as string,
|
|
47
|
+
readTextIfExists: (p) => (fs.existsSync(p) ? (fs.readFileSync(p, 'utf8') as string) : null),
|
|
48
|
+
readBytes: (p) => new Uint8Array(fs.readFileSync(p) as Uint8Array),
|
|
49
|
+
writeText: (p, text) => {
|
|
50
|
+
fs.mkdirSync(dirnameOf(p), { recursive: true })
|
|
51
|
+
fs.writeFileSync(p, text)
|
|
52
|
+
},
|
|
53
|
+
writeBytes: (p, bytes) => {
|
|
54
|
+
fs.mkdirSync(dirnameOf(p), { recursive: true })
|
|
55
|
+
fs.writeFileSync(p, bytes)
|
|
56
|
+
},
|
|
57
|
+
exists: (p) => fs.existsSync(p),
|
|
58
|
+
mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
|
|
59
|
+
mtimeMs: (p) => (fs.existsSync(p) ? fs.statSync(p).mtimeMs : null),
|
|
60
|
+
homedir: () => os.homedir(),
|
|
61
|
+
cwd: () => process.cwd(),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** in-memory backend: the web default, also handy for hermetic tests.
|
|
66
|
+
* Paths are LITERAL keys (no normalization — core callers resolve through
|
|
67
|
+
* pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp
|
|
68
|
+
* dirs only, never implicit parents. Bytes are copied in AND out so neither
|
|
69
|
+
* side can mutate the store. */
|
|
70
|
+
export function createMemoryStorage(p: { homedir?: string; cwd?: string } = {}): ComfyStorage {
|
|
71
|
+
const files = new Map<string, Uint8Array>()
|
|
72
|
+
const mtimes = new Map<string, number>()
|
|
73
|
+
const dirs = new Set<string>()
|
|
74
|
+
const td = new TextDecoder()
|
|
75
|
+
const te = new TextEncoder()
|
|
76
|
+
const write = (path: string, bytes: Uint8Array): void => {
|
|
77
|
+
files.set(path, bytes.slice())
|
|
78
|
+
mtimes.set(path, Date.now())
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
kind: 'memory',
|
|
82
|
+
readText: (path) => {
|
|
83
|
+
const hit = files.get(path)
|
|
84
|
+
if (hit == null) throw new Error(`[memory storage] no such file: ${path}`)
|
|
85
|
+
return td.decode(hit)
|
|
86
|
+
},
|
|
87
|
+
readTextIfExists: (path) => {
|
|
88
|
+
const hit = files.get(path)
|
|
89
|
+
return hit == null ? null : td.decode(hit)
|
|
90
|
+
},
|
|
91
|
+
readBytes: (path) => {
|
|
92
|
+
const hit = files.get(path)
|
|
93
|
+
if (hit == null) throw new Error(`[memory storage] no such file: ${path}`)
|
|
94
|
+
return hit.slice()
|
|
95
|
+
},
|
|
96
|
+
writeText: (path, text) => write(path, te.encode(text)),
|
|
97
|
+
writeBytes: write,
|
|
98
|
+
exists: (path) => files.has(path) || dirs.has(path),
|
|
99
|
+
mkdirp: (path) => void dirs.add(path),
|
|
100
|
+
mtimeMs: (path) => mtimes.get(path) ?? null,
|
|
101
|
+
homedir: () => p.homedir ?? '/home/web',
|
|
102
|
+
cwd: () => p.cwd ?? '/',
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---- default resolution (architecture item 13) ------------------------------
|
|
107
|
+
// explicit ComfyTS.create({storage}) → entry-installed default → node builtins
|
|
108
|
+
// autodetect (node 22+/bun: no static import needed) → loud throw.
|
|
109
|
+
|
|
110
|
+
let installedDefault: ComfyStorage | null = null
|
|
111
|
+
|
|
112
|
+
/** entries call this at import time: index.ts installs node, web.ts memory */
|
|
113
|
+
export function setDefaultComfyStorage(storage: ComfyStorage): void {
|
|
114
|
+
installedDefault = storage
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function autodetectNodeStorage(): ComfyStorage | null {
|
|
118
|
+
const get = globalThis.process?.getBuiltinModule
|
|
119
|
+
if (typeof get !== 'function') return null
|
|
120
|
+
const fs = get('node:fs') as NodeFsLike | undefined
|
|
121
|
+
const os = get('node:os') as NodeOsLike | undefined
|
|
122
|
+
if (fs == null || os == null) return null
|
|
123
|
+
return createNodeStorageFrom(fs, os)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function resolveComfyStorage(explicit?: ComfyStorage): ComfyStorage {
|
|
127
|
+
if (explicit != null) return explicit
|
|
128
|
+
if (installedDefault != null) return installedDefault
|
|
129
|
+
const detected = autodetectNodeStorage()
|
|
130
|
+
if (detected != null) {
|
|
131
|
+
installedDefault = detected
|
|
132
|
+
return detected
|
|
133
|
+
}
|
|
134
|
+
throw new Error(
|
|
135
|
+
`no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`,
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** the ONE accessor call sites use: the instance's storage when the global
|
|
140
|
+
* exists, the resolved default otherwise (vars constructed before create()) */
|
|
141
|
+
export function getComfyStorage(): ComfyStorage {
|
|
142
|
+
const g = globalThis as { comfyts?: { storage?: ComfyStorage } }
|
|
143
|
+
return g.comfyts?.storage ?? resolveComfyStorage()
|
|
144
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// the ONLY core-path module allowed to import node:fs statically
|
|
2
|
+
// (architecture item 13) — index.ts installs it; the web graph never sees it
|
|
3
|
+
import * as fs from 'node:fs'
|
|
4
|
+
import * as os from 'node:os'
|
|
5
|
+
import { type ComfyStorage, createNodeStorageFrom } from 'src/storage/ComfyStorage.ts'
|
|
6
|
+
|
|
7
|
+
export function createNodeStorage(): ComfyStorage {
|
|
8
|
+
return createNodeStorageFrom(fs, os)
|
|
9
|
+
}
|
|
@@ -1,77 +1,19 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
1
|
+
// fetch-based (node:https replaced 2026-07-31, architecture item 13): the
|
|
2
|
+
// manager registry chain is in the web graph via ComfyRegistry, so this file
|
|
3
|
+
// must stay portable — fetch follows redirects itself, storage owns the write
|
|
4
|
+
import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
|
|
5
5
|
import type { AbsolutePath } from 'src/types/index.ts'
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
* | ;(async () => {
|
|
9
|
-
* | try {
|
|
10
|
-
* | await downloadFile('https://example.com/file', 'folder/filename')
|
|
11
|
-
* | console.log('Download completed successfully')
|
|
12
|
-
* | } catch (error) {
|
|
13
|
-
* | console.error('Download failed:', error)
|
|
14
|
-
* | }
|
|
15
|
-
* | })()
|
|
16
|
-
* |
|
|
17
|
-
*/
|
|
18
|
-
export function downloadFile(
|
|
7
|
+
export async function downloadFile(
|
|
19
8
|
//
|
|
20
9
|
url: string,
|
|
21
10
|
outputPath: AbsolutePath | string,
|
|
22
11
|
logPrefix = ' - ',
|
|
23
12
|
): Promise<true> {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
// Check for redirect
|
|
31
|
-
if (response.statusCode === 302 || response.statusCode === 301) {
|
|
32
|
-
// Follow the redirect and call downloadFile recursively
|
|
33
|
-
const newUrl = response.headers.location!
|
|
34
|
-
console.log(`Redirected to ${newUrl}`)
|
|
35
|
-
resolve(downloadFile(newUrl, outputPath))
|
|
36
|
-
return
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
if (response.statusCode !== 200) {
|
|
40
|
-
reject(`Failed to download file: Status Code ${response.statusCode}`)
|
|
41
|
-
return
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// progress --------------------------------------------------
|
|
45
|
-
const rawLen = response.headers['content-length']
|
|
46
|
-
if (rawLen == null) {
|
|
47
|
-
console.warn(`download file: progress not available because no content-length header in response.`)
|
|
48
|
-
} else {
|
|
49
|
-
const totalSize = parseInt(rawLen, 10)
|
|
50
|
-
let downloaded = 0
|
|
51
|
-
let lastLoggedPercentage = 0
|
|
52
|
-
|
|
53
|
-
response.on('data', (chunk) => {
|
|
54
|
-
downloaded += chunk.length
|
|
55
|
-
const percentage = Math.round((downloaded / totalSize) * 100)
|
|
56
|
-
if (percentage >= lastLoggedPercentage + 1) {
|
|
57
|
-
// console.log(`${percentage}% downloaded`)
|
|
58
|
-
stdout.write(`\r${logPrefix}${percentage}% downloaded`)
|
|
59
|
-
lastLoggedPercentage = percentage
|
|
60
|
-
}
|
|
61
|
-
})
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// file stream -------------------------------------------
|
|
65
|
-
const fileStream = fs.createWriteStream(outputPath)
|
|
66
|
-
response.pipe(fileStream)
|
|
67
|
-
|
|
68
|
-
fileStream.on('finish', () => {
|
|
69
|
-
console.log(` (DONE)`)
|
|
70
|
-
fileStream.close()
|
|
71
|
-
resolve(true)
|
|
72
|
-
})
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
request.on('error', (err) => reject(err))
|
|
76
|
-
})
|
|
13
|
+
const res = await fetch(url)
|
|
14
|
+
if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`)
|
|
15
|
+
const bytes = new Uint8Array(await res.arrayBuffer())
|
|
16
|
+
getComfyStorage().writeBytes(outputPath, bytes)
|
|
17
|
+
console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`)
|
|
18
|
+
return true
|
|
77
19
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { sha1Hex } from 'src/utils/sha1.ts'
|
|
2
2
|
|
|
3
|
-
export const hashArrayBuffer = (buffer:
|
|
4
|
-
|
|
5
|
-
return crypto.createHash('sha1').update(data).digest('hex')
|
|
3
|
+
export const hashArrayBuffer = (buffer: Uint8Array): string => {
|
|
4
|
+
return sha1Hex(buffer)
|
|
6
5
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// sharp is node-only; the web graph must never carry it (architecture item 13).
|
|
2
|
+
// The import specifier is a VARIABLE on purpose: bundlers cannot statically
|
|
3
|
+
// chase it, so browser builds of comfy-ts/web don't try to resolve sharp —
|
|
4
|
+
// in a browser the import throws at runtime and callers get the loud error.
|
|
5
|
+
import type SharpNS from 'sharp'
|
|
6
|
+
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
7
|
+
|
|
8
|
+
export type SharpModule = typeof SharpNS
|
|
9
|
+
|
|
10
|
+
let cached: SharpModule | null = null
|
|
11
|
+
|
|
12
|
+
export async function importSharp(reason: string): Promise<SharpModule> {
|
|
13
|
+
if (cached != null) return cached
|
|
14
|
+
const specifier = 'sharp'
|
|
15
|
+
try {
|
|
16
|
+
const mod = (await import(specifier)) as { default: SharpModule }
|
|
17
|
+
cached = mod.default
|
|
18
|
+
return cached
|
|
19
|
+
} catch (e) {
|
|
20
|
+
throw new Error(
|
|
21
|
+
`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`,
|
|
22
|
+
{ cause: e },
|
|
23
|
+
)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// pure-JS SHA-1, browser-safe (architecture item 13): replaces node:crypto in
|
|
2
|
+
// the core path. Output matches node's createHash('sha1') byte-for-byte —
|
|
3
|
+
// upload-dedupe names and preview-cache keys stay identical across the swap
|
|
4
|
+
// (vector-tested against node:crypto in tests/sha1.test.ts).
|
|
5
|
+
|
|
6
|
+
export function sha1Hex(data: Uint8Array): string {
|
|
7
|
+
const ml = data.length
|
|
8
|
+
const total = Math.ceil((ml + 1 + 8) / 64) * 64
|
|
9
|
+
const bytes = new Uint8Array(total)
|
|
10
|
+
bytes.set(data)
|
|
11
|
+
bytes[ml] = 0x80
|
|
12
|
+
const dv = new DataView(bytes.buffer)
|
|
13
|
+
const bitLen = ml * 8
|
|
14
|
+
dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32))
|
|
15
|
+
dv.setUint32(total - 4, bitLen >>> 0)
|
|
16
|
+
|
|
17
|
+
let h0 = 0x67452301
|
|
18
|
+
let h1 = 0xefcdab89
|
|
19
|
+
let h2 = 0x98badcfe
|
|
20
|
+
let h3 = 0x10325476
|
|
21
|
+
let h4 = 0xc3d2e1f0
|
|
22
|
+
const w = new Uint32Array(80)
|
|
23
|
+
|
|
24
|
+
for (let i = 0; i < total; i += 64) {
|
|
25
|
+
for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4)
|
|
26
|
+
for (let j = 16; j < 80; j++) {
|
|
27
|
+
const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0)
|
|
28
|
+
w[j] = (n << 1) | (n >>> 31)
|
|
29
|
+
}
|
|
30
|
+
let a = h0
|
|
31
|
+
let b = h1
|
|
32
|
+
let c = h2
|
|
33
|
+
let d = h3
|
|
34
|
+
let e = h4
|
|
35
|
+
for (let j = 0; j < 80; j++) {
|
|
36
|
+
let f: number
|
|
37
|
+
let k: number
|
|
38
|
+
if (j < 20) {
|
|
39
|
+
f = (b & c) | (~b & d)
|
|
40
|
+
k = 0x5a827999
|
|
41
|
+
} else if (j < 40) {
|
|
42
|
+
f = b ^ c ^ d
|
|
43
|
+
k = 0x6ed9eba1
|
|
44
|
+
} else if (j < 60) {
|
|
45
|
+
f = (b & c) | (b & d) | (c & d)
|
|
46
|
+
k = 0x8f1bbcdc
|
|
47
|
+
} else {
|
|
48
|
+
f = b ^ c ^ d
|
|
49
|
+
k = 0xca62c1d6
|
|
50
|
+
}
|
|
51
|
+
const temp = (((a << 5) | (a >>> 27)) + f + e + k + (w[j] ?? 0)) >>> 0
|
|
52
|
+
e = d
|
|
53
|
+
d = c
|
|
54
|
+
c = (b << 30) | (b >>> 2)
|
|
55
|
+
b = a
|
|
56
|
+
a = temp
|
|
57
|
+
}
|
|
58
|
+
h0 = (h0 + a) >>> 0
|
|
59
|
+
h1 = (h1 + b) >>> 0
|
|
60
|
+
h2 = (h2 + c) >>> 0
|
|
61
|
+
h3 = (h3 + d) >>> 0
|
|
62
|
+
h4 = (h4 + e) >>> 0
|
|
63
|
+
}
|
|
64
|
+
return [h0, h1, h2, h3, h4].map((x) => x.toString(16).padStart(8, '0')).join('')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function sha1HexOfString(s: string): string {
|
|
68
|
+
return sha1Hex(new TextEncoder().encode(s))
|
|
69
|
+
}
|
package/src/vars/ComfyVars.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
// Vars: the standard "tweak & re-run" contract. A workflow defined via
|
|
2
2
|
// host.defineWorkflow({ vars, build }) rebuilds its graph from current var
|
|
3
3
|
// values on every run — drivers (scripts, the TUI) edit vars between runs.
|
|
4
|
-
import { readFileSync } from 'node:fs'
|
|
5
|
-
import { homedir } from 'node:os'
|
|
6
4
|
import { imageMeta } from 'image-meta'
|
|
7
5
|
import { action, makeObservable, observable } from 'mobx'
|
|
8
6
|
import { basename, isAbsolute, join, resolve } from 'pathe'
|
|
7
|
+
import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
|
|
9
8
|
import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
|
|
10
9
|
|
|
11
10
|
export type VarKind = 'text' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | 'image'
|
|
@@ -228,6 +227,12 @@ export class SeedVar extends ComfyVar<number> {
|
|
|
228
227
|
override afterRun(): void {
|
|
229
228
|
this.advance()
|
|
230
229
|
}
|
|
230
|
+
/** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive
|
|
231
|
+
* ('=' is the construction default; drafts restore their own mode via loadJSON) */
|
|
232
|
+
override reset(): this {
|
|
233
|
+
this.setMode('=')
|
|
234
|
+
return super.reset()
|
|
235
|
+
}
|
|
231
236
|
/** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
|
|
232
237
|
parse(raw: string): boolean {
|
|
233
238
|
const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/)
|
|
@@ -469,7 +474,7 @@ export class SizeVar extends ComfyVar<SizeValue> {
|
|
|
469
474
|
if (iv == null || iv.value === '') return null
|
|
470
475
|
try {
|
|
471
476
|
const abs = iv.absPath()
|
|
472
|
-
const meta = imageMeta(
|
|
477
|
+
const meta = imageMeta(getComfyStorage().readBytes(abs))
|
|
473
478
|
if (meta.width == null || meta.height == null) return null
|
|
474
479
|
return { width: meta.width, height: meta.height, name: basename(abs) }
|
|
475
480
|
} catch {
|
|
@@ -519,7 +524,7 @@ export class ImageVarEmptyError extends Error {
|
|
|
519
524
|
/** trim + expand a leading `~/` — every ImageVar write funnels through this */
|
|
520
525
|
function expandUserPath(raw: string): string {
|
|
521
526
|
const trimmed = raw.trim()
|
|
522
|
-
return trimmed.startsWith('~/') ? join(homedir(), trimmed.slice(2)) : trimmed
|
|
527
|
+
return trimmed.startsWith('~/') ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed
|
|
523
528
|
}
|
|
524
529
|
|
|
525
530
|
/**
|
|
@@ -558,7 +563,7 @@ export class ImageVar extends ComfyVar<string> {
|
|
|
558
563
|
absPath(): string {
|
|
559
564
|
if (!this.isSet()) throw this.emptyError()
|
|
560
565
|
if (isAbsolute(this.value)) return this.value
|
|
561
|
-
return resolve(this.opts.folder ??
|
|
566
|
+
return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value)
|
|
562
567
|
}
|
|
563
568
|
/** empty = unset: the build fails LOUD here (varValues calls outValue) */
|
|
564
569
|
override outValue(): string {
|
|
@@ -567,7 +572,7 @@ export class ImageVar extends ComfyVar<string> {
|
|
|
567
572
|
}
|
|
568
573
|
override display(): string {
|
|
569
574
|
if (!this.isSet()) return '(unset) pick a file'
|
|
570
|
-
const home = homedir()
|
|
575
|
+
const home = getComfyStorage().homedir()
|
|
571
576
|
return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value
|
|
572
577
|
}
|
|
573
578
|
}
|
|
@@ -603,11 +608,13 @@ export const v = {
|
|
|
603
608
|
export type AnyVar = {
|
|
604
609
|
readonly kind: VarKind
|
|
605
610
|
readonly value: unknown
|
|
611
|
+
readonly defaultValue: unknown
|
|
606
612
|
readonly label?: string
|
|
607
613
|
/** the vars-spec key — DefinedWorkflow writes it at define time */
|
|
608
614
|
name?: string
|
|
609
615
|
parse(raw: string): boolean
|
|
610
616
|
loadJSON(value: unknown): unknown
|
|
617
|
+
reset(): unknown
|
|
611
618
|
toJSON(): unknown
|
|
612
619
|
outValue(): unknown
|
|
613
620
|
display(): string
|