comfy-ts 0.2.0 → 0.3.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/LICENSE +21 -0
- package/README.md +363 -0
- package/dist/cli.js +764 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +4128 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9862 -0
- package/dist/index.d.ts +9846 -58
- package/dist/index.js +4049 -2
- package/dist/index.js.map +1 -1
- package/dist/log-CdfgILde.js +10 -0
- package/dist/log-CdfgILde.js.map +1 -0
- package/dist/run-tui-Io8Xea0L.js +3340 -0
- package/dist/run-tui-Io8Xea0L.js.map +1 -0
- package/package.json +104 -75
- package/src/cli/comfy-ts-cli.ts +36 -0
- package/src/cli/gen.ts +47 -0
- package/src/cli/outline.ts +82 -0
- package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
- package/src/cli/tui/components/EditField.tsx +27 -0
- package/src/cli/tui/components/Header.tsx +51 -0
- package/src/cli/tui/components/HostPanel.tsx +37 -0
- package/src/cli/tui/components/LorasOverlay.tsx +49 -0
- package/src/cli/tui/components/OverlayList.tsx +25 -0
- package/src/cli/tui/components/PickerOverlays.tsx +66 -0
- package/src/cli/tui/components/PreviewPanel.tsx +33 -0
- package/src/cli/tui/components/PromptOverlay.tsx +16 -0
- package/src/cli/tui/components/StatusBar.tsx +165 -0
- package/src/cli/tui/components/TextOverlay.tsx +72 -0
- package/src/cli/tui/components/TreePanel.tsx +51 -0
- package/src/cli/tui/components/TuiApp.tsx +223 -0
- package/src/cli/tui/components/VarsPanel.tsx +86 -0
- package/src/cli/tui/findDefinedWorkflow.ts +16 -0
- package/src/cli/tui/keys.ts +20 -0
- package/src/cli/tui/protocolImagePainter.ts +59 -0
- package/src/cli/tui/run-tui.tsx +73 -0
- package/src/cli/tui/state/DraftsSt.ts +273 -0
- package/src/cli/tui/state/EditorSt.ts +289 -0
- package/src/cli/tui/state/ExecSt.ts +170 -0
- package/src/cli/tui/state/HostSt.ts +107 -0
- package/src/cli/tui/state/LorasSt.ts +185 -0
- package/src/cli/tui/state/PickerSt.ts +112 -0
- package/src/cli/tui/state/PreviewSt.ts +138 -0
- package/src/cli/tui/state/QueueSt.ts +59 -0
- package/src/cli/tui/state/SettingsSt.ts +73 -0
- package/src/cli/tui/state/TreeSt.ts +122 -0
- package/src/cli/tui/state/TuiSt.ts +169 -0
- package/src/cli/tui/state/WorkflowsSt.ts +92 -0
- package/src/cli/tui-env.ts +8 -0
- package/src/errors/InvalidPromptError.ts +12 -0
- package/src/graph/ComfyNode.ts +403 -0
- package/src/graph/ComfyNodeID.ts +28 -0
- package/src/graph/ComfyNodeOutput.ts +16 -0
- package/src/graph/NodeSlotSize.ts +4 -0
- package/src/graph/autoValue.ts +17 -0
- package/src/host/ComfyHost.ts +646 -0
- package/src/host/ComfyInstallType.ts +15 -0
- package/src/host/ComfyManager.ts +232 -0
- package/src/host/ComfyUploader.ts +110 -0
- package/src/host/ComfyWorkflowBuilder.ts +60 -0
- package/src/host/Requirements.ts +55 -0
- package/src/host/ResilientWebsocket.ts +147 -0
- package/src/host/loraManagerApi.ts +98 -0
- package/src/image-utils/_getPngMetadata.ts +53 -0
- package/src/image-utils/_getWebpMetadata.ts +38 -0
- package/src/image-utils/_parseExifData.ts +53 -0
- package/src/index.ts +89 -0
- package/src/litegraph/LiteGraphGroup.ts +22 -0
- package/src/litegraph/LiteGraphJSON.ts +46 -0
- package/src/litegraph/LiteGraphLink.ts +23 -0
- package/src/litegraph/LiteGraphLinkID.ts +6 -0
- package/src/litegraph/LiteGraphNode.ts +69 -0
- package/src/litegraph/LiteGraphNodeInput.ts +27 -0
- package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
- package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
- package/src/manager/ComfyRegistry.ts +124 -0
- package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
- package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
- package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
- package/src/manager/generated/KnownModel_Base.ts +126 -0
- package/src/manager/generated/KnownModel_FileName.ts +2287 -0
- package/src/manager/generated/KnownModel_Name.ts +2287 -0
- package/src/manager/generated/KnownModel_SavePath.ts +263 -0
- package/src/manager/generated/KnownModel_Type.ts +97 -0
- package/src/manager/json/alter-list.json +224 -0
- package/src/manager/json/custom-node-list.extra.ts +13 -0
- package/src/manager/json/custom-node-list.json +21948 -0
- package/src/manager/json/extension-node-map.json +31282 -0
- package/src/manager/json/github-stats.json +12602 -0
- package/src/manager/json/model-list.extra.ts +26 -0
- package/src/manager/json/model-list.json +5052 -0
- package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
- package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
- package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
- package/src/manager/loaders/step4_model-list-loader.ts +159 -0
- package/src/manager/script-update-manager.bun.ts +18 -0
- package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
- package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
- package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
- package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
- package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
- package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
- package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
- package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
- package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
- package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
- package/src/runner/ComfyExecution.ts +301 -0
- package/src/runner/ComfyExecutionStatus.ts +2 -0
- package/src/runner/ComfyWorkflow.ts +395 -0
- package/src/runner/ComfyWorkflowLayout.ts +96 -0
- package/src/runner/ComfyWsApi.ts +159 -0
- package/src/runner/MediaImage.ts +262 -0
- package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
- package/src/sdk-generator/ComfySchema.ts +369 -0
- package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
- package/src/sdk-generator/Primitives.ts +76 -0
- package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
- package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
- package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
- package/src/sdk-generator/comfy-api-json.ts +16 -0
- package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
- package/src/sdk-generator/comfyui-types.ts +56 -0
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
- package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
- package/src/ssh-host-manager/ssh-config.windows.md +32 -0
- package/src/ssh-host-manager/ssh-manager.ts +129 -0
- package/src/state.ts +136 -0
- package/src/types/comfy-sdk.ts +106 -0
- package/src/types/index.ts +55 -0
- package/src/utils/CodeBuffer.ts +61 -0
- package/src/utils/ComfyColors.ts +38 -0
- package/src/utils/ansi.ts +26 -0
- package/src/utils/ansiImage.ts +36 -0
- package/src/utils/bang.ts +39 -0
- package/src/utils/deepCopyNaive.ts +1 -0
- package/src/utils/downloadFile.ts +77 -0
- package/src/utils/escapeJSKey.ts +32 -0
- package/src/utils/exhaust.ts +4 -0
- package/src/utils/extractErrorMessage.ts +11 -0
- package/src/utils/fuzzyMatch.ts +8 -0
- package/src/utils/githubRegexes.ts +2 -0
- package/src/utils/hashArrayBuffer.ts +6 -0
- package/src/utils/log.ts +9 -0
- package/src/utils/loraTag.ts +10 -0
- package/src/utils/printArkResultInConsole.ts +16 -0
- package/src/utils/softValidate.ts +8 -0
- package/src/utils/stringifyReadable.ts +32 -0
- package/src/utils/toposort.ts +59 -0
- package/src/utils/tryExtracting.ts +41 -0
- package/src/utils/writeFile.ts +16 -0
- package/src/vars/ComfyVars.ts +531 -0
- package/src/vars/DefinedWorkflow.ts +112 -0
- package/src/vars/loraKeywords.ts +56 -0
- package/dist/index.d.mts +0 -74
- package/dist/index.mjs +0 -3
- package/dist/index.mjs.map +0 -1
- package/readme.md +0 -40
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
|
|
2
|
+
|
|
3
|
+
import type { Type } from 'arktype'
|
|
4
|
+
import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
|
|
5
|
+
import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
|
|
6
|
+
import type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'
|
|
7
|
+
import type { ComfyManagerAPIFetchPolicy } from 'src/manager/types/ComfyManagerAPIFetchPolicy.ts'
|
|
8
|
+
import {
|
|
9
|
+
type ComfyManagerAPIModelList,
|
|
10
|
+
ComfyManagerAPIModelList_ark,
|
|
11
|
+
} from 'src/manager/types/ComfyManagerAPIModelList.ts'
|
|
12
|
+
import {
|
|
13
|
+
type ComfyManagerAPIPluginList,
|
|
14
|
+
ComfyManagerAPIPluginList_ark,
|
|
15
|
+
} from 'src/manager/types/ComfyManagerAPIPluginList.ts'
|
|
16
|
+
import type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'
|
|
17
|
+
import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
|
|
18
|
+
import type { Maybe } from 'src/types/index.ts'
|
|
19
|
+
import { logError as toastError, logSuccess as toastSuccess } from 'src/utils/log.ts'
|
|
20
|
+
import { softValidate } from 'src/utils/softValidate.ts'
|
|
21
|
+
import type { PluginInstallStatus } from 'src/host/Requirements.ts'
|
|
22
|
+
|
|
23
|
+
export class ComfyManager {
|
|
24
|
+
constructor(public host: { getServerHostHTTP: () => string }) {
|
|
25
|
+
// void this.updateHostPluginsAndModels()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
get registry(): ComfyRegistry {
|
|
29
|
+
return comfyts.registry
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
fetchPluginsAndModels = async (): Promise<void> => {
|
|
33
|
+
const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()])
|
|
34
|
+
this.pluginList = _pluginList
|
|
35
|
+
this.modelList = _modelList
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// -----------
|
|
39
|
+
configureLogging = (mi: boolean): Promise<unknown> => {
|
|
40
|
+
// return this.repository.getModelInfoFinalFilePath(mi)
|
|
41
|
+
return this.fetchGetText(`/manager/terminal?mode=${mi}`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// utils ------------------------------------------------------------------------------
|
|
45
|
+
getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {
|
|
46
|
+
return comfyts.registry.getModelInfoFinalFilePath(mi)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
waitForHostToBeBackOnline(maxAttempt: 10): Promise<true> {
|
|
50
|
+
return new Promise<true>((yes, no) => {
|
|
51
|
+
let attempt = 0
|
|
52
|
+
let abortCtrl: AbortController
|
|
53
|
+
const interval = setInterval(async () => {
|
|
54
|
+
attempt++
|
|
55
|
+
if (attempt > maxAttempt) {
|
|
56
|
+
console.log(` - failure`)
|
|
57
|
+
clearInterval(interval)
|
|
58
|
+
no()
|
|
59
|
+
}
|
|
60
|
+
if (abortCtrl) abortCtrl.abort()
|
|
61
|
+
const url = this.host.getServerHostHTTP()
|
|
62
|
+
abortCtrl = new AbortController()
|
|
63
|
+
try {
|
|
64
|
+
console.log(` - trying...`)
|
|
65
|
+
await fetch(url, { signal: abortCtrl.signal })
|
|
66
|
+
clearInterval(interval)
|
|
67
|
+
yes(true)
|
|
68
|
+
} catch {
|
|
69
|
+
/* empty */
|
|
70
|
+
}
|
|
71
|
+
}, 1000)
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// actions ---------------------------------------------------------------------------
|
|
76
|
+
rebootComfyUIAndUpdateHostPluginsAndModelsAfter10Seconds(): Promise<void> {
|
|
77
|
+
// 🔴 bad code
|
|
78
|
+
setTimeout(() => void this.fetchPluginsAndModels(), 10_000)
|
|
79
|
+
// curl 'http://<host>:8188/api/manager/reboot' \
|
|
80
|
+
// -H 'Accept: */*' \
|
|
81
|
+
// -H 'Accept-Language: en-GB' \
|
|
82
|
+
// -H 'Cache-Control: max-age=0' \
|
|
83
|
+
// -H 'Comfy-User: undefined' \
|
|
84
|
+
// -H 'Connection: keep-alive' \
|
|
85
|
+
// -H 'Referer: http://<host>:8188/' \
|
|
86
|
+
// -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) cushystudio-shell/32.1.2 Chrome/128.0.6613.162 Electron/32.1.2 Safari/537.36'
|
|
87
|
+
return this.fetchGetJSON('/manager/reboot')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
restartComfyUI = async (): Promise<unknown> => {
|
|
91
|
+
return this.fetchGetJSON('/manager/reboot')
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
modelList: Maybe<ComfyManagerAPIModelList> = null
|
|
95
|
+
|
|
96
|
+
fetchModels = (): Promise<ComfyManagerAPIModelList> => {
|
|
97
|
+
return this.fetchGetJSON('/externalmodel/getlist?mode=cache', ComfyManagerAPIModelList_ark)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
fetchLogs = (): Promise<any> => {
|
|
101
|
+
return this.fetchGetJSON<unknown>('/internal/logs')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
isModelInstalled = (name: KnownModel_Name): boolean => {
|
|
105
|
+
return this.modelList?.models.some((x) => x.name === name && x.installed === 'True') ?? false
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
modelsBeeingInstalled = new Set<KnownModel_Name>()
|
|
109
|
+
|
|
110
|
+
installModel = async (model: ComfyManagerModelInfo): Promise<boolean> => {
|
|
111
|
+
try {
|
|
112
|
+
this.modelsBeeingInstalled.add(model.name)
|
|
113
|
+
await this.fetchPost('/model/install', model)
|
|
114
|
+
this.modelsBeeingInstalled.delete(model.name)
|
|
115
|
+
toastSuccess('Model installed')
|
|
116
|
+
return true
|
|
117
|
+
} catch (exception) {
|
|
118
|
+
console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)
|
|
119
|
+
toastError('Model Installation Failed')
|
|
120
|
+
this.modelsBeeingInstalled.delete(model.name)
|
|
121
|
+
return false
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
getModelStatus = (modelName: KnownModel_Name): PluginInstallStatus => {
|
|
126
|
+
if (this.modelList == null) return 'unknown'
|
|
127
|
+
const entry = this.modelList?.models.find((x) => x.name === modelName)
|
|
128
|
+
const status = ((): PluginInstallStatus => {
|
|
129
|
+
if (!entry) return 'unknown'
|
|
130
|
+
if (entry?.installed === 'False') return 'not-installed'
|
|
131
|
+
if (entry?.installed === 'True') return 'installed'
|
|
132
|
+
if (entry?.installed === 'Update') return 'update-available'
|
|
133
|
+
return 'error'
|
|
134
|
+
})()
|
|
135
|
+
return status
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// PLUGINS (A.K.A. Custom nodes) ----------------------------------------------------------------------------
|
|
139
|
+
/**
|
|
140
|
+
* you need to call `fetchPluginList()` to populate this field
|
|
141
|
+
*/
|
|
142
|
+
pluginList: Maybe<ComfyManagerAPIPluginList> = null // hasModel = async (model: ModelInfo) => {
|
|
143
|
+
|
|
144
|
+
get titlesOfAllInstalledPlugins(): KnownComfyPluginTitle[] {
|
|
145
|
+
return (
|
|
146
|
+
this.pluginList?.custom_nodes //
|
|
147
|
+
.filter((x) => x.installed === 'True')
|
|
148
|
+
.map((x) => x.title) ?? []
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
isPluginInstalled = (title: KnownComfyPluginTitle): boolean => {
|
|
153
|
+
if (!this.pluginList || !this.pluginList.custom_nodes) return false
|
|
154
|
+
return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === 'True') ?? false
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
getPluginStatus = (title: KnownComfyPluginTitle): PluginInstallStatus => {
|
|
158
|
+
if (this.pluginList == null) return 'unknown'
|
|
159
|
+
const entry = this.pluginList?.custom_nodes.find((x) => x.title === title)
|
|
160
|
+
const status = ((): PluginInstallStatus => {
|
|
161
|
+
if (!entry) return 'unknown'
|
|
162
|
+
if (entry?.installed === 'False') return 'not-installed'
|
|
163
|
+
if (entry?.installed === 'True') return 'installed'
|
|
164
|
+
if (entry?.installed === 'Update') return 'update-available'
|
|
165
|
+
return 'error'
|
|
166
|
+
})()
|
|
167
|
+
return status
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// --------------------------------------------------------------
|
|
171
|
+
// https://github.com/ltdrdata/ComfyUI-Manager/blob/4649d216b1842aa48b95d3f064c679a1b698e506/js/custom-nodes-downloader.js#L14C25-L14C88
|
|
172
|
+
fetchPlugins = async (
|
|
173
|
+
/** @default: 'cache' */
|
|
174
|
+
mode: ComfyManagerAPIFetchPolicy = 'cache',
|
|
175
|
+
/** @default: true */
|
|
176
|
+
skipUpdate: boolean = true,
|
|
177
|
+
): Promise<ComfyManagerAPIPluginList> => {
|
|
178
|
+
try {
|
|
179
|
+
const skip_update = skipUpdate ? '&skip_update=true' : ''
|
|
180
|
+
return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark)
|
|
181
|
+
} catch (exception) {
|
|
182
|
+
console.error(`node list retrieval failed: ${exception}`)
|
|
183
|
+
toastError('node list retrieveal failed')
|
|
184
|
+
throw exception
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
installPlugin = async (model: ComfyManagerPluginInfo): Promise<boolean> => {
|
|
189
|
+
try {
|
|
190
|
+
await this.fetchPost('/customnode/install', model)
|
|
191
|
+
console.log('✅ Custom Node installed')
|
|
192
|
+
toastSuccess('Custom Node installed')
|
|
193
|
+
return true
|
|
194
|
+
} catch (exception) {
|
|
195
|
+
console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)
|
|
196
|
+
toastError('Custom Node Installation Failed')
|
|
197
|
+
return false
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// --------------------------------------------------------------
|
|
202
|
+
private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {
|
|
203
|
+
const url = this.host.getServerHostHTTP() + endpoint
|
|
204
|
+
const response = await fetch(url, {
|
|
205
|
+
method: 'POST',
|
|
206
|
+
headers: { 'Content-Type': 'application/json' },
|
|
207
|
+
body: JSON.stringify(body),
|
|
208
|
+
})
|
|
209
|
+
if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`)
|
|
210
|
+
const status = await response.json()
|
|
211
|
+
if (validator) return softValidate(validator, status)
|
|
212
|
+
// wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json
|
|
213
|
+
return status as OUT
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {
|
|
217
|
+
const url = this.host.getServerHostHTTP() + endpoint
|
|
218
|
+
const response = await fetch(url)
|
|
219
|
+
if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)
|
|
220
|
+
const jsonResult = await response.json()
|
|
221
|
+
if (validator) return softValidate(validator, jsonResult)
|
|
222
|
+
// wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json
|
|
223
|
+
return jsonResult as OUT
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private fetchGetText = async (endopint: string): Promise<string> => {
|
|
227
|
+
const url = this.host.getServerHostHTTP() + endopint
|
|
228
|
+
const response = await fetch(url)
|
|
229
|
+
const status = await response.text()
|
|
230
|
+
return status
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { type } from 'arktype'
|
|
2
|
+
import type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'
|
|
3
|
+
import type { MediaImage } from 'src/runner/MediaImage.ts'
|
|
4
|
+
import type { Maybe } from 'src/types/index.ts'
|
|
5
|
+
import { softValidate } from 'src/utils/softValidate.ts'
|
|
6
|
+
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
7
|
+
|
|
8
|
+
export type ComfyUploadImageResult = {
|
|
9
|
+
name: ComfyImageName
|
|
10
|
+
subfolder: string
|
|
11
|
+
type: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const ComfyUploadImageResult_ark = type({
|
|
15
|
+
name: type.string.as<ComfyImageName>(),
|
|
16
|
+
subfolder: 'string',
|
|
17
|
+
type: 'string',
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
/** all those functions are kinda legacy */
|
|
21
|
+
export class ComfyUploader {
|
|
22
|
+
constructor(public host: ComfyHost) {}
|
|
23
|
+
|
|
24
|
+
/** upload a blob */
|
|
25
|
+
uploadImage = async (
|
|
26
|
+
//
|
|
27
|
+
img: MediaImage,
|
|
28
|
+
p: {
|
|
29
|
+
type?: Maybe<'input' | 'temp' | 'output'>
|
|
30
|
+
override?: Maybe<boolean>
|
|
31
|
+
subfolder?: string
|
|
32
|
+
},
|
|
33
|
+
): Promise<ComfyImageName> => {
|
|
34
|
+
const uniqFileName = img.enumName as ComfyImageName
|
|
35
|
+
// console.warn(`[🌁] UPLOAD: ${img.relPath} required as "${uniqFileName}"...`)
|
|
36
|
+
|
|
37
|
+
const expectedFinalName = p.subfolder //
|
|
38
|
+
? `${p.subfolder}/${uniqFileName}`
|
|
39
|
+
: uniqFileName
|
|
40
|
+
// 2. if image already exists, return it
|
|
41
|
+
if (this.host.schema.hasImage(expectedFinalName)) {
|
|
42
|
+
console.log(`[🌁] UPLOAD: 🩶 "${img.absPath}" already exists on current ComfyUI instance`)
|
|
43
|
+
return expectedFinalName as ComfyImageName
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 3. upload
|
|
47
|
+
const form = new FormData()
|
|
48
|
+
form.set('image', img.getAsBlob(), uniqFileName)
|
|
49
|
+
if (p.type) form.set('type', p.type)
|
|
50
|
+
if (p.override ?? true) form.set('override', 'true')
|
|
51
|
+
// const subfolder = p.subfolder ?? 'comfyts-upload'
|
|
52
|
+
if (p.subfolder) form.set('subfolder', p.subfolder)
|
|
53
|
+
const uploadURL = this.host.getServerHostHTTP() + '/upload/image'
|
|
54
|
+
const resp = await fetch(uploadURL, { method: 'POST', body: form })
|
|
55
|
+
const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())
|
|
56
|
+
|
|
57
|
+
// 4. check upload is successfull
|
|
58
|
+
console.log('[🌁] UPLOAD: ✅ got', result)
|
|
59
|
+
if (result.name == null) throw new Error('upload failed')
|
|
60
|
+
|
|
61
|
+
const finalName = result.subfolder //
|
|
62
|
+
? (`${result.subfolder}/${result.name}` as ComfyImageName)
|
|
63
|
+
: result.name
|
|
64
|
+
|
|
65
|
+
if (finalName !== expectedFinalName) {
|
|
66
|
+
console.warn(`[🌁] UPLOAD: ⚠️ expected "${expectedFinalName}" but got "${finalName}"`)
|
|
67
|
+
} else {
|
|
68
|
+
console.log(`[🌁] UPLOAD: ✅ finalName is "${finalName}"`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 5. patch the local ComfyUI schema locally
|
|
72
|
+
this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName)
|
|
73
|
+
|
|
74
|
+
// 6. return the image
|
|
75
|
+
return finalName
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** upload an image present on disk to ComfyUI */
|
|
79
|
+
// ⏸️ upload_FileAtAbsolutePath = async (filePath: AbsolutePath): Promise<ComfyUploadImageResult> => {
|
|
80
|
+
// ⏸️ const mime = asSTRING_orCrash(lookup(filePath))
|
|
81
|
+
// ⏸️ const file = new Blob([readFileSync(filePath)], { type: mime })
|
|
82
|
+
// ⏸️ return await this.upload_Blob(file)
|
|
83
|
+
// ⏸️ }
|
|
84
|
+
|
|
85
|
+
// ⏸️ /** upload an image from dataURL */
|
|
86
|
+
// ⏸️ upload_dataURL = async (dataURL: string): Promise<ComfyUploadImageResult> => {
|
|
87
|
+
// ⏸️ const mime = dataURL.split(';')[0].split(':')[1]
|
|
88
|
+
// ⏸️ console.log('[⬆️] upload_dataURL', mime)
|
|
89
|
+
// ⏸️ const file = new Blob([Buffer.from(dataURL.split(',')[1], 'base64')], { type: mime })
|
|
90
|
+
// ⏸️ return await this.upload_Blob(file)
|
|
91
|
+
// ⏸️ }
|
|
92
|
+
|
|
93
|
+
// ⏸️ /** upload an image present on disk to ComfyUI */
|
|
94
|
+
// ⏸️ upload_NativeFile = async (file: File): Promise<ComfyUploadImageResult> => {
|
|
95
|
+
// ⏸️ const blob = new Blob([await file.arrayBuffer()], { type: file.type })
|
|
96
|
+
// ⏸️ return await this.upload_Blob(blob)
|
|
97
|
+
// ⏸️ }
|
|
98
|
+
|
|
99
|
+
// ⏸️ /** upload an image that can be downloaded form a given URL to ComfyUI */
|
|
100
|
+
// ⏸️ upload_ImageAtURL = async (url: string): Promise<ComfyUploadImageResult> => {
|
|
101
|
+
// ⏸️ const blob: Blob = await this.st.getUrlAsBlob(url)
|
|
102
|
+
// ⏸️ return this.upload_Blob(blob)
|
|
103
|
+
// ⏸️ }
|
|
104
|
+
|
|
105
|
+
// ⏸️ /** upload a deck asset to ComfyUI */
|
|
106
|
+
// ⏸️ upload_Asset = async (assetName: RelativePath): Promise<ComfyUploadImageResult> => {
|
|
107
|
+
// ⏸️ const absPath = asAbsolutePath(path.join(this.st.rootPath, assetName))
|
|
108
|
+
// ⏸️ return this.st.uploader.upload_FileAtAbsolutePath(absPath)
|
|
109
|
+
// ⏸️ }
|
|
110
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ComfyNode } from 'src/graph/ComfyNode.ts'
|
|
2
|
+
import type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
|
|
3
|
+
import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
|
|
4
|
+
import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* runtime builder: one factory method per node of the live schema, defined
|
|
8
|
+
* dynamically. The typed face is `SdkForHost<ID>['Builder']`, obtained via
|
|
9
|
+
* `workflow.builder` (see ComfyWorkflow). The index signature below is what
|
|
10
|
+
* makes the cast between the two legal.
|
|
11
|
+
*/
|
|
12
|
+
export interface ComfyWorkflowBuilder {
|
|
13
|
+
[nodeName: string]: unknown
|
|
14
|
+
}
|
|
15
|
+
export class ComfyWorkflowBuilder {
|
|
16
|
+
constructor(public graph: ComfyWorkflow) {
|
|
17
|
+
const schema = graph.host.schema
|
|
18
|
+
|
|
19
|
+
for (const node of schema.nodes) {
|
|
20
|
+
try {
|
|
21
|
+
Object.defineProperty(this, node.nodeKey, {
|
|
22
|
+
value: (inputs: ComfyApiNodeJson['inputs'], meta?: ComfyNodeMetadata) => {
|
|
23
|
+
const uidString = this.___allocateNodeUID(meta)
|
|
24
|
+
const nodePayload: ComfyApiNodeJson = {
|
|
25
|
+
class_type: node.nameInComfy,
|
|
26
|
+
inputs,
|
|
27
|
+
}
|
|
28
|
+
return new ComfyNode(graph, uidString, nodePayload, meta ?? {})
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
} catch (e) {
|
|
32
|
+
console.log(e)
|
|
33
|
+
console.error('impossible to create builder for node')
|
|
34
|
+
console.log(`current:`, JSON.stringify(node.nameInComfy), JSON.stringify(node.nodeKey))
|
|
35
|
+
const prev = schema.nodes.find((n) => n.nodeKey === node.nodeKey)
|
|
36
|
+
console.log(`prev`, JSON.stringify(prev?.nameInComfy), JSON.stringify(prev?.nodeKey))
|
|
37
|
+
throw e
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* helper function to allocate an unique node Id while
|
|
44
|
+
* while respecting user provided metadata id if present.
|
|
45
|
+
*/
|
|
46
|
+
private ___allocateNodeUID(meta?: ComfyNodeMetadata): string {
|
|
47
|
+
let uidString: string
|
|
48
|
+
if (meta?.id != null && meta.id !== '') {
|
|
49
|
+
// increment the graph _uiNumber, so if we modify this later
|
|
50
|
+
// we won't reuse the same uid and have broken conflicts
|
|
51
|
+
const uidNumber = parseInt(meta.id, 10)
|
|
52
|
+
if (!Number.isNaN(uidNumber) && uidNumber > this.graph._uidNumber)
|
|
53
|
+
this.graph._uidNumber = Math.round(uidNumber + 1)
|
|
54
|
+
uidString = meta.id
|
|
55
|
+
} else {
|
|
56
|
+
uidString = (this.graph._uidNumber++).toString()
|
|
57
|
+
}
|
|
58
|
+
return uidString
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'
|
|
2
|
+
import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
|
|
3
|
+
import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'
|
|
4
|
+
import type { KnownModel_Base } from 'src/manager/generated/KnownModel_Base.ts'
|
|
5
|
+
import type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'
|
|
6
|
+
import type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'
|
|
7
|
+
import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* comfyts-specific types to allow
|
|
11
|
+
* 2024-03-13 rvion: TODO: split outside of this file, add a new type-level config for
|
|
12
|
+
* project-specific FormNode metadata
|
|
13
|
+
*/
|
|
14
|
+
export type Requirements =
|
|
15
|
+
// models
|
|
16
|
+
| {
|
|
17
|
+
type: 'modelInCivitai'
|
|
18
|
+
civitaiModelId: string
|
|
19
|
+
optional?: true
|
|
20
|
+
base: KnownModel_Base
|
|
21
|
+
}
|
|
22
|
+
| {
|
|
23
|
+
type: 'modelInManager'
|
|
24
|
+
modelName: KnownModel_Name
|
|
25
|
+
optional?: true
|
|
26
|
+
}
|
|
27
|
+
| {
|
|
28
|
+
type: 'modelCustom'
|
|
29
|
+
infos: ComfyManagerModelInfo
|
|
30
|
+
optional?: true
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// custom nodes
|
|
34
|
+
| {
|
|
35
|
+
type: 'customNodesByTitle'
|
|
36
|
+
title: KnownComfyPluginTitle
|
|
37
|
+
optional?: true
|
|
38
|
+
}
|
|
39
|
+
| {
|
|
40
|
+
type: 'customNodesByURI'
|
|
41
|
+
uri: KnownComfyPluginURL
|
|
42
|
+
optional?: true
|
|
43
|
+
}
|
|
44
|
+
| {
|
|
45
|
+
type: 'customNodesByNodeKey'
|
|
46
|
+
nodeName: KnownComfyCustomNodeName
|
|
47
|
+
optional?: true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type PluginInstallStatus = 'installed' | 'not-installed' | 'update-available' | 'unknown' | 'error'
|
|
51
|
+
|
|
52
|
+
export type PluginSuggestion = {
|
|
53
|
+
reason: string
|
|
54
|
+
plugin: ComfyManagerPluginInfo
|
|
55
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import WebSocket, { type CloseEvent, type Event, type MessageEvent } from 'ws'
|
|
2
|
+
import type { Maybe } from 'src/types/index.ts'
|
|
3
|
+
import { bang } from 'src/utils/bang.ts'
|
|
4
|
+
import { logInfo } from 'src/utils/log.ts'
|
|
5
|
+
|
|
6
|
+
type Message = string | Buffer
|
|
7
|
+
|
|
8
|
+
type WsDebugMessage = {
|
|
9
|
+
type: 'info' | 'error'
|
|
10
|
+
timestamp: number
|
|
11
|
+
message: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class ResilientWebSocketClient {
|
|
15
|
+
// private protocols?: string | string[]
|
|
16
|
+
private url: string
|
|
17
|
+
private currentWS?: Maybe<WebSocket>
|
|
18
|
+
private messageBuffer: Message[] = []
|
|
19
|
+
|
|
20
|
+
isOpen: boolean = false
|
|
21
|
+
debugMessages: WsDebugMessage[] = []
|
|
22
|
+
|
|
23
|
+
private addInfo(msg: string): void {
|
|
24
|
+
this.debugMessages.push({ type: 'info', timestamp: Date.now(), message: msg })
|
|
25
|
+
logInfo(`[🧦] WS: ${msg}`)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
private addError(err: string): void {
|
|
29
|
+
this.debugMessages.push({ type: 'error', timestamp: Date.now(), message: err })
|
|
30
|
+
console.error('[🧦] WS:', err)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
public options: {
|
|
35
|
+
url: () => string /*protocols?: string | string[]*/
|
|
36
|
+
onMessage: (event: MessageEvent) => void
|
|
37
|
+
onConnectOrReconnect: () => void
|
|
38
|
+
onClose: () => void
|
|
39
|
+
},
|
|
40
|
+
) {
|
|
41
|
+
this.url = options.url()
|
|
42
|
+
this.connect()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private reconnectTimeout?: Maybe<NodeJS.Timeout>
|
|
46
|
+
private permanentlyClosed: boolean = false
|
|
47
|
+
|
|
48
|
+
/** close and stop reconnecting (lets a script exit cleanly) */
|
|
49
|
+
disconnectPermanently(): void {
|
|
50
|
+
this.permanentlyClosed = true
|
|
51
|
+
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)
|
|
52
|
+
this.currentWS?.close()
|
|
53
|
+
this.currentWS = null
|
|
54
|
+
this.isOpen = false
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private connect(): void {
|
|
58
|
+
this.isOpen = false
|
|
59
|
+
const prevWS = this.currentWS
|
|
60
|
+
|
|
61
|
+
// cleanup a possible re-connection timeout for an other url
|
|
62
|
+
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)
|
|
63
|
+
|
|
64
|
+
this.currentWS = null
|
|
65
|
+
if (prevWS) {
|
|
66
|
+
this.addInfo('Previous WebSocket discarded')
|
|
67
|
+
prevWS.close()
|
|
68
|
+
}
|
|
69
|
+
const ws = new WebSocket(this.url)
|
|
70
|
+
ws.binaryType = 'arraybuffer'
|
|
71
|
+
|
|
72
|
+
this.currentWS = ws
|
|
73
|
+
|
|
74
|
+
if (this.options.onMessage) {
|
|
75
|
+
ws.onmessage = (event: MessageEvent): void => {
|
|
76
|
+
this.options.onMessage(event)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
ws.onopen = (_event: Event): void => {
|
|
81
|
+
if (ws !== this.currentWS) return
|
|
82
|
+
this.addInfo('✅ WebSocket connected to ' + this.url)
|
|
83
|
+
this.isOpen = true
|
|
84
|
+
this.options.onConnectOrReconnect()
|
|
85
|
+
this.flushMessageBuffer()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
ws.onclose = (event: CloseEvent): void => {
|
|
89
|
+
if (ws !== this.currentWS) return
|
|
90
|
+
this.isOpen = false
|
|
91
|
+
this.options.onClose()
|
|
92
|
+
if (this.permanentlyClosed) return
|
|
93
|
+
this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`)
|
|
94
|
+
this.addInfo('⏱️ reconnecting in 2 seconds...')
|
|
95
|
+
this.reconnectTimeout = setTimeout(() => this.connect(), 2000)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
ws.onerror = (event: Event): void => {
|
|
99
|
+
if (ws !== this.currentWS) return
|
|
100
|
+
this.addError(`WebSocket ERROR` + JSON.stringify(event))
|
|
101
|
+
console.error({ event })
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
public send(message: Message): void {
|
|
106
|
+
if (this.isOpen) {
|
|
107
|
+
this.currentWS?.send(message)
|
|
108
|
+
} else {
|
|
109
|
+
this.messageBuffer.push(message)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private flushMessageBuffer(): void {
|
|
114
|
+
while (this.messageBuffer.length > 0) {
|
|
115
|
+
const message = bang(this.messageBuffer.shift())
|
|
116
|
+
this.currentWS?.send(message)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** forward WebSocket add event listeners to the current WebSocket instance */
|
|
121
|
+
public addEventListener<K extends keyof WebSocketEventMap>(
|
|
122
|
+
type: K,
|
|
123
|
+
listener:
|
|
124
|
+
| ((event: WebSocket.WebSocketEventMap[K]) => void)
|
|
125
|
+
| { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
|
|
126
|
+
options?: WebSocket.EventListenerOptions,
|
|
127
|
+
): void {
|
|
128
|
+
this.currentWS?.addEventListener(type, listener, options)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** forward WebSocket remove event listeners to the current WebSocket instance */
|
|
132
|
+
public removeEventListener<K extends keyof WebSocketEventMap>(
|
|
133
|
+
type: K,
|
|
134
|
+
listener:
|
|
135
|
+
| ((event: WebSocket.WebSocketEventMap[K]) => void)
|
|
136
|
+
| { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
|
|
137
|
+
): void {
|
|
138
|
+
this.currentWS?.removeEventListener(type, listener)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
type WebSocketEventMap = {
|
|
143
|
+
open: Event
|
|
144
|
+
close: CloseEvent
|
|
145
|
+
error: Event
|
|
146
|
+
message: MessageEvent
|
|
147
|
+
}
|