comfy-ts 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) 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 +4171 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9910 -0
  8. package/dist/index.d.ts +9894 -58
  9. package/dist/index.js +4092 -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-SDSJo1Qf.js +3896 -0
  14. package/dist/run-tui-SDSJo1Qf.js.map +1 -0
  15. package/package.json +103 -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 +56 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  24. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  25. package/src/cli/tui/components/OverlayList.tsx +25 -0
  26. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  27. package/src/cli/tui/components/PreviewPanel.tsx +78 -0
  28. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  29. package/src/cli/tui/components/StatusBar.tsx +171 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  31. package/src/cli/tui/components/TreePanel.tsx +51 -0
  32. package/src/cli/tui/components/TuiApp.tsx +246 -0
  33. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  34. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  35. package/src/cli/tui/keys.ts +20 -0
  36. package/src/cli/tui/protocolImagePainter.ts +95 -0
  37. package/src/cli/tui/run-tui.tsx +76 -0
  38. package/src/cli/tui/state/DraftsSt.ts +273 -0
  39. package/src/cli/tui/state/EditorSt.ts +289 -0
  40. package/src/cli/tui/state/ExecSt.ts +173 -0
  41. package/src/cli/tui/state/HostSt.ts +230 -0
  42. package/src/cli/tui/state/LogsSt.ts +107 -0
  43. package/src/cli/tui/state/LorasSt.ts +185 -0
  44. package/src/cli/tui/state/PickerSt.ts +112 -0
  45. package/src/cli/tui/state/PreviewSt.ts +288 -0
  46. package/src/cli/tui/state/QueueSt.ts +59 -0
  47. package/src/cli/tui/state/SettingsSt.ts +100 -0
  48. package/src/cli/tui/state/TreeSt.ts +122 -0
  49. package/src/cli/tui/state/TuiSt.ts +175 -0
  50. package/src/cli/tui/state/WorkflowsSt.ts +93 -0
  51. package/src/cli/tui-env.ts +8 -0
  52. package/src/errors/InvalidPromptError.ts +12 -0
  53. package/src/graph/ComfyNode.ts +403 -0
  54. package/src/graph/ComfyNodeID.ts +28 -0
  55. package/src/graph/ComfyNodeOutput.ts +16 -0
  56. package/src/graph/NodeSlotSize.ts +4 -0
  57. package/src/graph/autoValue.ts +17 -0
  58. package/src/host/ComfyHost.ts +690 -0
  59. package/src/host/ComfyInstallType.ts +15 -0
  60. package/src/host/ComfyManager.ts +232 -0
  61. package/src/host/ComfyUploader.ts +110 -0
  62. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  63. package/src/host/Requirements.ts +55 -0
  64. package/src/host/ResilientWebsocket.ts +147 -0
  65. package/src/host/loraManagerApi.ts +98 -0
  66. package/src/image-utils/_getPngMetadata.ts +53 -0
  67. package/src/image-utils/_getWebpMetadata.ts +38 -0
  68. package/src/image-utils/_parseExifData.ts +53 -0
  69. package/src/index.ts +89 -0
  70. package/src/litegraph/LiteGraphGroup.ts +22 -0
  71. package/src/litegraph/LiteGraphJSON.ts +46 -0
  72. package/src/litegraph/LiteGraphLink.ts +23 -0
  73. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  74. package/src/litegraph/LiteGraphNode.ts +69 -0
  75. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  76. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  77. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  78. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  79. package/src/manager/ComfyRegistry.ts +124 -0
  80. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  81. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  82. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  83. package/src/manager/generated/KnownModel_Base.ts +126 -0
  84. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  85. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  86. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  87. package/src/manager/generated/KnownModel_Type.ts +97 -0
  88. package/src/manager/json/alter-list.json +224 -0
  89. package/src/manager/json/custom-node-list.extra.ts +13 -0
  90. package/src/manager/json/custom-node-list.json +21948 -0
  91. package/src/manager/json/extension-node-map.json +31282 -0
  92. package/src/manager/json/github-stats.json +12602 -0
  93. package/src/manager/json/model-list.extra.ts +26 -0
  94. package/src/manager/json/model-list.json +5052 -0
  95. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  96. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  97. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  98. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  99. package/src/manager/script-update-manager.bun.ts +18 -0
  100. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  101. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  102. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  103. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  104. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  105. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  106. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  107. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  108. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  109. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  110. package/src/runner/ComfyExecution.ts +301 -0
  111. package/src/runner/ComfyExecutionStatus.ts +2 -0
  112. package/src/runner/ComfyWorkflow.ts +395 -0
  113. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  114. package/src/runner/ComfyWsApi.ts +170 -0
  115. package/src/runner/MediaImage.ts +262 -0
  116. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  117. package/src/sdk-generator/ComfySchema.ts +369 -0
  118. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  119. package/src/sdk-generator/Primitives.ts +76 -0
  120. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  121. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  122. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  123. package/src/sdk-generator/comfy-api-json.ts +16 -0
  124. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  125. package/src/sdk-generator/comfyui-types.ts +56 -0
  126. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  127. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  128. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  129. package/src/ssh-host-manager/ssh-manager.ts +114 -0
  130. package/src/state.ts +136 -0
  131. package/src/types/comfy-sdk.ts +106 -0
  132. package/src/types/index.ts +55 -0
  133. package/src/utils/CodeBuffer.ts +61 -0
  134. package/src/utils/ComfyColors.ts +38 -0
  135. package/src/utils/ansi.ts +33 -0
  136. package/src/utils/ansiImage.ts +36 -0
  137. package/src/utils/bang.ts +39 -0
  138. package/src/utils/deepCopyNaive.ts +1 -0
  139. package/src/utils/downloadFile.ts +77 -0
  140. package/src/utils/escapeJSKey.ts +32 -0
  141. package/src/utils/exhaust.ts +4 -0
  142. package/src/utils/extractErrorMessage.ts +11 -0
  143. package/src/utils/fuzzyMatch.ts +8 -0
  144. package/src/utils/githubRegexes.ts +2 -0
  145. package/src/utils/hashArrayBuffer.ts +6 -0
  146. package/src/utils/log.ts +9 -0
  147. package/src/utils/loraTag.ts +10 -0
  148. package/src/utils/mojibake.ts +60 -0
  149. package/src/utils/printArkResultInConsole.ts +16 -0
  150. package/src/utils/softValidate.ts +8 -0
  151. package/src/utils/stringifyReadable.ts +32 -0
  152. package/src/utils/toposort.ts +59 -0
  153. package/src/utils/tryExtracting.ts +41 -0
  154. package/src/utils/writeFile.ts +16 -0
  155. package/src/vars/ComfyVars.ts +531 -0
  156. package/src/vars/DefinedWorkflow.ts +112 -0
  157. package/src/vars/loraKeywords.ts +56 -0
  158. package/dist/index.d.mts +0 -74
  159. package/dist/index.mjs +0 -3
  160. package/dist/index.mjs.map +0 -1
  161. package/readme.md +0 -40
@@ -0,0 +1,114 @@
1
+ import { type ChildProcess, exec, spawn } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+
4
+ const execAsync = promisify(exec)
5
+
6
+ export class SSHHost {
7
+ private host: string
8
+ private activeProcesses: Set<ChildProcess>
9
+
10
+ constructor(host: string) {
11
+ this.host = host
12
+ this.activeProcesses = new Set()
13
+ }
14
+
15
+ async executeCommand(command: string): Promise<string> {
16
+ const { stdout, stderr } = await execAsync(`ssh ${this.host} "${command}"`)
17
+ if (stderr) console.error('SSH Error:', stderr)
18
+ return stdout.trim()
19
+ }
20
+
21
+ async executeCommandAndStream(
22
+ command: string,
23
+ onStdOut: (data: string) => void,
24
+ onStdErr: (data: string) => void,
25
+ ): Promise<number> {
26
+ return new Promise<number>((resolve, reject) => {
27
+ const sshArgs = [this.host, command]
28
+ const sshProcess: ChildProcess = spawn('ssh', sshArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
29
+ this.activeProcesses.add(sshProcess)
30
+
31
+ sshProcess.stdout?.on('data', (dataBuffer) => {
32
+ onStdOut(dataBuffer.toString())
33
+ })
34
+
35
+ sshProcess.stderr?.on('data', (dataBuffer) => {
36
+ onStdErr(dataBuffer.toString())
37
+ })
38
+
39
+ sshProcess.on('close', (code: number | null) => {
40
+ this.activeProcesses.delete(sshProcess)
41
+ if (code === 0) {
42
+ resolve(code)
43
+ } else {
44
+ // Non-zero exit code. Error messages should have been streamed via onStdErr.
45
+ resolve(code ?? 1) // Resolve with the actual code, or 1 if null
46
+ }
47
+ })
48
+
49
+ sshProcess.on('error', (err) => {
50
+ this.activeProcesses.delete(sshProcess)
51
+ // This event is emitted if the process could not be spawned, or could not be killed.
52
+ onStdErr(`Failed to start or manage SSH process: ${err.message}\n`)
53
+ reject(err) // Reject the promise on a spawn error
54
+ })
55
+ })
56
+ }
57
+
58
+ async executeCommandAndLog(command: string): Promise<number> {
59
+ console.log(`[SSH ${this.host}] Executing: ${command}`)
60
+ return this.executeCommandAndStream(
61
+ command,
62
+ (data) => console.log(`[SSH ${this.host} STDOUT] ${data.trimEnd()}`),
63
+ (data) => console.error(`[SSH ${this.host} STDERR] ${data.trimEnd()}`),
64
+ )
65
+ }
66
+
67
+ async closeConnection(): Promise<void> {
68
+ // Terminate any active streamed commands
69
+ if (this.activeProcesses.size > 0) {
70
+ console.log(`🔌 Terminating ${this.activeProcesses.size} active SSH command(s)...`)
71
+ this.activeProcesses.forEach((proc) => {
72
+ if (!proc.killed) {
73
+ proc.kill('SIGTERM') // Send SIGTERM to allow graceful shutdown
74
+ // proc.kill('SIGKILL'); // Uncomment for forceful termination if SIGTERM is not effective
75
+ }
76
+ })
77
+ this.activeProcesses.clear() // Clear the set
78
+ }
79
+
80
+ try {
81
+ await execAsync(`ssh -O exit ${this.host}`)
82
+ console.log('🔌 SSH master connection closed')
83
+ } catch (_error) {
84
+ // This error might mean the master connection was already down or never established.
85
+ // If activeProcesses were found and killed, it's still useful information.
86
+ const activeProcessesWereRunning = this.activeProcesses.size > 0 // Check before clearing, though it's cleared above
87
+ if (!activeProcessesWereRunning) {
88
+ // only log "no active connection" if there were no processes either
89
+ console.log('No active SSH master connection to close, or it was already closed.')
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ // Usage
96
+ // async function main() {
97
+ // const ssh = new SSHManager('windows-machine')
98
+
99
+ // try {
100
+ // // Your commands here
101
+ // const result = await ssh.executeCommand('dir C:\\')
102
+ // console.log('Directory listing:', result)
103
+
104
+ // const powershell = await ssh.executeCommand('powershell "Get-Date"')
105
+ // console.log('Current time:', powershell)
106
+ // } catch (error) {
107
+ // console.error('Error:', error)
108
+ // }
109
+
110
+ // // Don't close connection - let it persist
111
+ // // await ssh.closeConnection();
112
+ // }
113
+
114
+ // main()
package/src/state.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'pathe'
3
+ import pkgJson from '../package.json' with { type: 'json' }
4
+ import { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'
5
+ import { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
6
+ import { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'
7
+
8
+ /** singleton */
9
+ export class ComfyTS {
10
+ version = pkgJson.version
11
+
12
+ constructor(p: { rootPath?: string } = {}) {
13
+ // global registration: the rest of the lib resolves paths through `comfyts`
14
+ const globalHack = globalThis as { comfyts?: ComfyTS }
15
+ if (globalHack.comfyts != null) throw new Error('ComfyTS instance already created')
16
+ globalHack.comfyts = this
17
+ if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath)
18
+ this.baseFolder = asAbsolutePath(join(this.rootPath, '.comfy-ts'))
19
+ this.hostsFolder = asAbsolutePath(join(this.baseFolder, 'hosts'))
20
+ this.outputPath = asAbsolutePath(join(this.baseFolder, 'outputs'))
21
+ }
22
+
23
+ /**
24
+ * multi-module entrypoint: returns the existing global instance or creates
25
+ * it. Workflow modules MUST use this (the TUI imports many of them into one
26
+ * process); `new ComfyTS()` still throws on a second instance.
27
+ */
28
+ static create(p: { rootPath?: string } = {}): ComfyTS {
29
+ const globalHack = globalThis as { comfyts?: ComfyTS }
30
+ const existing = globalHack.comfyts
31
+ if (existing == null) return new ComfyTS(p)
32
+ if (p.rootPath != null && asAbsolutePath(p.rootPath) !== existing.rootPath)
33
+ throw new Error(
34
+ `ComfyTS.create({rootPath: '${p.rootPath}'}) conflicts with the existing instance rooted at '${existing.rootPath}'`,
35
+ )
36
+ return existing
37
+ }
38
+
39
+ /** every host created through host(), keyed by id — one instance (and one ws) per id */
40
+ hosts: Map<string, ComfyHost> = new Map()
41
+
42
+ host<const ID extends string>(data: ComfyHostData & { id: ID }): ComfyHost<ID> {
43
+ const existing = this.hosts.get(data.id)
44
+ if (existing != null) {
45
+ if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https)
46
+ throw new Error(
47
+ `host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`,
48
+ )
49
+ // cast: whitelist item 7 (agent/coding.md) — id equality checked just above
50
+ return existing as ComfyHost<ID>
51
+ }
52
+ const created = new ComfyHost(data)
53
+ this.hosts.set(data.id, created)
54
+ return created
55
+ }
56
+
57
+ /**
58
+ * A ComfyRegistry instance that provides access to all
59
+ * known Comfy nodes, models, plugins, ...
60
+ * lazy: constructing it parses ~3MB of ComfyUI-Manager JSON, only pay when used
61
+ */
62
+ private _registry: ComfyRegistry | null = null
63
+ get registry(): ComfyRegistry {
64
+ if (this._registry == null) this._registry = new ComfyRegistry({ check: false, genTypes: false })
65
+ return this._registry
66
+ }
67
+
68
+ /** root path used to resolve things */
69
+ rootPath: AbsolutePath = asAbsolutePath(process.cwd())
70
+
71
+ /**
72
+ * every repo using comfy-ts gets ONE `.comfy-ts/` folder:
73
+ * .comfy-ts/hosts/<id>/{object_info.json, embeddings.json, sdk.d.ts}
74
+ * .comfy-ts/outputs/... generated images & workflows
75
+ * .comfy-ts/drafts/<workflow-id>/<draft>.json TUI var snapshots (local, gitignored)
76
+ */
77
+ baseFolder: AbsolutePath
78
+ hostsFolder: AbsolutePath
79
+ outputPath: AbsolutePath
80
+
81
+ resolveFromDrafts(relativePath: string): AbsolutePath {
82
+ return asAbsolutePath(join(this.baseFolder, 'drafts', relativePath))
83
+ }
84
+
85
+ resolveFromCache(relativePath: string): AbsolutePath {
86
+ return asAbsolutePath(join(this.baseFolder, 'cache', relativePath))
87
+ }
88
+
89
+ /** local TUI settings (preview mode, last draft per workflow) — gitignored */
90
+ get settingsPath(): AbsolutePath {
91
+ return asAbsolutePath(join(this.baseFolder, 'settings.json'))
92
+ }
93
+
94
+ resolveFromHosts(relativePath: string): AbsolutePath {
95
+ return asAbsolutePath(join(this.hostsFolder, relativePath))
96
+ }
97
+
98
+ /**
99
+ * Resolves a relative path against an absolute path.
100
+ * @param from - The absolute path to resolve from.
101
+ * @param relativePath - The relative path to resolve.
102
+ * @returns The resolved absolute path.
103
+ */
104
+ resolve(from: AbsolutePath, relativePath: RelativePath): AbsolutePath {
105
+ return asAbsolutePath(join(from, relativePath))
106
+ }
107
+ resolveFromOutput(relativePath: string): AbsolutePath {
108
+ return asAbsolutePath(join(this.outputPath, relativePath))
109
+ }
110
+
111
+ readJSON_ = <T>(absPath: AbsolutePath, def?: T): T => {
112
+ const exists = existsSync(absPath)
113
+ if (!exists) {
114
+ if (def != null) return def
115
+ throw new Error(`file does not exist ${absPath}`)
116
+ }
117
+ const str = readFileSync(absPath, 'utf8')
118
+ const json = JSON.parse(str)
119
+ return json
120
+ }
121
+
122
+ // for automatic formating of produced ComfyUI workflow
123
+ autolayoutOpts: {
124
+ node_hsep: number
125
+ node_vsep: number
126
+ forceLeft: boolean
127
+ } = {
128
+ node_hsep: 50,
129
+ node_vsep: 50,
130
+ forceLeft: false,
131
+ }
132
+ }
133
+
134
+ declare global {
135
+ var comfyts: ComfyTS
136
+ }
@@ -0,0 +1,106 @@
1
+ import type { ComfyNode } from 'src/graph/ComfyNode.ts'
2
+ import type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
3
+ import type { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
4
+
5
+ // base (untyped) node shapes: what you get when no generated sdk is in scope
6
+ export type BaseNodeInputs = Record<string, unknown>
7
+ export type BaseNodeOutputs = Record<string, ComfyNodeOutput<string, number>>
8
+ export type BaseNode = ComfyNode<BaseNodeInputs, BaseNodeOutputs>
9
+ export type BaseNodeFactory = (inputs: BaseNodeInputs, meta?: ComfyNodeMetadata) => BaseNode
10
+
11
+ declare global {
12
+ namespace Comfy {
13
+ /**
14
+ * registry of generated per-host SDKs.
15
+ * each generated `output/hosts/<id>/sdk.d.ts` merges one entry:
16
+ *
17
+ * interface Hosts { 'windows-1': Windows1.Sdk }
18
+ *
19
+ * `SdkForHost<'windows-1'>` then resolves to the precise types of that host.
20
+ */
21
+ interface Hosts {}
22
+
23
+ // ---- permissive base surface --------------------------------------
24
+ // lets the library itself (and untyped consumers) typecheck with NO
25
+ // generated sdk around. generated per-host namespaces provide the
26
+ // precise versions of these under Comfy.<HostNs>.*
27
+ interface Accepts {
28
+ [slotTypeName: string]: unknown
29
+ }
30
+ interface Slots {
31
+ [slotName: string]: string
32
+ }
33
+ interface Union {
34
+ [unionName: string]: string | number | boolean
35
+ }
36
+ interface IN {
37
+ [nodeName: string]: BaseNodeInputs
38
+ }
39
+ interface OUT {
40
+ [nodeName: string]: BaseNodeOutputs
41
+ }
42
+ interface Node {
43
+ [nodeName: string]: BaseNode
44
+ }
45
+ interface Builder {
46
+ [nodeName: string]: BaseNodeFactory
47
+ }
48
+ interface Producer {
49
+ [slotTypeName: string]: Partial<Builder>
50
+ }
51
+ }
52
+ }
53
+
54
+ /** the shape every generated per-host Sdk interface follows */
55
+ export interface ComfySdkShape {
56
+ IN: object
57
+ OUT: object
58
+ Node: object
59
+ Builder: object
60
+ Slots: object
61
+ Accepts: object
62
+ Union: object
63
+ Producer: object
64
+ Embeddings: string
65
+ }
66
+
67
+ /** fallback sdk: the permissive base surface above */
68
+ export interface ComfySdkBase extends ComfySdkShape {
69
+ IN: Comfy.IN
70
+ OUT: Comfy.OUT
71
+ Node: Comfy.Node
72
+ Builder: Comfy.Builder
73
+ Slots: Comfy.Slots
74
+ Accepts: Comfy.Accepts
75
+ Union: Comfy.Union
76
+ Producer: Comfy.Producer
77
+ Embeddings: string
78
+ }
79
+
80
+ /**
81
+ * resolve the sdk types for a given host id:
82
+ * precise generated types when `Comfy.Hosts` has an entry, base types otherwise.
83
+ *
84
+ * The `[keyof Comfy.Hosts] extends [never]` guard is load-bearing, not style:
85
+ * with an EMPTY registry (no sdk.d.ts anywhere, i.e. a fresh clone or a consumer
86
+ * before their first codegen) `ID extends keyof Comfy.Hosts` stays a DEFERRED
87
+ * conditional for any generic ID. A deferred type in the contravariant `build`
88
+ * parameter of DefineWorkflowSpec makes `ComfyHost<ID>` unassignable to
89
+ * `ComfyHost<string>`, and 10 errors erupt across state/ComfyHost/ComfyWorkflow/
90
+ * MediaImage. Resolving to the base sdk EAGERLY when the registry is empty keeps
91
+ * the library typechecking with nothing generated on disk (frozen invariant).
92
+ */
93
+ export type SdkForHost<ID extends string> = [keyof Comfy.Hosts] extends [never]
94
+ ? ComfySdkBase
95
+ : ID extends keyof Comfy.Hosts
96
+ ? Comfy.Hosts[ID] extends ComfySdkShape
97
+ ? Comfy.Hosts[ID]
98
+ : ComfySdkBase
99
+ : ComfySdkBase
100
+
101
+ /** the typed node K of host ID (falls back to BaseNode when unknown) */
102
+ export type NodeOf<ID extends string, K extends string> = SdkForHost<ID>['Node'] extends infer N
103
+ ? K extends keyof N
104
+ ? N[K]
105
+ : BaseNode
106
+ : BaseNode
@@ -0,0 +1,55 @@
1
+ // #region Safety
2
+ export type Flavor<T, FlavorT> = T & { __tag?: FlavorT }
3
+ export type Tagged<O, Tag> = O & { __tag?: Tag }
4
+ export type Branded<O, Brand extends { [key: string]: true }> = O & Brand
5
+
6
+ // #region Utils
7
+ export type Maybe<T> = T | null | undefined
8
+ /**
9
+ * Make some keys optional
10
+ * Usage: PartialOmit<{ a: string, b: string }, 'a'> -> { a?: string, b: string }
11
+ */
12
+ export type PartialOmit<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
13
+ export type IsEqual<T, S> = [T] extends [S] ? ([S] extends [T] ? true : false) : false
14
+ export type EmptyRecord = Record<never, never>
15
+
16
+ // #region Misc
17
+ export type number_Timestamp = Tagged<number, 'Timestamp'>
18
+
19
+ // #region Paths
20
+ export type AbsolutePath = Tagged<string, { AbsolutePath: true }>
21
+ export type RelativePath = Tagged<string, { RelativePath: true }>
22
+ export const asAbsolutePath = (path: string): AbsolutePath => path as AbsolutePath
23
+ export const asRelativePath = (path: string): RelativePath => path as RelativePath
24
+
25
+ // #region Image
26
+ export type ConvertibleImageFormat = 'image/png' | 'image/jpeg' | 'image/webp' | 'raw'
27
+ export type ImageSaveFormat = {
28
+ format: ConvertibleImageFormat
29
+ prefix?: string
30
+ quality?: number
31
+ }
32
+
33
+ // #region Either
34
+ export type Either<L, R> = { success: false; value: L } | { success: true; value: R }
35
+ export const resultSuccess = <T>(value: T): Either<never, T> => ({ success: true, value })
36
+ export const resultFailure = <T>(value: T): Either<T, never> => ({ success: false, value })
37
+
38
+ // #region Result
39
+ export type ResultFailure = { success: false; message: string; error: unknown; value: undefined }
40
+ export type Result<R> = { success: true; value: R } | ResultFailure
41
+ export const __OK = <T>(value: T): Result<T> => ({ success: true, value })
42
+ export const __FAIL = (message: string, error?: unknown): Result<any> => ({
43
+ success: false,
44
+ message,
45
+ error,
46
+ value: undefined,
47
+ })
48
+
49
+ // #region Markdown
50
+ export type MDContent = Branded<string, { MDContent: true }>
51
+ export const asMDContent = (s: string): MDContent => s as MDContent
52
+
53
+ // #region HTML
54
+ export type HTMLContent = Branded<string, { HTML: true }>
55
+ export const asHTMLContent = (s: string): HTMLContent => s as HTMLContent
@@ -0,0 +1,61 @@
1
+ /** this class is used to buffer text and then write it to a file */
2
+ export class CodeBuffer {
3
+ public tab: string = ' '
4
+ constructor(
5
+ private _indent: number = 0,
6
+ lines: string[] = [],
7
+ ) {
8
+ for (const line of lines) this.writeLine(line)
9
+ }
10
+
11
+ content: string = ''
12
+
13
+ // #region adding text
14
+ newLine = (): string => (this.content += '\n')
15
+ line = (...txts: string[]): this => this.writeLine(txts.join(''))
16
+ append = (str: string): string => (this.content += str)
17
+ writeLine = (txt: string): this => {
18
+ this.content +=
19
+ txt
20
+ .split('\n')
21
+ .map((line) => repeatStr(this._indent, this.tab) + line)
22
+ .join('\n') + '\n'
23
+ return this
24
+ }
25
+ w = (txt: string, opts: { if: boolean } = { if: true }): void => {
26
+ if (opts.if) this.writeLine(txt)
27
+ }
28
+
29
+ // #region indentations
30
+ indent = (): number => this._indent++
31
+ deindent = (): number => this._indent--
32
+ indented = (fn: () => void): void => {
33
+ this._indent++
34
+ fn()
35
+ this._indent--
36
+ }
37
+
38
+ bar = (text: string): void => this.w(renderBar(text, '// '))
39
+
40
+ // writeTS = (path: string) => {
41
+ // // const prefix = `// FILE GENERATED: do not edit. Changes made manually will be overwritten.\n\n`
42
+ // // const outPretty = prefix + prettify(this.content)
43
+ // const outPretty = prettify(this.content)
44
+ // writeFileSync(path, outPretty, 'utf-8')
45
+ // }
46
+ }
47
+
48
+ export const repeatStr = (x: number, str: string): string => {
49
+ let out = ''
50
+ for (let i = 0; i < x; i++) out += str
51
+ return out
52
+ }
53
+
54
+ export const renderBar = (text: string, prefix: string = ''): string => {
55
+ const ___bar___ = '============================================================================='
56
+ return (
57
+ `${prefix}|${___bar___}|\n` +
58
+ `${prefix}| ${text} ${repeatStr(___bar___.length - text.length - 4, ' ')} |\n` +
59
+ `${prefix}|${___bar___}|`
60
+ )
61
+ }
@@ -0,0 +1,38 @@
1
+ export const palette = {
2
+ primitive: 'var(--comfy-primitive)',
3
+ loader: 'var(--comfy-loader)',
4
+ latent: 'var(--comfy-latent)',
5
+ conditioning: 'var(--comfy-conditioning)',
6
+ sampl: 'var(--comfy-sampl)',
7
+ image: 'var(--comfy-image)',
8
+ }
9
+
10
+ export const paletteKeys = Object.keys(palette) as (keyof typeof palette)[]
11
+
12
+ export const comfyColors: { [category: string]: string } = {
13
+ loaders: palette.loader,
14
+ latent: palette.latent,
15
+ 'latent/transform': palette.latent,
16
+ conditioning: palette.conditioning, // '#0d430d',
17
+ 'conditioning/style_model': palette.conditioning,
18
+ sampling: palette.sampl,
19
+ image: palette.image,
20
+ primitive: palette.primitive,
21
+ }
22
+
23
+ export const getColorForCategory = (_category: string): string | undefined => {
24
+ const category = _category.toLowerCase()
25
+ if (category in comfyColors) return comfyColors[category]
26
+ return 'var(--comfy-default)'
27
+ }
28
+
29
+ // INPUT ----------------------------------------------------------------
30
+ export const getColorForInputNameInComfy = (nameInComfy: string): string | undefined => {
31
+ const name = nameInComfy.toLowerCase()
32
+ if (name.includes('width')) return palette.primitive
33
+ if (name.includes('height')) return palette.primitive
34
+ for (const k of paletteKeys) if (name.startsWith(k)) return palette[k]
35
+ return 'var(--comfy-default)'
36
+ }
37
+
38
+ // OUTPUTS ----------------------------------------------------------------
@@ -0,0 +1,33 @@
1
+ // tiny chalk-compatible terminal styler (chainable), keeps chalk out of the deps
2
+ const codes = {
3
+ bold: [1, 22],
4
+ underline: [4, 24],
5
+ red: [31, 39],
6
+ green: [32, 39],
7
+ yellow: [33, 39],
8
+ blue: [34, 39],
9
+ greenBright: [92, 39],
10
+ } as const
11
+
12
+ type StyleName = keyof typeof codes
13
+ export type Styler = ((s: string) => string) & { [k in StyleName]: Styler }
14
+
15
+ function styler(open: string = '', close: string = ''): Styler {
16
+ const fn = (s: string): string => open + s + close
17
+ return new Proxy(fn, {
18
+ get(_target, prop: string) {
19
+ const c = codes[prop as StyleName]
20
+ if (c == null) throw new Error(`unknown ansi style: ${prop}`)
21
+ return styler(`${open}\x1b[${c[0]}m`, `\x1b[${c[1]}m${close}`)
22
+ },
23
+ }) as Styler
24
+ }
25
+
26
+ export const ansi: Styler = styler()
27
+
28
+ // CSI sequences + lone ESC-letter escapes (server logs re-rendered inside ink)
29
+ const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g
30
+
31
+ export function stripAnsi(s: string): string {
32
+ return s.replace(ANSI_RE, '')
33
+ }
@@ -0,0 +1,36 @@
1
+ import sharp from 'sharp'
2
+
3
+ /**
4
+ * render an image as truecolor half-block ANSI: each char cell is 1px wide and
5
+ * 2px tall (bg color = top pixel, fg '▄' = bottom pixel). Works in any
6
+ * truecolor terminal and — unlike protocol images (iTerm/kitty/sixel) —
7
+ * survives ink's layout engine. width/height are CHAR CELLS.
8
+ */
9
+ export async function imageBufferToAnsi(
10
+ input: Uint8Array | Buffer | string,
11
+ p: { width: number; height: number; background?: string },
12
+ ): Promise<string> {
13
+ const { data, info } = await sharp(input)
14
+ .flatten({ background: p.background ?? '#1e1e1e' })
15
+ .resize(p.width, p.height * 2, { fit: 'inside' })
16
+ .raw()
17
+ .toBuffer({ resolveWithObject: true })
18
+ const w = info.width
19
+ const h = info.height
20
+ const c = info.channels
21
+ const px = (x: number, y: number): [number, number, number] => {
22
+ const i = (y * w + x) * c
23
+ return [data[i] ?? 0, data[i + 1] ?? 0, data[i + 2] ?? 0]
24
+ }
25
+ const rows: string[] = []
26
+ for (let y = 0; y < h; y += 2) {
27
+ let row = ''
28
+ for (let x = 0; x < w; x++) {
29
+ const [tr, tg, tb] = px(x, y)
30
+ const [br, bg, bb] = y + 1 < h ? px(x, y + 1) : px(x, y)
31
+ row += `\x1b[48;2;${tr};${tg};${tb}m\x1b[38;2;${br};${bg};${bb}m▄`
32
+ }
33
+ rows.push(row + '\x1b[0m')
34
+ }
35
+ return rows.join('\n')
36
+ }
@@ -0,0 +1,39 @@
1
+ import type { Maybe } from 'src/types/index.ts'
2
+
3
+ /** assertNotNull */
4
+ export const bang = <T>(x: Maybe<T>, msg: string = ''): T => {
5
+ if (x == null) {
6
+ console.error(`[🔴] BANG FAILED`, msg)
7
+ throw new Error('bang: ' + (msg ?? 'no message'))
8
+ }
9
+ return x
10
+ }
11
+
12
+ /** soft assertNotNull — LIES on failure: logs then returns the null as T. Prefer bang(). */
13
+ export const bong = <T>(x: Maybe<T>, msg: string = ''): T => {
14
+ if (x == null) {
15
+ console.error(`[🔴] BONG FAILED`, msg)
16
+ return x as T
17
+ }
18
+ return x
19
+ }
20
+
21
+ export function ASSERT_ARRAY(a: unknown): a is unknown[] {
22
+ if (!Array.isArray(a)) throw new Error('❌ not an array')
23
+ return true
24
+ }
25
+
26
+ export function ASSERT_EQUAL(a: unknown, b: unknown): a is unknown[] {
27
+ if (a !== b) throw new Error('❌ not equal')
28
+ return true
29
+ }
30
+
31
+ // ----------
32
+ export function ASSERT_STRING(a: unknown): a is string {
33
+ if (typeof a !== 'string') throw new Error('❌ not a string')
34
+ return true
35
+ }
36
+ export function asSTRING_orCrash(a: unknown, errMsg: string = '❌ not a string'): string {
37
+ if (typeof a !== 'string') throw new Error(errMsg)
38
+ return a
39
+ }
@@ -0,0 +1 @@
1
+ export const deepCopyNaive = <T>(x: T): T => JSON.parse(JSON.stringify(x))