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.
- 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 +4171 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9910 -0
- package/dist/index.d.ts +9894 -58
- package/dist/index.js +4092 -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-SDSJo1Qf.js +3896 -0
- package/dist/run-tui-SDSJo1Qf.js.map +1 -0
- package/package.json +103 -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 +56 -0
- package/src/cli/tui/components/HostPanel.tsx +37 -0
- package/src/cli/tui/components/LogsPanel.tsx +23 -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 +78 -0
- package/src/cli/tui/components/PromptOverlay.tsx +16 -0
- package/src/cli/tui/components/StatusBar.tsx +171 -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 +246 -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 +95 -0
- package/src/cli/tui/run-tui.tsx +76 -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 +173 -0
- package/src/cli/tui/state/HostSt.ts +230 -0
- package/src/cli/tui/state/LogsSt.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 +288 -0
- package/src/cli/tui/state/QueueSt.ts +59 -0
- package/src/cli/tui/state/SettingsSt.ts +100 -0
- package/src/cli/tui/state/TreeSt.ts +122 -0
- package/src/cli/tui/state/TuiSt.ts +175 -0
- package/src/cli/tui/state/WorkflowsSt.ts +93 -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 +690 -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 +170 -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 +114 -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 +33 -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/mojibake.ts +60 -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 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["type","type","crypto","type","type","types","chalk","type","crypto","type","chalk","type","type","type","ws","WebSocket","observable","observable","action","type","https","fs","chalk","type","type","chalk","type","type","type","type","chalk","type","type","chalk","chalk","pkgJson.version","globalHack"],"sources":["../package.json","../src/sdk-generator/Primitives.ts","../src/sdk-generator/litegraphToApiRequestPayload.ts","../src/errors/InvalidPromptError.ts","../src/utils/ComfyColors.ts","../src/graph/autoValue.ts","../src/graph/ComfyNodeOutput.ts","../src/graph/ComfyNode.ts","../src/host/ComfyWorkflowBuilder.ts","../src/utils/bang.ts","../src/litegraph/LiteGraphLinkID.ts","../src/litegraph/LiteGraphSlotIndex.ts","../src/litegraph/convertFlowToLiteGraphJSON.ts","../src/types/index.ts","../src/image-utils/_getPngMetadata.ts","../src/utils/exhaust.ts","../src/utils/hashArrayBuffer.ts","../src/graph/ComfyNodeID.ts","../src/runner/ComfyWsApi.ts","../src/runner/MediaImage.ts","../src/runner/ComfyExecution.ts","../src/utils/deepCopyNaive.ts","../src/utils/ansi.ts","../src/utils/log.ts","../src/utils/printArkResultInConsole.ts","../src/utils/softValidate.ts","../src/utils/toposort.ts","../src/runner/ComfyWorkflowLayout.ts","../src/runner/ComfyWorkflow.ts","../src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts","../src/sdk-generator/_pythonModuleToNamespace.ts","../src/sdk-generator/_toQualifiedNodeKey.ts","../src/utils/CodeBuffer.ts","../src/utils/escapeJSKey.ts","../src/sdk-generator/ComfyNodeSchema.ts","../src/sdk-generator/comfyui-sdk-codegen.ts","../src/sdk-generator/comfyui-types.ts","../src/sdk-generator/ComfySchema.ts","../src/sdk-generator/ComfyUIObjectInfoTypes.ts","../src/utils/extractErrorMessage.ts","../src/utils/stringifyReadable.ts","../src/utils/writeFile.ts","../src/manager/types/ComfyManagerAPIModelList.ts","../src/manager/types/ComfyManagerAPIPluginList.ts","../src/host/ComfyManager.ts","../src/host/ComfyUploader.ts","../src/host/ResilientWebsocket.ts","../src/vars/loraKeywords.ts","../src/vars/ComfyVars.ts","../src/vars/DefinedWorkflow.ts","../src/host/ComfyHost.ts","../src/utils/downloadFile.ts","../src/manager/loaders/step1_downloadComfyManagerJSONs.ts","../src/utils/githubRegexes.ts","../src/utils/tryExtracting.ts","../src/manager/json/custom-node-list.extra.ts","../src/manager/types/ComfyManagerPluginInfo.ts","../src/manager/types/ComfyManagerFilePluginList.ts","../src/manager/loaders/step2_custom-node-list-loader.ts","../src/manager/types/ComfyManagerPluginContentMetadata.ts","../src/manager/types/ComfyManagerPluginEnums.ts","../src/manager/types/ComfyManagerFilePluginContent.ts","../src/manager/loaders/step3_extension-node-map-loader.ts","../src/manager/json/model-list.extra.ts","../src/manager/types/ComfyManagerModelInfo.ts","../src/manager/loaders/step4_model-list-loader.ts","../src/manager/ComfyRegistry.ts","../src/state.ts","../src/cli/tui-env.ts","../src/utils/loraTag.ts"],"sourcesContent":["","import type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { ComfyNodeSchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'\n\nexport const ComfyPrimitiveMapping: { [key: string]: string } = {\n // BACK\n BOOLEAN: 'boolean',\n FLOAT: 'number',\n INT: 'number',\n STRING: 'string',\n\n // ????\n // ⏸️ Boolean: 'boolean',\n // ⏸️ Float: 'number',\n // ⏸️ Integer: 'number',\n // ⏸️ SchedulerName: 'string',\n // ⏸️ SamplerName: 'string',\n // ⏸️ IMAGE_PATH: 'string',\n}\n\nexport const ComfyPrimitives: string[] = Object.keys(ComfyPrimitiveMapping)\n\n/**\n * when a litegraph node has no input for a given ComfyUI node input\n * (e.g. a seed or an enum that has not been turned into a primitive)\n */\nexport const howManyWidgetValuesForThisSchemaType = (input: NodeInputExt): number => {\n if (input.typeName === 'INT') {\n if (input.nameInComfy === 'seed' || input.nameInComfy === 'noise_seed') return 2\n }\n if (input.isPrimitive) return 1\n // 🔴\n if (input.typeName.startsWith('E_')) return 1\n // console.log(343, input)\n return 0\n}\n\n/**\n * then a litegraph node has an input entry, some convoluted logic seems to be necessary\n * to determine how many Field_values need to be consumed for this input\n */\nexport const howManyWidgetValuesForThisInputType = (type: string, nameInComfy: string): number => {\n if (type === 'INT') {\n if (nameInComfy === 'seed' || nameInComfy === 'noise_seed') return 2\n return 1\n }\n if (type === 'BOOLEAN') return 1\n if (type === 'FLOAT') return 1\n if (type === 'STRING') return 1\n if (type === 'COMBO') return 1\n if (type === 'INT:seed') return 2\n if (type === 'INT:noise_seed') return 2\n\n // not a primitive, no Field_values\n return 0\n}\nexport const ComfyDefaultNodeWhenUnknown_Name: string = 'UnknownNodeXX'\n\nexport const ComfyDefaultNodeWhenUnknown_Schema: ComfyNodeSchemaJSON = {\n category: 'test',\n input: {},\n output: [],\n description: 'This is a test node',\n output_name: [],\n display_name: 'UnknownNodeXX',\n name: 'UnknownNodeXX',\n output_is_list: [],\n output_node: false,\n python_module: 'nodes',\n}\n\nexport class UnknownCustomNode extends Error {\n constructor(public node: LiteGraphNode) {\n super(`❌ node ${node.id}(${node.type}) has no known schema; you probably need to install some custom node`)\n }\n}\n","import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'\nimport type { LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport {\n howManyWidgetValuesForThisInputType,\n howManyWidgetValuesForThisSchemaType,\n UnknownCustomNode,\n} from 'src/sdk-generator/Primitives.ts'\nimport type { Maybe } from 'src/types/index.ts'\n\n/**\n * convert a saved ComfyUI workflow.json (litegraph format) into the api.json\n * (prompt format) ComfyUI's POST /prompt takes.\n * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes\n * unwrapped, primitives inlined into their consumers), widget-value offsets\n * (incl. the phantom `control_after_generate` value after seeds).\n */\nexport const convertLiteGraphToPrompt = (\n /** the ComfySchema object (to look for references/definitions) */\n schema: ComfySchema,\n /** the litegraph */\n workflow: LiteGraphJSON,\n opts: { verbose?: boolean } = {},\n): ComfyApiJson => {\n const prompt: ComfyApiJson = {}\n const LOG = opts.verbose ? (...args: unknown[]): void => console.log('[🔥] converter:', ...args) : (): void => {}\n\n // 1. cache primitive node values so links from PrimitiveNode inline as values\n const PRIMITIVE_VALUES: { [nodeId: string]: unknown } = {}\n for (const node of workflow.nodes) {\n if (node.type === 'PrimitiveNode') {\n const widgetValues = node.widgets_values\n if (widgetValues == null || widgetValues.length === 0) {\n throw new Error(`PrimitiveNode#${node.id} has no widget values`)\n }\n PRIMITIVE_VALUES[node.id] = widgetValues[0]\n }\n }\n\n // 2. every executable node\n for (const node of workflow.nodes) {\n if (node.isVirtualNode) continue // frontend-only nodes\n if (node.mode === 2) continue // muted\n if (node.type === 'Reroute') continue // unwrapped below\n if (node.type === 'Note') continue // comments\n if (node.type === 'PrimitiveNode') continue // inlined into consumers\n\n const inputs: ComfyApiNodeJson['inputs'] = {}\n const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name))\n const nodeSchema_ = schema.nodesByNameInComfy[node.type]\n if (nodeSchema_ == null) throw new UnknownCustomNode(node)\n const nodeSchema: ComfyNodeSchema = nodeSchema_\n\n // 2.a widget values, consumed in schema order\n let offset = 0\n const inputsInNodeJSON: LiteGraphNodeInput[] = node.inputs ?? []\n const inputsInNodeSchema: NodeInputExt[] = nodeSchema.inputs\n for (const field of inputsInNodeSchema) {\n const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy)\n const MUST_CONSUME = input?.type\n ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)\n : howManyWidgetValuesForThisSchemaType(field)\n\n if (MUST_CONSUME > 0) {\n if (node.widgets_values == null)\n throw new Error(\n `node ${node.id}(${node.type}) has no widgets_values but \"${field.nameInComfy}\" needs one`,\n )\n if (node.widgets_values.length < offset + 1)\n throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for \"${field.nameInComfy}\"`)\n const _value = node.widgets_values[offset]\n LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`)\n if (!isValidValue(_value))\n throw new Error(\n `node ${node.id}(${node.type}) has an invalid widget value for \"${field.nameInComfy}\": ${JSON.stringify(_value)}`,\n )\n inputs[field.nameInComfy] = _value\n offset += MUST_CONSUME\n } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {\n if (field.required)\n throw new Error(\n `node ${node.id}(${node.type}): required input \"${field.nameInComfy}\" (${field.typeName}) has neither widget value nor link`,\n )\n }\n }\n\n // 2.b links\n type ParentInfo = { node: LiteGraphNode; link: LiteGraphLink }\n const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {\n const link = workflow.links.find((link) => link[0] === linkId)\n if (link == null)\n throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`)\n const parentId = link[1]\n const parentNode = workflow.nodes.find((n) => n.id === parentId)\n if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`)\n return { node: parentNode, link }\n }\n\n INPT: for (const ipt of node.inputs ?? []) {\n const isPrimitive = howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0\n if (isPrimitive) continue\n\n // not a primitive => we assume it's a link\n if (ipt.link == null) {\n LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`)\n continue\n }\n let parent: Maybe<ParentInfo> = getParentNode(ipt.link)\n\n // unwrap reroute chains\n let max = 100\n while (parent != null && parent.node.type === 'Reroute' && max-- > 0) {\n const firstParentInput = parent.node.inputs?.[0]\n if (firstParentInput?.link == null) {\n LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`)\n continue INPT\n }\n parent = getParentNode(firstParentInput.link)\n }\n if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`)\n\n // inline primitive nodes as plain values\n if (parent.node.type === 'PrimitiveNode') {\n inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id] as ComfyApiNodeJson['inputs'][string]\n LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`)\n continue\n }\n\n LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`)\n inputs[ipt.name] = [String(parent.node.id), parent.link[2]]\n }\n\n prompt[String(node.id)] = { inputs, class_type: node.type }\n }\n\n return prompt\n}\n\n/** alias cause I keep forgetting about this */\nexport const convertWorkflowToPrompt = convertLiteGraphToPrompt\n\ntype ValidValue = string | number | boolean | [string, number] | null\nfunction isValidValue(value: unknown): value is ValidValue {\n if (value == null) return true // null is valid\n if (typeof value === 'string') return true\n if (typeof value === 'number') return true\n if (typeof value === 'boolean') return true\n if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number')\n return true\n return false\n}\n","import type { ExecutionSnapshot } from 'src/runner/ComfyWorkflow.ts'\n\nexport class InvalidPromptError extends Error {\n constructor(\n public override message: string,\n /** exactly what was sent to the host when the error happened */\n public snapshot: ExecutionSnapshot,\n public details: unknown,\n ) {\n super(message)\n }\n}\n","export const palette = {\n primitive: 'var(--comfy-primitive)',\n loader: 'var(--comfy-loader)',\n latent: 'var(--comfy-latent)',\n conditioning: 'var(--comfy-conditioning)',\n sampl: 'var(--comfy-sampl)',\n image: 'var(--comfy-image)',\n}\n\nexport const paletteKeys = Object.keys(palette) as (keyof typeof palette)[]\n\nexport const comfyColors: { [category: string]: string } = {\n loaders: palette.loader,\n latent: palette.latent,\n 'latent/transform': palette.latent,\n conditioning: palette.conditioning, // '#0d430d',\n 'conditioning/style_model': palette.conditioning,\n sampling: palette.sampl,\n image: palette.image,\n primitive: palette.primitive,\n}\n\nexport const getColorForCategory = (_category: string): string | undefined => {\n const category = _category.toLowerCase()\n if (category in comfyColors) return comfyColors[category]\n return 'var(--comfy-default)'\n}\n\n// INPUT ----------------------------------------------------------------\nexport const getColorForInputNameInComfy = (nameInComfy: string): string | undefined => {\n const name = nameInComfy.toLowerCase()\n if (name.includes('width')) return palette.primitive\n if (name.includes('height')) return palette.primitive\n for (const k of paletteKeys) if (name.startsWith(k)) return palette[k]\n return 'var(--comfy-default)'\n}\n\n// OUTPUTS ----------------------------------------------------------------\n","import type { Branded } from 'src/types/index.ts'\n\n/**\n * a fake value that is detected at serialization\n * time to try to magically inject stuff\n * */\nexport type AUTO = Branded<{ ___AUTO___: true }, { AUTO: true }>\n\n/**\n * you can use this as a placeholder anywhere in your graph\n * comfy-ts wires the most recent output of a matching type at serialization time\n */\n// sanctioned cast (agent/coding.md): auto() is a SENTINEL detected at\n// serialization time and replaced by a real link — it never survives to runtime\nexport const auto = <T>(): T => auto_ as T\n\nexport const auto_: AUTO = { ___AUTO___: true } as AUTO\n","import type { ComfyNode } from 'src/graph/ComfyNode.ts'\n\nexport class ComfyNodeOutput<T extends string = string, Ix extends number = number> {\n constructor(\n public node: ComfyNode<object>,\n public slotIx: Ix,\n public type: T,\n /**\n * as of 2024-11-16, output slots have no name in comfy, only a type.\n * Problem is that some nodes have multiple outputs of the same type.\n * so subsequent outputs with a previous used name will be suffixed\n * and have named like `output_2`, `output_3`, etc.\n */\n public name: string,\n ) {}\n}\n","import type { ComfyWorkflow, ProgressReport } from 'src/runner/ComfyWorkflow.ts'\nimport type { NodeProgress } from 'src/runner/ComfyWsApi.ts'\nimport type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyDefaultNodeWhenUnknown_Name } from 'src/sdk-generator/Primitives.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { comfyColors } from 'src/utils/ComfyColors.ts'\nimport { auto_ } from 'src/graph/autoValue.ts'\nimport type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'\nimport { NodeSlotSize, NodeTitleHeight, nodeLineHeight } from 'src/graph/NodeSlotSize.ts'\n\ntype NodeExecutionStatus = 'executing' | 'done' | 'error' | 'waiting' | 'cached' | null\n\nexport type NodePort = {\n id: string\n label: string\n width: number\n height: number\n type: string\n x: number\n y: number\n toNode?: ComfyNode<object, object> | undefined\n fromNode?: ComfyNode<object, object> | undefined\n}\n\nexport type ComfyNodeUID = string\n\n/** ComfyNode\n * - correspond to a signal in the graph\n * - belongs to a script\n */\nexport class ComfyNode<\n //\n ComfyNode_input extends object = object,\n ComfyNode_output extends object = object,\n> {\n storeAs(storeName: string): this {\n this.meta.storeAs = storeName\n return this\n }\n\n tag(tagName: string): this {\n this.addTag(tagName)\n return this\n }\n\n addTag(tag: string): this {\n if (this.meta.tags == null) this.meta.tags = [tag]\n else this.meta.tags.push(tag)\n return this\n }\n // ---------------------------------------\n\n /** reported though websocket by ComfyUI */\n status: NodeExecutionStatus = null\n\n /** last raw progress message reported by comfy */\n progress: NodeProgress | null = null\n\n /**\n * updated on websocket progress report from the progress property just above\n * between [0, 1]\n * */\n progressRatio: number = 0\n\n get progressReport(): ProgressReport {\n const percent = this.status === 'done' ? 100 : this.progressRatio * 100\n const isDone = this.status === 'done'\n return { percent, isDone, countDone: this.progressRatio * 100, countTotal: 100 }\n }\n\n $schema: ComfyNodeSchema\n updatedAt: number = Date.now()\n json: ComfyApiNodeJson\n\n get isExecuting(): boolean {\n return this.status === 'executing'\n }\n\n disabled: boolean = false\n\n disable(): void {\n this.disabled = true\n }\n\n get inputs(): ComfyNode_input {\n // sanctioned cast (agent/coding.md): runtime graph json <-> generated\n // static face; both derive from the same object_info\n return this.json.inputs as ComfyNode_input\n }\n\n /** update a node */\n set(p: Partial<ComfyNode_input>): this {\n for (const [key, value] of Object.entries(p)) {\n const next = this.serializeValue(key, value)\n const prev = this.json.inputs[key]\n if (next === prev) continue\n this.json.inputs[key] = next as any // 🔴\n }\n return this\n // 🔴 wrong resonsibility\n // console.log('CHANGES', changes)\n }\n\n get color(): string {\n return comfyColors[this.$schema.category] ?? '#aaa'\n }\n\n uidNumber: number\n $outputs: ComfyNodeOutput<string>[] = []\n outputs: ComfyNode_output\n uidPrefixed: string\n\n constructor(\n public graph: ComfyWorkflow,\n public uid: ComfyNodeUID, // = graph.getUID(),\n jsonExt: ComfyApiNodeJson,\n public meta: ComfyNodeMetadata = {},\n ) {\n // strictly-numeric uids keep uid === uidNumber (litegraph export must agree\n // with prompt keys); anything else gets the next free number ('12abc' must\n // NOT partial-parse to 12 — that collides with node '12')\n const parsedUid = /^\\d+$/.test(uid) ? Number(uid) : Number.NaN\n this.uidNumber = Number.isNaN(parsedUid) ? this.graph._uidNumber++ : parsedUid\n if (this.uidNumber >= this.graph._uidNumber) this.graph._uidNumber = this.uidNumber + 1\n if (jsonExt == null) throw new Error('invariant violation: jsonExt is null')\n // this.json = graph.data.apiJson[uid]\n // if (this.json == null) graph.data.apiJson = {}\n // console.log('CONSTRUCTING', xxx.class_type, uid)\n\n // this.uidNumber = parseInt(uid) // 🔴 ugly\n const exactSchema = graph.schema.nodesByNameInComfy[jsonExt.class_type]\n if (exactSchema == null) {\n // loud fallback: imported json referencing a node this host doesn't have\n graph.recordProblem(\n `unknown node type \"${jsonExt.class_type}\" — schema fallback to ${ComfyDefaultNodeWhenUnknown_Name}; install the missing custom node on the host`,\n )\n }\n this.$schema = exactSchema ?? graph.schema.nodesByNameInComfy[ComfyDefaultNodeWhenUnknown_Name]!\n\n if (this.$schema == null) {\n console.log(`❌ available nodes:`, Object.keys(graph.schema.nodesByNameInComfy).join(','))\n throw new Error(`❌ no schema found for node \"${jsonExt.class_type}\"`)\n // throw new Error('')\n }\n this.uidPrefixed = `${this.$schema.nodeKey}_${this.uidNumber}`\n let ix = 0\n\n // 🔶 1 this declare the json locally,\n // but Node are not live instances, they're local subinstances to a LiveGraph\n this.json = this._convertPromptExtToPrompt(jsonExt)\n // 🔶 2 so we need to ensure the json is properly synced with the LiveGraph data\n // register node ensure this\n this.graph.registerNode(this)\n\n // dynamically add properties for every outputs\n const outputs: { [key: string]: any } = {}\n for (const x of this.$schema.outputs) {\n const output = new ComfyNodeOutput(this, ix++, x.typeName, x.nameInComfy)\n outputs[x.outKey] = output\n this.$outputs.push(output)\n // console.log(` - .${x.outKey} as ComfyNodeOutput(${ix})`)\n }\n this.outputs = outputs as ComfyNode_output\n\n // implements the _<typeName> properties (HasSingle interfaces)\n const extensions: { [key: string]: any } = {}\n for (const x of this.$schema.singleOutputs) {\n extensions[`_${x.typeName}`] = outputs[x.outKey]\n }\n Object.assign(this, extensions)\n }\n\n _convertPromptExtToPrompt(promptExt: ComfyApiNodeJson): ComfyApiNodeJson {\n const inputs: { [inputName: string]: any } = {}\n const _done = new Set<string>()\n for (const i of this.$schema.inputs) {\n _done.add(i.nameInComfy)\n const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy])\n inputs[i.nameInComfy] = value\n }\n for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {\n if (_done.has(nameInComfy)) continue\n const value = this.serializeValue(nameInComfy, rawVal)\n inputs[nameInComfy] = value\n }\n return { class_type: this.$schema.nameInComfy, inputs }\n }\n\n /** return the list of nodes piped into this node */\n _incomingNodes(): ComfyNodeId[] {\n const incomingNodes: ComfyNodeId[] = []\n for (const [_name, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) {\n const [from, _slotIx] = val\n incomingNodes.push(from)\n }\n }\n return incomingNodes\n }\n\n _primitives(): { inputName: string; value: string }[] {\n const primitives: { inputName: string; value: string }[] = []\n for (const [inputName, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) continue\n primitives.push({ inputName: inputName, value: val?.toString() })\n }\n return primitives\n }\n\n /** return true if the given node is plugged into this one */\n isChildrenOf(node: ComfyNode<any>): boolean {\n return this._incomingNodes().includes(node.uid)\n }\n\n get parents(): ComfyNode<any>[] {\n return this._incomingNodes().map((id) => this.graph.getNode(id)!)\n }\n // get children(): ComfyNode<any>[] {\n // return this._incomingNodes().map((id) => this.graph.getNode(id)!)\n // }\n\n _visible: boolean = true\n set visible(value: boolean) {\n this._visible = value\n } // biome-ignore format: misc\n get visible(): boolean {\n return this._visible\n } // biome-ignore format: misc\n\n _x: number = 0\n get x(): number {\n return this._x\n } // biome-ignore format: misc\n set x(value: number) {\n this.isDirty = true\n this._x = value\n }\n\n _y: number = 0\n get y(): number {\n return this._y\n } // biome-ignore format: misc\n set y(value: number) {\n this.isDirty = true\n this._y = value\n }\n\n isDirty = true\n\n tagDirty(value: boolean): void {\n this.isDirty = value\n }\n\n col: number = 0\n selected: boolean = false\n get outgoingPorts(): NodePort[] {\n return this.$outputs.map(\n (o, ix): NodePort => ({\n id: this.uid + '#' + o.slotIx,\n label: o.type,\n width: NodeSlotSize,\n height: NodeSlotSize,\n fromNode: this,\n toNode: o.node ?? undefined,\n type: o.type,\n x: this.x + this.width, // + NodeSlotSize / 2,\n y:\n this.y + // start\n NodeTitleHeight + // title\n ix * nodeLineHeight + // e.fromSlotIx * 10,\n nodeLineHeight / 2, //\n }),\n )\n }\n\n get incomingPorts(): NodePort[] {\n return this._incomingEdges().map(\n (e, ix): NodePort => ({\n id: this.uid + '<-' + e.from + '#' + e.fromSlotIx,\n width: NodeSlotSize,\n height: NodeSlotSize,\n fromNode: this.graph.getNode(e.from) ?? undefined,\n toNode: this,\n label: e.inputName,\n type: e.type,\n x: this.x, // - NodeSlotSize / 2,\n y:\n this.y + // start\n NodeTitleHeight + // title\n ix * nodeLineHeight + // e.fromSlotIx * 10,\n nodeLineHeight / 2,\n }),\n )\n }\n\n _incomingEdges(): {\n from: ComfyNodeId\n inputName: string\n type: string\n fromSlotIx: number\n }[] {\n const incomingEdges: {\n from: ComfyNodeId\n inputName: string\n fromSlotIx: number\n type: string\n }[] = []\n\n for (const [inputName, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) {\n const [from, _slotIx] = val as [ComfyNodeId, number]\n const type = this.graph.getNode(from)?.$outputs[_slotIx]?.type ?? 'UNKNOWN'\n incomingEdges.push({ from, inputName, fromSlotIx: _slotIx, type })\n }\n }\n return incomingEdges\n }\n\n /** number of primitive fields in this node */\n primitivesCount(): number {\n return Object.values(this.inputs).filter((val) => !Array.isArray(val)).length\n }\n\n /** width dimensions for autolayout algorithm */\n get width(): number {\n return 200\n }\n\n /** height dimensions for autolayout algorithm */\n get height(): number {\n const inputLen = this._incomingEdges().length\n const outputLen = this.$schema.outputs.length\n const headerCount = Math.max(inputLen, outputLen)\n\n // max height since some nodes have many invisible inputs\n return (this.primitivesCount() + headerCount + 1) * nodeLineHeight\n }\n\n serializeValue(field: string, value: unknown): unknown {\n if (value == null) {\n const schema = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === field)\n if (schema == null) throw new Error(`❌ no schema for field \"${field}\" (of node ${this.$schema.nodeKey})`)\n // console.log('def1=', field, schema.opts.default)\n const opts = schema.opts == null || typeof schema.opts !== 'object' ? undefined : schema.opts\n if (opts?.default != null) return opts.default\n // console.log('def2=', field, schema.required)\n if (!schema.required) return undefined\n console.error(field, 'is required but value is ', value, this.json) //, this)\n this.graph.recordProblem(\n `🔴 [serializeValue] field \"${field}\" (of node ${this.$schema.nodeKey}#${this.uid}) value is null but field is not optional`,\n )\n return undefined\n // throw new Error(\n // `🔴 [serializeValue] field \"${field}\" (of node ${this.$schema.nodeKey}#${this.uid}) value is null`,\n // )\n }\n if (typeof value === 'function') {\n return this.serializeValue(field, value(this.graph.builder, this.graph))\n }\n if (value === auto_) {\n const expectedType = this._getExpectedTypeForField(field)\n console.info(`🔍 looking for type ${expectedType} for field ${field}`)\n for (const node of this.graph.nodes.slice().reverse()) {\n const output = node._getOutputForTypeOrNull(expectedType)\n if (output != null) return [node.uid, output.slotIx]\n }\n throw new Error(`🔴 [AUTO failed] field \"${field}\" (of node ${this.$schema.nodeKey}) value is null`)\n }\n if (value instanceof ComfyNodeOutput) return [value.node.uid, value.slotIx]\n if (value instanceof ComfyNode) {\n const expectedType = this._getExpectedTypeForField(field)\n const output = value._getOutputForTypeOrCrash(expectedType)\n return [value.uid, output.slotIx]\n }\n return value\n }\n\n private _getExpectedTypeForField(name: string): string {\n const input = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name)\n if (input == null) throw new Error('🔴 input not found asdf')\n return input.typeName\n }\n\n private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {\n const i: NodeOutputExt = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)!\n const val = (this.outputs as any)[i.outKey]\n // console.log(`this[i.name] = ${this.$schema.name}[${i.name}] = ${val}`)\n if (val instanceof ComfyNodeOutput) return val\n throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)\n }\n\n private _getOutputForTypeOrNull(type: string): ComfyNodeOutput<any> | null {\n const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)\n if (i == null) return null\n const val = (this.outputs as any)[i.outKey]\n if (val == null) return null\n if (val instanceof ComfyNodeOutput) return val\n throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)\n }\n}\n","import { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\n\n/**\n * runtime builder: one factory method per node of the live schema, defined\n * dynamically. The typed face is `SdkForHost<ID>['Builder']`, obtained via\n * `workflow.builder` (see ComfyWorkflow). The index signature below is what\n * makes the cast between the two legal.\n */\nexport interface ComfyWorkflowBuilder {\n [nodeName: string]: unknown\n}\nexport class ComfyWorkflowBuilder {\n constructor(public graph: ComfyWorkflow) {\n const schema = graph.host.schema\n\n for (const node of schema.nodes) {\n try {\n Object.defineProperty(this, node.nodeKey, {\n value: (inputs: ComfyApiNodeJson['inputs'], meta?: ComfyNodeMetadata) => {\n const uidString = this.___allocateNodeUID(meta)\n const nodePayload: ComfyApiNodeJson = {\n class_type: node.nameInComfy,\n inputs,\n }\n return new ComfyNode(graph, uidString, nodePayload, meta ?? {})\n },\n })\n } catch (e) {\n console.log(e)\n console.error('impossible to create builder for node')\n console.log(`current:`, JSON.stringify(node.nameInComfy), JSON.stringify(node.nodeKey))\n const prev = schema.nodes.find((n) => n.nodeKey === node.nodeKey)\n console.log(`prev`, JSON.stringify(prev?.nameInComfy), JSON.stringify(prev?.nodeKey))\n throw e\n }\n }\n }\n\n /**\n * helper function to allocate an unique node Id while\n * while respecting user provided metadata id if present.\n */\n private ___allocateNodeUID(meta?: ComfyNodeMetadata): string {\n let uidString: string\n if (meta?.id != null && meta.id !== '') {\n // increment the graph _uiNumber, so if we modify this later\n // we won't reuse the same uid and have broken conflicts\n const uidNumber = parseInt(meta.id, 10)\n if (!Number.isNaN(uidNumber) && uidNumber > this.graph._uidNumber)\n this.graph._uidNumber = Math.round(uidNumber + 1)\n uidString = meta.id\n } else {\n uidString = (this.graph._uidNumber++).toString()\n }\n return uidString\n }\n}\n","import type { Maybe } from 'src/types/index.ts'\n\n/** assertNotNull */\nexport const bang = <T>(x: Maybe<T>, msg: string = ''): T => {\n if (x == null) {\n console.error(`[🔴] BANG FAILED`, msg)\n throw new Error('bang: ' + (msg ?? 'no message'))\n }\n return x\n}\n\n/** soft assertNotNull — LIES on failure: logs then returns the null as T. Prefer bang(). */\nexport const bong = <T>(x: Maybe<T>, msg: string = ''): T => {\n if (x == null) {\n console.error(`[🔴] BONG FAILED`, msg)\n return x as T\n }\n return x\n}\n\nexport function ASSERT_ARRAY(a: unknown): a is unknown[] {\n if (!Array.isArray(a)) throw new Error('❌ not an array')\n return true\n}\n\nexport function ASSERT_EQUAL(a: unknown, b: unknown): a is unknown[] {\n if (a !== b) throw new Error('❌ not equal')\n return true\n}\n\n// ----------\nexport function ASSERT_STRING(a: unknown): a is string {\n if (typeof a !== 'string') throw new Error('❌ not a string')\n return true\n}\nexport function asSTRING_orCrash(a: unknown, errMsg: string = '❌ not a string'): string {\n if (typeof a !== 'string') throw new Error(errMsg)\n return a\n}\n","import { type } from 'arktype'\nimport type { Branded } from 'src/types/index.ts'\n\nexport const asLiteGraphLinkID = (id: number): LiteGraphLinkID => id as LiteGraphLinkID\nexport const LiteGraphLinkID_ = type.number.atLeast(0).as<Branded<number, { LiteGraphLinkID: true }>>()\nexport type LiteGraphLinkID = typeof LiteGraphLinkID_.infer\n","import { type } from 'arktype'\nimport type { Branded } from 'src/types/index.ts'\n\nexport const asLiteGraphSlotIndex = (id: number): LiteGraphSlotIndex => id as LiteGraphSlotIndex\nexport const LiteGraphSlotIndex_ = type.number.atLeast(0).as<Branded<number, { LiteGraphSlotIndex: true }>>()\nexport type LiteGraphSlotIndex = typeof LiteGraphSlotIndex_.infer\n","import type { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { howManyWidgetValuesForThisSchemaType } from 'src/sdk-generator/Primitives.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'\nimport { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'\nimport { asLiteGraphSlotIndex } from 'src/litegraph/LiteGraphSlotIndex.ts'\n\nexport const convertFlowToLiteGraphJSON = (graph: ComfyWorkflow): LiteGraphJSON => {\n const ctx = new LiteGraphCtx(graph)\n const last_node_id = Math.max(...graph.nodes.map((n) => n.uidNumber))\n const xxx = graph.nodes.map((comfyNode) => ({\n liteGraphNode: convertNodeToLiteGraphNode(ctx, comfyNode),\n comfyNode,\n }))\n for (const xx of xxx) {\n const n = xx.liteGraphNode\n n.pos[0] = bang(xx.comfyNode.x)\n n.pos[1] = bang(xx.comfyNode.y)\n for (const o of n.outputs) {\n o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0])\n }\n }\n return {\n last_node_id,\n last_link_id: ctx.nextLinkId,\n nodes: xxx.map((n) => n.liteGraphNode),\n links: ctx.links,\n config: {},\n extra: {},\n groups: [],\n version: 0.4,\n }\n}\n\nconst convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): LiteGraphNode => {\n const inputs: LiteGraphNodeInput[] = []\n const widgets_values: unknown[] = []\n for (const ipt of node.$schema.inputs) {\n const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])\n const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0\n if (_isLink(raw)) {\n const nodeUidNumber = bang(\n ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,\n `link target node \"${raw[0]}\" not found in graph`,\n )\n inputs.push({\n name: ipt.nameInComfy,\n type: ipt.typeName,\n // target_slot = index within THIS node's litegraph inputs array,\n // not the schema input index (widget inputs are not litegraph slots)\n link: ctx.allocateLink(\n nodeUidNumber,\n raw[1],\n node.uidNumber,\n asLiteGraphSlotIndex(inputs.length),\n ipt.typeName,\n ),\n })\n } else if (isWidget) {\n widgets_values.push(raw)\n // ComfyUI stores a phantom control_after_generate value after seeds\n const isSeed = ipt.typeName === 'INT' && (ipt.nameInComfy === 'seed' || ipt.nameInComfy === 'noise_seed')\n if (isSeed) widgets_values.push(false)\n } else {\n // unconnected link-kind input: a litegraph slot with no link —\n // NEVER a widget value (that would misalign the round-trip import)\n inputs.push({ name: ipt.nameInComfy, type: ipt.typeName, link: null })\n }\n }\n const outputs = node.$schema.outputs.map(\n (i, ix): LiteGraphNodeOutput => ({\n // ❌9 name: i.nameInComfy,\n type: i.typeName,\n links: [], // empty links by default 🔴\n slot_index: asLiteGraphSlotIndex(ix),\n name: i.outKey,\n }),\n )\n return {\n type: node.$schema.nameInComfy,\n id: node.uidNumber,\n inputs,\n outputs,\n pos: [0, 0],\n size: [node.width, node.height],\n widgets_values,\n }\n}\n\nconst _isLink = (v: unknown): v is [string, number] => {\n return Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number'\n}\n\nexport class LiteGraphCtx {\n constructor(public graph: ComfyWorkflow) {}\n nextLinkId: number = 0\n links: LiteGraphLink[] = []\n allocateLink = (\n fromNodeId: number,\n fromNodeOutputIx: number,\n toNodeId: number,\n toNodeInputIx: number,\n linkType: string,\n ): LiteGraphLinkID => {\n const linkId = asLiteGraphLinkID(++this.nextLinkId)\n this.links.push([linkId, fromNodeId, fromNodeOutputIx, toNodeId, toNodeInputIx, linkType])\n return linkId\n }\n}\n","// #region Safety\nexport type Flavor<T, FlavorT> = T & { __tag?: FlavorT }\nexport type Tagged<O, Tag> = O & { __tag?: Tag }\nexport type Branded<O, Brand extends { [key: string]: true }> = O & Brand\n\n// #region Utils\nexport type Maybe<T> = T | null | undefined\n/**\n * Make some keys optional\n * Usage: PartialOmit<{ a: string, b: string }, 'a'> -> { a?: string, b: string }\n */\nexport type PartialOmit<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>\nexport type IsEqual<T, S> = [T] extends [S] ? ([S] extends [T] ? true : false) : false\nexport type EmptyRecord = Record<never, never>\n\n// #region Misc\nexport type number_Timestamp = Tagged<number, 'Timestamp'>\n\n// #region Paths\nexport type AbsolutePath = Tagged<string, { AbsolutePath: true }>\nexport type RelativePath = Tagged<string, { RelativePath: true }>\nexport const asAbsolutePath = (path: string): AbsolutePath => path as AbsolutePath\nexport const asRelativePath = (path: string): RelativePath => path as RelativePath\n\n// #region Image\nexport type ConvertibleImageFormat = 'image/png' | 'image/jpeg' | 'image/webp' | 'raw'\nexport type ImageSaveFormat = {\n format: ConvertibleImageFormat\n prefix?: string\n quality?: number\n}\n\n// #region Either\nexport type Either<L, R> = { success: false; value: L } | { success: true; value: R }\nexport const resultSuccess = <T>(value: T): Either<never, T> => ({ success: true, value })\nexport const resultFailure = <T>(value: T): Either<T, never> => ({ success: false, value })\n\n// #region Result\nexport type ResultFailure = { success: false; message: string; error: unknown; value: undefined }\nexport type Result<R> = { success: true; value: R } | ResultFailure\nexport const __OK = <T>(value: T): Result<T> => ({ success: true, value })\nexport const __FAIL = (message: string, error?: unknown): Result<any> => ({\n success: false,\n message,\n error,\n value: undefined,\n})\n\n// #region Markdown\nexport type MDContent = Branded<string, { MDContent: true }>\nexport const asMDContent = (s: string): MDContent => s as MDContent\n\n// #region HTML\nexport type HTMLContent = Branded<string, { HTML: true }>\nexport const asHTMLContent = (s: string): HTMLContent => s as HTMLContent\n","import { type Either, resultFailure, resultSuccess } from 'src/types/index.ts'\n\nexport type TextChunks = {\n [key: string]: string\n}\n\nexport const getPngMetadataFromUint8Array = (pngData: Uint8Array): Either<string, TextChunks> => {\n const dataView = new DataView(\n pngData.buffer,\n pngData.byteOffset, // <-- it just doesn't work without this\n pngData.byteLength, // <-- it just doesn't work without this\n )\n\n // console.log('🟢', dataView.getUint32(0))\n // console.log('🟢', dataView)\n\n // Check that the PNG signature is present\n if (dataView.getUint32(0) !== 0x89504e47) {\n // 🔴 showErrorMessage('Not a valid PNG file')\n return resultFailure('Not a valid PNG file')\n }\n\n // Start searching for chunks after the PNG signature\n let offset = 8\n\n const txt_chunks: TextChunks = {}\n\n // Loop through the chunks in the PNG file\n while (offset < pngData.length) {\n // Get the length of the chunk\n const length = dataView.getUint32(offset)\n // Get the chunk type\n const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))\n if (type === 'tEXt') {\n // Get the keyword\n let keyword_end = offset + 8\n while (pngData[keyword_end] !== 0) {\n keyword_end++\n }\n const keyword = String.fromCharCode(...pngData.slice(offset + 8, keyword_end))\n // Get the text\n const contentArraySegment = pngData.slice(keyword_end + 1, offset + 8 + length)\n const contentJson = Array.from(contentArraySegment)\n .map((s) => String.fromCharCode(s))\n .join('')\n txt_chunks[keyword] = contentJson\n }\n\n offset += 12 + length\n }\n\n return resultSuccess(txt_chunks)\n}\n","/* please, keep this file as minimal as possible; it's imported by many apps */\nexport function exhaust(x: never): never {\n return x\n}\n","import crypto from 'node:crypto'\n\nexport const hashArrayBuffer = (buffer: /* ArrayBuffer | */ Uint8Array): string => {\n const data = Buffer.from(buffer)\n return crypto.createHash('sha1').update(data).digest('hex')\n}\n","import { type } from 'arktype'\nimport type { Maybe, Tagged } from 'src/types/index.ts'\n\n// #region ComfyNodeID\nexport type ComfyNodeId = Tagged<string, 'ComfyNodeId'>\nexport const ComfyNodeId_ark = type.string.as<ComfyNodeId>()\n\n// #region ComfyNodeMetadata\nexport type ComfyNodeMetadata = {\n id?: Maybe<ComfyNodeId>\n\n tag?: string\n\n /** list of tags;\n * those tags will be copied to assets generated by this node.\n * e.g. you can add tags to SaveImage or PreviewImage to automatically tag images they'll produce. */\n tags?: string[]\n\n /** If the node produces an image, image will be stored in an ImageStore with given name.\n * ImageStore are useful for example to always have access to the image when re-running a workflow despite ComfyUI caching. */\n storeAs?: string\n}\nexport const ComfyNodeMetadata_ark = type({\n 'id?': ComfyNodeId_ark,\n 'tag?': 'string',\n 'tags?': 'string[]',\n 'storeAs?': 'string',\n}).as<ComfyNodeMetadata>()\n","import { scope, type } from 'arktype'\nimport { ComfyNodeId_ark } from 'src/graph/ComfyNodeID.ts'\nimport type { Tagged } from 'src/types/index.ts'\n\n/** the id ComfyUI assigns to one queued execution (wire-level name kept) */\nexport type PromptID = Tagged<string, { PromptID: true }>\nexport const PromptID_ark = type.string.as<PromptID>()\n\n// Define the scope and export its types for inference\nconst tempScope = scope({\n PromptID: PromptID_ark,\n ComfyNodeID: ComfyNodeId_ark, // Use the aliased schema\n Timestamp: 'number', // Define Timestamp directly in the scope\n\n ApiPromptInput: {\n client_id: 'string',\n extra_data: { extra_pnginfo: 'unknown' },\n prompt: 'unknown',\n },\n\n NodeProgress: { value: 'number', max: 'number' },\n\n ComfyStatusData: {\n 'sid?': 'string',\n status: {\n exec_info: { queue_remaining: 'number' },\n 'sid?': 'string',\n },\n },\n WsMsgStatus: {\n type: \"'status'\",\n data: 'ComfyStatusData',\n },\n\n _WsMsgExecutionStartData: { prompt_id: 'PromptID' },\n WsMsgExecutionStart: {\n type: \"'execution_start'\",\n data: '_WsMsgExecutionStartData',\n },\n\n _WsMsgExecutionCachedData: { nodes: 'ComfyNodeID[]', prompt_id: 'PromptID' },\n WsMsgExecutionCached: {\n type: \"'execution_cached'\",\n data: '_WsMsgExecutionCachedData',\n },\n\n // node is null on the final 'executing' message (prompt done)\n _WSMsgExecutingData: {\n prompt_id: 'PromptID',\n 'node?': 'ComfyNodeID | null',\n },\n WsMsgExecuting: {\n type: \"'executing'\",\n data: '_WSMsgExecutingData',\n },\n\n ComfyImageInfo: {\n filename: 'string',\n subfolder: 'string',\n type: 'string',\n },\n _WsMsgExecutedData: {\n node: 'ComfyNodeID',\n output: {\n 'previews?': [{ filepath: 'string' }, '[]'],\n 'images?': 'ComfyImageInfo[]',\n },\n prompt_id: 'PromptID',\n },\n WsMsgExecuted: {\n type: \"'executed'\",\n data: '_WsMsgExecutedData',\n },\n\n WsMsgExecutionSuccessData: {\n prompt_id: 'PromptID',\n timestamp: 'Timestamp',\n },\n WsMsgExecutionSuccess: {\n type: \"'execution_success'\",\n data: 'WsMsgExecutionSuccessData',\n },\n\n _WsMsgExecutionErrorData: {\n prompt_id: 'PromptID',\n node_id: 'ComfyNodeID',\n node_type: 'string',\n executed: 'ComfyNodeID[]',\n exception_message: 'string',\n exception_type: 'string',\n traceback: 'string[]',\n current_inputs: 'Record<string, unknown>',\n current_outputs: 'Record<string, unknown>',\n },\n WsMsgExecutionError: {\n type: \"'execution_error'\",\n data: '_WsMsgExecutionErrorData',\n },\n\n WSMsgManagerFeedbackData: { data: 'string' },\n WSMsgManagerFeedback: {\n type: \"'manager-terminal-feedback'\",\n data: 'WSMsgManagerFeedbackData',\n },\n\n // server console stream (/internal/logs): entries are WRITE CHUNKS, not lines\n LogEntry: { t: 'string', m: 'string' },\n _WsMsgLogsData: { entries: 'LogEntry[]', 'size?': 'unknown' },\n WsMsgLogs: {\n type: \"'logs'\",\n data: '_WsMsgLogsData',\n },\n\n // WsMsgProgress must be after NodeProgress\n WsMsgProgress: { type: \"'progress'\", data: 'NodeProgress' },\n\n // per-node progress map (ComfyUI ≥ 0.3.x)\n _WsMsgProgressStateData: {\n prompt_id: 'PromptID',\n nodes: 'Record<string, unknown>',\n },\n WsMsgProgressState: {\n type: \"'progress_state'\",\n data: '_WsMsgProgressStateData',\n },\n\n // UNION TYPES\n PromptRelated_WsMsg:\n 'WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess',\n WsMsg: 'WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg',\n})\n\nexport const types = tempScope.export()\n\n// REQUEST PAYLOADS ------------------------------------------------\nexport type ApiPromptInput = typeof types.ApiPromptInput.infer\n\n// MISC -------------------------------------------------------------\nexport type NodeProgress = typeof types.NodeProgress.infer\n\n// LIVE UPDATES ----------------------------------------------------\nexport type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer\nexport type WsMsg = typeof types.WsMsg.infer\nexport type ComfyStatusData = typeof types.ComfyStatusData.infer\nexport type WsMsgStatus = typeof types.WsMsgStatus.infer\nexport type WsMsgExecutionStart = typeof types.WsMsgExecutionStart.infer\nexport type WsMsgExecutionCached = typeof types.WsMsgExecutionCached.infer\nexport type _WSMsgExecutingData = typeof types._WSMsgExecutingData.infer\nexport type WsMsgExecuting = typeof types.WsMsgExecuting.infer\nexport type WsMsgProgress = typeof types.WsMsgProgress.infer\nexport type WsMsgProgressState = typeof types.WsMsgProgressState.infer\nexport type WsMsgExecuted = typeof types.WsMsgExecuted.infer\nexport type WsMsgExecutionSuccess = typeof types.WsMsgExecutionSuccess.infer\nexport type WsMsgExecutionError = typeof types.WsMsgExecutionError.infer\nexport type WSMsgManagerFeedback = typeof types.WSMsgManagerFeedback.infer\nexport type LogEntry = typeof types.LogEntry.infer\nexport type WsMsgLogs = typeof types.WsMsgLogs.infer\nexport type _WsMsgExecutionStartData = typeof types._WsMsgExecutionStartData.infer\nexport type _WsMsgExecutionCachedData = typeof types._WsMsgExecutionCachedData.infer\nexport type ComfyImageInfo = typeof types.ComfyImageInfo.infer\nexport type _WsMsgExecutedData = typeof types._WsMsgExecutedData.infer\nexport type _WsMsgExecutionErrorData = typeof types._WsMsgExecutionErrorData.infer\nexport type PromptId = typeof types.PromptID.infer\n\nexport type PromptInfo = { prompt_id: PromptID }\nexport const PromptInfo_ark = type({ prompt_id: types.PromptID }).as<PromptInfo>()\n\nexport const WsMsg_ark = types.WsMsg\nexport const ComfyImageInfo_ark = types.ComfyImageInfo\nexport const WsMsgLogsData_ark = types._WsMsgLogsData\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { type } from 'arktype'\nimport { type ImageMeta, imageMeta } from 'image-meta'\nimport { basename, dirname } from 'pathe'\nimport sharp, { type Sharp } from 'sharp'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { AbsolutePath, Maybe } from 'src/types/index.ts'\nimport type { NodeOf } from 'src/types/comfy-sdk.ts'\nimport type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport { type ComfyImageInfo, ComfyImageInfo_ark } from 'src/runner/ComfyWsApi.ts'\n\nexport type MediaImageData = {\n path: AbsolutePath\n\n // to avoid having to read the file if we already have the buffer around\n buffer?: Uint8Array\n\n // provenance ?\n execution?: ComfyExecution\n promptNodeID?: string | null\n\n comfyUIInfos?: ImageInfos_ComfyGenerated\n}\n\nexport type ImageInfos_ComfyGenerated = {\n comfyHostHttpURL: string\n comfyImageInfo: ComfyImageInfo\n}\n\nexport const ImageInfos_ComfyGenerated_ark = type({\n comfyHostHttpURL: 'string',\n comfyImageInfo: ComfyImageInfo_ark,\n})\n\nexport class MediaImage {\n absPath: AbsolutePath\n\n /** the execution this image came from (null when not generated via comfy-ts) */\n execution: Maybe<ComfyExecution>\n\n /** return the workflow from which this image was generated */\n get workflow(): ComfyWorkflow | undefined {\n return this.execution?.workflow\n }\n\n promptNodeID: Maybe<string>\n\n constructor(data: MediaImageData) {\n this.absPath = data.path\n this.execution = data.execution\n this.promptNodeID = data.promptNodeID\n if (data.buffer != null) this.updateBuffer(data.buffer)\n }\n\n /** free-form labels; filled from ComfyNodeMetadata.tag(s) when generated via a prompt */\n tags: string[] = []\n\n /** the image as a Blob, e.g. to feed FormData uploads */\n getAsBlob(): Blob {\n return new Blob([this.buffer as Uint8Array<ArrayBuffer>], { type: `image/${this.metadata.type ?? 'png'}` })\n }\n\n /** return the image filename */\n get filename(): string {\n return basename(this.absPath)\n }\n\n get baseNameWithoutExtension(): string {\n const fname = this.filename\n return fname.slice(0, fname.lastIndexOf('.'))\n }\n\n /**\n * return file extension including dot\n * e.g. `.png`, or `.webp`\n * */\n get extension(): string {\n const fname = this.filename\n return fname.slice(((fname.lastIndexOf('.') - 1) >>> 0) + 1)\n }\n\n /** get the expected enum name (hash) */\n get enumName(): ComfyImageName {\n return `${this.hash}${this.extension}` as ComfyImageName\n }\n\n uploadAndReturnEnumName = async (host: ComfyHost): Promise<ComfyImageName> => {\n const finalName = await host.uploader.uploadImage(this, { type: 'input', override: true })\n return finalName\n }\n\n /** upload the media (hash-named, deduped) and load it in the given workflow as a `LoadImage` node */\n loadInWorkflow_viaLoadImageNode = async <WID extends string>(\n workflow: ComfyWorkflow<WID>,\n ): Promise<NodeOf<WID, 'LoadImage'>> => {\n const enumName = await this.uploadAndReturnEnumName(workflow.host)\n const img = bang(workflow.builderBase.LoadImage, 'host has no LoadImage node')({ image: enumName })\n // sanctioned cast: uploaded names are runtime-known; the node itself is the host's LoadImage\n return img as NodeOf<WID, 'LoadImage'>\n }\n\n /** load an image as mask in a comfy workflow beeing created */\n loadInWorkflowAsMask_viaLoadImageMask = async <WID extends string>(\n /** \"alpha\" | \"blue\" | \"green\" | \"red\" */\n channel: 'alpha' | 'blue' | 'green' | 'red',\n /** workflow to load image as mask into */\n workflow: ComfyWorkflow<WID>,\n ): Promise<NodeOf<WID, 'LoadImageMask'>> => {\n const enumName = await this.uploadAndReturnEnumName(workflow.host)\n const mask = bang(\n workflow.builderBase.LoadImageMask,\n 'host has no LoadImageMask node',\n )({\n image: enumName,\n channel,\n })\n // sanctioned cast: same as above\n return mask as NodeOf<WID, 'LoadImageMask'>\n }\n\n /** return the json of the ComfyNode that led to this image */\n get ComfyNode(): Maybe<ComfyApiNodeJson> {\n const nodeID = this.promptNodeID\n if (nodeID == null) return null\n return this.workflow?.apiJson[nodeID]\n }\n\n /**\n * return the metadata of the ComfyNode that led to this image\n * null if not generated by comfy through a ComfyTS prompt\n * null if no metadata associated in the node in ComfyTS\n */\n get ComfyNodeMetadata(): Maybe<ComfyNodeMetadata> {\n const nodeID = this.promptNodeID\n if (nodeID == null) return null\n return this.workflow?.data.metadata[nodeID]\n }\n\n get width(): number | undefined {\n return this.metadata.width\n } // biome-ignore format: misc\n get height(): number | undefined {\n return this.metadata.height\n } // biome-ignore format: misc\n\n get width_orCrash(): number {\n return bang(this.metadata.width)\n } // biome-ignore format: misc\n get height_orCrash(): number {\n return bang(this.metadata.height)\n } // biome-ignore format: misc\n\n /**\n * return the base64 url for this file, regardless of it's exact representation\n * includes the prefix `data:image/<type>;base64,`\n */\n getBase64Url(): string {\n const imgType = this.metadata.type ?? 'png'\n return `data:image/${imgType};base64,${this.getBase64Payload()}`\n }\n\n /**\n * return the base64 url for this file, regardless of it's exact representation\n * does not includes the prefix `data:image/png;base64,`\n */\n getBase64Payload(): string {\n const bin = Buffer.from(this.buffer)\n return bin.toString('base64')\n }\n\n /** return the ArrayBuffer for this file, regardless it's exact representation */\n\n /** lazilly loaded, call recomputeMetadata to expire */\n private _buffer: Maybe<Uint8Array> = null\n get buffer(): Uint8Array {\n if (this._buffer != null) return this._buffer\n const buff: Buffer | ArrayBuffer = readFileSync(this.absPath)\n const uint8arr = new Uint8Array(buff)\n this._buffer = uint8arr\n return this._buffer\n }\n freeBuffer = (): void => void (this._buffer = null)\n updateBuffer = (buff: Uint8Array): void => {\n this._buffer = buff\n this._metadata = null // expire metadata\n this._hash = null // expire hash\n }\n reloadBuffer = (): Uint8Array => {\n this._buffer = null // expire buffer\n this._metadata = null // expire metadata\n this._hash = null // expire hash\n return this.buffer\n }\n\n /** lazilly computed, call recomputeMetadata to expire */\n private _metadata: Maybe<ImageMeta> = null\n get metadata(): ImageMeta {\n if (this._metadata != null) return this._metadata\n const buff = readFileSync(this.absPath)\n const uint8arr = new Uint8Array(buff)\n this._metadata = imageMeta(uint8arr)\n return this._metadata\n }\n\n private _hash: Maybe<string> = null\n get hash(): string {\n if (this._hash != null) return this._hash\n const buff: Buffer | ArrayBuffer = readFileSync(this.absPath)\n this._hash = hashArrayBuffer(new Uint8Array(buff))\n return this._hash\n }\n\n /**\n * Modify the image directly (inplace) by passing it though a `Sharp` pipeline\n * Sharp is a high performance image processing library.\n */\n processWithSharp_inplace = async (\n /** processing function */\n fn: (sharp: Sharp) => Sharp,\n ): Promise<this> => {\n const buff = await fn(sharp(this.absPath)).toBuffer()\n writeFileSync(this.absPath, buff)\n this.updateBuffer(new Uint8Array(buff))\n return this\n }\n\n /**\n * Allow to run an image though some `Sharp` pipeline to produce an other image.\n * Sharp is a high performance image processing library.\n * to modify the image directly (inplace), use `processWithSharp_inplace` instead.\n */\n processWithSharp = async (\n /** processing function */\n fn: (sharp: Sharp) => Sharp,\n /** where to save the resulting image */\n path?: AbsolutePath,\n ): Promise<MediaImage> => {\n const res: Sharp = fn(sharp(this.absPath))\n path ??= this.absPath + `.processed-${Date.now()}` + this.extension\n await res.toFile(path)\n const buffer = await res.toBuffer()\n return new MediaImage({ path, buffer })\n }\n\n generatePreview = async (targetPath: string): Promise<void> => {\n const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true })\n mkdirSync(dirname(targetPath), { recursive: true })\n await img.toFile(targetPath)\n }\n\n generateMiniPreview = async (): Promise<string> => {\n const image2 = await sharp(this.absPath).resize(32, 32, { fit: 'inside' }).webp({ quality: 1 }).toBuffer()\n const x = image2.toString('base64')\n return x\n }\n}\n","import { mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'pathe'\nimport sharp, { type FormatEnum } from 'sharp'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'\nimport type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'\nimport { asAbsolutePath, type ImageSaveFormat, type Maybe } from 'src/types/index.ts'\nimport { exhaust } from 'src/utils/exhaust.ts'\nimport type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'\nimport type { ComfyWorkflow, ComfyWorkflowID, ExecutionSnapshot, ProgressReport } from 'src/runner/ComfyWorkflow.ts'\n\nimport type {\n ComfyImageInfo,\n PromptID,\n PromptRelated_WsMsg,\n WsMsgExecuted,\n WsMsgExecuting,\n WsMsgExecutionError,\n WsMsgExecutionSuccess,\n} from 'src/runner/ComfyWsApi.ts'\nimport { MediaImage } from 'src/runner/MediaImage.ts'\n\nexport type ComfyExecutionData = {\n id: PromptID\n graphID: ComfyWorkflowID\n executed: boolean\n error?: WsMsgExecutionError | null\n status?: ComfyExecutionStatus | null\n}\n\nexport type ExecutionProgress = ProgressReport & {\n promptId: PromptID\n nodeName: string | null\n elapsedMs: number\n}\n\nexport class ComfyExecution {\n get host(): ComfyHost {\n return this.workflow.host\n }\n\n constructor(\n public workflow: ComfyWorkflow,\n public data: ComfyExecutionData,\n init: {\n snapshot?: ExecutionSnapshot\n saveFormat?: Maybe<ImageSaveFormat>\n onProgress?: Maybe<(p: ExecutionProgress) => void>\n logProgress?: boolean\n } = {},\n ) {\n // settings FIRST: onCreate flushes buffered ws messages whose handlers read them\n this.snapshot = init.snapshot ?? null\n this.saveFormat = init.saveFormat ?? null\n this.onProgress = init.onProgress ?? null\n this.logProgress = init.logProgress ?? false\n // register with the host so websocket messages route here,\n // then flush messages that arrived before we existed\n this.host.executions.set(data.id, this)\n this.onCreate()\n }\n\n // post-process\n saveFormat: Maybe<ImageSaveFormat> = null\n\n /** exactly what was sent to the host, frozen at send time (replayable) */\n snapshot: Maybe<ExecutionSnapshot> = null\n\n // ---- progress ----------------------------------------------------------\n /** called on every progress-relevant websocket message */\n onProgress: Maybe<(p: ExecutionProgress) => void> = null\n /** render a live single-line progress report to the console */\n logProgress: boolean = false\n readonly startedAt: number = Date.now()\n\n get progress(): ExecutionProgress {\n const report = this.progressGlobal\n return {\n ...report,\n promptId: this.data.id,\n nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,\n elapsedMs: Date.now() - this.startedAt,\n }\n }\n\n private _lastLoggedLine: string = ''\n private emitProgress(): void {\n const p = this.progress\n this.onProgress?.(p)\n if (!this.logProgress) return\n const width = 12\n const filled = Math.round((p.percent / 100) * width)\n const bar = '█'.repeat(filled) + '░'.repeat(width - filled)\n const node = p.nodeName ? ` · ${p.nodeName}` : ''\n const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1000).toFixed(0)}s`\n if (line === this._lastLoggedLine) return\n this._lastLoggedLine = line\n if (process.stdout.isTTY) process.stdout.write(`\\r\\x1b[2K${line}`)\n else console.log(line)\n }\n\n private finishProgressLine(): void {\n if (!this.logProgress) return\n const p = this.progress\n const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${this.images.length} image(s)`\n if (process.stdout.isTTY) process.stdout.write(`\\r\\x1b[2K${line}\\n`)\n else console.log(line)\n }\n\n // promise handle so that we can wait for this execution to finish.\n // resolves in BOTH success and failure — inspect `status` / `data.error`.\n private _resolve!: (value: this) => void\n done: Promise<this> = new Promise((resolve) => {\n this._resolve = resolve\n })\n\n log(...args: unknown[]): void {\n console.log(`[ComfyExecution#${this.data.id}]`, ...args)\n }\n\n onCreate(): void {\n const data: ComfyExecutionData = this.data\n const pending = this.host._pendingMsgs.get(data.id)\n if (pending == null) return\n this.log(`🟢 onCreate: ${pending.length} pending messages`)\n this.host._pendingMsgs.delete(data.id) // buffered once, never again\n for (const msg of pending) this.onPromptRelatedMessage(msg)\n }\n\n get progressGlobal(): ProgressReport {\n if (this.data.status === 'Success') return { countDone: 1, countTotal: 1, isDone: true, percent: 100 }\n return this.workflow.progressGlobal\n }\n\n get status(): 'New' | 'Scheduled' | 'Running' | 'Success' | 'Failure' {\n return this.data.status ?? 'New'\n }\n\n onPromptRelatedMessage = (msg: PromptRelated_WsMsg): void => {\n const graph = this.workflow\n if (msg.type === 'execution_start') return\n else if (msg.type === 'execution_cached') graph.onExecutionCached(msg)\n else if (msg.type === 'executing') this.onExecuting(msg)\n else if (msg.type === 'progress') graph.onProgress(msg)\n else if (msg.type === 'progress_state') {\n // per-node progress map; global progress is derived from the msgs above\n } else if (msg.type === 'executed') this.onExecuted(msg)\n else if (msg.type === 'execution_error') return void this.onError(msg)\n else if (msg.type === 'execution_success') return void this.onExecutionSuccess(msg)\n else {\n console.log(`🔴 UNEXPECTED MESSAGE:`, msg)\n return exhaust(msg)\n }\n this.emitProgress()\n }\n\n /** update pointer to the currently executing node */\n private onExecuting = (msg: WsMsgExecuting): void => {\n this.workflow.onExecuting(msg)\n }\n\n private onExecutionSuccess = async (_msg: WsMsgExecutionSuccess): Promise<void> => {\n await Promise.all(this.pendingPromises)\n return this._finish({ status: 'Success' })\n }\n\n private onError = async (msg: WsMsgExecutionError): Promise<void> => {\n console.error('❌ Execution error:')\n console.error(msg)\n return this._finish({ status: 'Failure', error: msg })\n }\n\n /** update execution list */\n private onExecuted = (msg: WsMsgExecuted): void => {\n const promptNodeID = msg.data.node\n const images = msg.data.output?.images\n if (images) {\n for (const img of images) {\n // guard every retrieval: one failed download must not hang `done`\n this.pendingPromises.push(\n this.retrieveImage(img, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${img.filename}:`, e)\n this.imageErrors.push({ image: img, error: e })\n }),\n )\n }\n }\n }\n private pendingPromises: Promise<void>[] = []\n\n /** image retrievals that failed (their images are missing from `images`) */\n imageErrors: { image: ComfyImageInfo; error: unknown }[] = []\n\n retrieveImage = async (\n //\n comfyImageInfo: ComfyImageInfo,\n promptNodeID: ComfyNodeId,\n ): Promise<void> => {\n // retrieve the node\n const promptNode = this.workflow.data.apiJson?.[promptNodeID]\n const promptMeta = this.workflow.data.metadata?.[promptNodeID]\n if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`)\n\n // get image url from ComfyUI\n const serverURL = this.host.getServerHostHTTP()\n const imgUrl = serverURL + '/view?' + new URLSearchParams(comfyImageInfo).toString()\n\n // target path on disk\n const sf = this.saveFormat\n let absPath: string = comfyts.resolveFromOutput(\n join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename),\n )\n if (sf?.format && sf.format !== 'raw') {\n const extension = sf.format.split('/')[1]\n absPath += '.' + extension\n }\n const dir = dirname(absPath)\n mkdirSync(dir, { recursive: true })\n\n // ref\n let img: MediaImage\n\n // RE-ENCODE (COMPRESSED)\n if (sf && sf.format !== 'raw') {\n const response = await fetch(imgUrl, { headers: { 'Content-Type': 'image/png' }, method: 'GET' })\n const buff = await response.arrayBuffer()\n let textChunk = {}\n try {\n const res = getPngMetadataFromUint8Array(new Uint8Array(buff))\n if (res.success) textChunk = res.value\n } catch {}\n\n const format = ((): keyof FormatEnum => {\n if (sf.format === 'image/jpeg') return 'jpeg'\n if (sf.format === 'image/png') return 'png'\n if (sf.format === 'image/webp') return 'webp'\n return 'png'\n })()\n\n await sharp(buff)\n .withMetadata()\n .withExif({ IFD0: textChunk })\n // sharp expect quality between 1 and 100\n .toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : undefined)\n .toFile(absPath)\n\n img = new MediaImage({\n path: asAbsolutePath(absPath),\n execution: this,\n promptNodeID: promptNodeID,\n comfyUIInfos: {\n comfyImageInfo: comfyImageInfo,\n comfyHostHttpURL: this.host.getServerHostHTTP(),\n },\n })\n }\n\n // SAVE RAW ------------------------------------------------------------------------------------------\n else {\n const response = await fetch(imgUrl, { headers: { 'Content-Type': 'image/png' }, method: 'GET' })\n const buff = await response.arrayBuffer()\n const uint8arr = new Uint8Array(buff)\n writeFileSync(absPath, uint8arr)\n img = new MediaImage({\n path: asAbsolutePath(absPath),\n buffer: uint8arr,\n execution: this,\n promptNodeID: promptNodeID,\n comfyUIInfos: {\n comfyImageInfo: comfyImageInfo,\n comfyHostHttpURL: this.host.getServerHostHTTP(),\n },\n })\n }\n\n // accumulate outputs on the prompt; tags from node metadata ride along\n if (promptMeta?.tag) img.tags.push(promptMeta.tag)\n if (promptMeta?.tags) img.tags.push(...promptMeta.tags)\n this.images.push(img)\n }\n\n /** images retrieved for this execution, in arrival order (final once `done` resolves) */\n images: MediaImage[] = []\n\n update(data: Partial<ComfyExecutionData>): void {\n Object.assign(this.data, data)\n }\n\n private alreadyDone: boolean = false\n private _finish = async (p: Pick<ComfyExecutionData, 'status' | 'error'>): Promise<void> => {\n if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`)\n this.alreadyDone = true\n this.update({ ...p, executed: true })\n await Promise.all(this.pendingPromises)\n // finished executions receive no further messages — free the routing maps\n this.host.executions.delete(this.data.id)\n this.host._pendingMsgs.delete(this.data.id)\n this.finishProgressLine()\n this._resolve(this)\n }\n}\n","export const deepCopyNaive = <T>(x: T): T => JSON.parse(JSON.stringify(x))\n","// tiny chalk-compatible terminal styler (chainable), keeps chalk out of the deps\nconst codes = {\n bold: [1, 22],\n underline: [4, 24],\n red: [31, 39],\n green: [32, 39],\n yellow: [33, 39],\n blue: [34, 39],\n greenBright: [92, 39],\n} as const\n\ntype StyleName = keyof typeof codes\nexport type Styler = ((s: string) => string) & { [k in StyleName]: Styler }\n\nfunction styler(open: string = '', close: string = ''): Styler {\n const fn = (s: string): string => open + s + close\n return new Proxy(fn, {\n get(_target, prop: string) {\n const c = codes[prop as StyleName]\n if (c == null) throw new Error(`unknown ansi style: ${prop}`)\n return styler(`${open}\\x1b[${c[0]}m`, `\\x1b[${c[1]}m${close}`)\n },\n }) as Styler\n}\n\nexport const ansi: Styler = styler()\n\n// CSI sequences + lone ESC-letter escapes (server logs re-rendered inside ink)\nconst ANSI_RE = /\\x1b\\[[0-9;?]*[A-Za-z]|\\x1b[A-Za-z]/g\n\nexport function stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '')\n}\n","// loud console logging; errors must be observable to human AND LLM.\n// COMFY_TS_QUIET=1 (set by drivers like the TUI) silences INFO chatter only —\n// errors always print.\nexport const isQuiet = (): boolean => process.env.COMFY_TS_QUIET === '1'\nexport const logInfo = (msg: string): void => {\n if (!isQuiet()) console.log(msg)\n}\nexport const logError = (msg: string): void => console.error(`[comfy-ts] 🔴 ${msg}`)\nexport const logSuccess = (msg: string): void => console.log(`[comfy-ts] 🟢 ${msg}`)\n","import type { ArkErrors } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { isQuiet } from 'src/utils/log.ts'\n\nconst MAX_PRINTED_ERRORS = 10\n\nexport function printArkResultInConsole(res: ArkErrors): void {\n if (isQuiet()) return\n console.log(chalk.red(' ❌ Ark validation failed:'))\n for (const error of res.slice(0, MAX_PRINTED_ERRORS)) {\n console.log(chalk.red(` - ${error.path.join('.')} : ${error.message}`))\n }\n if (res.length > MAX_PRINTED_ERRORS) {\n console.log(chalk.red(` … ${res.length - MAX_PRINTED_ERRORS} more (${res.length} total)`))\n }\n}\n","import { type Type, type } from 'arktype'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\n\nexport const softValidate = <T>(schema: Type<T>, stuff: unknown): T => {\n const res = schema(stuff)\n if (res instanceof type.errors) printArkResultInConsole(res)\n return stuff as T\n}\n","type ObjMap<T> = { [key: string]: T }\n\nexport type TNode = string\nexport type TEdge = [TNode, TNode]\n\nexport function toposort(nodes: TNode[], edges: TEdge[]): TNode[] {\n return toposortAlgo(nodes, edges)\n}\n\nfunction toposortAlgo(nodes: TNode[], edges: TEdge[]) {\n let cursor = nodes.length\n const sorted = Array.from<TNode>({ length: cursor })\n const visited: ObjMap<boolean> = {}\n let k = cursor\n\n while (k--) {\n if (!visited[k]) visit(BONG(nodes[k]), k, [])\n }\n\n return sorted\n\n function visit(node: TNode, ix: number, predecessors: TNode[]): void {\n let i = ix\n if (predecessors.indexOf(node) >= 0) {\n console.log(predecessors, node)\n throw new Error('Cyclic dependency: ' + JSON.stringify(node))\n }\n\n if (nodes.indexOf(node) === -1) {\n throw new Error(\n '[toposort] Found unknown node. Make sure to provided all involved nodes. Unknown node: ' +\n JSON.stringify(node) +\n '; known nodes are ' +\n JSON.stringify(nodes),\n )\n }\n\n if (visited[i]) return\n visited[i] = true\n\n // outgoing edges\n const outgoing = edges.filter((edge) => edge[0] === node)\n i = outgoing.length\n if (i) {\n const preds = predecessors.concat(node)\n do {\n const child = BONG(outgoing[--i])[1]\n visit(child, nodes.indexOf(child), preds)\n } while (i)\n }\n\n sorted[--cursor] = node\n }\n}\n\nfunction BONG<T>(x: T): NonNullable<T> {\n if (x == null) throw new Error('BONG')\n return x\n}\n","/** biome-ignore-all lint/style/noNonNullAssertion: later */\nimport type { ComfyNode, ComfyNodeUID } from 'src/graph/ComfyNode.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { type TEdge, toposort } from 'src/utils/toposort.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\n\n/**\n * compute autolayout\n *\n * 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive\n * libraries were pretty bad; ended up writing my own simple algorithm, and I'm\n * happy with it. Feel free to improve it, but I think it works well enough.\n * I will accept PRs for new layout algorithms if they don't have massive dependencies.\n **/\nexport function comfyWorkflowAutoLayout(\n this: ComfyWorkflow,\n p?: {\n /** @default: 20 */\n node_vsep?: number\n /** @default: 20 */\n node_hsep?: number\n /** @default false */\n forceLeft?: boolean\n },\n): ComfyWorkflow {\n const nodeIds = toposort(\n this.nodes.map((n) => n.uid),\n this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid] as TEdge)),\n )\n const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`))\n const cols: ComfyNode[][] = Array.from({ length: nodeIds.length })\n\n type NodePlacement = {\n node: ComfyNode\n minCol: number\n maxCol?: number\n }\n const ranges: {\n [nodeId: ComfyNodeUID]: NodePlacement\n } = {}\n\n // console.log(`[🤠] 1/3 ----------------------------`)\n for (const node of nodes) {\n // must be at least 1 after the closest parent\n const parentCols = node.parents.map((p) => ranges[p.uid]!.minCol)\n const minCol = Math.max(...parentCols, -1) + 1\n const range: NodePlacement = { node: node, minCol: minCol }\n ranges[node.uid] = range\n }\n\n // console.log(`[🤠] 2/3 ----------------------------`)\n if (!p?.forceLeft === true) {\n for (const node of nodes) {\n const range = ranges[node.uid]!\n for (const p of node.parents) {\n const parentRange = ranges[p.uid]!\n parentRange.maxCol =\n parentRange.maxCol != null\n ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1)\n : (range.maxCol ?? range.minCol) - 1\n }\n }\n }\n\n // console.log(`[🤠] 3/3 ----------------------------`)\n for (const node of nodes) {\n const range = ranges[node.uid]!\n const at = range.maxCol ?? range.minCol\n if (cols[at]) cols[at]!.push(node)\n else cols[at] = [node]\n }\n\n const HSEP = p?.node_hsep ?? 20\n const VSEP = p?.node_vsep ?? 20\n // cols.reverse()\n let colX = 0\n let maxY = 0\n for (const col of cols) {\n if (col == null) continue\n let colWidth = 0\n let currNodeY = 32\n const nodesSorted = col.toSorted((a, b) => b.height - a.height)\n for (const node of nodesSorted) {\n colWidth = Math.max(colWidth, node.width)\n node.x = colX\n node.y = currNodeY\n currNodeY += node.height + VSEP /* V SEP */\n }\n maxY = Math.max(maxY, currNodeY)\n colX += colWidth + HSEP /* H SEP */\n }\n\n this.height = maxY\n this.width = colX\n return this\n}\n","import { nanoid } from 'nanoid'\nimport { join } from 'pathe'\nimport { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'\nimport { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { type AbsolutePath, type ImageSaveFormat, type Maybe, type Tagged } from 'src/types/index.ts'\nimport type { SdkForHost } from 'src/types/comfy-sdk.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { deepCopyNaive } from 'src/utils/deepCopyNaive.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport { comfyWorkflowAutoLayout } from 'src/runner/ComfyWorkflowLayout.ts'\nimport {\n type ApiPromptInput,\n type PromptInfo,\n PromptInfo_ark,\n type WsMsgExecuting,\n type WsMsgExecutionCached,\n type WsMsgProgress,\n} from 'src/runner/ComfyWsApi.ts'\n\nexport type ProgressReport = {\n percent: number\n isDone: boolean\n countDone: number\n countTotal: number\n}\n\nexport type ComfyNodeIdMode = 'use_stringified_numbers_only' | 'use_class_name_and_number'\n\nexport type RunSettings = {\n saveFormat?: ImageSaveFormat\n idMode?: ComfyNodeIdMode\n /** render a live single-line progress report to the console */\n log?: boolean\n /** called on every progress-relevant websocket message */\n onProgress?: (p: ExecutionProgress) => void\n}\n\n/** exactly what was sent to the host for one execution, frozen at send time */\nexport type ExecutionSnapshot = {\n apiJson: ComfyApiJson\n workflowJson: LiteGraphJSON\n}\n\n/**\n * ComfyWorkflowL\n * - holds the nodes\n * - can be instanciated in both extension and webview\n * - so no link to workspace or run\n */\n\n// #region ComfyWorkflow\nexport type ComfyWorkflow_metadata = { [key: ComfyNodeId]: ComfyNodeMetadata }\n\nexport type ComfyWorkflowID = Tagged<string, { ComfyWorkflowID: true }>\nexport const asComfyWorkflowID = (x: string): ComfyWorkflowID => x\n\nexport type ComfyWorkflowData = {\n id?: Maybe<ComfyWorkflowID>\n\n apiJson?: ComfyApiJson\n metadata: ComfyWorkflow_metadata\n}\n\nexport class ComfyWorkflow<ID extends string = string> {\n id: ComfyWorkflowID\n apiJson: ComfyApiJson\n outputFolder: AbsolutePath\n\n constructor(\n public host: ComfyHost<ID>,\n public data: ComfyWorkflowData,\n ) {\n this.id = data.id ?? (nanoid(8) as ComfyWorkflowID)\n // ONE json object, shared by the field and the data record (registerNode writes there)\n this.apiJson = data.apiJson ?? {}\n data.apiJson = this.apiJson\n this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`)\n }\n\n /** nodes, in creation order */\n nodes: ComfyNode[] = []\n\n /** @internal every node constructor must call this */\n registerNode = (node: ComfyNode): void => {\n if (this.data.apiJson == null) throw new Error('graph not hydrated')\n this.data.apiJson[node.uid] = node.json\n this.data.metadata[node.uid] = node.meta\n this.nodesIndex.set(node.uid, node)\n this.nodes.push(node)\n }\n\n /** number of node in the graph */\n get size(): number {\n return this.nodes.length\n }\n\n setMetadata = (nodeID: ComfyNodeId, meta: ComfyNodeMetadata): void => {\n this.data.metadata[nodeID] = meta\n }\n\n getMetadata = (nodeID: ComfyNodeId): Maybe<ComfyNodeMetadata> => {\n return this.data.metadata[nodeID] ?? null\n }\n\n /** problem accumulator */\n problems: { title: string; data?: unknown }[] = []\n\n recordProblem = (title: string, data?: unknown): void => {\n this.problems.push({ title, data })\n }\n\n /** workflow builder, typed from the generated per-host sdk when one is in scope */\n private _builder: ComfyWorkflowBuilder | null = null\n get builder(): SdkForHost<ID>['Builder'] {\n if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)\n // sanctioned cast (see agent/coding.md): the runtime builder defines its\n // methods dynamically from the live schema; the static face comes from\n // the generated per-host sdk. Both derive from the same object_info.\n return this._builder as SdkForHost<ID>['Builder']\n }\n\n /** base (untyped) view of the same builder, for generic library code */\n get builderBase(): Comfy.Builder {\n if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)\n return this._builder as Comfy.Builder\n }\n\n onUpdate = (prev: Maybe<ComfyWorkflowData>, next: ComfyWorkflowData): void => {\n if (prev != null) {\n this.nodes = []\n this.nodesIndex.clear()\n this.currentExecutingNode = null\n }\n for (const [uid, node] of Object.entries(bang(next.apiJson))) {\n const meta: Maybe<ComfyNodeMetadata> = next.metadata?.[uid]\n new ComfyNode(this, uid, node, meta)\n }\n }\n\n /** proxy to this.db.schema */\n get schema(): ComfySchema {\n return this.host.schema\n }\n\n /** nodes that are still pending execution */\n get pendingNodes(): ComfyNode[] {\n return this.nodes.filter((n) => n.status == null || n.status === 'waiting')\n }\n\n get nodesByUpdatedAt(): ComfyNode[] {\n return this.nodes //\n .filter((n) => n.status != null && n.status !== 'waiting')\n .sort((a, b) => b.updatedAt - a.updatedAt)\n // return this.nodes.slice().sort((a, b) => b.updatedAt - a.updatedAt)\n }\n\n // findNodeByType = <T extends keyof ComfySetup>(nodeKey: T): Maybe<ReturnType<ComfySetup[T]>> => {\n // return this.nodes.find((n) => n.$schema.nodeKey === nodeKey) as any\n // }\n\n /** nodes, indexed by nodeID */\n nodesIndex = new Map<string, ComfyNode>()\n\n /** convert to mermaid DSL expression for nice graph rendering */\n toMermaid = (DIR: 'LR' | 'TD' = 'LR'): string => {\n const out = [\n `graph ${DIR}`,\n this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join('\\n'),\n this.nodes\n .map((n) =>\n n\n ._incomingEdges()\n .map((i) => {\n const from = this.nodesIndex.get(i.from)\n\n return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${\n n.$schema.nodeKey\n }]`\n })\n .join('\\n'),\n )\n .join('\\n'),\n ].join('\\n')\n return out\n }\n\n /** export the graph in ComfyUI's saved-workflow format (autolayouted by default) */\n toWorkflowJson = async (p: { layout?: boolean } = {}): Promise<LiteGraphJSON> => {\n if (p.layout !== false) this.autoLayout()\n return convertFlowToLiteGraphJSON(this)\n }\n\n /** export the graph in ComfyUI's api format (what POST /prompt takes) */\n toApiJson = (ns: ComfyNodeIdMode = 'use_stringified_numbers_only'): ComfyApiJson => {\n const json: ComfyApiJson = {}\n const keyOf = (uid: string): string =>\n ns === 'use_stringified_numbers_only' ? uid : (this.nodesIndex.get(uid)?.uidPrefixed ?? uid)\n for (const node of this.nodes) {\n if (node.disabled) continue\n const key = ns === 'use_stringified_numbers_only' ? node.uid : node.uidPrefixed\n // links reference node keys — remap them to whatever key scheme we emit\n const inputs: ComfyApiNodeJson['inputs'] = {}\n for (const [name, value] of Object.entries(node.json.inputs)) {\n inputs[name] =\n Array.isArray(value) && typeof value[0] === 'string' && typeof value[1] === 'number'\n ? [keyOf(value[0]), value[1]]\n : value\n }\n json[key] = { class_type: node.json.class_type, inputs }\n }\n return json\n }\n\n /** @internal pointer to the currently executing node */\n currentExecutingNode: ComfyNode | null = null\n\n get progressCurrentNode(): Maybe<ProgressReport> {\n return this.currentExecutingNode?.progressReport\n }\n\n get progressGlobal(): ProgressReport {\n const totalNode = this.nodes.length\n const doneNodes = this.nodes.filter((n) => n.status === 'done' || n.status === 'cached').length\n const bonus = this.currentExecutingNode?.progressRatio ?? 0\n const score = (doneNodes + bonus) / totalNode\n const percent = this.done ? 100 : score * 100\n const isDone = this.done\n return { percent, isDone, countDone: doneNodes + bonus, countTotal: totalNode }\n }\n\n /** @internal update the progress value of the currently focused onde */\n onProgress = (msg: WsMsgProgress): void => {\n if (this.currentExecutingNode == null) return void console.log('❌ no current executing node', msg)\n this.currentExecutingNode.progress = msg.data\n this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1)\n }\n\n getTargetWorkflowFilePath = (): AbsolutePath => {\n return join(this.cacheFolderPath, 'workflow.json')\n }\n\n getTargetPromptFilePath = (): AbsolutePath => {\n return join(this.cacheFolderPath, 'prompt.json')\n }\n\n get cacheFolderPath(): AbsolutePath {\n return comfyts.resolveFromOutput(`workflows/${this.id}`)\n }\n\n // private outputs: WsMsgExecuted[] = []\n // images: ImageL[] = []\n\n done: boolean = false\n\n /** @internal update pointer to the currently executing node */\n onExecuting = (msg: WsMsgExecuting): void => {\n // 1. mark currentExecutingNode as done\n if (this.currentExecutingNode) {\n this.currentExecutingNode.status = 'done'\n // this.currentExecutingNode.updatedAt = Date.now() + 1000\n }\n // 2. then two cases:\n // 2.A. no node => the prompt is done\n if (msg.data.node == null) {\n this.currentExecutingNode = null\n this.done = true\n return\n }\n\n this.done = false\n // 2.B. a node => node evaluation is starting\n const node = this.getNodeOrCrash(msg.data.node)\n this.currentExecutingNode = node\n node.status = 'executing'\n node.updatedAt = Date.now()\n }\n\n onExecutionCached = (msg: WsMsgExecutionCached): void => {\n for (const x of msg.data.nodes) {\n const node = this.getNodeOrCrash(x)\n node.status = 'cached'\n }\n }\n\n // onExecuted = (msg: WsMsgExecuted) => {\n // const node = this.getNodeOrCrash(msg.data.node)\n // const images = msg.data.output.images.map((i) => new PromptOutputImage(this, i))\n\n // // console.log(`🟢 `, images.length, `CushyImages`)\n // // accumulate in self\n // this.outputs.push(msg)\n // this.images.push(...images)\n // // console.log(`🟢 `, this.uid, 'has', this.images.length, `CushyImages`)\n\n // // accumulate in node\n // node.artifacts.push(msg.data)\n // node.images.push(...images)\n // }\n\n _uidNumber: number = 0\n\n getNodeOrCrash = (nodeID: ComfyNodeId): ComfyNode => {\n const node = this.nodesIndex.get(nodeID)\n if (node == null) throw new Error('Node not found:' + nodeID)\n return node\n }\n\n getNode = (nodeID: ComfyNodeId): Maybe<ComfyNode> => {\n const node = this.nodesIndex.get(nodeID)\n return node\n }\n\n width: number = 100\n height: number = 100\n\n /** compute autolayout **/\n autoLayout = comfyWorkflowAutoLayout.bind(this)\n\n /** send the workflow and wait for it to finish (with all outputs downloaded) */\n run = async (p: RunSettings = {}): Promise<ComfyExecution> => {\n const execution = await this.start(p)\n await execution.done\n return execution\n }\n\n /** reset per-run node state so the same workflow can run again cleanly */\n private resetRunState(): void {\n this.done = false\n this.currentExecutingNode = null\n for (const node of this.nodes) {\n node.status = null\n node.progress = null\n node.progressRatio = 0\n }\n }\n\n /** send the workflow; returns the live execution (await `execution.done` yourself) */\n start = async (p: RunSettings = {}): Promise<ComfyExecution> => {\n this.resetRunState()\n // snapshot: exactly what runs, frozen at send time (the live workflow stays editable)\n const snapshot: ExecutionSnapshot = {\n apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? 'use_stringified_numbers_only')),\n workflowJson: await this.toWorkflowJson(),\n }\n const out: ApiPromptInput = {\n client_id: this.host.comfySessionId,\n prompt: snapshot.apiJson,\n extra_data: {\n extra_pnginfo: {\n // regular ComfyUI metadata (drag the file in the editor -> the graph)\n workflow: snapshot.workflowJson,\n comfy_ts_workflow_id: this.id,\n comfy_ts_version: comfyts.version,\n },\n },\n }\n\n const promptEndpoint = `${this.host.getServerHostHTTP()}/prompt`\n const res = await fetch(promptEndpoint, {\n method: 'POST',\n body: JSON.stringify(out),\n })\n const promptInfoJson = await res.json()\n const promptInfo: PromptInfo = softValidate(PromptInfo_ark, promptInfoJson)\n\n if (res.status !== 200) {\n throw new InvalidPromptError('ComfyUI /prompt request failed', snapshot, promptInfo)\n }\n // settings + snapshot go through the constructor: the ctor flushes ws\n // messages that raced ahead, and those handlers need the settings\n const execution = new ComfyExecution(\n this,\n {\n id: promptInfo.prompt_id,\n executed: false,\n graphID: this.id,\n },\n {\n snapshot,\n saveFormat: p.saveFormat,\n onProgress: p.onProgress,\n logProgress: p.log ?? false,\n },\n )\n return execution\n }\n}\n","/** having a bunch of sensible default will help slightly */\nexport function getUnionNameBasedOnFirstFoundEnumName(\n //\n enumName: string,\n hash: string,\n hashContent: string,\n): string {\n // core enums\n if (enumName === 'KSampler.sampler_name') return 'E_SamplerName'\n if (enumName === 'KSampler.scheduler') return 'E_SchedulerName'\n if (enumName === 'CheckpointLoaderSimple.ckpt_name') return 'E_CkptName'\n if (enumName === 'VAELoader.vae_name') return 'E_VaeName'\n if (enumName === 'LoraLoader.lora_name') return 'E_LoraName'\n // upscape methods\n if (enumName === 'LatentUpscale.upscale_method') return 'E_LatentUpscaleMethod'\n if (enumName === 'ImageScale.upscale_method') return 'E_ImageUpscaleMethod'\n // core objects\n if (enumName === 'LoadImage.image') return 'E_Image'\n if (enumName === 'LoadImageMask.channel') return 'E_Channel'\n // misc\n if (enumName === 'KSamplerAdvanced.add_noise') return 'E_EnableOrDisable'\n if (enumName === 'LatentRotate.rotation') return 'E_Rotation'\n if (enumName === 'LatentFlip.flip_method') return 'E_FlipMethod'\n if (enumName === 'CLIPLoader.type') return 'E_ClipType'\n if (enumName === 'UNETLoader.weight_dtype') return 'E_WeightDType'\n if (enumName === 'DualCLIPLoader.type') return 'E_DualClipType'\n if (enumName === 'CheckpointLoader.config_name') return 'E_CkptConfigName'\n\n // civitai_comfy_nodes\n if (enumName === 'civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name') return 'E_CivitAICkptName'\n\n // Impact-Specific\n if (enumName === 'Impact-Pack.SAMDetectorCombined.detection_hint') return 'E_ImpactDetectionHint'\n\n // Misc\n if (hashContent === 'false|true') return 'E_TrueOrFalse'\n if (hashContent === 'CPU|GPU') return 'E_CpuOrGpu'\n return 'E_' + hash\n}\n","export function pythonModuleToPrefix(pythonModule: string): string {\n // if (pythonModule == null) console.error(`[🔴🔴🔴🔴🔴🔴] `, pythonModule)\n if (pythonModule === 'nodes') return ''\n if (pythonModule.startsWith('comfy_extras.')) return '' //''\n if (pythonModule.startsWith('comfy_api_nodes.')) return pythonModule.replace('comfy_api_nodes.', 'api.')\n if (pythonModule.startsWith('custom_nodes.')) {\n // return `${pythonModuleToNamespace_(pythonModule.replace('custom_nodes.', ''))}.`\n return (\n pythonModule //\n // remove always present \"custom_nodes.\" prefix\n .replace(/^custom_nodes\\./i, '')\n // remove common ~comfyui prefixes and suffixes\n .replace(/^comfyui[-_]/i, '')\n .replace(/[-_]comfyui$/i, '')\n // remove common ~comfy prefixes and suffixes\n .replace(/^comfy[-_]/i, '')\n .replace(/[-_]comfy$/i, '')\n // remove common ~nodes prefixes and suffixes\n .replace(/^nodes[-_]/i, '')\n .replace(/[-_]node[-_]suite$/i, '') + '.'\n )\n }\n // unknown module layout: fall back to a sanitized module prefix instead of\n // crashing the whole codegen because of one unusual custom node\n console.warn(`[comfy-ts] unexpected pythonModule \"${pythonModule}\", using it as prefix as-is`)\n return `${pythonModule}.`\n}\n","import { pythonModuleToPrefix } from 'src/sdk-generator/_pythonModuleToNamespace.ts'\n\nexport const toQualifiedNodeKey = (pythonModule: string, nameInComfy: string): string => {\n return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`\n}\n","/** this class is used to buffer text and then write it to a file */\nexport class CodeBuffer {\n public tab: string = ' '\n constructor(\n private _indent: number = 0,\n lines: string[] = [],\n ) {\n for (const line of lines) this.writeLine(line)\n }\n\n content: string = ''\n\n // #region adding text\n newLine = (): string => (this.content += '\\n')\n line = (...txts: string[]): this => this.writeLine(txts.join(''))\n append = (str: string): string => (this.content += str)\n writeLine = (txt: string): this => {\n this.content +=\n txt\n .split('\\n')\n .map((line) => repeatStr(this._indent, this.tab) + line)\n .join('\\n') + '\\n'\n return this\n }\n w = (txt: string, opts: { if: boolean } = { if: true }): void => {\n if (opts.if) this.writeLine(txt)\n }\n\n // #region indentations\n indent = (): number => this._indent++\n deindent = (): number => this._indent--\n indented = (fn: () => void): void => {\n this._indent++\n fn()\n this._indent--\n }\n\n bar = (text: string): void => this.w(renderBar(text, '// '))\n\n // writeTS = (path: string) => {\n // // const prefix = `// FILE GENERATED: do not edit. Changes made manually will be overwritten.\\n\\n`\n // // const outPretty = prefix + prettify(this.content)\n // const outPretty = prettify(this.content)\n // writeFileSync(path, outPretty, 'utf-8')\n // }\n}\n\nexport const repeatStr = (x: number, str: string): string => {\n let out = ''\n for (let i = 0; i < x; i++) out += str\n return out\n}\n\nexport const renderBar = (text: string, prefix: string = ''): string => {\n const ___bar___ = '============================================================================='\n return (\n `${prefix}|${___bar___}|\\n` +\n `${prefix}| ${text} ${repeatStr(___bar___.length - text.length - 4, ' ')} |\\n` +\n `${prefix}|${___bar___}|`\n )\n}\n","const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nconst isValidJSKey = (s: string): boolean => {\n return regex.test(s)\n}\n\nexport const escapeJSKey = (s: string): string => {\n if (typeof s !== 'string') {\n return 'string'\n // console.log(s)\n // debugger\n }\n // ❌ probably wrong\n if (!isValidJSKey(s)) {\n // debugger\n return `\"${s}\"`\n }\n return s\n}\n\nexport const asJSAccessor = (s: string): string => {\n if (typeof s !== 'string') {\n return 'string'\n // console.log(s)\n // debugger\n }\n if (!isValidJSKey(s)) {\n // debugger\n return `[\"${s}\"]`\n }\n return `.${s}`\n}\n","import type { Maybe } from 'src/types/index.ts'\nimport { CodeBuffer } from 'src/utils/CodeBuffer.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport type { ComfyInputOpts, ComfyNodeSchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { ComfyUnionInfo, NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'\n\nexport type NodeOwnEnum = {\n in: 'input' | 'output'\n ownName: string\n enum: ComfyUnionInfo\n}\n\nexport class ComfyNodeSchema {\n /** list of types the node has a single output of */\n _singleOutputs: Maybe<NodeOutputExt[]> = null\n\n get singleOutputs(): NodeOutputExt[] {\n if (this._singleOutputs != null) return this._singleOutputs\n const x: { [key: string]: number } = {}\n for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1\n this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1)\n return this._singleOutputs\n }\n\n constructor(\n public raw: ComfyNodeSchemaJSON,\n public nameInComfy: string,\n public nodeKey: string, // same but qualified to keep track of pythonNamespace\n public category: string,\n public inputs: NodeInputExt[],\n public outputs: NodeOutputExt[],\n public pythonModule: string,\n ) {\n this.category = this.category.replaceAll('/', '_')\n }\n\n codegenUI(): string {\n const b = new CodeBuffer()\n const p = b.w\n p(` ${escapeJSKey(this.nodeKey)}: {`)\n this.inputs.forEach((i, _ix) => {\n // 1/3\n if (i.isPrimitive) {\n const tsType = ComfyPrimitiveMapping[i.typeName]\n if (tsType == null) return console.log(`[🔶] invariant violation`)\n p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`)\n }\n // 2/3\n else if (i.isEnum) {\n p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`)\n // p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: '${this.nodeKey}.${i.nameInComfy}' }`) // prettier-ignore\n }\n // 3/3\n else {\n p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`)\n }\n })\n p(` }`)\n return b.content\n }\n\n renderOpts(opts?: ComfyInputOpts): Maybe<string> {\n if (opts == null) return null\n if (typeof opts === 'string') return null\n let out = '/**'\n if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`\n if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`\n if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`\n if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`\n out += ' */'\n return out\n }\n}\n\nexport const wrapQuote = (s: string): string => {\n if (s.includes(\"'\")) return `\"${s}\"`\n return `'${s}'`\n}\n","import type { Maybe } from 'src/types/index.ts'\nimport { CodeBuffer } from 'src/utils/CodeBuffer.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\n\nimport { type ComfyNodeSchema, wrapQuote } from 'src/sdk-generator/ComfyNodeSchema.ts'\n\n/**\n * convert a host id to the namespace name it gets inside the global `Comfy` namespace\n * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'\n */\nexport function hostIdToNamespace(hostId: string): string {\n const parts = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean)\n const ns = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('')\n if (ns.length === 0) throw new Error(`cannot derive a namespace from host id \"${hostId}\"`)\n // namespaces can't start with a digit\n return /^[0-9]/.test(ns) ? `Host${ns}` : ns\n}\n\nexport type CodegenOptions = {\n /** host id; drives both the `Comfy.Hosts` registry key and the namespace name */\n hostId: string\n /** module to import runtime-facing types from (default: 'comfy-ts') */\n packageName?: string\n}\n\n/**\n * emit the typed SDK for one host:\n *\n * declare global {\n * namespace Comfy {\n * namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }\n * interface Hosts { '<host-id>': <HostNs>.Sdk }\n * }\n * }\n */\nexport function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {\n const ns = hostIdToNamespace(opts.hostId)\n const packageName = opts.packageName ?? 'comfy-ts'\n const b = new CodeBuffer()\n const p = b.w\n\n p(`/** generated by comfy-ts for host \"${opts.hostId}\" — do not edit */`)\n p(``)\n p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`)\n p(``)\n p(`declare global {`)\n b.indent()\n\n p(`namespace Comfy {`)\n b.indent()\n\n p(`namespace ${ns} {`)\n b.indent()\n\n // #region PythonModules ----------------------------------------------------------------------\n p(`// #${''}region PythonModules`)\n p(`/** list of all python modules installed on this host */`)\n p(`export type PythonModules =`)\n b.indent()\n const pythonModulesArr: [string, string[]][] = Array.from(this.pythonModules.entries()) //\n .toSorted((a, b) => a[0].localeCompare(b[0]))\n for (const [k, v] of pythonModulesArr) {\n p(`/**`)\n p(`* Nodes: ${v.join(', ')}`)\n p(`*/`)\n p(`| ${wrapQuote(k)}`)\n }\n b.deindent()\n p(`// #${''}endregion`)\n\n // #region IN ---------------------------------------------------------------------------------\n const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey))\n p(`interface IN {`)\n b.indent()\n for (const n of nodes) {\n p(`${escapeJSKey(n.nodeKey)}: {`)\n for (const i of n.inputs) {\n const opts_ = typeof i.opts === 'string' ? null : i.opts\n let type = `Accepts[${JSON.stringify(i.typeName)}]`\n // COMBO inputs (ComfyUI ≥ 0.3.x) carry literal choices in opts.options\n const comboOptions =\n i.typeName === 'COMBO' && Array.isArray(opts_?.options)\n ? opts_.options.filter(\n (o): o is string | number | boolean =>\n typeof o === 'string' || typeof o === 'number' || typeof o === 'boolean',\n )\n : []\n if (comboOptions.length > 0) {\n type = `${comboOptions.map((o) => JSON.stringify(o)).join(' | ')} | ${type}`\n }\n // custom text/primitive widget types (placeholder/multiline/default in opts)\n // also accept the raw literal, e.g. AUTOCOMPLETE_TEXT_LORAS is just a string\n else if (opts_ && !i.isPrimitive && !i.isEnum) {\n if (typeof opts_.default === 'string' || opts_.placeholder != null || opts_.multiline != null) {\n type = `string | ${type}`\n } else if (typeof opts_.default === 'number') {\n type = `number | ${type}`\n } else if (typeof opts_.default === 'boolean') {\n type = `boolean | ${type}`\n }\n }\n if (opts_) {\n const rendered = n.renderOpts(opts_)\n if (rendered) p(` ${rendered}`)\n }\n const canBeOmmited = opts_?.default !== undefined || !i.required\n p(` ${i.nameInComfyEscaped}${canBeOmmited ? '?' : ''}: ${type}`)\n }\n p(`},`)\n }\n b.deindent()\n p('}')\n p('')\n\n // #region OUT --------------------------------------------------------------------------------\n p(`interface OUT {`)\n b.indent()\n for (const n of nodes) {\n p(`${escapeJSKey(n.nodeKey)}: {`)\n n.outputs.forEach((i, ix) => {\n p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`)\n })\n p(`}`)\n }\n b.deindent()\n p('}')\n\n // #region Node -------------------------------------------------------------------------------\n p(`interface Node {`)\n for (const n of nodes) {\n p(\n ` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`,\n )\n for (const hassingle of n.singleOutputs) {\n p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`)\n }\n p(` }`)\n }\n p('}')\n\n // #region Builder ----------------------------------------------------------------------------\n p(`interface Builder {`)\n for (const n of nodes) {\n const baseDescription = `displayName=\"${n.raw.display_name}\" category=\"${n.category}\" name=\"${n.nameInComfy}\" output=[${n.outputs.map((o) => o.outKey).join(', ')}]`\n if (n.raw.description) {\n p(` /**`)\n p(\n n.raw.description\n .split('\\n')\n .map((i) => ` * ${i}`)\n .join('\\n'),\n )\n p(` * ${baseDescription}`)\n p(` **/`)\n } else {\n p(` /** ${baseDescription} */`)\n }\n p(\n ` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`,\n )\n }\n p(`}`)\n\n // #region Slots ------------------------------------------------------------------------------\n p(`interface Slots {`)\n for (const e of this.knownUnionByHash.values()) {\n p(' // ' + e.unionName)\n for (const alias of e.enumNames) {\n p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`)\n }\n }\n p(`}`)\n\n // #region Embeddings -------------------------------------------------------------------------\n p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(' | ') || '\"\"'}`)\n\n const slotTypes = [...this.knownSlotTypes.values()] //\n .map((comfyType) => ({\n comfyType,\n tsType: this.toTSType(comfyType),\n tsType2: this.toAcceptsType(comfyType),\n }))\n .sort((a, b) => b.tsType.length - a.tsType.length)\n\n // #region Producer ---------------------------------------------------------------------------\n p('')\n p('interface Producer {')\n b.indent()\n for (const tp of slotTypes) {\n const allProducingNodes: Maybe<ComfyNodeSchema[]> = this.nodesByProduction[tp.comfyType]\n if (allProducingNodes) {\n p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(' | ')}>`)\n } else {\n p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`)\n }\n }\n b.deindent()\n p('}')\n\n // #region Accepts -----------------------------------------------------------------------------\n p(`interface Accepts {`)\n b.indent()\n // 1/3\n p('// injected bottom type (broken/null input specs land here)')\n p(`INVALID_null: any`)\n\n // 2/3\n p('')\n p('// named slot types: everything an input of that type accepts')\n for (const t of slotTypes) {\n p(\n `${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`,\n )\n }\n\n // 3/3\n p('')\n p('// enum unions: literal values or an output carrying one')\n for (const t of this.knownUnionByHash.values()) {\n p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`)\n }\n b.deindent()\n p(`}\\n`)\n\n // #region Union ------------------------------------------------------------------------------\n p('interface Union {')\n for (const e of this.knownUnionByHash.values()) {\n if (e.values.length > 0) {\n p(` // ${JSON.stringify(e.enumNames)}`)\n p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(' | ')}`)\n } else {\n p(` ${e.unionName}: '🔴' // never`)\n }\n }\n p('}')\n\n // #region HasSingle --------------------------------------------------------------------------\n p(`export interface HasSingle {`)\n for (const t of slotTypes) {\n p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`)\n }\n p(`}`)\n\n for (const t of this.enumsAppearingInOutput.values()) {\n p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`)\n }\n\n // #region Schemas ----------------------------------------------------------------------------\n p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`)\n p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(' | ')}`)\n\n // #region Sdk --------------------------------------------------------------------------------\n p(``)\n p(`/** everything above, packaged for the Comfy.Hosts registry */`)\n p(`interface Sdk {`)\n p(` IN: IN`)\n p(` OUT: OUT`)\n p(` Node: Node`)\n p(` Builder: Builder`)\n p(` Slots: Slots`)\n p(` Accepts: Accepts`)\n p(` Union: Union`)\n p(` Producer: Producer`)\n p(` Embeddings: Embeddings`)\n p(` Schemas: Schemas`)\n p(` NodeType: NodeType`)\n p(`}`)\n\n b.deindent()\n p(`}`) // end namespace <HostNs>\n\n p(``)\n p(`interface Hosts {`)\n p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`)\n p(`}`)\n\n b.deindent()\n p('}') // end namespace Comfy\n\n b.deindent()\n p('}') // end declare global\n p(``)\n p(`export {}`)\n\n return b.content\n}\n","import type { Branded } from 'src/types/index.ts'\nimport type { ComfyInputOpts } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\n\nexport type ComfyUnionHash = string // '26c34bf761d4be4554ab944105c5a3c017c99453\nexport type ComfyUnionName = string // 'E_26c34bf761d4be4554ab944105c5a3c017c99453'\nexport type ComfyUnionValue = string | boolean | number\n\nexport type ComfyPythonModule = string\nexport type NodeNameInComfy = string\nexport type QualifiedNodeKey = string\n\n/**\n * the textual name of a slot type (slot = input or output of a node),\n * e.g. 'MODEL', 'IMAGE', 'E_CkptName'.\n * Branded string — internals never depend on the global Comfy namespace\n * (that would break host encapsulation: slot types are per-host).\n */\nexport type ComfyNodeSlotTypeName = Branded<string, { SlotTypeName: true }>\nexport const asComfyNodeSlotTypeName = (x: string): ComfyNodeSlotTypeName => x as ComfyNodeSlotTypeName\n\n/** a fully-qualified slot name, e.g. 'LoadImage.image' or 'KSampler.LATENT.OUT' */\nexport type ComfyNodeSlotName = Branded<string, { SlotName: true }>\nexport const asComfyNodeSlotName = (x: string): ComfyNodeSlotName => x as ComfyNodeSlotName\n\nexport type EmbeddingName = Branded<string, { Embedding: true }>\n\nexport type NodeInputExt = {\n slotName: ComfyNodeSlotName\n nameInComfy: string\n nameInComfyEscaped: string\n typeName: ComfyNodeSlotTypeName\n opts?: ComfyInputOpts\n isPrimitive: boolean\n isEnum: boolean\n required: boolean\n index: number\n}\n\nexport type NodeOutputExt = {\n slotName: ComfyNodeSlotName\n typeName: ComfyNodeSlotTypeName\n outKey: string\n nameInComfy: string\n isPrimitive: boolean\n}\n\nexport type ComfyUnionInfo = {\n hash: ComfyUnionHash\n unionName: ComfyUnionName\n values: ComfyUnionValue[]\n enumNames: ComfyNodeSlotName[]\n}\n\n/** an image file name as known by the host (hash-named upload or existing input) */\nexport type ComfyImageName = Branded<string, { ComfyImageName: true }>\nexport const asComfyImageName = (x: string): ComfyImageName => x as ComfyImageName\n","import crypto from 'node:crypto'\nimport { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'\nimport { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'\nimport { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyEnumDef, ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { codegenSDK } from 'src/sdk-generator/comfyui-sdk-codegen.ts'\nimport {\n asComfyNodeSlotName,\n asComfyNodeSlotTypeName,\n type ComfyImageName,\n type ComfyNodeSlotName,\n type ComfyNodeSlotTypeName,\n type ComfyPythonModule,\n type ComfyUnionHash,\n type ComfyUnionInfo,\n type ComfyUnionName,\n type ComfyUnionValue,\n type EmbeddingName,\n type NodeInputExt,\n type NodeNameInComfy,\n type NodeOutputExt,\n type QualifiedNodeKey,\n} from 'src/sdk-generator/comfyui-types.ts'\nimport {\n ComfyDefaultNodeWhenUnknown_Name,\n ComfyDefaultNodeWhenUnknown_Schema,\n ComfyPrimitiveMapping,\n ComfyPrimitives,\n} from 'src/sdk-generator/Primitives.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\nexport type ComfySchemaId = string\n\nexport type ComfySchemaData = {\n spec: ComfySchemaJSON\n embeddings: string[]\n}\n\n/**\n * ONE host's schema: the parsed view of its object_info.json + embeddings.\n * Owns union dedup (by sha1 of values), node indexing, and the per-host\n * sdk codegen (`codegenDTS`).\n */\nexport class ComfySchema {\n codegenDTS = codegenSDK.bind(this)\n\n constructor(public data: ComfySchemaData) {\n this.parse()\n }\n\n update(data: Partial<ComfySchemaData>): void {\n const prev: ComfySchemaData = { spec: this.data.spec, embeddings: this.data.embeddings }\n Object.assign(this.data, data)\n try {\n this.parse()\n this.isInvalid = false\n } catch (error) {\n console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error)\n // roll back: a failed update must not leave half-built indexes in use\n this.data = prev\n try {\n this.parse()\n } catch {\n // previous data unparsable too (first update): indexes stay empty\n }\n this.isInvalid = true\n }\n }\n\n isInvalid: boolean = false\n\n /** number of nodes in the current schema (quick way to check your instance infos) */\n get size(): number {\n return Object.keys(this.data.spec).length\n }\n\n // #region parsed indexes\n knownSlotTypes = new Set<ComfyNodeSlotTypeName>()\n knownUnionBySlotName = new Map<ComfyNodeSlotName, ComfyUnionInfo>()\n knownUnionByHash = new Map<ComfyUnionHash, ComfyUnionInfo>()\n knownUnionByName = new Map<ComfyUnionName, ComfyUnionInfo>()\n nodes: ComfyNodeSchema[] = []\n pythonModuleByNodeKey: Map<QualifiedNodeKey, ComfyPythonModule> = new Map()\n pythonModuleByNodeNameInComfy: Map<NodeNameInComfy, ComfyPythonModule> = new Map()\n nodesByNameInComfy: { [key: NodeNameInComfy]: ComfyNodeSchema } = {}\n nodesByKey: { [key: QualifiedNodeKey]: ComfyNodeSchema } = {}\n nodesByProduction: { [key in ComfyNodeSlotTypeName]?: ComfyNodeSchema[] } = {}\n\n // some nodes output anonymous unions. we need to keep track of them for codegen\n enumsAppearingInOutput = new Set<ComfyNodeSlotTypeName>()\n\n pythonModules = new Map<string, NodeNameInComfy[]>()\n\n // #region parse\n private parse(): void {\n // reset all indexes: parse() re-runs on every update()\n this.knownSlotTypes.clear()\n this.knownUnionBySlotName.clear()\n this.knownUnionByHash.clear()\n this.knownUnionByName.clear()\n this.nodes = []\n this.pythonModuleByNodeKey.clear()\n this.pythonModuleByNodeNameInComfy.clear()\n this.nodesByNameInComfy = {}\n this.nodesByKey = {}\n this.nodesByProduction = {}\n this.enumsAppearingInOutput.clear()\n this.pythonModules.clear()\n\n // skip log for the initial dummy empty data\n if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0)\n this.log(`parsing ComfyUI object_info.json`)\n\n const entries: [string, ComfyNodeSchemaJSON][] = Object.entries(this.data.spec)\n entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema])\n\n for (const [KK, VV] of entries) {\n // record python module\n const pythonModule = VV.python_module\n const prev = this.pythonModules.get(pythonModule)\n if (prev == null) this.pythonModules.set(pythonModule, [KK])\n else prev.push(KK)\n\n const nodeNameInComfy = KK\n const nodeDef = VV\n const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy)\n\n if (typeof nodeDef.output === 'string') {\n console.log(\n `[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`,\n )\n nodeDef.output = []\n }\n this.pythonModuleByNodeKey.set(nodeKey, pythonModule)\n this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule)\n\n const inputs: NodeInputExt[] = []\n const outputs: NodeOutputExt[] = []\n const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule)\n\n // INDEX NODE\n this.nodesByNameInComfy[nodeNameInComfy] = node\n this.nodesByKey[nodeKey] = node\n this.nodes.push(node)\n\n // #region outputs ----------------------------------------------------------------------\n const nameCountDict: { [key: string]: number } = {}\n for (const [ix, slotType] of nodeDef.output.entries()) {\n const rawOutputSlotName =\n nodeDef.output_name[ix] || //\n (typeof slotType === 'string' ? slotType : `input_${ix}`)\n\n const outputNameInComfy = rawOutputSlotName\n const at = (nameCountDict[outputNameInComfy] ??= 0)\n const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`\n nameCountDict[outputNameInComfy]++\n\n let slotTypeName: ComfyNodeSlotTypeName\n const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`)\n\n // 1. Primitive\n if (typeof slotType === 'string') {\n slotTypeName = asComfyNodeSlotTypeName(slotType)\n this.knownSlotTypes.add(slotTypeName)\n }\n // 2. ENUM\n else if (Array.isArray(slotType)) {\n const RESX = this.processSlot({ pythonModule, slotName: outputSlotName, comfyUnionDef: slotType })\n slotTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n this.enumsAppearingInOutput.add(slotTypeName)\n }\n // 3. ????\n else {\n throw new Error(`invalid output ${ix} \"${slotType}\" in node \"${nodeNameInComfy}\"`)\n }\n\n // index production\n const arr = this.nodesByProduction[slotTypeName]\n if (arr == null) this.nodesByProduction[slotTypeName] = [node]\n else arr.push(node)\n\n outputs.push({\n slotName: outputSlotName,\n typeName: slotTypeName,\n nameInComfy: outputNameInComfy,\n outKey: outKeyValue,\n isPrimitive: false,\n })\n }\n\n // #region inputs ----------------------------------------------------------------------\n const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}) //\n .map(([name, spec]) => ({ required: false, name, spec }))\n\n const requiredInputs = Object.entries(nodeDef.input?.required ?? {}) //\n .map(([name, spec]) => ({ required: true, name, spec }))\n // when an input is BOTH required and optional (seen in the wild), keep the optional one\n .filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null)\n const allInputs = [...requiredInputs, ...optionalInputs]\n\n for (const ipt of allInputs) {\n const inputNameInComfy = ipt.name\n const typeDef = ipt.spec\n const slotType = typeDef[0]\n const slotOpts = typeDef[1]\n\n let inputTypeName: ComfyNodeSlotTypeName\n const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`)\n\n // 1/4 broken input (null type)\n if (slotType == null) {\n const RESX = this.processSlot({ pythonModule, slotName: inputSlotName, comfyUnionDef: ['❌'] })\n inputTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n }\n // 2/4 named slot type\n else if (typeof slotType === 'string') {\n inputTypeName = asComfyNodeSlotTypeName(slotType)\n this.knownSlotTypes.add(inputTypeName)\n }\n // 3/4 inline enum\n else if (Array.isArray(slotType)) {\n const RESX = this.processSlot({ pythonModule, slotName: inputSlotName, comfyUnionDef: slotType })\n inputTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n }\n // 4/4\n else {\n throw new Error(\n `invalid schema (${JSON.stringify(slotType)}) for input \"${\n ipt.name\n }\" in node \"${nodeNameInComfy}\" (type: ${typeof slotType}; expected: Array | string)`,\n )\n }\n\n node.inputs.push({\n slotName: inputSlotName,\n required: ipt.required,\n nameInComfy: inputNameInComfy,\n nameInComfyEscaped: escapeJSKey(inputNameInComfy),\n typeName: inputTypeName,\n opts: slotOpts,\n isPrimitive: ComfyPrimitives.includes(inputTypeName),\n isEnum: this.knownUnionByName.has(inputTypeName),\n index: node.inputs.length,\n })\n }\n }\n }\n\n // #region processSlot\n processSlot = (p: {\n pythonModule: string\n slotName: ComfyNodeSlotName\n comfyUnionDef: ComfyEnumDef\n }): ComfyUnionInfo => {\n // 1. build enum\n const enumValues: ComfyUnionValue[] = []\n for (const enumValue of p.comfyUnionDef) {\n if (typeof enumValue === 'string') enumValues.push(enumValue)\n else if (typeof enumValue === 'boolean') enumValues.push(enumValue)\n else if (typeof enumValue === 'number') enumValues.push(enumValue)\n else enumValues.push(enumValue.content)\n }\n // 2. hash its value\n const hashContent =\n enumValues.length === 0 //\n ? `[[empty]]`\n : enumValues.sort().join('|')\n const hash = crypto.createHash('sha1').update(hashContent).digest('hex').slice(0, 8)\n\n // 3. retrieve or create an EnumInfo\n let unionInfo: Maybe<ComfyUnionInfo> = this.knownUnionByHash.get(hash)\n if (unionInfo == null) {\n const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent)\n unionInfo = { hash, unionName, values: enumValues, enumNames: [] }\n this.knownUnionByHash.set(hash, unionInfo)\n this.knownUnionByName.set(unionName, unionInfo)\n }\n unionInfo.enumNames.push(p.slotName)\n\n // 4. store enum by name\n this.knownUnionBySlotName.set(p.slotName, unionInfo)\n return unionInfo\n }\n\n private log(...args: unknown[]): void {\n logInfo(`[👅]: ${args.join(' ')}`)\n }\n\n toTSType(t: string): string {\n // '*' is ComfyUI's wildcard: any output or primitive fits\n if (t === '*') return `string | number | boolean | ComfyNodeOutput<string, number>`\n return ComfyPrimitiveMapping[t]\n ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>`\n : `ComfyNodeOutput<'${t}'>`\n }\n\n toAcceptsType(t: string): string {\n return `ComfyNodeOutput<'${t}'>`\n }\n\n // #region discovery helpers\n /**\n * every possible value for a given slot, straight from the live schema.\n * e.g. schema.values('LoraLoader.lora_name') -> all loras on this host\n */\n values(slotName: string): ComfyUnionValue[] {\n return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? []\n }\n\n /** string values only (most enums are), for quick discovery */\n stringValues(slotName: string): string[] {\n return this.values(slotName).filter((v): v is string => typeof v === 'string')\n }\n\n /**\n * for now, simply ensure that the number of parsed nodes matches the number\n * of nodes present in the object_info.json\n */\n RUN_BASIC_CHECKS = (): void => {\n const numNodesInSource = Object.keys(this.data.spec).length\n // +1: the injected UnknownNodeXX default schema\n const numNodesInSchema = this.nodes.length - 1\n if (numNodesInSource !== numNodesInSchema) {\n console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`)\n }\n }\n\n hasEmbedding(embedding: string): embedding is EmbeddingName {\n return this.data.embeddings.includes(embedding)\n }\n\n hasLora(loraName: string): boolean {\n return this.getLoras().includes(loraName)\n }\n\n /** all loras on the host, optionally narrowed by a regex */\n getLoras = (filter?: RegExp): string[] => {\n const all = this.stringValues('LoraLoader.lora_name')\n return filter == null ? all : all.filter((n) => filter.test(n))\n }\n\n hasImage(imgName: string): imgName is ComfyImageName {\n return this.getImages().includes(imgName)\n }\n\n getImages = (): string[] => {\n return this.stringValues('LoadImage.image')\n }\n\n /**\n * only use this function after an upload success,\n * when you say this asset is now part of ComfyUI\n **/\n unsafely_addImageInSchemaWithoutReloading = (imgName: ComfyImageName): void => {\n const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName('LoadImage.image'))\n if (enumInfo == null) throw new Error(`LoadImage.image not found`)\n enumInfo.values.push(imgName)\n }\n\n hasCheckpoint(ckptName: string): boolean {\n return this.getCheckpoints().includes(ckptName)\n }\n\n getCheckpoints = (): string[] => {\n return this.stringValues('CheckpointLoaderSimple.ckpt_name')\n }\n}\n","import { scope, type } from 'arktype'\n\nexport const ComfyUIObjectInfoScope = scope({\n ComfySchemaJSON: { '[string]': 'ComfyNodeSchemaJSON' },\n ComfyNodeSchemaJSON: {\n input: {\n 'required?': { '[string]': 'ComfyInputSpec' },\n 'optional?': { '[string]': 'ComfyInputSpec' },\n 'hidden?': { '[string]': 'ComfyInputHiddenEntry' },\n },\n 'input_order?': {\n 'required?': 'string[]',\n 'optional?': 'string[]',\n 'hidden?': 'string[]',\n },\n output: 'ComfyInputType[]',\n output_is_list: 'boolean[]',\n output_name: 'string[]',\n name: 'string',\n display_name: 'string',\n description: 'string',\n /** */\n python_module: 'string',\n category: 'string',\n output_node: 'boolean',\n 'output_tooltips?': 'string[]',\n // Stability Flags\n 'deprecated?': 'boolean',\n 'experimental?': 'boolean',\n },\n ComfyInputSpecAlt1: ['ComfyInputType', 'ComfyInputOpts'],\n ComfyInputSpecAlt2: ['ComfyInputType'],\n // means it's broken: some nodes declare an input whose spec is literally\n // [null] — accepted here so ONE bad node cannot fail a whole schema parse\n ComfyInputSpecAlt3: type([type.null]),\n ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,\n\n ComfyInputType: `string | ComfyEnumDef`,\n\n ComfyInputHiddenEntry_broken1: '\"CHOOSE\"[][]', // BROKEN STUFF (e.g. found in several 'rgthree' nodes)\n ComfyInputHiddenEntry_broken2: type.Record('string', type.unknown), // BROKEN STUFF (e.g. found in \"ttN xyPlot\")\n ComfyInputHiddenEntry: 'string | ComfyInputHiddenEntry_broken1 | ComfyInputHiddenEntry_broken2 ',\n\n ComfyInputOpts_simple: 'string',\n ComfyInputOpts_advanced: {\n // 💬 2025-06-11 rvion: \"ComfyInputOpts_advanced\" added because of Segment.input.optional.background : Segment.input.optional.background[1].tooltip must be a string or null (was an object) or Segment.input.optional.background must be exactly length 1 (was 2)\n 'tooltip?': 'string | null | ComfyInputOpts_advanced',\n 'multiline?': 'boolean | null',\n\n // 💬 2025-06-11 rvion: \"number[]\" added because of CreateShapeImageOnPath.input.optional.size_multiplier : CreateShapeImageOnPath.input.optional.size_multiplier[1].default must be a number, a string, boolean or null (was an object) or CreateShapeImageOnPath.input.optional.size_multiplier must be exactly length 1 (was 2)\n 'default?': 'boolean | number | string | null | number[]',\n\n 'forceInput?': 'boolean | null',\n 'min?': 'number | null',\n 'round?': 'boolean | number | null',\n 'max?': 'number | null',\n 'step?': 'number | null',\n /** Observed on 2024-11-01; 171 occurrences */\n 'dynamicPrompts?': 'boolean',\n\n /** text widgets (e.g. LoraManager autocomplete fields) */\n 'placeholder?': 'string | null',\n\n /** COMBO-typed inputs (ComfyUI ≥ 0.3.x) carry their choices here */\n 'options?': 'unknown[] | null',\n 'multiselect?': 'boolean | null',\n\n // 💬 2025-06-11 rvion: \"0\" added because of CustomControlNetWeightsFluxFromList.input.optional.autosize : CustomControlNetWeightsFluxFromList.input.optional.autosize[1].padding must be boolean (was 0) or CustomControlNetWeightsFluxFromList.input.optional.autosize must be exactly length 1 (was 2)\n 'padding?': 'boolean | 0',\n },\n ComfyInputOpts: 'ComfyInputOpts_simple | ComfyInputOpts_advanced',\n\n ComfyEnumIllustratedItem: {\n content: 'string',\n 'image?': 'string | null',\n },\n ComfyEnumItem: 'string | number | boolean | ComfyEnumIllustratedItem',\n ComfyEnumDef: `ComfyEnumItem[]`,\n})\n\nconst types = ComfyUIObjectInfoScope.export()\n\nexport type ComfySchemaJSON = typeof types.ComfySchemaJSON.infer\nexport type ComfyNodeSchemaJSON = typeof types.ComfyNodeSchemaJSON.infer\nexport type ComfyInputSpec = typeof types.ComfyInputSpec.infer\nexport type ComfyInputType = typeof types.ComfyInputType.infer\nexport type ComfyEnumDef = typeof types.ComfyEnumDef.infer\nexport type ComfyInputOpts = typeof types.ComfyInputOpts.infer\n\nexport const ComfySchemaJSON_ark = types.ComfySchemaJSON\nexport const ComfyNodeSchemaJSON_ark = types.ComfyNodeSchemaJSON\nexport const ComfyInputSpec_ark = types.ComfyInputSpec\nexport const ComfyInputType_ark = types.ComfyInputType\nexport const ComfyEnumDef_ark = types.ComfyEnumDef\nexport const ComfyInputOpts_ark = types.ComfyInputOpts\n","/** Extracts an error message from an exception stuff. */\nexport const extractErrorMessage = (error: unknown): string => {\n if (error instanceof Error) return error.message\n if (error === null) return 'null'\n if (typeof error === 'string') return error\n if (typeof error === 'object') {\n if ('message' in error && typeof error.message === 'string') return error.message\n return JSON.stringify(error)\n }\n return String(error)\n}\n","const tab = ' '\n\nexport function readableStringify(obj: unknown, maxLevel = 3, level = 0): string {\n if (level > maxLevel) return JSON.stringify(obj)\n if (typeof obj !== 'object' || obj === null) return JSON.stringify(obj)\n const indent = ' '.repeat(level + 1)\n let result = '{\\n'\n const keys = Object.keys(obj)\n for (let i = 0; i < keys.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: don't care\n const key = keys[i]!\n // biome-ignore lint/suspicious/noExplicitAny: don't care\n const value = (obj as any)[key]\n if (value === undefined) continue\n const valueType = typeof value\n\n if (i > 0) result += ','\n const thisIndent = i > 0 ? indent.slice(1) : indent\n if (Array.isArray(value)) {\n result += `${thisIndent}${JSON.stringify(key)}: ${JSON.stringify(value)}`\n } else if (valueType === 'object' && value !== null) {\n result += `${thisIndent}${JSON.stringify(key)}: ${readableStringify(value, maxLevel, level + 1)}`\n } else {\n const formattedValue = valueType === 'string' ? JSON.stringify(value) : value\n result += `${thisIndent}${JSON.stringify(key)}: ${formattedValue}`\n }\n result += '\\n'\n }\n result += `${tab.repeat(Math.max(0, level))}}`\n\n return result\n}\n","import { writeFile } from 'node:fs'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\nexport const writeFileAsync = async (path: string, data: string, fmt: 'utf-8') => {\n return new Promise<void>((resolve, reject) => {\n logInfo(`writing file: ${chalk.blue(path)}`)\n writeFile(path, data, fmt, (err) => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n })\n}\n","import { type } from 'arktype'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\n\nexport type ComfyManagerAPIModelList = typeof ComfyManagerAPIModelList_ark.infer\nexport const ComfyManagerAPIModelList_ark = type({\n models: type({\n name: type.string.as<KnownModel_Name>(),\n installed: `'False' | 'True' | 'Update'`,\n }).array(),\n})\n","import { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\n\nexport type ComfyManagerAPIPluginList = typeof ComfyManagerAPIPluginList_ark.infer\nexport const ComfyManagerAPIPluginList_ark = type({\n custom_nodes: type({\n title: type.string.as<KnownComfyPluginTitle>(),\n installed: `'False' | 'True' | 'Update'`,\n }).array(),\n chanel: 'string',\n})\n","/** 🔶 NAMING DISCLAIMER: I call a \"custom node package\" => \"PLUGIN\" */\n\nimport type { Type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport type { ComfyManagerAPIFetchPolicy } from 'src/manager/types/ComfyManagerAPIFetchPolicy.ts'\nimport {\n type ComfyManagerAPIModelList,\n ComfyManagerAPIModelList_ark,\n} from 'src/manager/types/ComfyManagerAPIModelList.ts'\nimport {\n type ComfyManagerAPIPluginList,\n ComfyManagerAPIPluginList_ark,\n} from 'src/manager/types/ComfyManagerAPIPluginList.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { logError as toastError, logSuccess as toastSuccess } from 'src/utils/log.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { PluginInstallStatus } from 'src/host/Requirements.ts'\n\nexport class ComfyManager {\n constructor(public host: { getServerHostHTTP: () => string }) {\n // void this.updateHostPluginsAndModels()\n }\n\n get registry(): ComfyRegistry {\n return comfyts.registry\n }\n\n fetchPluginsAndModels = async (): Promise<void> => {\n const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()])\n this.pluginList = _pluginList\n this.modelList = _modelList\n }\n\n // -----------\n configureLogging = (mi: boolean): Promise<unknown> => {\n // return this.repository.getModelInfoFinalFilePath(mi)\n return this.fetchGetText(`/manager/terminal?mode=${mi}`)\n }\n\n // utils ------------------------------------------------------------------------------\n getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {\n return comfyts.registry.getModelInfoFinalFilePath(mi)\n }\n\n waitForHostToBeBackOnline(maxAttempt: 10): Promise<true> {\n return new Promise<true>((yes, no) => {\n let attempt = 0\n let abortCtrl: AbortController\n const interval = setInterval(async () => {\n attempt++\n if (attempt > maxAttempt) {\n console.log(` - failure`)\n clearInterval(interval)\n no()\n }\n if (abortCtrl) abortCtrl.abort()\n const url = this.host.getServerHostHTTP()\n abortCtrl = new AbortController()\n try {\n console.log(` - trying...`)\n await fetch(url, { signal: abortCtrl.signal })\n clearInterval(interval)\n yes(true)\n } catch {\n /* empty */\n }\n }, 1000)\n })\n }\n\n // actions ---------------------------------------------------------------------------\n rebootComfyUIAndUpdateHostPluginsAndModelsAfter10Seconds(): Promise<void> {\n // 🔴 bad code\n setTimeout(() => void this.fetchPluginsAndModels(), 10_000)\n // curl 'http://<host>:8188/api/manager/reboot' \\\n // -H 'Accept: */*' \\\n // -H 'Accept-Language: en-GB' \\\n // -H 'Cache-Control: max-age=0' \\\n // -H 'Comfy-User: undefined' \\\n // -H 'Connection: keep-alive' \\\n // -H 'Referer: http://<host>:8188/' \\\n // -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'\n return this.fetchGetJSON('/manager/reboot')\n }\n\n restartComfyUI = async (): Promise<unknown> => {\n return this.fetchGetJSON('/manager/reboot')\n }\n\n modelList: Maybe<ComfyManagerAPIModelList> = null\n\n fetchModels = (): Promise<ComfyManagerAPIModelList> => {\n return this.fetchGetJSON('/externalmodel/getlist?mode=cache', ComfyManagerAPIModelList_ark)\n }\n\n fetchLogs = (): Promise<any> => {\n return this.fetchGetJSON<unknown>('/internal/logs')\n }\n\n isModelInstalled = (name: KnownModel_Name): boolean => {\n return this.modelList?.models.some((x) => x.name === name && x.installed === 'True') ?? false\n }\n\n modelsBeeingInstalled = new Set<KnownModel_Name>()\n\n installModel = async (model: ComfyManagerModelInfo): Promise<boolean> => {\n try {\n this.modelsBeeingInstalled.add(model.name)\n await this.fetchPost('/model/install', model)\n this.modelsBeeingInstalled.delete(model.name)\n toastSuccess('Model installed')\n return true\n } catch (exception) {\n console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)\n toastError('Model Installation Failed')\n this.modelsBeeingInstalled.delete(model.name)\n return false\n }\n }\n\n getModelStatus = (modelName: KnownModel_Name): PluginInstallStatus => {\n if (this.modelList == null) return 'unknown'\n const entry = this.modelList?.models.find((x) => x.name === modelName)\n const status = ((): PluginInstallStatus => {\n if (!entry) return 'unknown'\n if (entry?.installed === 'False') return 'not-installed'\n if (entry?.installed === 'True') return 'installed'\n if (entry?.installed === 'Update') return 'update-available'\n return 'error'\n })()\n return status\n }\n\n // PLUGINS (A.K.A. Custom nodes) ----------------------------------------------------------------------------\n /**\n * you need to call `fetchPluginList()` to populate this field\n */\n pluginList: Maybe<ComfyManagerAPIPluginList> = null // hasModel = async (model: ModelInfo) => {\n\n get titlesOfAllInstalledPlugins(): KnownComfyPluginTitle[] {\n return (\n this.pluginList?.custom_nodes //\n .filter((x) => x.installed === 'True')\n .map((x) => x.title) ?? []\n )\n }\n\n isPluginInstalled = (title: KnownComfyPluginTitle): boolean => {\n if (!this.pluginList || !this.pluginList.custom_nodes) return false\n return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === 'True') ?? false\n }\n\n getPluginStatus = (title: KnownComfyPluginTitle): PluginInstallStatus => {\n if (this.pluginList == null) return 'unknown'\n const entry = this.pluginList?.custom_nodes.find((x) => x.title === title)\n const status = ((): PluginInstallStatus => {\n if (!entry) return 'unknown'\n if (entry?.installed === 'False') return 'not-installed'\n if (entry?.installed === 'True') return 'installed'\n if (entry?.installed === 'Update') return 'update-available'\n return 'error'\n })()\n return status\n }\n\n // --------------------------------------------------------------\n // https://github.com/ltdrdata/ComfyUI-Manager/blob/4649d216b1842aa48b95d3f064c679a1b698e506/js/custom-nodes-downloader.js#L14C25-L14C88\n fetchPlugins = async (\n /** @default: 'cache' */\n mode: ComfyManagerAPIFetchPolicy = 'cache',\n /** @default: true */\n skipUpdate: boolean = true,\n ): Promise<ComfyManagerAPIPluginList> => {\n try {\n const skip_update = skipUpdate ? '&skip_update=true' : ''\n return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark)\n } catch (exception) {\n console.error(`node list retrieval failed: ${exception}`)\n toastError('node list retrieveal failed')\n throw exception\n }\n }\n\n installPlugin = async (model: ComfyManagerPluginInfo): Promise<boolean> => {\n try {\n await this.fetchPost('/customnode/install', model)\n console.log('✅ Custom Node installed')\n toastSuccess('Custom Node installed')\n return true\n } catch (exception) {\n console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)\n toastError('Custom Node Installation Failed')\n return false\n }\n }\n\n // --------------------------------------------------------------\n private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {\n const url = this.host.getServerHostHTTP() + endpoint\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`)\n const status = await response.json()\n if (validator) return softValidate(validator, status)\n // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json\n return status as OUT\n }\n\n private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {\n const url = this.host.getServerHostHTTP() + endpoint\n const response = await fetch(url)\n if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)\n const jsonResult = await response.json()\n if (validator) return softValidate(validator, jsonResult)\n // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json\n return jsonResult as OUT\n }\n\n private fetchGetText = async (endopint: string): Promise<string> => {\n const url = this.host.getServerHostHTTP() + endopint\n const response = await fetch(url)\n const status = await response.text()\n return status\n }\n}\n","import { type } from 'arktype'\nimport type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'\nimport type { MediaImage } from 'src/runner/MediaImage.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\n\nexport type ComfyUploadImageResult = {\n name: ComfyImageName\n subfolder: string\n type: string\n}\n\nexport const ComfyUploadImageResult_ark = type({\n name: type.string.as<ComfyImageName>(),\n subfolder: 'string',\n type: 'string',\n})\n\n/** all those functions are kinda legacy */\nexport class ComfyUploader {\n constructor(public host: ComfyHost) {}\n\n /** upload a blob */\n uploadImage = async (\n //\n img: MediaImage,\n p: {\n type?: Maybe<'input' | 'temp' | 'output'>\n override?: Maybe<boolean>\n subfolder?: string\n },\n ): Promise<ComfyImageName> => {\n const uniqFileName = img.enumName as ComfyImageName\n // console.warn(`[🌁] UPLOAD: ${img.relPath} required as \"${uniqFileName}\"...`)\n\n const expectedFinalName = p.subfolder //\n ? `${p.subfolder}/${uniqFileName}`\n : uniqFileName\n // 2. if image already exists, return it\n if (this.host.schema.hasImage(expectedFinalName)) {\n console.log(`[🌁] UPLOAD: 🩶 \"${img.absPath}\" already exists on current ComfyUI instance`)\n return expectedFinalName as ComfyImageName\n }\n\n // 3. upload\n const form = new FormData()\n form.set('image', img.getAsBlob(), uniqFileName)\n if (p.type) form.set('type', p.type)\n if (p.override ?? true) form.set('override', 'true')\n // const subfolder = p.subfolder ?? 'comfyts-upload'\n if (p.subfolder) form.set('subfolder', p.subfolder)\n const uploadURL = this.host.getServerHostHTTP() + '/upload/image'\n const resp = await fetch(uploadURL, { method: 'POST', body: form })\n const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())\n\n // 4. check upload is successfull\n console.log('[🌁] UPLOAD: ✅ got', result)\n if (result.name == null) throw new Error('upload failed')\n\n const finalName = result.subfolder //\n ? (`${result.subfolder}/${result.name}` as ComfyImageName)\n : result.name\n\n if (finalName !== expectedFinalName) {\n console.warn(`[🌁] UPLOAD: ⚠️ expected \"${expectedFinalName}\" but got \"${finalName}\"`)\n } else {\n console.log(`[🌁] UPLOAD: ✅ finalName is \"${finalName}\"`)\n }\n\n // 5. patch the local ComfyUI schema locally\n this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName)\n\n // 6. return the image\n return finalName\n }\n\n /** upload an image present on disk to ComfyUI */\n // ⏸️ upload_FileAtAbsolutePath = async (filePath: AbsolutePath): Promise<ComfyUploadImageResult> => {\n // ⏸️ const mime = asSTRING_orCrash(lookup(filePath))\n // ⏸️ const file = new Blob([readFileSync(filePath)], { type: mime })\n // ⏸️ return await this.upload_Blob(file)\n // ⏸️ }\n\n // ⏸️ /** upload an image from dataURL */\n // ⏸️ upload_dataURL = async (dataURL: string): Promise<ComfyUploadImageResult> => {\n // ⏸️ const mime = dataURL.split(';')[0].split(':')[1]\n // ⏸️ console.log('[⬆️] upload_dataURL', mime)\n // ⏸️ const file = new Blob([Buffer.from(dataURL.split(',')[1], 'base64')], { type: mime })\n // ⏸️ return await this.upload_Blob(file)\n // ⏸️ }\n\n // ⏸️ /** upload an image present on disk to ComfyUI */\n // ⏸️ upload_NativeFile = async (file: File): Promise<ComfyUploadImageResult> => {\n // ⏸️ const blob = new Blob([await file.arrayBuffer()], { type: file.type })\n // ⏸️ return await this.upload_Blob(blob)\n // ⏸️ }\n\n // ⏸️ /** upload an image that can be downloaded form a given URL to ComfyUI */\n // ⏸️ upload_ImageAtURL = async (url: string): Promise<ComfyUploadImageResult> => {\n // ⏸️ const blob: Blob = await this.st.getUrlAsBlob(url)\n // ⏸️ return this.upload_Blob(blob)\n // ⏸️ }\n\n // ⏸️ /** upload a deck asset to ComfyUI */\n // ⏸️ upload_Asset = async (assetName: RelativePath): Promise<ComfyUploadImageResult> => {\n // ⏸️ const absPath = asAbsolutePath(path.join(this.st.rootPath, assetName))\n // ⏸️ return this.st.uploader.upload_FileAtAbsolutePath(absPath)\n // ⏸️ }\n}\n","import WebSocket, { type CloseEvent, type Event, type MessageEvent } from 'ws'\nimport type { Maybe } from 'src/types/index.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\ntype Message = string | Buffer\n\ntype WsDebugMessage = {\n type: 'info' | 'error'\n timestamp: number\n message: string\n}\n\nexport class ResilientWebSocketClient {\n // private protocols?: string | string[]\n private url: string\n private currentWS?: Maybe<WebSocket>\n private messageBuffer: Message[] = []\n\n isOpen: boolean = false\n debugMessages: WsDebugMessage[] = []\n\n private addInfo(msg: string): void {\n this.debugMessages.push({ type: 'info', timestamp: Date.now(), message: msg })\n logInfo(`[🧦] WS: ${msg}`)\n }\n\n private addError(err: string): void {\n this.debugMessages.push({ type: 'error', timestamp: Date.now(), message: err })\n console.error('[🧦] WS:', err)\n }\n\n constructor(\n public options: {\n url: () => string /*protocols?: string | string[]*/\n onMessage: (event: MessageEvent) => void\n onConnectOrReconnect: () => void\n onClose: () => void\n },\n ) {\n this.url = options.url()\n this.connect()\n }\n\n private reconnectTimeout?: Maybe<NodeJS.Timeout>\n private permanentlyClosed: boolean = false\n\n /** close and stop reconnecting (lets a script exit cleanly) */\n disconnectPermanently(): void {\n this.permanentlyClosed = true\n if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)\n this.currentWS?.close()\n this.currentWS = null\n this.isOpen = false\n }\n\n private connect(): void {\n this.isOpen = false\n const prevWS = this.currentWS\n\n // cleanup a possible re-connection timeout for an other url\n if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)\n\n this.currentWS = null\n if (prevWS) {\n this.addInfo('Previous WebSocket discarded')\n prevWS.close()\n }\n const ws = new WebSocket(this.url)\n ws.binaryType = 'arraybuffer'\n\n this.currentWS = ws\n\n if (this.options.onMessage) {\n ws.onmessage = (event: MessageEvent): void => {\n this.options.onMessage(event)\n }\n }\n\n ws.onopen = (_event: Event): void => {\n if (ws !== this.currentWS) return\n this.addInfo('✅ WebSocket connected to ' + this.url)\n this.isOpen = true\n this.options.onConnectOrReconnect()\n this.flushMessageBuffer()\n }\n\n ws.onclose = (event: CloseEvent): void => {\n if (ws !== this.currentWS) return\n this.isOpen = false\n this.options.onClose()\n if (this.permanentlyClosed) return\n this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`)\n this.addInfo('⏱️ reconnecting in 2 seconds...')\n this.reconnectTimeout = setTimeout(() => this.connect(), 2000)\n }\n\n ws.onerror = (event: Event): void => {\n if (ws !== this.currentWS) return\n this.addError(`WebSocket ERROR` + JSON.stringify(event))\n console.error({ event })\n }\n }\n\n public send(message: Message): void {\n if (this.isOpen) {\n this.currentWS?.send(message)\n } else {\n this.messageBuffer.push(message)\n }\n }\n\n private flushMessageBuffer(): void {\n while (this.messageBuffer.length > 0) {\n const message = bang(this.messageBuffer.shift())\n this.currentWS?.send(message)\n }\n }\n\n /** forward WebSocket add event listeners to the current WebSocket instance */\n public addEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener:\n | ((event: WebSocket.WebSocketEventMap[K]) => void)\n | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },\n options?: WebSocket.EventListenerOptions,\n ): void {\n this.currentWS?.addEventListener(type, listener, options)\n }\n\n /** forward WebSocket remove event listeners to the current WebSocket instance */\n public removeEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener:\n | ((event: WebSocket.WebSocketEventMap[K]) => void)\n | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },\n ): void {\n this.currentWS?.removeEventListener(type, listener)\n }\n}\n\ntype WebSocketEventMap = {\n open: Event\n close: CloseEvent\n error: Event\n message: MessageEvent\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { observable, runInAction } from 'mobx'\nimport { dirname, join } from 'pathe'\nimport { logError } from 'src/utils/log.ts'\n\n/**\n * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras\n * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at\n * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data\n * and must survive a cache wipe). Observable map: overlay rows re-render on\n * assignment. Keys are the RAW lora names (folder/file.safetensors).\n */\nconst keywords = observable.map<string, string>()\nlet loaded = false\n\nfunction filePath(): string {\n return join(comfyts.baseFolder, 'lora-keywords.json')\n}\n\nfunction loadOnce(): void {\n if (loaded) return\n loaded = true\n const path = filePath()\n if (!existsSync(path)) return\n try {\n const raw: unknown = JSON.parse(readFileSync(path, 'utf8'))\n if (raw == null || typeof raw !== 'object') return\n runInAction(() => {\n for (const [name, kw] of Object.entries(raw)) if (typeof kw === 'string') keywords.set(name, kw)\n })\n } catch (e) {\n logError(`[loraKeywords] unreadable ${path}: ${String(e)}`)\n }\n}\n\nexport function getLoraKeyword(name: string): string {\n loadOnce()\n return keywords.get(name) ?? ''\n}\n\n/** empty keyword deletes the entry; every set writes the file (tiny, rare) */\nexport function setLoraKeyword(name: string, keyword: string): void {\n loadOnce()\n const trimmed = keyword.trim()\n runInAction(() => {\n if (trimmed === '') keywords.delete(name)\n else keywords.set(name, trimmed)\n })\n const path = filePath()\n try {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2))\n } catch (e) {\n logError(`[loraKeywords] write failed ${path}: ${String(e)}`)\n }\n}\n","// Vars: the standard \"tweak & re-run\" contract. A workflow defined via\n// host.defineWorkflow({ vars, build }) rebuilds its graph from current var\n// values on every run — drivers (scripts, the TUI) edit vars between runs.\nimport { action, makeObservable, observable } from 'mobx'\nimport { getLoraKeyword } from 'src/vars/loraKeywords.ts'\n\nexport type VarKind = 'text' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size'\n\n/**\n * full base: T is what's STORED/edited, Out what the GRAPH consumes at build\n * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is\n * the one Out-specialized var (string in, PromptValue out); the split keeps\n * outValue() cast-free.\n */\nexport abstract class ComfyVarBase<T, Out> {\n abstract readonly kind: VarKind\n value: T\n constructor(\n public readonly defaultValue: T,\n public label?: string,\n ) {\n this.value = defaultValue\n // observable value: the TUI (mobx) re-renders when drivers mutate vars.\n // explicit makeObservable (not makeAutoObservable): base-class + subclass\n // combo. All mutators funnel through set()/reset()/parse() so they are\n // actions — subclass helpers call this.set(...) rather than assigning.\n makeObservable(this, { value: observable, set: action, reset: action, parse: action, loadJSON: action })\n }\n set(value: T): this {\n this.value = value\n return this\n }\n /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */\n toJSON(): unknown {\n return this.value\n }\n /** what the GRAPH consumes at build time (varValues maps these return types) */\n abstract outValue(): Out\n /**\n * restore a value produced by toJSON() (drafts). The cast is sanctioned:\n * drafts are our own round-trip, subclasses re-validate via set().\n */\n loadJSON(value: unknown): this {\n return this.set(value as T)\n }\n reset(): this {\n this.value = this.defaultValue\n return this\n }\n /** parse a raw string (TUI text input) into this var's value; returns false when invalid */\n abstract parse(raw: string): boolean\n /** how the value renders in a var list */\n display(): string {\n return String(this.value)\n }\n /** the string the inline editor starts from (round-trips through parse) */\n toEditBuffer(): string {\n return String(this.value)\n }\n /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */\n afterRun(): void {}\n}\n\n/** the standard var: the graph consumes the stored value AS-IS (Out = T) */\nexport abstract class ComfyVar<T> extends ComfyVarBase<T, T> {\n outValue(): T {\n return this.value\n }\n}\n\nexport class TextVar extends ComfyVar<string> {\n readonly kind = 'text' as const\n parse(raw: string): boolean {\n this.set(raw)\n return true\n }\n}\n\nconst commentLineRe = /^\\s*\\/\\//\nconst negativeLineRe = /^\\s*- (.*)$/\n\n/** what PromptVar needs from a loras var: covariant face, so LorasVar<'a'|'b'> fits */\nexport type ActiveLoraSource = { activeNames(): string[] }\n\n/** what a prompt CONTRIBUTES to build: `vars.prompt.positive` / `.negative` */\nexport type PromptValue = { positive: string; negative: string }\n\n/**\n * prompt text with editor comforts, all resolved at BUILD time (the editor and\n * drafts keep the raw text):\n * - `//` lines are COMMENTS — stripped\n * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,\n * comma-joined into `.negative`\n * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords\n * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —\n * `injectedKeywords()` is public so the TUI can PREVIEW the injection.\n */\nexport class PromptVar extends ComfyVarBase<string, PromptValue> {\n readonly kind = 'text' as const\n constructor(\n defaultValue: string,\n public promptOpts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {},\n ) {\n super(defaultValue, promptOpts.label)\n }\n parse(raw: string): boolean {\n this.set(raw)\n return true\n }\n static isCommentLine(line: string): boolean {\n return commentLineRe.test(line)\n }\n static isNegativeLine(line: string): boolean {\n return negativeLineRe.test(line)\n }\n /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */\n injectedKeywords(): string[] {\n const src = this.promptOpts.loraKeywordsFrom\n if (src == null) return []\n return [\n ...new Set(\n src\n .activeNames()\n .map(getLoraKeyword)\n .filter((k) => k !== ''),\n ),\n ]\n }\n outValue(): PromptValue {\n const pos: string[] = []\n const neg: string[] = []\n for (const line of this.value.split('\\n')) {\n if (commentLineRe.test(line)) continue\n const m = negativeLineRe.exec(line)\n if (m != null) {\n const text = (m[1] ?? '').trim()\n if (text !== '') neg.push(text)\n } else pos.push(line)\n }\n const body = pos.join('\\n').trim()\n const keywords = this.injectedKeywords()\n const positive =\n keywords.length === 0 ? body : body === '' ? keywords.join(', ') : `${keywords.join(', ')}, ${body}`\n return { positive, negative: neg.join(', ') }\n }\n}\n\nexport class IntVar extends ComfyVar<number> {\n readonly kind = 'int' as const\n constructor(\n defaultValue: number,\n public opts: { min?: number; max?: number; label?: string } = {},\n ) {\n super(defaultValue, opts.label)\n }\n override set(value: number): this {\n const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)))\n return super.set(clamped)\n }\n parse(raw: string): boolean {\n const n = Number(raw)\n if (Number.isNaN(n)) return false\n this.set(n)\n return true\n }\n}\n\nexport class FloatVar extends ComfyVar<number> {\n readonly kind = 'float' as const\n constructor(\n defaultValue: number,\n public opts: { min?: number; max?: number; label?: string } = {},\n ) {\n super(defaultValue, opts.label)\n }\n override set(value: number): this {\n return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)))\n }\n parse(raw: string): boolean {\n const n = Number(raw)\n if (Number.isNaN(n)) return false\n this.set(n)\n return true\n }\n}\n\n/** '=' fixed · '+' increment each run · '-' decrement each run · '?' reroll each run */\nexport type SeedMode = '=' | '+' | '-' | '?'\n\n/**\n * a seed is a MODE + a number. `value` stays a plain number (what the graph\n * consumes); `mode` decides how it advances after each run (afterRun()):\n * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.\n * The number shown is always the seed the NEXT run will use.\n */\nexport class SeedVar extends ComfyVar<number> {\n readonly kind = 'seed' as const\n mode: SeedMode = '='\n constructor(defaultValue: number = 0, label?: string) {\n super(defaultValue, label)\n // subclass-owned observable field (base makeObservable already ran in super)\n makeObservable(this, { mode: observable, setMode: action, randomize: action, advance: action })\n }\n setMode(mode: SeedMode): this {\n this.mode = mode\n return this\n }\n randomize(): this {\n return this.set(Math.floor(Math.random() * 2 ** 32))\n }\n override set(value: number): this {\n // seeds are unsigned: clamp at 0 so decrement can't go negative\n return super.set(Math.max(0, Math.floor(value)))\n }\n /** move the seed to what the NEXT run should use, per mode */\n advance(): this {\n if (this.mode === '+') return this.set(this.value + 1)\n if (this.mode === '-') return this.set(this.value - 1)\n if (this.mode === '?') return this.randomize()\n return this // '=' stays fixed\n }\n override afterRun(): void {\n this.advance()\n }\n /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */\n parse(raw: string): boolean {\n const m = raw.trim().match(/^([+\\-=?])?\\s*(\\d+)?$/)\n if (m == null) return false\n const modeChar = m[1]\n const numStr = m[2]\n if (modeChar == null && numStr == null) return false\n this.setMode(modeChar == null ? '=' : (modeChar as SeedMode))\n if (numStr != null) this.set(Number(numStr))\n return true\n }\n override display(): string {\n return `${this.mode} ${this.value}`\n }\n override toEditBuffer(): string {\n return `${this.mode} ${this.value}`\n }\n override toJSON(): unknown {\n return { mode: this.mode, value: this.value }\n }\n override loadJSON(value: unknown): this {\n if (typeof value === 'number') return this.set(value) // legacy plain-number drafts\n if (value != null && typeof value === 'object') {\n const o = value as { mode?: unknown; value?: unknown }\n if (o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?') this.setMode(o.mode)\n if (typeof o.value === 'number') this.set(o.value)\n }\n return this\n }\n}\n\nexport class ToggleVar extends ComfyVar<boolean> {\n readonly kind = 'toggle' as const\n toggle(): this {\n return this.set(!this.value)\n }\n parse(raw: string): boolean {\n if (raw !== 'true' && raw !== 'false') return false\n this.set(raw === 'true')\n return true\n }\n override display(): string {\n return this.value ? 'ON' : 'OFF'\n }\n}\n\nexport class ChoiceVar<T extends string> extends ComfyVar<T> {\n readonly kind = 'choice' as const\n constructor(\n public readonly choices: readonly T[],\n defaultValue: T,\n label?: string,\n ) {\n super(defaultValue, label)\n }\n next(delta: number = 1): this {\n const ix = this.choices.indexOf(this.value)\n const nextIx = (ix + delta + this.choices.length) % this.choices.length\n return this.set(this.choices[nextIx] ?? this.value)\n }\n parse(raw: string): boolean {\n const hit = this.choices.find((c) => c === raw)\n if (hit == null) return false\n this.set(hit)\n return true\n }\n}\n\n/**\n * per-lora setting: false = off, true = 1/1, number = both strengths,\n * [strength_model, strength_clip] = each explicitly\n */\nexport type LoraStrength = boolean | number | [strengthModel: number, strengthClip: number]\n\nexport type ActiveLora<T extends string> = { lora_name: T; strength_model: number; strength_clip: number }\n\n/** normalize a loras record into what a standard LoraLoader chain consumes */\nexport function activeLoras<T extends string>(loras: Partial<Record<T, LoraStrength>>): ActiveLora<T>[] {\n const out: ActiveLora<T>[] = []\n for (const [lora_name, s] of Object.entries(loras) as [T, LoraStrength | undefined][]) {\n if (s == null || s === false) continue\n const [strength_model, strength_clip] = Array.isArray(s) ? s : s === true ? [1, 1] : [s, s]\n out.push({ lora_name, strength_model, strength_clip })\n }\n return out\n}\n\n/** what LorasVar.bindHost needs — structural, so ComfyVars never imports ComfyHost */\nexport type LorasHost = { schema: { getLoras(filter?: RegExp): string[] } }\n\n/**\n * multi-select lora stack over a DYNAMIC options list — a RegExp resolves\n * against the host's loras at define time (DefinedWorkflow calls bindHost),\n * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never\n * a hardcoded inventory. Selection is empty by default.\n */\nexport class LorasVar<T extends string> extends ComfyVar<Partial<Record<T, LoraStrength>>> {\n readonly kind = 'loras' as const\n /** last non-false strength per lora, so untick → re-tick restores it */\n private prev: Partial<Record<T, LoraStrength>> = {}\n /** a RegExp source resolves lazily (bindHost) — null until then */\n private resolvedOptions: readonly T[] | null = null\n\n constructor(\n private readonly optionsSource: readonly T[] | RegExp,\n initial: Partial<Record<T, LoraStrength>> = {},\n label?: string,\n ) {\n super(initial, label)\n }\n\n get options(): readonly T[] {\n if (!(this.optionsSource instanceof RegExp)) return this.optionsSource\n if (this.resolvedOptions == null)\n throw new Error(\n `v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`,\n )\n return this.resolvedOptions\n }\n\n /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.\n * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime\n * values of the SAME object_info enum the generated E_LoraName union comes from */\n bindHost(host: LorasHost): void {\n if (!(this.optionsSource instanceof RegExp)) return\n this.resolvedOptions = host.schema.getLoras(this.optionsSource) as T[]\n }\n\n get names(): T[] {\n return [...this.options]\n }\n\n /** loras currently ON (PromptVar keyword prefixing consumes this) */\n activeNames(): T[] {\n return this.names.filter((n) => this.isOn(n))\n }\n\n isOn(name: T): boolean {\n const s = this.value[name]\n return s != null && s !== false\n }\n\n toggleItem(name: T): this {\n const cur = this.value[name]\n if (cur == null || cur === false) return this.set({ ...this.value, [name]: this.prev[name] ?? true })\n this.prev[name] = cur\n return this.set({ ...this.value, [name]: false })\n }\n\n /** step both strengths by delta (true becomes 1 first); no-op when off */\n adjustItem(name: T, delta: number): this {\n const cur = this.value[name]\n if (cur == null || cur === false) return this\n const step = (n: number): number => Math.max(0, Math.round((n + delta) * 100) / 100)\n const next: LoraStrength = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur)\n return this.set({ ...this.value, [name]: next })\n }\n\n /** compact per-item strength label for lists */\n strengthLabel(name: T): string {\n const s = this.value[name]\n if (s == null || s === false) return ''\n if (s === true) return '1.00'\n if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`\n return s.toFixed(2)\n }\n\n parse(raw: string): boolean {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed !== 'object' || parsed == null || Array.isArray(parsed)) return false\n this.set(parsed as Partial<Record<T, LoraStrength>>)\n return true\n } catch {\n return false\n }\n }\n\n /** short human name: subfolder + extension stripped */\n static shortName(name: string): string {\n return (name.split(/[\\\\/]/).pop() ?? name).replace(/\\.safetensors$/, '')\n }\n\n /** tick (true) or untick (false) every lora in `names` (default: all options) */\n setAll(on: boolean, names: readonly T[] = this.options): this {\n const next = { ...this.value }\n for (const name of names) {\n const cur = next[name]\n if (on) {\n if (cur == null || cur === false) next[name] = this.prev[name] ?? true\n } else {\n if (cur != null && cur !== false) this.prev[name] = cur\n next[name] = false\n }\n }\n return this.set(next)\n }\n\n override display(): string {\n const on = this.activeNames()\n if (on.length === 0) return `(0/${this.options.length}) none`\n return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(', ')}`\n }\n}\n\nexport type SizeValue = { width: number; height: number }\nexport type SizePreset = { label: string; width: number; height: number }\n\n/** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */\nexport const DEFAULT_SIZE_PRESETS: SizePreset[] = [\n { label: '1:1 square', width: 1024, height: 1024 },\n { label: '4:3 landscape', width: 1152, height: 896 },\n { label: '3:4 portrait', width: 896, height: 1152 },\n { label: '3:2 landscape', width: 1216, height: 832 },\n { label: '2:3 portrait', width: 832, height: 1216 },\n { label: '16:9 widescreen', width: 1344, height: 768 },\n { label: '9:16 tall', width: 768, height: 1344 },\n]\n\n/** width/height picker: presets + free `WxH` entry */\nexport class SizeVar extends ComfyVar<SizeValue> {\n readonly kind = 'size' as const\n constructor(\n defaultValue: SizeValue = { width: 1024, height: 1024 },\n public readonly presets: SizePreset[] = DEFAULT_SIZE_PRESETS,\n label?: string,\n ) {\n super(defaultValue, label)\n }\n\n /** accepts '1024x768' / '1024×768' / a preset label */\n parse(raw: string): boolean {\n const m = raw.trim().match(/^(\\d+)\\s*[x×]\\s*(\\d+)$/)\n if (m != null) {\n this.set({ width: Number(m[1]), height: Number(m[2]) })\n return true\n }\n const preset = this.presets.find((p) => p.label === raw.trim())\n if (preset != null) {\n this.set({ width: preset.width, height: preset.height })\n return true\n }\n return false\n }\n\n override display(): string {\n const { width, height } = this.value\n const hit = this.presets.find((p) => p.width === width && p.height === height)\n return `${width}×${height}${hit ? ` (${hit.label})` : ''}`\n }\n}\n\n/** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size */\nexport const v = {\n text: (defaultValue: string, label?: string): TextVar => new TextVar(defaultValue, label),\n prompt: (defaultValue: string, opts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {}): PromptVar =>\n new PromptVar(defaultValue, opts),\n int: (defaultValue: number, opts: { min?: number; max?: number; label?: string } = {}): IntVar =>\n new IntVar(defaultValue, opts),\n float: (defaultValue: number, opts: { min?: number; max?: number; label?: string } = {}): FloatVar =>\n new FloatVar(defaultValue, opts),\n seed: (defaultValue: number = 0, label?: string): SeedVar => new SeedVar(defaultValue, label),\n toggle: (defaultValue: boolean, label?: string): ToggleVar => new ToggleVar(defaultValue, label),\n choice: <const T extends string>(choices: readonly T[], defaultValue: T, label?: string): ChoiceVar<T> =>\n new ChoiceVar(choices, defaultValue, label),\n loras: <T extends string = string>(\n options: readonly T[] | RegExp,\n initial: Partial<Record<T, LoraStrength>> = {},\n label?: string,\n ): LorasVar<T> => new LorasVar(options, initial, label),\n size: (defaultValue?: SizeValue, opts: { presets?: SizePreset[]; label?: string } = {}): SizeVar =>\n new SizeVar(defaultValue, opts.presets, opts.label),\n}\n\n/**\n * structural face of any var: readonly `value` keeps ComfyVar<T> assignable\n * despite T-invariance on the mutable field. VarValues re-derives the exact\n * value types via infer.\n */\nexport type AnyVar = {\n readonly kind: VarKind\n readonly value: unknown\n readonly label?: string\n parse(raw: string): boolean\n loadJSON(value: unknown): unknown\n toJSON(): unknown\n outValue(): unknown\n display(): string\n toEditBuffer(): string\n afterRun(): void\n /** host-dependent vars (LorasVar regex) resolve here — DefinedWorkflow calls it at define time */\n bindHost?(host: LorasHost): void\n}\n\nexport type VarsSpec = { [key: string]: AnyVar }\n\nexport type VarValues<V extends VarsSpec> = {\n // outValue() return type, not the stored type: PromptVar stores string, contributes PromptValue\n [K in keyof V]: V[K] extends { outValue(): infer O } ? O : never\n}\n\nexport function varValues<V extends VarsSpec>(vars: V): VarValues<V> {\n const out: Record<string, unknown> = {}\n // outValue, not value: PromptVar strips comments / prefixes lora keywords here\n for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue()\n return out as VarValues<V>\n}\n","import type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyWorkflow, RunSettings } from 'src/runner/ComfyWorkflow.ts'\nimport type { SdkForHost } from 'src/types/comfy-sdk.ts'\nimport {\n type AnyVar,\n type LorasVar,\n type LoraStrength,\n v,\n type VarsSpec,\n type VarValues,\n varValues,\n} from 'src/vars/ComfyVars.ts'\n\n/** the host's generated lora-name union (plain string when no sdk is generated) */\nexport type LoraNameOf<ID extends string> = 'E_LoraName' extends keyof SdkForHost<ID>['Union']\n ? SdkForHost<ID>['Union']['E_LoraName'] & string\n : string\n\n/**\n * the `v` handed to a vars LAMBDA: the global factory, host-typed —\n * `v.loras(regex)` yields the host's lora-name union (resolved via bindHost)\n */\nexport type BoundVars<ID extends string> = Omit<typeof v, 'loras'> & {\n loras(\n options: RegExp,\n initial?: Partial<Record<LoraNameOf<ID>, LoraStrength>>,\n label?: string,\n ): LorasVar<LoraNameOf<ID>>\n loras<T extends string>(\n options: readonly T[],\n initial?: Partial<Record<T, LoraStrength>>,\n label?: string,\n ): LorasVar<T>\n}\n\nexport type DefineWorkflowSpec<ID extends string, V extends VarsSpec> = {\n /** short id; also names the workflow instances */\n id?: string\n /** the tweakable knobs; drivers (scripts, TUI) edit these between runs.\n * A LAMBDA gives cross-referencing vars a scope (loras + prompt with\n * loraKeywordsFrom created inline) — resolved ONCE at define time, and it\n * RECEIVES the host-typed `v` (no import needed) */\n vars: V | ((v: BoundVars<ID>) => V)\n /** builds the graph from the CURRENT var values; re-executed on every run().\n * may be async (e.g. image uploads through the wf param) */\n build: (b: SdkForHost<ID>['Builder'], vars: VarValues<V>, wf: ComfyWorkflow<ID>) => void | Promise<void>\n}\n\n/** type predicate (not a cast): a VarsSpec is a plain record, never callable */\nfunction isVarsThunk<ID extends string, V extends VarsSpec>(\n vars: V | ((v: BoundVars<ID>) => V),\n): vars is (v: BoundVars<ID>) => V {\n return typeof vars === 'function'\n}\n\n/**\n * a re-runnable workflow definition: `build` re-executes per run with the\n * current var values, so every run gets a fresh, deterministic graph.\n */\nexport class DefinedWorkflow<ID extends string = string, V extends VarsSpec = VarsSpec> {\n /** spec.vars resolved once (may be given as a thunk) — the SAME instances for the workflow's lifetime */\n readonly vars: V\n\n constructor(\n public host: ComfyHost<ID>,\n public spec: DefineWorkflowSpec<ID, V>,\n ) {\n // cast: whitelist family 1 (agent/coding.md) — the runtime `v` IS the\n // factory BoundVars describes; the regex-loras typing claim it adds is\n // resolved from the same object_info enum via bindHost below\n this.vars = isVarsThunk(spec.vars) ? spec.vars(v as BoundVars<ID>) : spec.vars\n // host-dependent vars (v.loras(regex)) resolve NOW, at define time\n for (const [, varDef] of this.entries()) varDef.bindHost?.(this.host)\n }\n\n /** [name, var] pairs, for drivers that enumerate the knobs */\n entries(): [string, AnyVar][] {\n return Object.entries(this.vars)\n }\n\n /** the workflow built by the latest run() (null before the first run) */\n lastWorkflow: ComfyWorkflow<ID> | null = null\n /** the latest execution (null before the first run) */\n lastExecution: ComfyExecution | null = null\n\n /**\n * build a fresh graph from the CURRENT var values (no send). `p.advance`\n * (set by run()) fires each var's afterRun() right after snapshotting the\n * values — atomically, before any await — so the graph uses this run's seed\n * while the var moves to the next (queued runs get distinct seeds; a bare\n * build() for copy/export never advances).\n */\n async build(p: { advance?: boolean } = {}): Promise<ComfyWorkflow<ID>> {\n const wf = this.host.workflow({ id: this.spec.id })\n const values = varValues(this.vars)\n if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun()\n await this.spec.build(wf.builder, values, wf)\n this.lastWorkflow = wf\n return wf\n }\n\n /** build a fresh graph from the current var values, send it, wait for outputs.\n * connects first (idempotent) — modules can import offline from the schema cache */\n async run(settings: RunSettings = {}): Promise<ComfyExecution> {\n await this.host.connect()\n const wf = await this.build({ advance: true })\n const execution = await wf.run(settings)\n this.lastExecution = execution\n return execution\n }\n}\n","import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'\nimport { type } from 'arktype'\nimport type { MessageEvent } from 'ws'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'\nimport { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport {\n type ComfyStatusData,\n type LogEntry,\n type PromptID,\n type PromptRelated_WsMsg,\n type WsMsg,\n WsMsg_ark,\n WsMsgLogsData_ark,\n} from 'src/runner/ComfyWsApi.ts'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { EmbeddingName } from 'src/sdk-generator/comfyui-types.ts'\nimport { type AbsolutePath, type Maybe, type number_Timestamp, type Tagged } from 'src/types/index.ts'\nimport { exhaust } from 'src/utils/exhaust.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\nimport { logError as toastError, logInfo } from 'src/utils/log.ts'\nimport { writeFileAsync } from 'src/utils/writeFile.ts'\nimport type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'\nimport { ComfyManager } from 'src/host/ComfyManager.ts'\nimport { ComfyUploader } from 'src/host/ComfyUploader.ts'\nimport type { Requirements } from 'src/host/Requirements.ts'\nimport { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'\nimport { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'\nimport type { VarsSpec } from 'src/vars/ComfyVars.ts'\n\nexport type ComfyHostID = Tagged<string, { HostID: true }>\nexport type ComfyHostData = {\n id: string\n host: string\n port: number\n https?: boolean\n\n // for extra features using path manipulation\n installType?: ComfyInstallType\n\n // misc\n onWsMessageAny?: (e: MessageEvent) => void\n onWsMessageArrayBuffer?: (e: ArrayBuffer) => void\n onWsMessageJSON?: (e: WsMsg) => void\n}\n\nexport type ConnectOptions = {\n /** 'auto' (default): reuse cache when fresh · 'refresh': always fetch · 'cache': never fetch */\n schema?: 'auto' | 'refresh' | 'cache'\n /** max cache age for 'auto' (default 24h) */\n maxAgeMs?: number\n}\n\n// biome-ignore format: misc\ntype SchemaUpdateResult = Maybe<{ type: 'success' } | { type: 'error'; error: unknown }>\n\ntype ServerLog = {\n at: string\n content: string\n id: number\n}\n\nexport class ComfyHost<ID extends string = string> {\n // ----- misc paths where we'll store host-related files -----\n cacheFolder: AbsolutePath\n\n comfyJSONPath: AbsolutePath\n embeddingsPath: AbsolutePath\n sdkDTSPath: AbsolutePath\n\n /** the schema instance with all methods to interract with the host schema */\n schema: ComfySchema\n uploader = new ComfyUploader(this)\n\n constructor(public data: ComfyHostData & { id: ID }) {\n /** folder where file related to the host config will be cached */\n this.cacheFolder = comfyts.resolveFromHosts(this.data.id)\n\n // create the folder if it does not exist\n const exists = existsSync(this.cacheFolder)\n if (!exists) {\n console.log('🟢 creating folder', this.cacheFolder)\n mkdirSync(this.cacheFolder, { recursive: true })\n }\n\n this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)\n this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`)\n this.sdkDTSPath = comfyts.resolve(this.cacheFolder, `sdk.d.ts`)\n\n /** create a new schema */\n this.schema = new ComfySchema({ embeddings: [], spec: {} })\n }\n\n /** helper to check if your host have whatever it needs to run your workflow */\n matchRequirements = (requirements: Requirements[]): boolean => {\n const repo = comfyts.registry\n for (const req of requirements) {\n if (req.optional) continue\n if (req.type === 'customNodesByNodeKey') {\n const plugins: ComfyManagerPluginInfo[] = repo.plugins_byNodeKey.get(req.nodeName) ?? []\n if (!plugins.find((i) => this.manager.isPluginInstalled(i.title))) {\n // console.log(`[❌ A] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'customNodesByTitle') {\n const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byTitle.get(req.title)\n if (plugin == null) continue\n if (!this.manager.isPluginInstalled(plugin.title)) {\n // console.log(`[❌ B] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'customNodesByURI') {\n const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byFile.get(req.uri)\n if (plugin == null) continue\n if (!this.manager.isPluginInstalled(plugin.title)) {\n // console.log(`[❌ C] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'modelInManager') {\n if (!this.manager.isModelInstalled(req.modelName)) {\n // console.log(`[❌ D] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else {\n // exhaust(req.type)\n }\n }\n return true\n }\n\n // ----- Rotating srever logs -----\n\n /** server sent by the comfy-manager plugin */\n readonly serverLogs: ServerLog[] = []\n\n /** if true, request ComfyUI to forward logs */\n private wantLog: boolean = true\n\n /** maximum amount of logs to keep in memory */\n readonly maxLogs: number = 200\n\n /** last log id received */\n private logId: number = 0\n\n /** toggle server log forwarding so comfy-ts can */\n toggleServerLogs = (): Promise<unknown> => {\n this.wantLog = !this.wantLog\n return this.manager.configureLogging(this.wantLog)\n }\n\n addLog = (content: string): void => {\n if (this.serverLogs.length > this.maxLogs) this.serverLogs.shift()\n const d = new Date().toISOString().slice(11, 19)\n this.serverLogs.push({ content, id: this.logId++, at: d })\n }\n\n // ----- Misc helpers if you work with a local Comfy -----\n\n /** root install of ComfyUI on the host filesystem */\n get absolutePathToComfyUI(): Maybe<string> {\n return this.data.installType?.absolutePathToComfyRoot\n }\n\n // ----- Misc helpers if you work with a local Comfy -----\n\n get manager(): ComfyManager {\n const value = new ComfyManager(this)\n Object.defineProperty(this, 'manager', { value })\n return value\n }\n\n // INIT -----------------------------------------------------------------------------\n installCustomNodeByFile = async (customNodeFile: KnownComfyPluginURL): Promise<boolean> => {\n const manager = comfyts.registry\n const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byFile.get(customNodeFile)\n if (plugin == null) throw new Error(`Unknown custom node for file: \"${customNodeFile}\"`)\n return this.manager.installPlugin(plugin)\n }\n\n installCustomNodeByTitle = async (customNodeTitle: KnownComfyPluginTitle): Promise<boolean> => {\n const manager = comfyts.registry\n const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byTitle.get(customNodeTitle)\n if (plugin == null) throw new Error(`Unknown custom node for title: \"${customNodeTitle}\"`)\n return this.manager.installPlugin(plugin)\n }\n\n installCustomNode = async (customNode: ComfyManagerPluginInfo): Promise<boolean> => {\n return this.manager.installPlugin(customNode)\n }\n\n // URLS -----------------------------------------------------------------------------\n getServerHostHTTP(): string {\n const method = this.data.https ? 'https' : 'http'\n const host = this.data.host\n const port = this.data.port\n return `${method}://${host}:${port}`\n }\n\n getWSUrl = (): string => {\n const method = this.data.https ? 'wss' : 'ws'\n const host = this.data.host\n const port = this.data.port\n return `${method}://${host}:${port}/ws`\n }\n\n // LOGS -----------------------------------------------------------------------------\n schemaRetrievalLogs: string[] = []\n\n resetLog = (): void => {\n this.schemaRetrievalLogs.splice(0, this.schemaRetrievalLogs.length)\n }\n\n // STARTING -----------------------------------------------------------------------------\n get isConnected(): boolean {\n return this.ws?.isOpen ?? false\n }\n\n workflow = (p: { id?: string } = {}): ComfyWorkflow<ID> => {\n return new ComfyWorkflow(this, {\n metadata: {},\n id: p.id ? asComfyWorkflowID(p.id) : undefined,\n })\n }\n\n /**\n * define a re-runnable workflow: `build` re-executes with the current var\n * values on every run(). The standard contract for tweak & re-run drivers\n * (scripts, the TUI).\n */\n defineWorkflow = <V extends VarsSpec>(spec: DefineWorkflowSpec<ID, V>): DefinedWorkflow<ID, V> => {\n return new DefinedWorkflow(this, spec)\n }\n\n /** import a workflow.json (litegraph format) as a live, editable workflow */\n importWorkflowJson = (json: LiteGraphJSON, p: { id?: string } = {}): ComfyWorkflow<ID> => {\n const apiJson = convertLiteGraphToPrompt(this.schema, json)\n return this.importApiJson(apiJson, p)\n }\n\n /** import an api.json (ComfyUI prompt format) as a live, editable workflow */\n importApiJson = (json: ComfyApiJson, p: { id?: string } = {}): ComfyWorkflow<ID> => {\n const wf = new ComfyWorkflow(this, {\n apiJson: json,\n metadata: {},\n id: p.id ? asComfyWorkflowID(p.id) : undefined,\n })\n wf.onUpdate(null, wf.data) // hydrate ComfyNode instances from the json\n return wf\n }\n\n private _ready: Promise<void> | null = null\n private _readyResolve: (() => void) | null = null\n private _readyReject: ((e: unknown) => void) | null = null\n private _schemaStrategy: NonNullable<ConnectOptions['schema']> = 'auto'\n private _schemaMaxAgeMs: number = 24 * 3600_000\n\n /**\n * open the websocket; resolves once connected AND the schema is loaded.\n * Schema strategy:\n * - 'auto' (default): reuse .comfy-ts/ cache when younger than maxAgeMs — fast starts\n * - 'refresh': always fetch object_info + regen the sdk\n * - 'cache': never fetch (throws when no cache exists)\n */\n connect = (p: ConnectOptions = {}): Promise<void> => {\n if (this._ready == null) {\n this._schemaStrategy = p.schema ?? 'auto'\n this._schemaMaxAgeMs = p.maxAgeMs ?? 24 * 3600_000\n this._ready = new Promise<void>((res, rej) => {\n this._readyResolve = res\n this._readyReject = rej\n })\n this.initWebsocket()\n }\n return this._ready\n }\n\n /** close the websocket (e.g. to let a script exit) */\n disconnect = (): void => {\n this.ws?.disconnectPermanently()\n this.ws = null\n this._ready = null\n }\n\n private markReady(): void {\n this._readyResolve?.()\n this._readyResolve = null\n this._readyReject = null\n }\n\n private markFailed(error: unknown): void {\n // reject the pending connect() so callers fail fast instead of hanging\n this._readyReject?.(error)\n this._readyResolve = null\n this._readyReject = null\n }\n\n private async writeSDKToDisk(): Promise<void> {\n const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })\n // skip the 4MB write when nothing changed (fast re-connects)\n if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return\n await writeFileAsync(this.sdkDTSPath, comfySchemaTs, 'utf-8')\n }\n\n private shouldUseSchemaCache(): boolean {\n if (this._schemaStrategy === 'refresh') return false\n const exists = existsSync(this.comfyJSONPath)\n if (this._schemaStrategy === 'cache') {\n if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)\n return true\n }\n if (!exists) return false\n const ageMs = Date.now() - statSync(this.comfyJSONPath).mtimeMs\n return ageMs < this._schemaMaxAgeMs\n }\n\n // WEBSCKET -----------------------------------------------------------------------------\n /**\n * will be created only after we've loaded cnfig file\n * so we don't attempt to connect to some default server\n * */\n ws: Maybe<ResilientWebSocketClient> = null\n\n /** resolves once the server assigned us a session id (first ws 'status' message) */\n private _sessionResolve: (() => void) | null = null\n private waitForSession(timeoutMs: number = 5000): Promise<void> {\n if (this.comfySessionId !== 'temp') return Promise.resolve()\n return new Promise<void>((res) => {\n this._sessionResolve = res\n // some setups never send a sid — proceed after the timeout, loudly\n setTimeout(() => {\n if (this._sessionResolve != null) {\n console.error(\n `🔴 no session id from ${this.data.id} after ${timeoutMs}ms — executions may not route back`,\n )\n this._sessionResolve = null\n res()\n }\n }, timeoutMs).unref?.()\n })\n }\n\n private initWebsocket(): ResilientWebSocketClient {\n logInfo(`[👢] WEBSOCKET: starting client to ComfyUI host ${this.data.id}`)\n this.ws = new ResilientWebSocketClient({\n onConnectOrReconnect: async (): Promise<void> => {\n logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)\n if (this.shouldUseSchemaCache()) {\n try {\n await this.loadSchemaFromCache()\n // the server routes execution events by client_id: without the\n // session id from the first 'status' message, prompts we POST\n // would report to nobody. The slow fetch path masked this race.\n await this.waitForSession()\n this.markReady()\n return\n } catch (error) {\n console.error(`🔴 schema cache load failed, falling back to fetch`, extractErrorMessage(error))\n }\n }\n await this.fetchAndUpdateSchema()\n await this.waitForSession()\n this.markReady()\n },\n onMessage: (e: MessageEvent): void => this.onMessage(e),\n url: () => this.getWSUrl(),\n onClose: (): void => {\n logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)\n },\n })\n return this.ws\n }\n\n _isUpdatingSchema: boolean = false\n get isUpdatingSchema(): boolean {\n return this._isUpdatingSchema\n }\n set isUpdatingSchema(v: boolean) {\n this._isUpdatingSchema = v\n }\n\n schemaUpdateResult: SchemaUpdateResult = null\n\n private _schemaFromCache: Promise<void> | null = null\n\n /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).\n * idempotent like connect(): N co-imported modules parse the ~4MB cache once */\n loadSchemaFromCache(): Promise<void> {\n this._schemaFromCache ??= (async (): Promise<void> => {\n const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)\n const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])\n\n // update schema\n this.schema.update({ spec: object_info_json, embeddings: embeddings_json })\n this.schema.RUN_BASIC_CHECKS()\n\n // the on-disk sdk was generated from this same cache — only write when missing\n if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk()\n })().catch((e: unknown) => {\n this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)\n throw e\n })\n return this._schemaFromCache\n }\n\n /** POST a JSON route, preferring the /api prefix, falling back to the bare route */\n private postJSON_ = async (route: string, body: unknown): Promise<void> => {\n const base = this.getServerHostHTTP()\n for (const url of [`${base}/api${route}`, `${base}${route}`]) {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (res.ok) return\n }\n throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`)\n }\n\n /** drop every PENDING prompt from the server queue (the running one keeps going) */\n clearQueue = (): Promise<void> => {\n return this.postJSON_('/queue', { clear: true })\n }\n\n /** interrupt the CURRENTLY RUNNING prompt */\n interrupt = (): Promise<void> => {\n return this.postJSON_('/interrupt', {})\n }\n\n // SERVER LOGS ----------------------------------------------------------------------\n // /internal routes are served bare (no /api prefix, no custom-node hijacks)\n\n /** the server's recent console buffer (entries are write CHUNKS, not lines) */\n fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {\n const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`)\n if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)\n const json: unknown = await res.json()\n // wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast\n const checked = WsMsgLogsData_ark(json)\n if (checked instanceof type.errors) {\n console.log(`[🔴] /!\\\\ /internal/logs/raw payload does not match schema.`)\n printArkResultInConsole(checked)\n }\n return json as { entries: LogEntry[] }\n }\n\n /** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,\n * must be re-sent after every reconnect (see onSession) */\n subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {\n const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),\n })\n if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)\n }\n\n /** GET a JSON route, preferring the /api prefix, falling back to the bare route */\n private fetchJSON_ = async <T>(route: string): Promise<T> => {\n const base = this.getServerHostHTTP()\n for (const url of [`${base}/api${route}`, `${base}${route}`]) {\n const res = await fetch(url, { method: 'GET' })\n if (!res.ok) continue\n if (!(res.headers.get('content-type') ?? '').includes('json')) continue\n return (await res.json()) as T\n }\n throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`)\n }\n\n /** retrieve the comfy spec from the schema*/\n fetchAndUpdateSchema = async (): Promise<void> => {\n try {\n this.isUpdatingSchema = true\n // 1 ------------------------------------\n // download object_info (prefer /api/*: custom nodes hijack bare routes,\n // e.g. lora-manager serves HTML at /embeddings)\n const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')\n const object_info_str = readableStringify(object_info_json, 4)\n void writeFileAsync(this.comfyJSONPath, object_info_str, 'utf-8')\n // use ark to check if payload match the type, and display errors if not\n const res = ComfySchemaJSON_ark(object_info_json)\n if (res instanceof type.errors) {\n printArkResultInConsole(res)\n }\n\n // 2 ------------------------------------\n // download embeddings\n const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(\n () => [] as EmbeddingName[],\n )\n void writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), 'utf-8')\n\n // 3 ------------------------------------\n // update schema\n this.schema.update({ spec: object_info_json, embeddings: embeddings_json })\n this.schema.RUN_BASIC_CHECKS()\n\n // 3 ------------------------------------\n // regen sdk\n await this.writeSDKToDisk()\n this.isUpdatingSchema = false\n this.schemaUpdateResult = { type: 'success' }\n } catch (error) {\n this.isUpdatingSchema = false\n this.schemaUpdateResult = { type: 'error', error: error }\n\n console.error(error)\n console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))\n\n const schemaExists = existsSync(this.sdkDTSPath)\n if (!schemaExists) await this.writeSDKToDisk()\n this.markFailed(error)\n } finally {\n this.isUpdatingSchema = false\n }\n }\n\n /** executions we started */\n executions: Map<PromptID, ComfyExecution> = new Map()\n\n /** buffer in case we receive packets out of order */\n _pendingMsgs = new Map<PromptID, PromptRelated_WsMsg[]>()\n\n /** the active prompt currently running on this host */\n private activePromptID: PromptID | null = null\n\n /** method to either execute or buffer the incoming message */\n routeOrBuffer(prompt_id: PromptID, msg: PromptRelated_WsMsg): void {\n this.activePromptID = prompt_id\n const prompt = this.executions.get(prompt_id)\n\n // case 1. no prompt yet => just store the messages\n if (prompt == null) {\n const msgs = this._pendingMsgs.get(prompt_id)\n if (msgs) msgs.push(msg)\n else this._pendingMsgs.set(prompt_id, [msg])\n return\n }\n // case 2. prompt exists => send the messages\n prompt.onPromptRelatedMessage(msg)\n }\n\n /** the latent image beeing generated, in case you want to display it */\n latentPreview: Maybe<{\n promptID: Maybe<PromptID>\n receivedAt: number_Timestamp\n blob: Blob\n url: string\n }> = null\n\n /** byte-level latent-preview hook (e.g. TUI live preview panel) */\n onLatentPreview: Maybe<(p: { bytes: Uint8Array; mime: string; promptID: Maybe<PromptID> }) => void> = null\n\n /** fires on every ws 'status' message (queue length lives there) */\n onStatus: Maybe<(p: { queueRemaining: number }) => void> = null\n\n /** fires when the server assigns a NEW session id (first connect AND every\n * reconnect — per-sid server state like log subscriptions must be redone) */\n onSession: Maybe<(sid: string) => void> = null\n\n /** fires on ws 'logs' messages (server console stream, see subscribeLogs) */\n onLogs: Maybe<(p: { entries: LogEntry[] }) => void> = null\n\n /** the session assigned to us by the server */\n comfySessionId: string = 'temp' /** send by ComfyUI server */\n\n /** handy to keep around */\n status: ComfyStatusData['status'] | null = null\n\n onMessage(e: MessageEvent): void {\n if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)\n if (e.data instanceof ArrayBuffer) {\n // 🔴 console.log('[👢] WEBSOCKET: received ArrayBuffer', e.data)\n const view = new DataView(e.data)\n const eventType = view.getUint32(0)\n const buffer = e.data.slice(4)\n switch (eventType) {\n case 1: {\n const view2 = new DataView(e.data)\n const imageType = view2.getUint32(4)\n let imageMime: string\n switch (imageType) {\n case 1:\n imageMime = 'image/jpeg'\n break\n case 2:\n imageMime = 'image/png'\n break\n default:\n imageMime = 'image/jpeg'\n break\n }\n const imageBytes = buffer.slice(4)\n const imageBlob = new Blob([imageBytes], { type: imageMime })\n const imagePreview = URL.createObjectURL(imageBlob)\n this.latentPreview = {\n blob: imageBlob,\n url: imagePreview,\n receivedAt: Date.now() as number_Timestamp,\n promptID: this.activePromptID,\n }\n this.onLatentPreview?.({\n bytes: new Uint8Array(imageBytes),\n mime: imageMime,\n promptID: this.activePromptID,\n })\n break\n }\n default:\n throw new Error(`Unknown binary websocket message of type ${eventType}`)\n }\n return\n }\n\n const msg_: unknown = JSON.parse(String(e.data))\n\n // ----- crystools silent fix -----\n if (typeof msg_ === 'object' && msg_ != null && 'type' in msg_) {\n if (msg_.type === 'crystools.monitor') return\n }\n\n // ----- soft-validate against the schema -----\n const res = WsMsg_ark(msg_)\n if (res instanceof type.errors) {\n console.log(`[🔴] /!\\\\ Websocket payload does not match schema.`)\n printArkResultInConsole(res)\n }\n // wire tolerance (agent/coding.md): ComfyUI drifts faster than our schema;\n // failures are logged above, then we still route best-effort\n const msg = msg_ as WsMsg\n\n if (msg.type === 'status') {\n if (msg.data.sid) {\n const sidChanged = msg.data.sid !== this.comfySessionId\n this.comfySessionId = msg.data.sid\n this._sessionResolve?.()\n this._sessionResolve = null\n if (sidChanged) this.onSession?.(msg.data.sid)\n }\n this.status = msg.data.status\n this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })\n return\n }\n\n // defer accumulation to ScriptStep_prompt\n if (msg.type === 'progress') {\n const activePromptID = this.activePromptID\n if (activePromptID == null) {\n console.log(`❌ received a 'progress' msg, but activePromptID is not set`)\n return\n }\n this.routeOrBuffer(activePromptID, msg)\n return\n }\n if (\n msg.type === 'execution_start' ||\n msg.type === 'execution_cached' ||\n msg.type === 'execution_error' ||\n msg.type === 'execution_success' ||\n msg.type === 'executing' ||\n msg.type === 'executed' ||\n msg.type === 'progress_state'\n ) {\n this.routeOrBuffer(msg.data.prompt_id, msg)\n return\n }\n\n if (msg.type === 'manager-terminal-feedback') {\n this.addLog(msg.data.data)\n return\n }\n\n if (msg.type === 'logs') {\n this.onLogs?.(msg.data)\n return\n }\n exhaust(msg)\n console.log('❌', 'Unknown message:', msg)\n\n toastError('Unknown message type: ' + JSON.stringify(msg.type))\n // throw new Error('Unknown message type: ' + JSON.stringify(msg))\n }\n}\n","import fs, { mkdirSync } from 'node:fs'\nimport https from 'node:https'\nimport { stdout } from 'node:process'\nimport { dirname } from 'pathe'\nimport type { AbsolutePath } from 'src/types/index.ts'\n\n/** Usage example\n * | ;(async () => {\n * | try {\n * | await downloadFile('https://example.com/file', 'folder/filename')\n * | console.log('Download completed successfully')\n * | } catch (error) {\n * | console.error('Download failed:', error)\n * | }\n * | })()\n * |\n */\nexport function downloadFile(\n //\n url: string,\n outputPath: AbsolutePath | string,\n logPrefix = ' - ',\n): Promise<true> {\n const baseDir = dirname(outputPath)\n mkdirSync(baseDir, { recursive: true })\n\n return new Promise<true>((resolve, reject) => {\n const request = https.get(url, (response) => {\n // initial response --------------------------------------------\n // Check for redirect\n if (response.statusCode === 302 || response.statusCode === 301) {\n // Follow the redirect and call downloadFile recursively\n const newUrl = response.headers.location!\n console.log(`Redirected to ${newUrl}`)\n resolve(downloadFile(newUrl, outputPath))\n return\n }\n\n if (response.statusCode !== 200) {\n reject(`Failed to download file: Status Code ${response.statusCode}`)\n return\n }\n\n // progress --------------------------------------------------\n const rawLen = response.headers['content-length']\n if (rawLen == null) {\n console.warn(`download file: progress not available because no content-length header in response.`)\n } else {\n const totalSize = parseInt(rawLen, 10)\n let downloaded = 0\n let lastLoggedPercentage = 0\n\n response.on('data', (chunk) => {\n downloaded += chunk.length\n const percentage = Math.round((downloaded / totalSize) * 100)\n if (percentage >= lastLoggedPercentage + 1) {\n // console.log(`${percentage}% downloaded`)\n stdout.write(`\\r${logPrefix}${percentage}% downloaded`)\n lastLoggedPercentage = percentage\n }\n })\n }\n\n // file stream -------------------------------------------\n const fileStream = fs.createWriteStream(outputPath)\n response.pipe(fileStream)\n\n fileStream.on('finish', () => {\n console.log(` (DONE)`)\n fileStream.close()\n resolve(true)\n })\n })\n\n request.on('error', (err) => reject(err))\n })\n}\n","import { ansi as chalk } from 'src/utils/ansi.ts'\n\nimport { downloadFile } from 'src/utils/downloadFile.ts'\n\nexport async function DownloadComfyManagerJSONs(): Promise<void> {\n await SYNC_modelList()\n await SYNC_customNodeList()\n await SYNC_extensionNodeMap()\n await SYNC_alterList()\n await SYNC_githubStats()\n\n async function SYNC_modelList(): Promise<void> {\n await downloadFile(\n 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/model-list.json',\n 'src/manager/json/model-list.json',\n `- downloading ynchronizing model-list.json...`,\n )\n console.log(` saved at ${chalk.blue('src/manager/json/model-list.json')}`)\n }\n\n async function SYNC_customNodeList(): Promise<void> {\n await downloadFile(\n 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/custom-node-list.json',\n 'src/manager/json/custom-node-list.json',\n `- downloading synchronizing custom-node-list.json...`,\n )\n console.log(` saved at ${chalk.blue('src/manager/json/custom-node-list.json')}`)\n }\n\n async function SYNC_extensionNodeMap(): Promise<void> {\n await downloadFile(\n 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json',\n 'src/manager/json/extension-node-map.json',\n `- downloading synchronizing extension-node-map.json...`,\n )\n console.log(` saved at ${chalk.blue('src/manager/json/extension-node-map.json')}`)\n }\n\n async function SYNC_alterList(): Promise<void> {\n await downloadFile(\n 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/alter-list.json',\n 'src/manager/json/alter-list.json',\n `- downloading synchronizing alter-list.json...`,\n )\n console.log(` saved at ${chalk.blue('src/manager/json/alter-list.json')}`)\n }\n\n async function SYNC_githubStats(): Promise<void> {\n await downloadFile(\n 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/refs/heads/main/github-stats.json',\n 'src/manager/json/github-stats.json',\n `- downloading ynchronizing githubStats.json...`,\n )\n console.log(` saved at ${chalk.blue('src/manager/json/github-stats.json')}`)\n }\n}\n","export const githubRegexpV1 = /https:\\/\\/github.com\\/(.+?)\\/(.+?)\\/?/\nexport const githubRegexpV2 = /https:\\/\\/github.com\\/(.+?)\\/([a-zA-Z0-9-_]+)?/\n","import type { Maybe } from 'src/types/index.ts'\n\n/** quick utility to verbosely attempt various data recovery tricks */\nexport enum RecoveryVerbosity {\n Quiet = 0,\n info = 1,\n Verbose = 2,\n}\n\nexport function tryRecovering<T>({\n verbose = RecoveryVerbosity.Quiet,\n property,\n hacks,\n onFail,\n onSuccess,\n}: {\n verbose?: RecoveryVerbosity\n property: string\n hacks: {\n level?: RecoveryVerbosity\n attempt: string\n fn: () => Maybe<T>\n }[]\n onFail?: (propName: string) => void\n onSuccess?: (propName: string, value: T) => void\n}): T {\n if (verbose >= RecoveryVerbosity.Verbose) console.log(`[🔶] trying to find a suitable value for ${property}...`)\n\n for (const hack of hacks) {\n if (verbose >= RecoveryVerbosity.Verbose) console.log(` > trying to use ${hack.attempt}...`)\n const value = hack.fn()\n if (value != null) {\n if (verbose >= (hack.level ?? RecoveryVerbosity.info))\n if (verbose) console.log(` 🔶 recovered ${property} using ${hack.attempt}.`)\n onSuccess?.(property, value)\n return value\n }\n }\n onFail?.(property)\n throw new Error(`[🔶] ${property} could not be recovered`)\n}\n","import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const ComfyPluginExtra: ComfyManagerPluginInfo[] = [\n {\n id: 'TEMP_ComfyUI-BRIA_AI-RMBG',\n author: 'ZHO-ZHO-ZHO',\n title: 'TEMP_ComfyUI-BRIA_AI-RMBG',\n reference: 'https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG',\n files: ['https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG'],\n install_type: 'git-clone',\n description: 'better rembg ?',\n },\n]\n","import { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { ComfyManagerPluginID } from 'src/manager/types/ComfyManagerPluginEnums.ts'\n\nexport type ComfyManagerPluginInfo = typeof ComfyManagerPluginInfo_ark.infer\nexport const ComfyManagerPluginInfo_ark = type({\n // required\n author: 'string', // \"Dr.Lt.Data\",\n title: type.string.as<KnownComfyPluginTitle>(), // \"ComfyUI-Manager\",\n reference: 'string', // \"https://github.com/ltdrdata/ComfyUI-Manager\",\n files: type.string.as<KnownComfyPluginURL>().array(), // [\"https://github.com/ltdrdata/ComfyUI-Manager\"],\n install_type: 'string', // \"git-clone\",\n description: 'string', // \"ComfyUI-Manager itself is also a custom node.\"\n\n // optional, but shouldn't, so they'll pre-emptively auto-fixed before validation\n id: type.string.as<ComfyManagerPluginID>(), // on 2024-11-09, 579 fields are missing this\n\n // optional\n 'preemptions?': 'string[]',\n 'pip?': 'string[]',\n 'nodename_pattern?': 'string',\n 'apt_dependency?': 'string[]',\n 'js_path?': 'string',\n 'version?': 'string',\n\n // optional ?\n // (probably not really well specified, sicne some of those only appear one or two times)\n 'tags?': 'string[]', // 🔶 as of 2024-11-09, this shows only one time\n})\n\n// export type ComfyManagerPluginInfo = {\n// // required\n// author: string // \"Dr.Lt.Data\",\n// title: KnownComfyPluginTitle // \"ComfyUI-Manager\",\n// reference: string // \"https://github.com/ltdrdata/ComfyUI-Manager\",\n// files: KnownComfyPluginURL[] // [\"https://github.com/ltdrdata/ComfyUI-Manager\"],\n// install_type: string // \"git-clone\",\n// description: string // \"ComfyUI-Manager itself is also a custom node.\"\n\n// // optional, but shouldn't\n// // optional\n// id?: ComfyManagerPluginID // Added in 2024-??\n// preemptions?: string[] // ❓\n// pip?: string[] // [ \"ultralytics\" ],\n// nodename_pattern?: string // \"Inspire$\",\n// apt_dependency?: string[] // [ \"rustc\", \"cargo\" ],\n// js_path?: string // \"strimmlarn\",\n// version?: string\n// }\n","import { type } from 'arktype'\nimport { ComfyManagerPluginInfo_ark } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport type ComfyManagerFilePluginList = typeof ComfyManagerFilePluginList_ark.infer\nexport const ComfyManagerFilePluginList_ark = type({ custom_nodes: ComfyManagerPluginInfo_ark.array() })\n","import { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { readFileSync, writeFileSync } from 'fs'\nimport type { Maybe } from 'src/types/index.ts'\nimport { githubRegexpV1 } from 'src/utils/githubRegexes.ts'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\nimport { RecoveryVerbosity, tryRecovering } from 'src/utils/tryExtracting.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport { ComfyPluginExtra } from 'src/manager/json/custom-node-list.extra.ts'\nimport {\n type ComfyManagerFilePluginList,\n ComfyManagerFilePluginList_ark,\n} from 'src/manager/types/ComfyManagerFilePluginList.ts'\nimport type { ComfyManagerPluginID } from 'src/manager/types/ComfyManagerPluginEnums.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport type GetKnownPluginProps = {\n //\n updateCache?: boolean\n check?: boolean\n genTypes?: boolean\n}\n\nexport const _getKnownPlugins = (DB: ComfyRegistry): void => {\n let totalFileSeen = 0\n let totalPluginSeen = 0\n\n // load raw json\n const knownPluginFile: ComfyManagerFilePluginList = JSON.parse(\n readFileSync('src/manager/json/custom-node-list.json', 'utf8'),\n )\n\n // merge with extra\n const knownPluginList: ComfyManagerPluginInfo[] = knownPluginFile.custom_nodes.concat(ComfyPluginExtra)\n\n // auto-fix the (more often than not) json file\n // please... add validation or CI check or something!\n for (const plugin of knownPluginList) {\n plugin.id ??= tryRecoveringPluginId(plugin, RecoveryVerbosity.info)\n plugin.title ??= tryRecoveringPluginTitle(plugin, RecoveryVerbosity.info)\n }\n\n // validate file is well-formed\n const res = ComfyManagerFilePluginList_ark(knownPluginFile)\n if (DB.opts.check) {\n if (res instanceof type.errors) {\n printArkResultInConsole(res)\n process.exit(1)\n }\n }\n\n for (const plugin of knownPluginList) {\n // INITIALIZATION ------------------------------------------------------------\n totalPluginSeen++\n if (DB.opts.check && DB.plugins_byTitle.has(plugin.title))\n console.log(` ❌ plugin.title: \"${plugin.title}\" is duplicated`)\n DB.plugins_byTitle.set(plugin.title, plugin)\n for (const pluginURI of plugin.files) {\n totalFileSeen++\n if (DB.opts.check && DB.plugins_byFile.has(pluginURI))\n console.log(` ❌ plugin.file: \"${pluginURI}\" is duplicated`)\n DB.plugins_byFile.set(pluginURI, plugin)\n }\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n let out1 = ''\n // TitleType\n const allPlugins = [...DB.plugins_byTitle.values()]\n const allPluginsSortedByTitles = allPlugins.sort((a, b) =>\n (a.title ?? '❌missing-title').toLowerCase().localeCompare((b.title ?? '❌missing-title').toLowerCase()),\n )\n out1 += '// prettier-ignore\\n'\n out1 += 'export type KnownComfyPluginTitle =\\n'\n for (const plugin of allPluginsSortedByTitles) {\n out1 += ` /** ${plugin.id} - ${plugin.reference} */\\n`\n out1 += ` | ${JSON.stringify(plugin.title)}\\n`\n }\n out1 += '\\n'\n const out1Path = 'src/manager/generated/KnownComfyPluginTitle.ts'\n writeFileSync(out1Path, out1 + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out1Path)}`)\n\n // FileType\n let out2 = ''\n const allFileNames = [...DB.plugins_byFile.keys()]\n const sortedFileNames = allFileNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n out2 += '// prettier-ignore\\n'\n out2 += 'export type KnownComfyPluginURL =\\n'\n for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\\n`\n // out2 += '\\n'\n const out2Path = 'src/manager/generated/KnownComfyPluginURL.ts'\n writeFileSync(out2Path, out2, 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out2Path)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n // console.log(`${knownModelList.length} models found`)\n console.log(` - ${totalPluginSeen} CustomNodes in file`)\n console.log(` - ${DB.plugins_byTitle.size} CustomNodes registered in map`)\n console.log(` - ${totalFileSeen} CustomNodes-File Seen`)\n console.log(` - ${DB.plugins_byFile.size} CustomNodes-File registered in map`)\n }\n}\n\nfunction tryRecoveringPluginTitle(\n plugin: ComfyManagerPluginInfo,\n verbose = RecoveryVerbosity.Quiet,\n): KnownComfyPluginTitle {\n return tryRecovering<KnownComfyPluginTitle>({\n property: 'plugin.title',\n verbose,\n hacks: [\n {\n attempt: 'id',\n fn: (): Maybe<KnownComfyPluginTitle> => plugin.id as KnownComfyPluginTitle,\n },\n {\n attempt: 'github repo name',\n fn: (): Maybe<KnownComfyPluginTitle> => plugin.reference as KnownComfyPluginTitle,\n },\n ],\n })\n}\n\nfunction tryRecoveringPluginId(\n //\n plugin: ComfyManagerPluginInfo,\n verbose = RecoveryVerbosity.Quiet,\n): string {\n return tryRecovering<ComfyManagerPluginID>({\n property: 'plugin.id',\n verbose,\n hacks: [\n {\n level: RecoveryVerbosity.Verbose,\n attempt: 'title',\n fn: (): Maybe<ComfyManagerPluginID> => plugin.title as ComfyManagerPluginInfo['title'],\n },\n {\n attempt: 'github repo name',\n fn: (): Maybe<string> => plugin.reference.match(githubRegexpV1)?.[2],\n },\n ],\n })\n}\n","import { type } from 'arktype'\n\nexport type ComfyManagerPluginContentMetadata = typeof ComfyManagerPluginContentMetadata_ark.infer\nexport const ComfyManagerPluginContentMetadata_ark = type({\n // optional because on damn validation on comfy manager! 😬\n // should have been always present\n title_aux: type.string.or(type.null), // \"Jovimetrix Composition Nodes\",\n\n // optional\n 'author?': 'string', // \"amorano\",\n 'nickname?': 'string', // \"Comfy Deploy\",\n 'description?': 'string', // \"Webcams, GLSL shader, Media Streaming, Tick animation, Image manipulation,\",\n 'nodename_pattern?': 'string', // \" \\\\(jov\\\\)$\",\n 'title?': 'string', // \"Jovimetrix\",\n 'preemptions?': 'string[]', // ❓\n})\n","import { type } from 'arktype'\nimport type { Tagged } from 'src/types/index.ts'\n\nexport type ComfyManagerPluginContentNodeName = Tagged<string, 'ComfyManagerPluginContentNodeName'>\nexport const ComfyManagerPluginContentNodeName_ark = type.string.as<ComfyManagerPluginContentNodeName>()\n\nexport type ComfyManagerPluginID = string\nexport const ComfyManagerPluginID_ark = type('string')\n","import { type } from 'arktype'\nimport { ComfyManagerPluginContentMetadata_ark } from 'src/manager/types/ComfyManagerPluginContentMetadata.ts'\nimport { ComfyManagerPluginContentNodeName_ark } from 'src/manager/types/ComfyManagerPluginEnums.ts'\n\nexport type ComfyManagerFilePluginContent = typeof ComfyManagerFilePluginContent_ark.infer\nexport const ComfyManagerFilePluginContent_ark = type.Record(\n 'string',\n type([\n //\n ComfyManagerPluginContentNodeName_ark.array(),\n ComfyManagerPluginContentMetadata_ark,\n ]),\n)\n","import { readFileSync, writeFileSync } from 'node:fs'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'\nimport type { NodeNameInComfy } from 'src/sdk-generator/comfyui-types.ts'\nimport { githubRegexpV2 } from 'src/utils/githubRegexes.ts'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport {\n type ComfyManagerFilePluginContent,\n ComfyManagerFilePluginContent_ark,\n} from 'src/manager/types/ComfyManagerFilePluginContent.ts'\nimport type { ComfyManagerPluginContentMetadata } from 'src/manager/types/ComfyManagerPluginContentMetadata.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {\n let totalCustomNodeSeen: number = 0\n\n // 1. read file\n const extensionNodeMapFile: ComfyManagerFilePluginContent = JSON.parse(\n readFileSync('src/manager/json/extension-node-map.json', 'utf8'),\n )\n\n // validate file is well-formed\n const res = ComfyManagerFilePluginContent_ark(extensionNodeMapFile)\n\n if (DB.opts.check) {\n if (res instanceof type.errors) {\n printArkResultInConsole(res)\n process.exit(1)\n }\n }\n\n // 2. process file into something slightly more practical to use\n type ComfyManagerFilePluginContent_asObject = {\n url: string\n comfyNodeNames: NodeNameInComfy[]\n meta: ComfyManagerPluginContentMetadata\n /** should be what we will received once the plugin in installed */\n pythonModule: string\n /** plugin that contains this url listed in files */\n plugin: ComfyManagerPluginInfo\n }\n\n const enmEntries: ComfyManagerFilePluginContent_asObject[] = Object.entries(extensionNodeMapFile).map(\n (\n x: [url: string, infos: [NodeNameInComfy[], ComfyManagerPluginContentMetadata]],\n ): ComfyManagerFilePluginContent_asObject => {\n const url = x[0]\n const [comfyNodeNames, meta] = x[1]\n const confyPlugin = DB.plugins_byFile.get(url as KnownComfyPluginURL)\n if (confyPlugin == null) throw new Error(`[❌] plugin not found for ${url}`)\n return {\n url,\n comfyNodeNames,\n meta,\n plugin: confyPlugin,\n pythonModule: reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(confyPlugin, url, meta),\n }\n },\n )\n\n // 3. for each file\n for (const enmEntry of enmEntries) {\n totalCustomNodeSeen += enmEntry.comfyNodeNames.length\n // JSON CHECKS ------------------------------------------------------------\n // if (!hasErrors && DB.opts.check) {\n // const valid = Value.Check(ComfyManagerPluginContentMetadata_typebox, enmEntry.meta)\n // if (!valid) {\n // const errors: ValueError[] = [\n // ...Value.Errors(ComfyManagerPluginContentMetadata_typebox, enmEntry.meta),\n // ]\n // console.error(`❌ extensionNodeMap doesn't match schema:`, enmEntry.meta)\n // // console.error(`❌ errors`, errors)\n // for (const i of errors) console.log(`❌`, JSON.stringify(i))\n // hasErrors = true\n // }\n // }\n\n // 3 ensure we have a list of nodes for this plugin\n const plugin = enmEntry.plugin\n const nodesInPlugin: KnownComfyCustomNodeName[] = DB.customNodes_byPluginName.get(plugin.title) ?? []\n DB.customNodes_byPluginName.set(plugin.title, nodesInPlugin)\n\n // INITIALIZATION ------------------------------------------------------------\n // 4. for each node in file\n for (const nodeNameInComfy of enmEntry.comfyNodeNames) {\n // 4.1. index the plugin for this node name\n // const prevEntry1 = DB.plugins_byNodeNameInComfy.get(nodeNameInComfy)\n // if (prevEntry1 == null) DB.plugins_byNodeNameInComfy.set(nodeNameInComfy, [plugin])\n // else prevEntry1.push(plugin)\n\n // 4.2 index by nodeKey\n // const nodeKey = convertComfyNodeNameToCushyNodeNameValidInJS(nodeNameInComfy)\n\n const nodeKey = toQualifiedNodeKey(enmEntry.pythonModule, nodeNameInComfy)\n // console.log(`[🤠] nodeKey=`, JSON.stringify(nodeKey), enmEntry.pythonModule)\n // process.exit(2)\n const prevEntry2 = DB.plugins_byNodeKey.get(nodeKey)\n if (prevEntry2 == null) DB.plugins_byNodeKey.set(nodeKey, [plugin])\n else prevEntry2.push(plugin)\n\n // 4.3. index the node in the plugin (file is only giving index by files...)\n nodesInPlugin.push(nodeKey as KnownComfyCustomNodeName)\n }\n }\n\n // 6. CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n let out = ''\n\n // NameInCushy\n const allNodeKeys = [...DB.plugins_byNodeKey.keys()]\n const sortedNodeKeys = allNodeKeys.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n out += '// prettier-ignore\\n'\n out += 'export type KnownComfyCustomNodeName =\\n'\n for (const nodeName of sortedNodeKeys) {\n if (nodeName === 'sd_perturbed_attention.PerturbedAttention') {\n console.log(`[🤠] 🔴`, DB.plugins_byNodeKey.get(nodeName))\n }\n out += ` | ${JSON.stringify(nodeName)}\\n`\n }\n out += '\\n'\n\n const outPath = 'src/manager/generated/KnownComfyCustomNodeName.ts'\n writeFileSync(outPath, out + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(outPath)}`)\n }\n\n // // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n //\n // console.log(`${knownModelList.length} models found`)\n console.log(` - ${totalCustomNodeSeen} CustomNodes unique names processed`)\n // console.log(`${CustomNodeURL.byNodeNameInComfy.size} CustomNodes registered in map`)\n // if (totalPluginSeen !== CustomNodeURL.byNodeNameInComfy.size)\n // console.log(`❌ some customNodes are either duplicated or have overlapping titles`)\n\n // console.log(`${totalCustomNodeSeen} CustomNodes-File Seen`)\n // console.log(`${CustomNodeURL.byNodeNameInCushy.size} CustomNodes-File registered in map`)\n // if (totalCustomNodeSeen !== CustomNodeURL.byNodeNameInCushy.size)\n // console.log(`❌ some customNodes are either duplicated or have overlapping files`)\n\n // if (hasErrors) console.log(`❌ some CustomNodes don't match schema`)\n // else console.log(`✅ all CustomNodes match schema`)\n }\n\n // return DB\n}\n\n// // need to be an array, because multiple custom nodes can have the same name\n// type CustomNodeURL_by_NodeNameInComfy = Map<NodeNameInComfy, KnownComfyPluginURL[]>\n// type CustomNodeURL_by_NodeNameInCushy = Map<QualifiedNodeKey, KnownComfyPluginURL[]>\n// type CustomNodes_by_PluginTitle = Map<KnownComfyPluginURL, QualifiedNodeKey[]>\n\n// type CustomNodeRegistry = {\n// byNodeNameInComfy: CustomNodeURL_by_NodeNameInComfy\n// byNodeNameInCushy: CustomNodeURL_by_NodeNameInCushy\n// byPluginName: CustomNodes_by_PluginTitle\n// }\n\n// let DB: Maybe<CustomNodeRegistry> = null // = knownCustomNodesFile.custom_nodes\n\nfunction reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(\n plugin: ComfyManagerPluginInfo,\n _url: string,\n _meta: ComfyManagerPluginContentMetadata,\n): string {\n if (plugin.id === 'nodes' && plugin.reference === 'https://github.com/comfyanonymous/ComfyUI') return 'nodes'\n\n // if (meta.pythonModule) {\n // // console.log(`[🤠] got via pythonModule`, meta.pythonModule)\n // return meta.pythonModule\n // }\n const repoName = plugin.reference.match(githubRegexpV2)?.[2]\n // console.log(`[🤠] ${plugin.reference} => ${repoName}`)\n if (repoName) {\n // console.log(`[🤠] got via repoName`, plugin.reference, `custom_nodes.${repoName}`)\n return `custom_nodes.${repoName}`\n }\n if (plugin.id) {\n // console.log(`[🤠] got via repoName`, plugin.id, `custom_nodes.${plugin.id}`)\n return `custom_nodes.${plugin.id}`\n }\n const pythonModule = '🔴'\n return pythonModule\n}\n","import type { ComfyManagerFileModelInfo } from 'src/manager/types/ComfyManagerFileModelInfo.ts'\n\nexport const extraModels: ComfyManagerFileModelInfo = {\n models: [\n {\n name: 'TEMP_briaai_RMBG-1.4',\n type: 'controlnet',\n base: 'SDXL',\n save_path: 'custom_nodes/ComfyUI-BRIA_AI-RMBG/RMBG-1.4',\n description: '<3 stuff',\n reference: 'https://huggingface.co/briaai/RMBG-1.4',\n filename: 'model.pth',\n url: 'https://huggingface.co/briaai/RMBG-1.4/resolve/main/model.pth?download=true',\n },\n {\n name: '4x_NMKD-Siax_200k',\n type: 'upscale',\n base: 'upscale',\n save_path: 'default',\n description: '4xRealWebPhoto_v4_dat2',\n reference: 'https://openmodeldb.info/models/4x-RealWebPhoto-v4-dat2',\n filename: '4xRealWebPhoto_v4_dat2.pth',\n url: 'https://huggingface.co/gemasai/4x_NMKD-Siax_200k/resolve/main/4xRealWebPhoto_v4_dat2.pth',\n },\n ],\n}\n","import { type } from 'arktype'\nimport type { KnownModel_Base } from 'src/manager/generated/KnownModel_Base.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport type { KnownModel_SavePath } from 'src/manager/generated/KnownModel_SavePath.ts'\nimport type { KnownModel_Type } from 'src/manager/generated/KnownModel_Type.ts'\n\nexport type ComfyManagerModelInfo = typeof ComfyManagerModelInfo_ark.infer\nexport const ComfyManagerModelInfo_ark = type({\n name: type.string.as<KnownModel_Name>(), // e.g. \"ip-adapter_sd15_light.safetensors\",\n type: type.string.as<KnownModel_Type>(), // e.g. \"IP-Adapter\",\n base: type.string.as<KnownModel_Base>(), // e.g. \"SD1.5\",\n save_path: type.string.as<KnownModel_SavePath>(), // e.g. \"ipadapter\",\n description: 'string', // e.g. \"You can use this model in the [a/ComfyUI IPAdapter plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) extension.\",\n reference: 'string', // e.g. \"https://huggingface.co/h94/IP-Adapter\",\n filename: 'string', // e.g. \"ip-adapter_sd15_light.safetensors\",\n url: 'string', // e.g. \"https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15_light.safetensors\"\n 'size?': 'string', // e.g. \"698.4MB\"\n})\n","import { type ArkErrors, type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\n// https://github.com/ltdrdata/ComfyUI-Manager/blob/main/model-list.json\nimport { readFileSync, writeFileSync } from 'fs'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport { extraModels } from 'src/manager/json/model-list.extra.ts'\nimport type { ComfyManagerFileModelInfo } from 'src/manager/types/ComfyManagerFileModelInfo.ts'\nimport { ComfyManagerModelInfo_ark } from 'src/manager/types/ComfyManagerModelInfo.ts'\n\nexport const _getKnownModels = (\n DB: ComfyRegistry /* {\n} */,\n): void => {\n const knownModelsFile: ComfyManagerFileModelInfo = JSON.parse(\n readFileSync('src/manager/json/model-list.json', 'utf8'),\n )\n const knownModelList = knownModelsFile.models.concat(extraModels.models)\n\n let hasErrors = false\n\n for (const modelInfo of knownModelList) {\n // INITIALIZATION ------------------------------------------------------------\n DB.knownModels.set(modelInfo.name as KnownModel_Name, modelInfo)\n\n // JSON CHECKS -----------------------------------------------------------\n if (!hasErrors && DB.opts.check) {\n const res = ComfyManagerModelInfo_ark(modelInfo)\n if (res instanceof type.errors) {\n const errors: ArkErrors = res\n console.error(`❌ model doesn't match schema:`, modelInfo)\n printArkResultInConsole(errors)\n hasErrors = true\n // debugger\n }\n }\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n // #region type\n let out1 = ''\n const uniqCategories: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.type] != null) acc[cur.type]! += 1\n else acc[cur.type] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out1 += `// prettier-ignore\\n`\n out1 += 'export type KnownModel_Type =\\n'\n for (const [cat, count] of Object.entries(uniqCategories))\n out1 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\\n`\n out1 += '\\n'\n out1 += 'export const knownModel_Type: KnownModel_Type[] = [\\n'\n for (const [cat, count] of Object.entries(uniqCategories))\n out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\\n`\n out1 += ']\\n'\n const out1Path = 'src/manager/generated/KnownModel_Type.ts'\n writeFileSync(out1Path, out1 + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out1Path)}`)\n\n // #region savepath\n let out4 = ''\n const uniqSavePath: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.save_path] != null) acc[cur.save_path]! += 1\n else acc[cur.save_path] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out4 += `// prettier-ignore\\n`\n out4 += 'export type KnownModel_SavePath =\\n'\n for (const [cat, count] of Object.entries(uniqSavePath))\n out4 += ` | ${JSON.stringify(cat).padEnd(50)} // x ${count.toString().padStart(3)}\\n`\n out4 += '\\n'\n out4 += 'export const knownModel_SavePath: KnownModel_SavePath[] = [\\n'\n for (const [cat, count] of Object.entries(uniqSavePath))\n out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\\n`\n out4 += ']\\n'\n const out4Path = 'src/manager/generated/KnownModel_SavePath.ts'\n writeFileSync(out4Path, out4 + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out4Path)}`)\n\n // #region base\n let out2 = ''\n const uniqBases: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.base] != null) acc[cur.base]! += 1\n else acc[cur.base] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out2 += `// prettier-ignore\\n`\n out2 += 'export type KnownModel_Base =\\n'\n for (const [cat, count] of Object.entries(uniqBases))\n out2 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\\n`\n out2 += '\\n'\n out2 += '// prettier-ignore\\n'\n out2 += 'export const knownModel_Base: KnownModel_Base[] = [\\n'\n for (const [cat, count] of Object.entries(uniqBases))\n out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\\n`\n out2 += ']\\n'\n const out2Path = 'src/manager/generated/KnownModel_Base.ts'\n writeFileSync(out2Path, out2 + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out2Path)}`)\n\n // #region KnownModel_Name\n let out3 = ''\n const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()))\n out3 += `// prettier-ignore\\n`\n out3 += 'export type KnownModel_Name =\\n'\n for (const mi of sortedModels) {\n out3 += ` /** ${mi.description}\\n`\n out3 += ` * ${mi.size} - ${mi.url}\\n`\n out3 += ` * see ${mi.reference}\\n`\n out3 += ` */\\n`\n out3 += ` | ${JSON.stringify(mi.name)}\\n`\n }\n out3 += '\\n'\n const out3Path = 'src/manager/generated/KnownModel_Name.ts'\n writeFileSync(out3Path, out3 + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out3Path)}`)\n\n // #region KnownModel_FileName\n let out99 = ''\n out99 += `// prettier-ignore\\n`\n out99 += 'export type KnownModel_FileName =\\n'\n for (const mi of sortedModels) {\n out99 += ` /** ${mi.description}\\n`\n out99 += ` * ${mi.size} - ${mi.url}\\n`\n out99 += ` * see ${mi.reference}\\n`\n out99 += ` */\\n`\n out99 += ` | ${JSON.stringify(mi.filename)}\\n`\n }\n out99 += '\\n'\n const out99Path = 'src/manager/generated/KnownModel_FileName.ts'\n writeFileSync(out99Path, out99 + '\\n', 'utf-8')\n console.log(` > generated: ${chalk.blue.underline(out99Path)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n //\n console.log(`${knownModelList.length} models found`)\n console.log(`${DB.knownModels.size} models registered map`)\n if (knownModelList.length !== DB.knownModels.size)\n console.log(`❌ some models are either duplicated or have overlapping indexing keys`)\n //\n if (hasErrors) console.log(`❌ some models don't match schema`)\n else console.log(`✅ all models match schema`)\n }\n\n // return DB.knownModels\n}\n","import { ansi as chalk } from 'src/utils/ansi.ts'\nimport type { NodeNameInComfy, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'\nimport type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport { DownloadComfyManagerJSONs } from 'src/manager/loaders/step1_downloadComfyManagerJSONs.ts'\nimport { _getKnownPlugins } from 'src/manager/loaders/step2_custom-node-list-loader.ts'\nimport { _getCustomNodeRegistry } from 'src/manager/loaders/step3_extension-node-map-loader.ts'\nimport { _getKnownModels } from 'src/manager/loaders/step4_model-list-loader.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nconst log = (...args: unknown[]) => console.log(`[📘 registry]`, ...args)\n\nexport class ComfyRegistry {\n // plugins, indexed\n plugins_byTitle = new Map<KnownComfyPluginTitle, ComfyManagerPluginInfo>()\n plugins_byFile = new Map<KnownComfyPluginURL, ComfyManagerPluginInfo>()\n plugins_byNodeNameInComfy = new Map<NodeNameInComfy, ComfyManagerPluginInfo[]>()\n plugins_byNodeKey = new Map<QualifiedNodeKey, ComfyManagerPluginInfo[]>()\n\n // custom nodes\n customNodes_byPluginName = new Map<KnownComfyPluginTitle, KnownComfyCustomNodeName[]>()\n\n // Models\n knownModels = new Map<KnownModel_Name, ComfyManagerModelInfo>()\n\n static async DownloadAndUpdate(download: boolean): Promise<ComfyRegistry> {\n if (download) {\n log(chalk.bold(`1. Downloading comfy-manager JSONs...`))\n await DownloadComfyManagerJSONs()\n } else {\n log(`1. Downloading comfy-manager JSONs... ${chalk.bold('[SKIPPED]')}`)\n }\n // should take care of the code generation\n return new ComfyRegistry({\n check: true,\n genTypes: true,\n })\n }\n\n constructor(\n public opts: {\n check?: boolean\n genTypes?: boolean\n } = {},\n ) {\n this.plugins_byFile.set('https://github.com/comfyanonymous/ComfyUI' as any, {\n id: 'nodes',\n author: 'comfyanonymous',\n description: 'built-in',\n title: 'built-in' as any,\n files: [],\n reference: 'https://github.com/comfyanonymous/ComfyUI',\n install_type: '',\n })\n\n log(`loading src/manager/json/${chalk.yellow('custom-node-list.json')}...`)\n _getKnownPlugins(this)\n\n log(`loading src/manager/json/${chalk.yellow('extension-node-map.json')}...`)\n _getCustomNodeRegistry(this)\n\n log(`loading src/manager/json/${chalk.yellow('model-list.json')}...`)\n _getKnownModels(this)\n }\n\n getKnownCheckpoints = (): ComfyManagerModelInfo[] => {\n const allKnownModels = [...this.knownModels.values()]\n const allKnownCheckpoints = allKnownModels.filter((i) => i.type === 'checkpoint')\n // console.log(`[🤠] allKnownCheckpoints`, allKnownCheckpoints)\n // for (const mi of knownModels.values()) {\n // console.log(`[🧐] `, mi.type === 'checkpoint' ? '✅' : '❌', mi.name)\n // }\n return allKnownCheckpoints\n }\n\n /**\n * try to replicate the logic of ComfyUIManager to extract the final\n * file path of a downloaded managed model\n */\n getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {\n /**\n * the wide data-lt once told:\n *\n * | if save_path is 'default'\n * | models/type'/filename\n *\n * | if type is \"checkpoint\"\n * | models/checkpoints/filename\n *\n * | if save_path not starting with custom node\n * | base path is models\n * | e.g. save_path is \"checkpoints/SD1.5\"\n * | models/checkpoints/SD1.5/filename\n * | save_path is \"custom_nodes/AAA/models\"\n * | custom_nodes/AAA/models/filename\n *\n */\n if (mi.save_path === 'default') return `models/${mi.type}/${mi.filename}`\n if (mi.type === 'checkpoint') return `models/checkpoints/${mi.filename}`\n if (mi.save_path.startsWith('custom_nodes')) return `${mi.save_path}/${mi.filename}`\n else return `models/${mi.save_path}/${mi.filename}`\n }\n\n getModelInfoEnumName = (mi: ComfyManagerModelInfo, prefix: string = ''): { win: string; nix: string } => {\n const relPath = this.getModelInfoFinalFilePath(mi)\n\n const winPath = relPath.replace(/\\//g, '\\\\')\n const winPrefix = prefix?.replace(/\\//g, '\\\\')\n const isUnderPrefixWin = winPath.startsWith(winPrefix)\n\n const nixPath = relPath.replace(/\\\\/g, '/')\n const nixPrefix = prefix?.replace(/\\//g, '\\\\')\n const isUnderPrefixNix = nixPath.startsWith(nixPrefix)\n\n const isUnderPrefix = isUnderPrefixNix || isUnderPrefixWin\n return {\n win: isUnderPrefix ? winPath.slice(winPrefix.length) : mi.filename /* winRel */,\n nix: isUnderPrefix ? nixPath.slice(nixPrefix.length) : mi.filename /* nixRel */,\n }\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'pathe'\nimport pkgJson from '../package.json' with { type: 'json' }\nimport { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'\nimport { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'\n\n/** singleton */\nexport class ComfyTS {\n version = pkgJson.version\n\n constructor(p: { rootPath?: string } = {}) {\n // global registration: the rest of the lib resolves paths through `comfyts`\n const globalHack = globalThis as { comfyts?: ComfyTS }\n if (globalHack.comfyts != null) throw new Error('ComfyTS instance already created')\n globalHack.comfyts = this\n if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath)\n this.baseFolder = asAbsolutePath(join(this.rootPath, '.comfy-ts'))\n this.hostsFolder = asAbsolutePath(join(this.baseFolder, 'hosts'))\n this.outputPath = asAbsolutePath(join(this.baseFolder, 'outputs'))\n }\n\n /**\n * multi-module entrypoint: returns the existing global instance or creates\n * it. Workflow modules MUST use this (the TUI imports many of them into one\n * process); `new ComfyTS()` still throws on a second instance.\n */\n static create(p: { rootPath?: string } = {}): ComfyTS {\n const globalHack = globalThis as { comfyts?: ComfyTS }\n const existing = globalHack.comfyts\n if (existing == null) return new ComfyTS(p)\n if (p.rootPath != null && asAbsolutePath(p.rootPath) !== existing.rootPath)\n throw new Error(\n `ComfyTS.create({rootPath: '${p.rootPath}'}) conflicts with the existing instance rooted at '${existing.rootPath}'`,\n )\n return existing\n }\n\n /** every host created through host(), keyed by id — one instance (and one ws) per id */\n hosts: Map<string, ComfyHost> = new Map()\n\n host<const ID extends string>(data: ComfyHostData & { id: ID }): ComfyHost<ID> {\n const existing = this.hosts.get(data.id)\n if (existing != null) {\n if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https)\n throw new Error(\n `host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`,\n )\n // cast: whitelist item 7 (agent/coding.md) — id equality checked just above\n return existing as ComfyHost<ID>\n }\n const created = new ComfyHost(data)\n this.hosts.set(data.id, created)\n return created\n }\n\n /**\n * A ComfyRegistry instance that provides access to all\n * known Comfy nodes, models, plugins, ...\n * lazy: constructing it parses ~3MB of ComfyUI-Manager JSON, only pay when used\n */\n private _registry: ComfyRegistry | null = null\n get registry(): ComfyRegistry {\n if (this._registry == null) this._registry = new ComfyRegistry({ check: false, genTypes: false })\n return this._registry\n }\n\n /** root path used to resolve things */\n rootPath: AbsolutePath = asAbsolutePath(process.cwd())\n\n /**\n * every repo using comfy-ts gets ONE `.comfy-ts/` folder:\n * .comfy-ts/hosts/<id>/{object_info.json, embeddings.json, sdk.d.ts}\n * .comfy-ts/outputs/... generated images & workflows\n * .comfy-ts/drafts/<workflow-id>/<draft>.json TUI var snapshots (local, gitignored)\n */\n baseFolder: AbsolutePath\n hostsFolder: AbsolutePath\n outputPath: AbsolutePath\n\n resolveFromDrafts(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'drafts', relativePath))\n }\n\n resolveFromCache(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'cache', relativePath))\n }\n\n /** local TUI settings (preview mode, last draft per workflow) — gitignored */\n get settingsPath(): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'settings.json'))\n }\n\n resolveFromHosts(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.hostsFolder, relativePath))\n }\n\n /**\n * Resolves a relative path against an absolute path.\n * @param from - The absolute path to resolve from.\n * @param relativePath - The relative path to resolve.\n * @returns The resolved absolute path.\n */\n resolve(from: AbsolutePath, relativePath: RelativePath): AbsolutePath {\n return asAbsolutePath(join(from, relativePath))\n }\n resolveFromOutput(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.outputPath, relativePath))\n }\n\n readJSON_ = <T>(absPath: AbsolutePath, def?: T): T => {\n const exists = existsSync(absPath)\n if (!exists) {\n if (def != null) return def\n throw new Error(`file does not exist ${absPath}`)\n }\n const str = readFileSync(absPath, 'utf8')\n const json = JSON.parse(str)\n return json\n }\n\n // for automatic formating of produced ComfyUI workflow\n autolayoutOpts: {\n node_hsep: number\n node_vsep: number\n forceLeft: boolean\n } = {\n node_hsep: 50,\n node_vsep: 50,\n forceLeft: false,\n }\n}\n\ndeclare global {\n var comfyts: ComfyTS\n}\n","// contract between the TUI and workflow modules: the TUI sets this env var\n// before importing a module; example files also use `import.meta.main` to\n// only self-run when executed directly.\nexport const COMFY_TS_TUI_ENV = 'COMFY_TS_TUI'\n\nexport function isTuiActive(): boolean {\n return process.env[COMFY_TS_TUI_ENV] === '1'\n}\n","/**\n * build a LoraManager-style lora tag: `<lora:name:strength>` or\n * `<lora:name:strength:clipStrength>`. Pin the name to a host union for\n * autocomplete + validation:\n *\n * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)\n */\nexport function loraTag<N extends string = string>(name: N, strength: number = 1, clipStrength?: number): string {\n return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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