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.
- package/README.md +26 -0
- package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-C_QAxKr3.js} +64 -13
- package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
- package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-DcOTn0QR.js} +2 -2
- package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-DcOTn0QR.js.map} +1 -1
- package/dist/cli.js +3 -3
- package/dist/index.cjs +346 -183
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +93 -40
- package/dist/index.d.ts +94 -41
- package/dist/index.js +338 -174
- package/dist/index.js.map +1 -1
- package/dist/{run-serve-Bn6yIJB0.js → run-serve-CN0DhrsA.js} +3 -3
- package/dist/{run-serve-Bn6yIJB0.js.map → run-serve-CN0DhrsA.js.map} +1 -1
- package/dist/{run-tui-BtjaOXRh.js → run-tui-bN2hSD5i.js} +10 -11
- package/dist/{run-tui-BtjaOXRh.js.map → run-tui-bN2hSD5i.js.map} +1 -1
- package/dist/{state-DKCPy105.js → state-COlKYipO.js} +199 -146
- package/dist/state-COlKYipO.js.map +1 -0
- package/dist/web.d.ts +17340 -0
- package/dist/web.js +5569 -0
- 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 +8 -2
- 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/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 +14 -11
- package/src/runner/MediaImage.ts +18 -30
- package/src/sdk-generator/ComfySchema.ts +2 -2
- 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 +5 -6
- package/src/vars/loraKeywords.ts +6 -6
- package/src/web.ts +13 -0
- package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
- package/dist/state-DKCPy105.js.map +0 -1
- package/src/utils/writeFile.ts +0 -16
package/src/runner/MediaImage.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
1
|
import { type } from 'arktype'
|
|
3
2
|
import { type ImageMeta, imageMeta } from 'image-meta'
|
|
4
|
-
import { basename
|
|
5
|
-
import
|
|
3
|
+
import { basename } from 'pathe'
|
|
4
|
+
import type { Sharp } from 'sharp'
|
|
5
|
+
import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
|
|
6
|
+
import { importSharp } from 'src/utils/lazySharp.ts'
|
|
6
7
|
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
7
8
|
import type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
|
|
8
9
|
import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
|
|
@@ -170,8 +171,11 @@ export class MediaImage {
|
|
|
170
171
|
* does not includes the prefix `data:image/png;base64,`
|
|
171
172
|
*/
|
|
172
173
|
getBase64Payload(): string {
|
|
173
|
-
const
|
|
174
|
-
|
|
174
|
+
const bytes = this.buffer
|
|
175
|
+
let bin = ''
|
|
176
|
+
const chunk = 0x8000 // String.fromCharCode arg-count limit
|
|
177
|
+
for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk))
|
|
178
|
+
return btoa(bin)
|
|
175
179
|
}
|
|
176
180
|
|
|
177
181
|
/** return the ArrayBuffer for this file, regardless it's exact representation */
|
|
@@ -180,9 +184,7 @@ export class MediaImage {
|
|
|
180
184
|
private _buffer: Maybe<Uint8Array> = null
|
|
181
185
|
get buffer(): Uint8Array {
|
|
182
186
|
if (this._buffer != null) return this._buffer
|
|
183
|
-
|
|
184
|
-
const uint8arr = new Uint8Array(buff)
|
|
185
|
-
this._buffer = uint8arr
|
|
187
|
+
this._buffer = getComfyStorage().readBytes(this.absPath)
|
|
186
188
|
return this._buffer
|
|
187
189
|
}
|
|
188
190
|
freeBuffer = (): void => void (this._buffer = null)
|
|
@@ -202,17 +204,14 @@ export class MediaImage {
|
|
|
202
204
|
private _metadata: Maybe<ImageMeta> = null
|
|
203
205
|
get metadata(): ImageMeta {
|
|
204
206
|
if (this._metadata != null) return this._metadata
|
|
205
|
-
|
|
206
|
-
const uint8arr = new Uint8Array(buff)
|
|
207
|
-
this._metadata = imageMeta(uint8arr)
|
|
207
|
+
this._metadata = imageMeta(this.buffer)
|
|
208
208
|
return this._metadata
|
|
209
209
|
}
|
|
210
210
|
|
|
211
211
|
private _hash: Maybe<string> = null
|
|
212
212
|
get hash(): string {
|
|
213
213
|
if (this._hash != null) return this._hash
|
|
214
|
-
|
|
215
|
-
this._hash = hashArrayBuffer(new Uint8Array(buff))
|
|
214
|
+
this._hash = hashArrayBuffer(this.buffer)
|
|
216
215
|
return this._hash
|
|
217
216
|
}
|
|
218
217
|
|
|
@@ -224,8 +223,9 @@ export class MediaImage {
|
|
|
224
223
|
/** processing function */
|
|
225
224
|
fn: (sharp: Sharp) => Sharp,
|
|
226
225
|
): Promise<this> => {
|
|
227
|
-
const
|
|
228
|
-
|
|
226
|
+
const sharp = await importSharp('processWithSharp_inplace')
|
|
227
|
+
const buff = await fn(sharp(this.buffer)).toBuffer()
|
|
228
|
+
getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))
|
|
229
229
|
this.updateBuffer(new Uint8Array(buff))
|
|
230
230
|
return this
|
|
231
231
|
}
|
|
@@ -241,22 +241,10 @@ export class MediaImage {
|
|
|
241
241
|
/** where to save the resulting image */
|
|
242
242
|
path?: AbsolutePath,
|
|
243
243
|
): Promise<MediaImage> => {
|
|
244
|
-
const
|
|
244
|
+
const sharp = await importSharp('processWithSharp')
|
|
245
245
|
path ??= this.absPath + `.processed-${Date.now()}` + this.extension
|
|
246
|
-
await
|
|
247
|
-
|
|
246
|
+
const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer())
|
|
247
|
+
getComfyStorage().writeBytes(path, buffer)
|
|
248
248
|
return new MediaImage({ path, buffer })
|
|
249
249
|
}
|
|
250
|
-
|
|
251
|
-
generatePreview = async (targetPath: string): Promise<void> => {
|
|
252
|
-
const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true })
|
|
253
|
-
mkdirSync(dirname(targetPath), { recursive: true })
|
|
254
|
-
await img.toFile(targetPath)
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
generateMiniPreview = async (): Promise<string> => {
|
|
258
|
-
const image2 = await sharp(this.absPath).resize(32, 32, { fit: 'inside' }).webp({ quality: 1 }).toBuffer()
|
|
259
|
-
const x = image2.toString('base64')
|
|
260
|
-
return x
|
|
261
|
-
}
|
|
262
250
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { sha1HexOfString } from 'src/utils/sha1.ts'
|
|
2
2
|
import { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'
|
|
3
3
|
import { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'
|
|
4
4
|
import { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
|
|
@@ -280,7 +280,7 @@ export class ComfySchema {
|
|
|
280
280
|
enumValues.length === 0 //
|
|
281
281
|
? `[[empty]]`
|
|
282
282
|
: enumValues.sort().join('|')
|
|
283
|
-
const hash =
|
|
283
|
+
const hash = sha1HexOfString(hashContent).slice(0, 8)
|
|
284
284
|
|
|
285
285
|
// 3. retrieve or create an EnumInfo
|
|
286
286
|
let unionInfo: Maybe<ComfyUnionInfo> = this.knownUnionByHash.get(hash)
|
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'
|
|
@@ -475,7 +474,7 @@ export class SizeVar extends ComfyVar<SizeValue> {
|
|
|
475
474
|
if (iv == null || iv.value === '') return null
|
|
476
475
|
try {
|
|
477
476
|
const abs = iv.absPath()
|
|
478
|
-
const meta = imageMeta(
|
|
477
|
+
const meta = imageMeta(getComfyStorage().readBytes(abs))
|
|
479
478
|
if (meta.width == null || meta.height == null) return null
|
|
480
479
|
return { width: meta.width, height: meta.height, name: basename(abs) }
|
|
481
480
|
} catch {
|
|
@@ -525,7 +524,7 @@ export class ImageVarEmptyError extends Error {
|
|
|
525
524
|
/** trim + expand a leading `~/` — every ImageVar write funnels through this */
|
|
526
525
|
function expandUserPath(raw: string): string {
|
|
527
526
|
const trimmed = raw.trim()
|
|
528
|
-
return trimmed.startsWith('~/') ? join(homedir(), trimmed.slice(2)) : trimmed
|
|
527
|
+
return trimmed.startsWith('~/') ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed
|
|
529
528
|
}
|
|
530
529
|
|
|
531
530
|
/**
|
|
@@ -564,7 +563,7 @@ export class ImageVar extends ComfyVar<string> {
|
|
|
564
563
|
absPath(): string {
|
|
565
564
|
if (!this.isSet()) throw this.emptyError()
|
|
566
565
|
if (isAbsolute(this.value)) return this.value
|
|
567
|
-
return resolve(this.opts.folder ??
|
|
566
|
+
return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value)
|
|
568
567
|
}
|
|
569
568
|
/** empty = unset: the build fails LOUD here (varValues calls outValue) */
|
|
570
569
|
override outValue(): string {
|
|
@@ -573,7 +572,7 @@ export class ImageVar extends ComfyVar<string> {
|
|
|
573
572
|
}
|
|
574
573
|
override display(): string {
|
|
575
574
|
if (!this.isSet()) return '(unset) pick a file'
|
|
576
|
-
const home = homedir()
|
|
575
|
+
const home = getComfyStorage().homedir()
|
|
577
576
|
return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value
|
|
578
577
|
}
|
|
579
578
|
}
|
package/src/vars/loraKeywords.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
1
|
import { observable, runInAction } from 'mobx'
|
|
3
|
-
import {
|
|
2
|
+
import { join } from 'pathe'
|
|
3
|
+
import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
|
|
4
4
|
import { logError } from 'src/utils/log.ts'
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -21,9 +21,10 @@ function loadOnce(): void {
|
|
|
21
21
|
if (loaded) return
|
|
22
22
|
loaded = true
|
|
23
23
|
const path = filePath()
|
|
24
|
-
|
|
24
|
+
const text = getComfyStorage().readTextIfExists(path)
|
|
25
|
+
if (text == null) return
|
|
25
26
|
try {
|
|
26
|
-
const raw: unknown = JSON.parse(
|
|
27
|
+
const raw: unknown = JSON.parse(text)
|
|
27
28
|
if (raw == null || typeof raw !== 'object') return
|
|
28
29
|
runInAction(() => {
|
|
29
30
|
for (const [name, kw] of Object.entries(raw)) if (typeof kw === 'string') keywords.set(name, kw)
|
|
@@ -48,8 +49,7 @@ export function setLoraKeyword(name: string, keyword: string): void {
|
|
|
48
49
|
})
|
|
49
50
|
const path = filePath()
|
|
50
51
|
try {
|
|
51
|
-
|
|
52
|
-
writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2))
|
|
52
|
+
getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2))
|
|
53
53
|
} catch (e) {
|
|
54
54
|
logError(`[loraKeywords] write failed ${path}: ${String(e)}`)
|
|
55
55
|
}
|
package/src/web.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* comfy-ts/web — the BROWSER entry (architecture item 13): same library,
|
|
3
|
+
* in-memory storage, native WebSocket, no sharp. Types still come from a
|
|
4
|
+
* generated sdk.d.ts included in the consumer's tsconfig.
|
|
5
|
+
* Importing both entries in one process: the LAST import wins the default
|
|
6
|
+
* backend — pass ComfyTS.create({ storage }) to be explicit (SSR setups).
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
import { createMemoryStorage, setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'
|
|
10
|
+
|
|
11
|
+
setDefaultComfyStorage(createMemoryStorage())
|
|
12
|
+
|
|
13
|
+
export * from 'src/coreExports.ts'
|