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.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4128 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9862 -0
  8. package/dist/index.d.ts +9846 -58
  9. package/dist/index.js +4049 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-Io8Xea0L.js +3340 -0
  14. package/dist/run-tui-Io8Xea0L.js.map +1 -0
  15. package/package.json +104 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +51 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  24. package/src/cli/tui/components/OverlayList.tsx +25 -0
  25. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +33 -0
  27. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  28. package/src/cli/tui/components/StatusBar.tsx +165 -0
  29. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  30. package/src/cli/tui/components/TreePanel.tsx +51 -0
  31. package/src/cli/tui/components/TuiApp.tsx +223 -0
  32. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  33. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  34. package/src/cli/tui/keys.ts +20 -0
  35. package/src/cli/tui/protocolImagePainter.ts +59 -0
  36. package/src/cli/tui/run-tui.tsx +73 -0
  37. package/src/cli/tui/state/DraftsSt.ts +273 -0
  38. package/src/cli/tui/state/EditorSt.ts +289 -0
  39. package/src/cli/tui/state/ExecSt.ts +170 -0
  40. package/src/cli/tui/state/HostSt.ts +107 -0
  41. package/src/cli/tui/state/LorasSt.ts +185 -0
  42. package/src/cli/tui/state/PickerSt.ts +112 -0
  43. package/src/cli/tui/state/PreviewSt.ts +138 -0
  44. package/src/cli/tui/state/QueueSt.ts +59 -0
  45. package/src/cli/tui/state/SettingsSt.ts +73 -0
  46. package/src/cli/tui/state/TreeSt.ts +122 -0
  47. package/src/cli/tui/state/TuiSt.ts +169 -0
  48. package/src/cli/tui/state/WorkflowsSt.ts +92 -0
  49. package/src/cli/tui-env.ts +8 -0
  50. package/src/errors/InvalidPromptError.ts +12 -0
  51. package/src/graph/ComfyNode.ts +403 -0
  52. package/src/graph/ComfyNodeID.ts +28 -0
  53. package/src/graph/ComfyNodeOutput.ts +16 -0
  54. package/src/graph/NodeSlotSize.ts +4 -0
  55. package/src/graph/autoValue.ts +17 -0
  56. package/src/host/ComfyHost.ts +646 -0
  57. package/src/host/ComfyInstallType.ts +15 -0
  58. package/src/host/ComfyManager.ts +232 -0
  59. package/src/host/ComfyUploader.ts +110 -0
  60. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  61. package/src/host/Requirements.ts +55 -0
  62. package/src/host/ResilientWebsocket.ts +147 -0
  63. package/src/host/loraManagerApi.ts +98 -0
  64. package/src/image-utils/_getPngMetadata.ts +53 -0
  65. package/src/image-utils/_getWebpMetadata.ts +38 -0
  66. package/src/image-utils/_parseExifData.ts +53 -0
  67. package/src/index.ts +89 -0
  68. package/src/litegraph/LiteGraphGroup.ts +22 -0
  69. package/src/litegraph/LiteGraphJSON.ts +46 -0
  70. package/src/litegraph/LiteGraphLink.ts +23 -0
  71. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  72. package/src/litegraph/LiteGraphNode.ts +69 -0
  73. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  74. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  75. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  76. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  77. package/src/manager/ComfyRegistry.ts +124 -0
  78. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  79. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  80. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  81. package/src/manager/generated/KnownModel_Base.ts +126 -0
  82. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  83. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  84. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  85. package/src/manager/generated/KnownModel_Type.ts +97 -0
  86. package/src/manager/json/alter-list.json +224 -0
  87. package/src/manager/json/custom-node-list.extra.ts +13 -0
  88. package/src/manager/json/custom-node-list.json +21948 -0
  89. package/src/manager/json/extension-node-map.json +31282 -0
  90. package/src/manager/json/github-stats.json +12602 -0
  91. package/src/manager/json/model-list.extra.ts +26 -0
  92. package/src/manager/json/model-list.json +5052 -0
  93. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  94. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  95. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  96. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  97. package/src/manager/script-update-manager.bun.ts +18 -0
  98. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  99. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  100. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  101. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  102. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  103. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  104. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  105. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  106. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  107. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  108. package/src/runner/ComfyExecution.ts +301 -0
  109. package/src/runner/ComfyExecutionStatus.ts +2 -0
  110. package/src/runner/ComfyWorkflow.ts +395 -0
  111. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  112. package/src/runner/ComfyWsApi.ts +159 -0
  113. package/src/runner/MediaImage.ts +262 -0
  114. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  115. package/src/sdk-generator/ComfySchema.ts +369 -0
  116. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  117. package/src/sdk-generator/Primitives.ts +76 -0
  118. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  119. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  120. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  121. package/src/sdk-generator/comfy-api-json.ts +16 -0
  122. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  123. package/src/sdk-generator/comfyui-types.ts +56 -0
  124. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  125. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  126. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  127. package/src/ssh-host-manager/ssh-manager.ts +129 -0
  128. package/src/state.ts +136 -0
  129. package/src/types/comfy-sdk.ts +106 -0
  130. package/src/types/index.ts +55 -0
  131. package/src/utils/CodeBuffer.ts +61 -0
  132. package/src/utils/ComfyColors.ts +38 -0
  133. package/src/utils/ansi.ts +26 -0
  134. package/src/utils/ansiImage.ts +36 -0
  135. package/src/utils/bang.ts +39 -0
  136. package/src/utils/deepCopyNaive.ts +1 -0
  137. package/src/utils/downloadFile.ts +77 -0
  138. package/src/utils/escapeJSKey.ts +32 -0
  139. package/src/utils/exhaust.ts +4 -0
  140. package/src/utils/extractErrorMessage.ts +11 -0
  141. package/src/utils/fuzzyMatch.ts +8 -0
  142. package/src/utils/githubRegexes.ts +2 -0
  143. package/src/utils/hashArrayBuffer.ts +6 -0
  144. package/src/utils/log.ts +9 -0
  145. package/src/utils/loraTag.ts +10 -0
  146. package/src/utils/printArkResultInConsole.ts +16 -0
  147. package/src/utils/softValidate.ts +8 -0
  148. package/src/utils/stringifyReadable.ts +32 -0
  149. package/src/utils/toposort.ts +59 -0
  150. package/src/utils/tryExtracting.ts +41 -0
  151. package/src/utils/writeFile.ts +16 -0
  152. package/src/vars/ComfyVars.ts +531 -0
  153. package/src/vars/DefinedWorkflow.ts +112 -0
  154. package/src/vars/loraKeywords.ts +56 -0
  155. package/dist/index.d.mts +0 -74
  156. package/dist/index.mjs +0 -3
  157. package/dist/index.mjs.map +0 -1
  158. package/readme.md +0 -40
@@ -0,0 +1,287 @@
1
+ import type { Maybe } from 'src/types/index.ts'
2
+ import { CodeBuffer } from 'src/utils/CodeBuffer.ts'
3
+ import { escapeJSKey } from 'src/utils/escapeJSKey.ts'
4
+ import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
5
+
6
+ import { type ComfyNodeSchema, wrapQuote } from 'src/sdk-generator/ComfyNodeSchema.ts'
7
+
8
+ /**
9
+ * convert a host id to the namespace name it gets inside the global `Comfy` namespace
10
+ * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
11
+ */
12
+ export function hostIdToNamespace(hostId: string): string {
13
+ const parts = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean)
14
+ const ns = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('')
15
+ if (ns.length === 0) throw new Error(`cannot derive a namespace from host id "${hostId}"`)
16
+ // namespaces can't start with a digit
17
+ return /^[0-9]/.test(ns) ? `Host${ns}` : ns
18
+ }
19
+
20
+ export type CodegenOptions = {
21
+ /** host id; drives both the `Comfy.Hosts` registry key and the namespace name */
22
+ hostId: string
23
+ /** module to import runtime-facing types from (default: 'comfy-ts') */
24
+ packageName?: string
25
+ }
26
+
27
+ /**
28
+ * emit the typed SDK for one host:
29
+ *
30
+ * declare global {
31
+ * namespace Comfy {
32
+ * namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }
33
+ * interface Hosts { '<host-id>': <HostNs>.Sdk }
34
+ * }
35
+ * }
36
+ */
37
+ export function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {
38
+ const ns = hostIdToNamespace(opts.hostId)
39
+ const packageName = opts.packageName ?? 'comfy-ts'
40
+ const b = new CodeBuffer()
41
+ const p = b.w
42
+
43
+ p(`/** generated by comfy-ts for host "${opts.hostId}" — do not edit */`)
44
+ p(``)
45
+ p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`)
46
+ p(``)
47
+ p(`declare global {`)
48
+ b.indent()
49
+
50
+ p(`namespace Comfy {`)
51
+ b.indent()
52
+
53
+ p(`namespace ${ns} {`)
54
+ b.indent()
55
+
56
+ // #region PythonModules ----------------------------------------------------------------------
57
+ p(`// #${''}region PythonModules`)
58
+ p(`/** list of all python modules installed on this host */`)
59
+ p(`export type PythonModules =`)
60
+ b.indent()
61
+ const pythonModulesArr: [string, string[]][] = Array.from(this.pythonModules.entries()) //
62
+ .toSorted((a, b) => a[0].localeCompare(b[0]))
63
+ for (const [k, v] of pythonModulesArr) {
64
+ p(`/**`)
65
+ p(`* Nodes: ${v.join(', ')}`)
66
+ p(`*/`)
67
+ p(`| ${wrapQuote(k)}`)
68
+ }
69
+ b.deindent()
70
+ p(`// #${''}endregion`)
71
+
72
+ // #region IN ---------------------------------------------------------------------------------
73
+ const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey))
74
+ p(`interface IN {`)
75
+ b.indent()
76
+ for (const n of nodes) {
77
+ p(`${escapeJSKey(n.nodeKey)}: {`)
78
+ for (const i of n.inputs) {
79
+ const opts_ = typeof i.opts === 'string' ? null : i.opts
80
+ let type = `Accepts[${JSON.stringify(i.typeName)}]`
81
+ // COMBO inputs (ComfyUI ≥ 0.3.x) carry literal choices in opts.options
82
+ const comboOptions =
83
+ i.typeName === 'COMBO' && Array.isArray(opts_?.options)
84
+ ? opts_.options.filter(
85
+ (o): o is string | number | boolean =>
86
+ typeof o === 'string' || typeof o === 'number' || typeof o === 'boolean',
87
+ )
88
+ : []
89
+ if (comboOptions.length > 0) {
90
+ type = `${comboOptions.map((o) => JSON.stringify(o)).join(' | ')} | ${type}`
91
+ }
92
+ // custom text/primitive widget types (placeholder/multiline/default in opts)
93
+ // also accept the raw literal, e.g. AUTOCOMPLETE_TEXT_LORAS is just a string
94
+ else if (opts_ && !i.isPrimitive && !i.isEnum) {
95
+ if (typeof opts_.default === 'string' || opts_.placeholder != null || opts_.multiline != null) {
96
+ type = `string | ${type}`
97
+ } else if (typeof opts_.default === 'number') {
98
+ type = `number | ${type}`
99
+ } else if (typeof opts_.default === 'boolean') {
100
+ type = `boolean | ${type}`
101
+ }
102
+ }
103
+ if (opts_) {
104
+ const rendered = n.renderOpts(opts_)
105
+ if (rendered) p(` ${rendered}`)
106
+ }
107
+ const canBeOmmited = opts_?.default !== undefined || !i.required
108
+ p(` ${i.nameInComfyEscaped}${canBeOmmited ? '?' : ''}: ${type}`)
109
+ }
110
+ p(`},`)
111
+ }
112
+ b.deindent()
113
+ p('}')
114
+ p('')
115
+
116
+ // #region OUT --------------------------------------------------------------------------------
117
+ p(`interface OUT {`)
118
+ b.indent()
119
+ for (const n of nodes) {
120
+ p(`${escapeJSKey(n.nodeKey)}: {`)
121
+ n.outputs.forEach((i, ix) => {
122
+ p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`)
123
+ })
124
+ p(`}`)
125
+ }
126
+ b.deindent()
127
+ p('}')
128
+
129
+ // #region Node -------------------------------------------------------------------------------
130
+ p(`interface Node {`)
131
+ for (const n of nodes) {
132
+ p(
133
+ ` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`,
134
+ )
135
+ for (const hassingle of n.singleOutputs) {
136
+ p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`)
137
+ }
138
+ p(` }`)
139
+ }
140
+ p('}')
141
+
142
+ // #region Builder ----------------------------------------------------------------------------
143
+ p(`interface Builder {`)
144
+ for (const n of nodes) {
145
+ const baseDescription = `displayName="${n.raw.display_name}" category="${n.category}" name="${n.nameInComfy}" output=[${n.outputs.map((o) => o.outKey).join(', ')}]`
146
+ if (n.raw.description) {
147
+ p(` /**`)
148
+ p(
149
+ n.raw.description
150
+ .split('\n')
151
+ .map((i) => ` * ${i}`)
152
+ .join('\n'),
153
+ )
154
+ p(` * ${baseDescription}`)
155
+ p(` **/`)
156
+ } else {
157
+ p(` /** ${baseDescription} */`)
158
+ }
159
+ p(
160
+ ` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`,
161
+ )
162
+ }
163
+ p(`}`)
164
+
165
+ // #region Slots ------------------------------------------------------------------------------
166
+ p(`interface Slots {`)
167
+ for (const e of this.knownUnionByHash.values()) {
168
+ p(' // ' + e.unionName)
169
+ for (const alias of e.enumNames) {
170
+ p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`)
171
+ }
172
+ }
173
+ p(`}`)
174
+
175
+ // #region Embeddings -------------------------------------------------------------------------
176
+ p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(' | ') || '""'}`)
177
+
178
+ const slotTypes = [...this.knownSlotTypes.values()] //
179
+ .map((comfyType) => ({
180
+ comfyType,
181
+ tsType: this.toTSType(comfyType),
182
+ tsType2: this.toAcceptsType(comfyType),
183
+ }))
184
+ .sort((a, b) => b.tsType.length - a.tsType.length)
185
+
186
+ // #region Producer ---------------------------------------------------------------------------
187
+ p('')
188
+ p('interface Producer {')
189
+ b.indent()
190
+ for (const tp of slotTypes) {
191
+ const allProducingNodes: Maybe<ComfyNodeSchema[]> = this.nodesByProduction[tp.comfyType]
192
+ if (allProducingNodes) {
193
+ p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(' | ')}>`)
194
+ } else {
195
+ p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`)
196
+ }
197
+ }
198
+ b.deindent()
199
+ p('}')
200
+
201
+ // #region Accepts -----------------------------------------------------------------------------
202
+ p(`interface Accepts {`)
203
+ b.indent()
204
+ // 1/3
205
+ p('// injected bottom type (broken/null input specs land here)')
206
+ p(`INVALID_null: any`)
207
+
208
+ // 2/3
209
+ p('')
210
+ p('// named slot types: everything an input of that type accepts')
211
+ for (const t of slotTypes) {
212
+ p(
213
+ `${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`,
214
+ )
215
+ }
216
+
217
+ // 3/3
218
+ p('')
219
+ p('// enum unions: literal values or an output carrying one')
220
+ for (const t of this.knownUnionByHash.values()) {
221
+ p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`)
222
+ }
223
+ b.deindent()
224
+ p(`}\n`)
225
+
226
+ // #region Union ------------------------------------------------------------------------------
227
+ p('interface Union {')
228
+ for (const e of this.knownUnionByHash.values()) {
229
+ if (e.values.length > 0) {
230
+ p(` // ${JSON.stringify(e.enumNames)}`)
231
+ p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(' | ')}`)
232
+ } else {
233
+ p(` ${e.unionName}: '🔴' // never`)
234
+ }
235
+ }
236
+ p('}')
237
+
238
+ // #region HasSingle --------------------------------------------------------------------------
239
+ p(`export interface HasSingle {`)
240
+ for (const t of slotTypes) {
241
+ p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`)
242
+ }
243
+ p(`}`)
244
+
245
+ for (const t of this.enumsAppearingInOutput.values()) {
246
+ p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`)
247
+ }
248
+
249
+ // #region Schemas ----------------------------------------------------------------------------
250
+ p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`)
251
+ p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(' | ')}`)
252
+
253
+ // #region Sdk --------------------------------------------------------------------------------
254
+ p(``)
255
+ p(`/** everything above, packaged for the Comfy.Hosts registry */`)
256
+ p(`interface Sdk {`)
257
+ p(` IN: IN`)
258
+ p(` OUT: OUT`)
259
+ p(` Node: Node`)
260
+ p(` Builder: Builder`)
261
+ p(` Slots: Slots`)
262
+ p(` Accepts: Accepts`)
263
+ p(` Union: Union`)
264
+ p(` Producer: Producer`)
265
+ p(` Embeddings: Embeddings`)
266
+ p(` Schemas: Schemas`)
267
+ p(` NodeType: NodeType`)
268
+ p(`}`)
269
+
270
+ b.deindent()
271
+ p(`}`) // end namespace <HostNs>
272
+
273
+ p(``)
274
+ p(`interface Hosts {`)
275
+ p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`)
276
+ p(`}`)
277
+
278
+ b.deindent()
279
+ p('}') // end namespace Comfy
280
+
281
+ b.deindent()
282
+ p('}') // end declare global
283
+ p(``)
284
+ p(`export {}`)
285
+
286
+ return b.content
287
+ }
@@ -0,0 +1,56 @@
1
+ import type { Branded } from 'src/types/index.ts'
2
+ import type { ComfyInputOpts } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
3
+
4
+ export type ComfyUnionHash = string // '26c34bf761d4be4554ab944105c5a3c017c99453
5
+ export type ComfyUnionName = string // 'E_26c34bf761d4be4554ab944105c5a3c017c99453'
6
+ export type ComfyUnionValue = string | boolean | number
7
+
8
+ export type ComfyPythonModule = string
9
+ export type NodeNameInComfy = string
10
+ export type QualifiedNodeKey = string
11
+
12
+ /**
13
+ * the textual name of a slot type (slot = input or output of a node),
14
+ * e.g. 'MODEL', 'IMAGE', 'E_CkptName'.
15
+ * Branded string — internals never depend on the global Comfy namespace
16
+ * (that would break host encapsulation: slot types are per-host).
17
+ */
18
+ export type ComfyNodeSlotTypeName = Branded<string, { SlotTypeName: true }>
19
+ export const asComfyNodeSlotTypeName = (x: string): ComfyNodeSlotTypeName => x as ComfyNodeSlotTypeName
20
+
21
+ /** a fully-qualified slot name, e.g. 'LoadImage.image' or 'KSampler.LATENT.OUT' */
22
+ export type ComfyNodeSlotName = Branded<string, { SlotName: true }>
23
+ export const asComfyNodeSlotName = (x: string): ComfyNodeSlotName => x as ComfyNodeSlotName
24
+
25
+ export type EmbeddingName = Branded<string, { Embedding: true }>
26
+
27
+ export type NodeInputExt = {
28
+ slotName: ComfyNodeSlotName
29
+ nameInComfy: string
30
+ nameInComfyEscaped: string
31
+ typeName: ComfyNodeSlotTypeName
32
+ opts?: ComfyInputOpts
33
+ isPrimitive: boolean
34
+ isEnum: boolean
35
+ required: boolean
36
+ index: number
37
+ }
38
+
39
+ export type NodeOutputExt = {
40
+ slotName: ComfyNodeSlotName
41
+ typeName: ComfyNodeSlotTypeName
42
+ outKey: string
43
+ nameInComfy: string
44
+ isPrimitive: boolean
45
+ }
46
+
47
+ export type ComfyUnionInfo = {
48
+ hash: ComfyUnionHash
49
+ unionName: ComfyUnionName
50
+ values: ComfyUnionValue[]
51
+ enumNames: ComfyNodeSlotName[]
52
+ }
53
+
54
+ /** an image file name as known by the host (hash-named upload or existing input) */
55
+ export type ComfyImageName = Branded<string, { ComfyImageName: true }>
56
+ export const asComfyImageName = (x: string): ComfyImageName => x as ComfyImageName
@@ -0,0 +1,157 @@
1
+ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
2
+ import type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'
3
+ import type { LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'
4
+ import type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'
5
+ import type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'
6
+ import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
7
+ import type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
8
+ import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
9
+ import type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'
10
+ import {
11
+ howManyWidgetValuesForThisInputType,
12
+ howManyWidgetValuesForThisSchemaType,
13
+ UnknownCustomNode,
14
+ } from 'src/sdk-generator/Primitives.ts'
15
+ import type { Maybe } from 'src/types/index.ts'
16
+
17
+ /**
18
+ * convert a saved ComfyUI workflow.json (litegraph format) into the api.json
19
+ * (prompt format) ComfyUI's POST /prompt takes.
20
+ * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes
21
+ * unwrapped, primitives inlined into their consumers), widget-value offsets
22
+ * (incl. the phantom `control_after_generate` value after seeds).
23
+ */
24
+ export const convertLiteGraphToPrompt = (
25
+ /** the ComfySchema object (to look for references/definitions) */
26
+ schema: ComfySchema,
27
+ /** the litegraph */
28
+ workflow: LiteGraphJSON,
29
+ opts: { verbose?: boolean } = {},
30
+ ): ComfyApiJson => {
31
+ const prompt: ComfyApiJson = {}
32
+ const LOG = opts.verbose ? (...args: unknown[]): void => console.log('[🔥] converter:', ...args) : (): void => {}
33
+
34
+ // 1. cache primitive node values so links from PrimitiveNode inline as values
35
+ const PRIMITIVE_VALUES: { [nodeId: string]: unknown } = {}
36
+ for (const node of workflow.nodes) {
37
+ if (node.type === 'PrimitiveNode') {
38
+ const widgetValues = node.widgets_values
39
+ if (widgetValues == null || widgetValues.length === 0) {
40
+ throw new Error(`PrimitiveNode#${node.id} has no widget values`)
41
+ }
42
+ PRIMITIVE_VALUES[node.id] = widgetValues[0]
43
+ }
44
+ }
45
+
46
+ // 2. every executable node
47
+ for (const node of workflow.nodes) {
48
+ if (node.isVirtualNode) continue // frontend-only nodes
49
+ if (node.mode === 2) continue // muted
50
+ if (node.type === 'Reroute') continue // unwrapped below
51
+ if (node.type === 'Note') continue // comments
52
+ if (node.type === 'PrimitiveNode') continue // inlined into consumers
53
+
54
+ const inputs: ComfyApiNodeJson['inputs'] = {}
55
+ const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name))
56
+ const nodeSchema_ = schema.nodesByNameInComfy[node.type]
57
+ if (nodeSchema_ == null) throw new UnknownCustomNode(node)
58
+ const nodeSchema: ComfyNodeSchema = nodeSchema_
59
+
60
+ // 2.a widget values, consumed in schema order
61
+ let offset = 0
62
+ const inputsInNodeJSON: LiteGraphNodeInput[] = node.inputs ?? []
63
+ const inputsInNodeSchema: NodeInputExt[] = nodeSchema.inputs
64
+ for (const field of inputsInNodeSchema) {
65
+ const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy)
66
+ const MUST_CONSUME = input?.type
67
+ ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)
68
+ : howManyWidgetValuesForThisSchemaType(field)
69
+
70
+ if (MUST_CONSUME > 0) {
71
+ if (node.widgets_values == null)
72
+ throw new Error(
73
+ `node ${node.id}(${node.type}) has no widgets_values but "${field.nameInComfy}" needs one`,
74
+ )
75
+ if (node.widgets_values.length < offset + 1)
76
+ throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for "${field.nameInComfy}"`)
77
+ const _value = node.widgets_values[offset]
78
+ LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`)
79
+ if (!isValidValue(_value))
80
+ throw new Error(
81
+ `node ${node.id}(${node.type}) has an invalid widget value for "${field.nameInComfy}": ${JSON.stringify(_value)}`,
82
+ )
83
+ inputs[field.nameInComfy] = _value
84
+ offset += MUST_CONSUME
85
+ } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {
86
+ if (field.required)
87
+ throw new Error(
88
+ `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`,
89
+ )
90
+ }
91
+ }
92
+
93
+ // 2.b links
94
+ type ParentInfo = { node: LiteGraphNode; link: LiteGraphLink }
95
+ const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {
96
+ const link = workflow.links.find((link) => link[0] === linkId)
97
+ if (link == null)
98
+ throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`)
99
+ const parentId = link[1]
100
+ const parentNode = workflow.nodes.find((n) => n.id === parentId)
101
+ if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`)
102
+ return { node: parentNode, link }
103
+ }
104
+
105
+ INPT: for (const ipt of node.inputs ?? []) {
106
+ const isPrimitive = howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0
107
+ if (isPrimitive) continue
108
+
109
+ // not a primitive => we assume it's a link
110
+ if (ipt.link == null) {
111
+ LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`)
112
+ continue
113
+ }
114
+ let parent: Maybe<ParentInfo> = getParentNode(ipt.link)
115
+
116
+ // unwrap reroute chains
117
+ let max = 100
118
+ while (parent != null && parent.node.type === 'Reroute' && max-- > 0) {
119
+ const firstParentInput = parent.node.inputs?.[0]
120
+ if (firstParentInput?.link == null) {
121
+ LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`)
122
+ continue INPT
123
+ }
124
+ parent = getParentNode(firstParentInput.link)
125
+ }
126
+ if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`)
127
+
128
+ // inline primitive nodes as plain values
129
+ if (parent.node.type === 'PrimitiveNode') {
130
+ inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id] as ComfyApiNodeJson['inputs'][string]
131
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`)
132
+ continue
133
+ }
134
+
135
+ LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`)
136
+ inputs[ipt.name] = [String(parent.node.id), parent.link[2]]
137
+ }
138
+
139
+ prompt[String(node.id)] = { inputs, class_type: node.type }
140
+ }
141
+
142
+ return prompt
143
+ }
144
+
145
+ /** alias cause I keep forgetting about this */
146
+ export const convertWorkflowToPrompt = convertLiteGraphToPrompt
147
+
148
+ type ValidValue = string | number | boolean | [string, number] | null
149
+ function isValidValue(value: unknown): value is ValidValue {
150
+ if (value == null) return true // null is valid
151
+ if (typeof value === 'string') return true
152
+ if (typeof value === 'number') return true
153
+ if (typeof value === 'boolean') return true
154
+ if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number')
155
+ return true
156
+ return false
157
+ }
@@ -0,0 +1,89 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'pathe'
4
+ import { bang } from 'src/utils/bang.ts'
5
+
6
+ export interface SSHHostConfig {
7
+ host: string
8
+ hostname: string
9
+ user: string
10
+ controlMaster?: string
11
+ controlPath?: string
12
+ controlPersist?: string
13
+ identityFile?: string
14
+ [key: string]: string | undefined
15
+ }
16
+
17
+ export class SSHConfigManager {
18
+ private configPath: string
19
+
20
+ constructor() {
21
+ this.configPath = join(homedir(), '.ssh', 'config')
22
+ }
23
+
24
+ private parseConfig(): string {
25
+ if (!existsSync(this.configPath)) return ''
26
+ return readFileSync(this.configPath, 'utf8')
27
+ }
28
+
29
+ private formatHostConfig(config: SSHHostConfig): string {
30
+ const lines = [`Host ${config.host}`]
31
+
32
+ Object.entries(config).forEach(([key, value]) => {
33
+ if (key !== 'host' && value) {
34
+ const configKey = key
35
+ .replace(/([A-Z])/g, (_match, letter) => (letter === key[0] ? letter : letter))
36
+ .replace(/([a-z])([A-Z])/g, '$1$2')
37
+
38
+ // Convert camelCase to SSH config format
39
+ const sshKey =
40
+ configKey.charAt(0).toUpperCase() +
41
+ configKey.slice(1).replace(/([A-Z])/g, (_match, letter, index) => (index > 0 ? letter : letter))
42
+
43
+ lines.push(` ${sshKey} ${value}`)
44
+ }
45
+ })
46
+
47
+ return lines.join('\n')
48
+ }
49
+
50
+ upsertSSHHostEntryInShhConfig(config: SSHHostConfig): void {
51
+ const currentConfig = this.parseConfig()
52
+ const hostPattern = new RegExp(`^Host\\s+${config.host}\\s*$`, 'm')
53
+
54
+ // Find the host block
55
+ const hostMatch = currentConfig.match(hostPattern)
56
+
57
+ if (hostMatch) {
58
+ // Update existing host
59
+ const hostIndex = bang(hostMatch.index)
60
+ const lines = currentConfig.split('\n')
61
+ const hostLineIndex = currentConfig.substring(0, hostIndex).split('\n').length - 1
62
+
63
+ // Find the end of this host block (next Host line or end of file)
64
+ let endIndex = lines.length
65
+ for (let i = hostLineIndex + 1; i < lines.length; i++) {
66
+ if (lines[i]?.match(/^Host\s+/)) {
67
+ endIndex = i
68
+ break
69
+ }
70
+ }
71
+
72
+ // Replace the host block
73
+ const beforeHost = lines.slice(0, hostLineIndex)
74
+ const afterHost = lines.slice(endIndex)
75
+ const newConfig = [...beforeHost, this.formatHostConfig(config), ...afterHost].join('\n')
76
+
77
+ writeFileSync(this.configPath, newConfig)
78
+ } else {
79
+ // Add new host
80
+ const newHostConfig = this.formatHostConfig(config)
81
+ const separator = currentConfig.trim() ? '\n\n' : ''
82
+ const updatedConfig = currentConfig + separator + newHostConfig + '\n'
83
+
84
+ writeFileSync(this.configPath, updatedConfig)
85
+ }
86
+
87
+ console.log(`✅ SSH config updated for host: ${config.host}`)
88
+ }
89
+ }
@@ -0,0 +1,32 @@
1
+ # SSH configuration for Windows
2
+
3
+ ## install OpenSSH Server on Windows using PowerShell
4
+
5
+ ```powershell
6
+ # Install OpenSSH Server
7
+ Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
8
+
9
+ # Start the service
10
+ Start-Service sshd
11
+
12
+ # Set it to start automatically (optional)
13
+ Set-Service -Name sshd -StartupType 'Automatic'
14
+
15
+ # Configure firewall
16
+ New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
17
+ ```
18
+
19
+ ## Generate
20
+
21
+ ```shell
22
+ ssh-keygen -t rsa -P ""
23
+ ssh-copy-id windows-machine
24
+ ```
25
+
26
+ ## update your config.
27
+
28
+ ## test it wokrs.
29
+
30
+ ```
31
+ ssh windows-machine
32
+ ```