comfy-ts 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +66 -0
  2. package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/DraftsSt-DcOTn0QR.js +434 -0
  5. package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +476 -202
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +98 -40
  11. package/dist/index.d.ts +117 -59
  12. package/dist/index.js +468 -193
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-CN0DhrsA.js +638 -0
  15. package/dist/run-serve-CN0DhrsA.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
  17. package/dist/run-tui-bN2hSD5i.js.map +1 -0
  18. package/dist/state-COlKYipO.js +4743 -0
  19. package/dist/state-COlKYipO.js.map +1 -0
  20. package/dist/web.d.ts +17340 -0
  21. package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
  22. package/dist/web.js.map +1 -0
  23. package/examples/web/example.ts +71 -0
  24. package/examples/web/index.html +77 -0
  25. package/examples/web/serve.ts +42 -0
  26. package/examples/web/tsconfig.json +15 -0
  27. package/package.json +10 -3
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/StatusBar.tsx +1 -0
  34. package/src/cli/tui/components/TreePanel.tsx +17 -3
  35. package/src/cli/tui/components/TuiApp.tsx +7 -2
  36. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  37. package/src/cli/tui/imageClipboard.ts +39 -0
  38. package/src/cli/tui/listWindow.ts +36 -0
  39. package/src/cli/tui/state/ExecSt.ts +48 -0
  40. package/src/cli/tui/state/TreeSt.ts +25 -0
  41. package/src/cli/tui/state/TuiSt.ts +34 -0
  42. package/src/coreExports.ts +118 -0
  43. package/src/host/ComfyHost.ts +23 -23
  44. package/src/host/ResilientWebsocket.ts +93 -47
  45. package/src/host/hostUrl.ts +2 -1
  46. package/src/host/loraManagerApi.ts +6 -7
  47. package/src/index.ts +8 -107
  48. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  49. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  50. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  51. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  52. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  53. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  54. package/src/runner/ComfyExecution.ts +32 -12
  55. package/src/runner/MediaImage.ts +18 -30
  56. package/src/runner/outputPath.ts +75 -0
  57. package/src/sdk-generator/ComfySchema.ts +2 -2
  58. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  59. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  60. package/src/state.ts +13 -9
  61. package/src/storage/ComfyStorage.ts +144 -0
  62. package/src/storage/nodeStorage.ts +9 -0
  63. package/src/utils/downloadFile.ts +11 -69
  64. package/src/utils/hashArrayBuffer.ts +3 -4
  65. package/src/utils/lazySharp.ts +25 -0
  66. package/src/utils/sha1.ts +69 -0
  67. package/src/vars/ComfyVars.ts +13 -6
  68. package/src/vars/loraKeywords.ts +6 -6
  69. package/src/web.ts +13 -0
  70. package/dist/run-tui-BAdizWsO.js.map +0 -1
  71. package/dist/state-BYbxDgfr.js.map +0 -1
  72. package/src/utils/writeFile.ts +0 -16
@@ -1,7 +1,6 @@
1
- import { createHash } from 'node:crypto'
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
1
  import { type } from 'arktype'
4
- import { dirname } from 'pathe'
2
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
3
+ import { sha1HexOfString } from 'src/utils/sha1.ts'
5
4
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
6
5
  import { logError } from 'src/utils/log.ts'
7
6
 
@@ -80,8 +79,9 @@ export function looksLikeImage(bytes: Uint8Array): boolean {
80
79
  * a non-image content-type OR non-image magic bytes => no preview, not a crash.
81
80
  */
82
81
  export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string): Promise<Uint8Array | null> {
83
- const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash('sha1').update(previewUrl).digest('hex')}`)
84
- if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath))
82
+ const storage = getComfyStorage()
83
+ const cachePath = comfyts.resolveFromCache(`lora-previews/${sha1HexOfString(previewUrl)}`)
84
+ if (storage.exists(cachePath)) return storage.readBytes(cachePath)
85
85
  try {
86
86
  // preview_url is already a full server-relative path — no /api probing
87
87
  const res = await host.fetch(previewUrl, {}, { apiPrefix: false })
@@ -90,8 +90,7 @@ export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string)
90
90
  if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.
91
91
  const bytes = new Uint8Array(await res.arrayBuffer())
92
92
  if (!looksLikeImage(bytes)) return null
93
- mkdirSync(dirname(cachePath), { recursive: true })
94
- writeFileSync(cachePath, bytes)
93
+ storage.writeBytes(cachePath, bytes)
95
94
  return bytes
96
95
  } catch {
97
96
  return null
package/src/index.ts CHANGED
@@ -1,115 +1,16 @@
1
1
  /**
2
- * comfy-ts — type-safe ComfyUI workflow creation and execution
2
+ * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)
3
3
  * @packageDocumentation
4
4
  */
5
+ import { setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'
6
+ import { createNodeStorage } from 'src/storage/nodeStorage.ts'
5
7
 
6
- // global Comfy.* base namespace + per-host sdk registry (side-effectful types)
7
- export * from 'src/types/comfy-sdk.ts'
8
+ // entry side effect: node 20/21 dist consumers have no getBuiltinModule
9
+ // autodetect, so the node backend installs here (architecture item 13)
10
+ setDefaultComfyStorage(createNodeStorage())
8
11
 
9
- // entrypoint singleton
10
- export { ComfyTS } from 'src/state.ts'
12
+ export * from 'src/coreExports.ts'
11
13
 
12
- // host
13
- export {
14
- ComfyHost,
15
- ComfyHostAuthError,
16
- type ComfyHostData,
17
- type ComfyHostID,
18
- type ConnectOptions,
19
- } from 'src/host/ComfyHost.ts'
20
- export { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
21
- export { ComfyManager } from 'src/host/ComfyManager.ts'
22
- export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
23
- export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
24
- export type { Requirements, PluginInstallStatus, PluginSuggestion } from 'src/host/Requirements.ts'
25
- export { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
26
-
27
- // runner
28
- export {
29
- ComfyWorkflow,
30
- type ComfyNodeIdMode,
31
- type ComfyWorkflowData,
32
- type ComfyWorkflowID,
33
- type ExecutionSnapshot,
34
- type ProgressReport,
35
- type RunSettings,
36
- } from 'src/runner/ComfyWorkflow.ts'
37
- export { ComfyExecution, type ComfyExecutionData, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
38
- export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi.ts'
39
- export { MediaImage, type MediaImageData } from 'src/runner/MediaImage.ts'
40
- export type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
41
- export { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
42
-
43
- // graph (programmatic node graph)
44
- export { ComfyNode } from 'src/graph/ComfyNode.ts'
45
- export { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
46
- export type { ComfyNodeMetadata, ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
47
- export { auto, auto_ } from 'src/graph/autoValue.ts'
48
-
49
- // bundled example assets (ship in the tarball)
14
+ // node-only surface: fs-backed example assets + the TUI env contract
50
15
  export { exampleImagePath } from 'src/exampleAssets.ts'
51
-
52
- // sdk generator (schema parsing + per-host codegen)
53
- export { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
54
- export { codegenSDK, hostIdToNamespace, type CodegenOptions } from 'src/sdk-generator/comfyui-sdk-codegen.ts'
55
- export type { ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
56
- export type { ComfyImageName, ComfyUnionValue, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'
57
- export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
58
-
59
- // litegraph (ComfyUI saved-workflow JSON format)
60
- export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
61
- export { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
62
- export type {
63
- CanonicalGroup,
64
- CanonicalInput,
65
- CanonicalLink,
66
- CanonicalNode,
67
- CanonicalOutput,
68
- CanonicalWidgetValues,
69
- CanonicalWorkflow,
70
- NodeMode,
71
- } from 'src/litegraph/CanonicalWorkflow.ts'
72
- export { normalizeWorkflow, parseWorkflowJson, WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'
73
- export { convertLiteGraphToPrompt, WorkflowConvertError } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
74
-
75
- // vars + re-runnable workflows
76
- export {
77
- v,
78
- ComfyVarBase,
79
- ComfyVar,
80
- TextVar,
81
- PromptVar,
82
- IntVar,
83
- FloatVar,
84
- SeedVar,
85
- ToggleVar,
86
- ChoiceVar,
87
- LorasVar,
88
- SizeVar,
89
- ImageVar,
90
- ImageVarEmptyError,
91
- DEFAULT_SIZE_PRESETS,
92
- DEFAULT_IMAGE_EXTENSIONS,
93
- activeLoras,
94
- } from 'src/vars/ComfyVars.ts'
95
- export type {
96
- AnyVar,
97
- VarKind,
98
- VarsSpec,
99
- VarValues,
100
- PromptValue,
101
- ActiveLoraSource,
102
- LorasHost,
103
- LoraStrength,
104
- ActiveLora,
105
- SizeValue,
106
- SizePreset,
107
- ImageVarOpts,
108
- } from 'src/vars/ComfyVars.ts'
109
- export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
110
- export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
111
16
  export { isTuiActive } from 'src/cli/tui-env.ts'
112
- export { loraTag } from 'src/utils/loraTag.ts'
113
-
114
- // shared types
115
- export * from 'src/types/index.ts'
@@ -1,7 +1,7 @@
1
1
  import type { ComfyNode } from 'src/graph/ComfyNode.ts'
2
2
  import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
3
3
  import { bang } from 'src/utils/bang.ts'
4
- import { howManyWidgetValuesForThisSchemaType } from 'src/sdk-generator/inputWidgetKind.ts'
4
+ import { classifySchemaInput } from 'src/sdk-generator/inputWidgetKind.ts'
5
5
  import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
6
6
  import type { LiteGraphLinkTuple } from 'src/litegraph/LiteGraphLink.ts'
7
7
  import { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'
@@ -42,7 +42,7 @@ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): Li
42
42
  const widgets_values: unknown[] = []
43
43
  for (const ipt of node.$schema.inputs) {
44
44
  const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])
45
- const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0
45
+ const kind = classifySchemaInput(ipt)
46
46
  if (_isLink(raw)) {
47
47
  const nodeUidNumber = bang(
48
48
  ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,
@@ -61,11 +61,15 @@ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): Li
61
61
  ipt.typeName,
62
62
  ),
63
63
  })
64
- } else if (isWidget) {
65
- widgets_values.push(raw)
66
- // ComfyUI stores a phantom control_after_generate value after seeds
67
- const isSeed = ipt.typeName === 'INT' && (ipt.nameInComfy === 'seed' || ipt.nameInComfy === 'noise_seed')
68
- if (isSeed) widgets_values.push(false)
64
+ } else if (kind.kind === 'widget') {
65
+ // frontend button-widget values ride BEFORE the real value (LOAD_3D)
66
+ widgets_values.push(...kind.prefixValues, raw)
67
+ // control_after_generate phantom AFTER the value: the classifier's
68
+ // consumes covers prefix + value + control, config-driven (the 2024
69
+ // INT-named-seed heuristic lives inside controlConsumes), so export
70
+ // and import can never disagree on the run length
71
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length
72
+ for (let i = 0; i < phantoms; i++) widgets_values.push(false)
69
73
  } else {
70
74
  // unconnected link-kind input: a litegraph slot with no link —
71
75
  // NEVER a widget value (that would misalign the round-trip import)
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import { ansi as chalk } from 'src/utils/ansi.ts'
4
4
  import { githubRegexpV1 } from 'src/utils/githubRegexes.ts'
@@ -17,7 +17,7 @@ export const _getKnownPlugins = (DB: ComfyRegistry): void => {
17
17
  let totalFileSeen = 0
18
18
 
19
19
  // parse rows: loose raw schema per row, skip+report failures, normalize survivors
20
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/custom-node-list.json', 'utf8'))
20
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/custom-node-list.json'))
21
21
  const root = ComfyManagerFilePluginListRoot_ark(raw)
22
22
  if (root instanceof type.errors) throw new ManagerParseError('custom-node-list.json', root.summary)
23
23
 
@@ -68,7 +68,7 @@ export const _getKnownPlugins = (DB: ComfyRegistry): void => {
68
68
  }
69
69
  out1 += '\n'
70
70
  const out1Path = 'src/manager/generated/KnownComfyPluginTitle.ts'
71
- writeFileSync(out1Path, out1 + '\n', 'utf-8')
71
+ getComfyStorage().writeText(out1Path, out1 + '\n')
72
72
  console.log(` > generated: ${chalk.blue.underline(out1Path)}`)
73
73
 
74
74
  // FileType
@@ -79,7 +79,7 @@ export const _getKnownPlugins = (DB: ComfyRegistry): void => {
79
79
  out2 += 'export type KnownComfyPluginURL =\n'
80
80
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`
81
81
  const out2Path = 'src/manager/generated/KnownComfyPluginURL.ts'
82
- writeFileSync(out2Path, out2, 'utf-8')
82
+ getComfyStorage().writeText(out2Path, out2)
83
83
  console.log(` > generated: ${chalk.blue.underline(out2Path)}`)
84
84
  }
85
85
 
@@ -1,4 +1,4 @@
1
- import { writeFileSync, readFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import { ansi as chalk } from 'src/utils/ansi.ts'
4
4
  import { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'
@@ -14,7 +14,7 @@ export const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {
14
14
  const counter = DB.report.file('extension-node-map.json')
15
15
  let totalCustomNodeSeen: number = 0
16
16
 
17
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/extension-node-map.json', 'utf8'))
17
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/extension-node-map.json'))
18
18
  const root = type('Record<string, unknown>')(raw)
19
19
  if (root instanceof type.errors) throw new ManagerParseError('extension-node-map.json', root.summary)
20
20
 
@@ -64,7 +64,7 @@ export const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {
64
64
  out += '\n'
65
65
 
66
66
  const outPath = 'src/manager/generated/KnownComfyCustomNodeName.ts'
67
- writeFileSync(outPath, out + '\n', 'utf-8')
67
+ getComfyStorage().writeText(outPath, out + '\n')
68
68
  console.log(` > generated: ${chalk.blue.underline(outPath)}`)
69
69
  }
70
70
 
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import { ansi as chalk } from 'src/utils/ansi.ts'
4
4
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
@@ -10,7 +10,7 @@ import { type ComfyManagerModelInfo, ComfyManagerModelInfo_ark } from 'src/manag
10
10
  export const _getKnownModels = (DB: ComfyRegistry): void => {
11
11
  const counter = DB.report.file('model-list.json')
12
12
 
13
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/model-list.json', 'utf8'))
13
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/model-list.json'))
14
14
  const root = ComfyManagerFileModelInfoRoot_ark(raw)
15
15
  if (root instanceof type.errors) throw new ManagerParseError('model-list.json', root.summary)
16
16
 
@@ -54,7 +54,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
54
54
  out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`
55
55
  out1 += ']\n'
56
56
  const out1Path = 'src/manager/generated/KnownModel_Type.ts'
57
- writeFileSync(out1Path, out1 + '\n', 'utf-8')
57
+ getComfyStorage().writeText(out1Path, out1 + '\n')
58
58
  console.log(` > generated: ${chalk.blue.underline(out1Path)}`)
59
59
 
60
60
  // #region savepath
@@ -77,7 +77,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
77
77
  out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`
78
78
  out4 += ']\n'
79
79
  const out4Path = 'src/manager/generated/KnownModel_SavePath.ts'
80
- writeFileSync(out4Path, out4 + '\n', 'utf-8')
80
+ getComfyStorage().writeText(out4Path, out4 + '\n')
81
81
  console.log(` > generated: ${chalk.blue.underline(out4Path)}`)
82
82
 
83
83
  // #region base
@@ -101,7 +101,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
101
101
  out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`
102
102
  out2 += ']\n'
103
103
  const out2Path = 'src/manager/generated/KnownModel_Base.ts'
104
- writeFileSync(out2Path, out2 + '\n', 'utf-8')
104
+ getComfyStorage().writeText(out2Path, out2 + '\n')
105
105
  console.log(` > generated: ${chalk.blue.underline(out2Path)}`)
106
106
 
107
107
  // #region KnownModel_Name
@@ -118,7 +118,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
118
118
  }
119
119
  out3 += '\n'
120
120
  const out3Path = 'src/manager/generated/KnownModel_Name.ts'
121
- writeFileSync(out3Path, out3 + '\n', 'utf-8')
121
+ getComfyStorage().writeText(out3Path, out3 + '\n')
122
122
  console.log(` > generated: ${chalk.blue.underline(out3Path)}`)
123
123
 
124
124
  // #region KnownModel_FileName
@@ -134,7 +134,7 @@ export const _getKnownModels = (DB: ComfyRegistry): void => {
134
134
  }
135
135
  out99 += '\n'
136
136
  const out99Path = 'src/manager/generated/KnownModel_FileName.ts'
137
- writeFileSync(out99Path, out99 + '\n', 'utf-8')
137
+ getComfyStorage().writeText(out99Path, out99 + '\n')
138
138
  console.log(` > generated: ${chalk.blue.underline(out99Path)}`)
139
139
  }
140
140
 
@@ -1,4 +1,4 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
4
4
  import { ManagerParseError } from 'src/manager/loaders/parseReport.ts'
@@ -11,7 +11,7 @@ import {
11
11
  export const _getAlterList = (DB: ComfyRegistry): void => {
12
12
  const counter = DB.report.file('alter-list.json')
13
13
 
14
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/alter-list.json', 'utf8'))
14
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/alter-list.json'))
15
15
  const root = ComfyManagerFileAlterListRoot_ark(raw)
16
16
  if (root instanceof type.errors) throw new ManagerParseError('alter-list.json', root.summary)
17
17
 
@@ -1,4 +1,4 @@
1
- import { readFileSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
3
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
4
4
  import { ManagerParseError } from 'src/manager/loaders/parseReport.ts'
@@ -7,7 +7,7 @@ import { ComfyManagerGithubStatEntry_ark } from 'src/manager/types/ComfyManagerG
7
7
  export const _getGithubStats = (DB: ComfyRegistry): void => {
8
8
  const counter = DB.report.file('github-stats.json')
9
9
 
10
- const raw: unknown = JSON.parse(readFileSync('src/manager/json/github-stats.json', 'utf8'))
10
+ const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/github-stats.json'))
11
11
  const root = type('Record<string, unknown>')(raw)
12
12
  if (root instanceof type.errors) throw new ManagerParseError('github-stats.json', root.summary)
13
13
 
@@ -1,7 +1,12 @@
1
- import { mkdirSync, writeFileSync } from 'node:fs'
2
- import { dirname, join } from 'pathe'
3
- import sharp, { type FormatEnum } from 'sharp'
1
+ import { localOutputPath, runTimestamp, uniquifyOutputPath } from 'src/runner/outputPath.ts'
2
+
3
+ /** paths claimed by in-flight retrievals: two same-second runs on a
4
+ * counter-resetting cloud host compute the same name before either writes */
5
+ const CLAIMED_OUTPUT_PATHS = new Set<string>()
6
+ import type { FormatEnum } from 'sharp'
4
7
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
8
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
9
+ import { importSharp } from 'src/utils/lazySharp.ts'
5
10
  import { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'
6
11
  import type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
7
12
  import { asAbsolutePath, type ImageSaveFormat, type Maybe } from 'src/types/index.ts'
@@ -95,7 +100,7 @@ export class ComfyExecution {
95
100
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1000).toFixed(0)}s`
96
101
  if (line === this._lastLoggedLine) return
97
102
  this._lastLoggedLine = line
98
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`)
103
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`)
99
104
  else console.log(line)
100
105
  }
101
106
 
@@ -103,7 +108,7 @@ export class ComfyExecution {
103
108
  if (!this.logProgress) return
104
109
  const p = this.progress
105
110
  const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${this.images.length} image(s)`
106
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
111
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
107
112
  else console.log(line)
108
113
  }
109
114
 
@@ -204,17 +209,28 @@ export class ComfyExecution {
204
209
  // image route on the host (cloud answers a 302 signed url — fetchFile follows it unauthed)
205
210
  const imgRoute = '/view?' + new URLSearchParams(comfyImageInfo).toString()
206
211
 
207
- // target path on disk
212
+ // target path on disk: OUR naming, never the raw server filename — a
213
+ // cloud host resets its _00001_ counter per run, so the server name
214
+ // overwrote the same local file on every run (his repro 2026-07-31)
208
215
  const sf = this.saveFormat
216
+ const promptPrefix = promptNode.inputs['filename_prefix']
209
217
  let absPath: string = comfyts.resolveFromOutput(
210
- join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename),
218
+ localOutputPath({
219
+ localDir: sf?.prefix,
220
+ filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,
221
+ subfolder: comfyImageInfo.subfolder,
222
+ filename: comfyImageInfo.filename,
223
+ timestamp: runTimestamp(new Date(this.startedAt)),
224
+ }),
211
225
  )
212
226
  if (sf?.format && sf.format !== 'raw') {
213
227
  const extension = sf.format.split('/')[1]
214
228
  absPath += '.' + extension
215
229
  }
216
- const dir = dirname(absPath)
217
- mkdirSync(dir, { recursive: true })
230
+ // last-resort uniquifier: bump past files on disk AND paths claimed by
231
+ // still-downloading retrievals — never overwrite
232
+ const storage = getComfyStorage()
233
+ absPath = uniquifyOutputPath({ path: absPath, exists: (p) => storage.exists(p), claimed: CLAIMED_OUTPUT_PATHS })
218
234
 
219
235
  // ref
220
236
  let img: MediaImage
@@ -236,15 +252,19 @@ export class ComfyExecution {
236
252
  return 'png'
237
253
  })()
238
254
 
239
- await sharp(buff)
255
+ // node-only branch: re-encoding needs sharp (saveFormat 'raw' is the web path)
256
+ const sharp = await importSharp(`saveFormat '${sf.format}' re-encoding`)
257
+ const encoded = await sharp(buff)
240
258
  .withMetadata()
241
259
  .withExif({ IFD0: textChunk })
242
260
  // sharp expect quality between 1 and 100
243
261
  .toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : undefined)
244
- .toFile(absPath)
262
+ .toBuffer()
263
+ storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded))
245
264
 
246
265
  img = new MediaImage({
247
266
  path: asAbsolutePath(absPath),
267
+ buffer: new Uint8Array(encoded),
248
268
  execution: this,
249
269
  promptNodeID: promptNodeID,
250
270
  comfyUIInfos: {
@@ -259,7 +279,7 @@ export class ComfyExecution {
259
279
  const response = await this.host.fetchFile(imgRoute)
260
280
  const buff = await response.arrayBuffer()
261
281
  const uint8arr = new Uint8Array(buff)
262
- writeFileSync(absPath, uint8arr)
282
+ storage.writeBytes(asAbsolutePath(absPath), uint8arr)
263
283
  img = new MediaImage({
264
284
  path: asAbsolutePath(absPath),
265
285
  buffer: uint8arr,
@@ -1,8 +1,9 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
1
  import { type } from 'arktype'
3
2
  import { type ImageMeta, imageMeta } from 'image-meta'
4
- import { basename, dirname } from 'pathe'
5
- import sharp, { type Sharp } from 'sharp'
3
+ import { basename } from 'pathe'
4
+ import type { Sharp } from 'sharp'
5
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
6
+ import { importSharp } from 'src/utils/lazySharp.ts'
6
7
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
7
8
  import type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
8
9
  import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
@@ -170,8 +171,11 @@ export class MediaImage {
170
171
  * does not includes the prefix `data:image/png;base64,`
171
172
  */
172
173
  getBase64Payload(): string {
173
- const bin = Buffer.from(this.buffer)
174
- return bin.toString('base64')
174
+ const bytes = this.buffer
175
+ let bin = ''
176
+ const chunk = 0x8000 // String.fromCharCode arg-count limit
177
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk))
178
+ return btoa(bin)
175
179
  }
176
180
 
177
181
  /** return the ArrayBuffer for this file, regardless it's exact representation */
@@ -180,9 +184,7 @@ export class MediaImage {
180
184
  private _buffer: Maybe<Uint8Array> = null
181
185
  get buffer(): Uint8Array {
182
186
  if (this._buffer != null) return this._buffer
183
- const buff: Buffer | ArrayBuffer = readFileSync(this.absPath)
184
- const uint8arr = new Uint8Array(buff)
185
- this._buffer = uint8arr
187
+ this._buffer = getComfyStorage().readBytes(this.absPath)
186
188
  return this._buffer
187
189
  }
188
190
  freeBuffer = (): void => void (this._buffer = null)
@@ -202,17 +204,14 @@ export class MediaImage {
202
204
  private _metadata: Maybe<ImageMeta> = null
203
205
  get metadata(): ImageMeta {
204
206
  if (this._metadata != null) return this._metadata
205
- const buff = readFileSync(this.absPath)
206
- const uint8arr = new Uint8Array(buff)
207
- this._metadata = imageMeta(uint8arr)
207
+ this._metadata = imageMeta(this.buffer)
208
208
  return this._metadata
209
209
  }
210
210
 
211
211
  private _hash: Maybe<string> = null
212
212
  get hash(): string {
213
213
  if (this._hash != null) return this._hash
214
- const buff: Buffer | ArrayBuffer = readFileSync(this.absPath)
215
- this._hash = hashArrayBuffer(new Uint8Array(buff))
214
+ this._hash = hashArrayBuffer(this.buffer)
216
215
  return this._hash
217
216
  }
218
217
 
@@ -224,8 +223,9 @@ export class MediaImage {
224
223
  /** processing function */
225
224
  fn: (sharp: Sharp) => Sharp,
226
225
  ): Promise<this> => {
227
- const buff = await fn(sharp(this.absPath)).toBuffer()
228
- writeFileSync(this.absPath, buff)
226
+ const sharp = await importSharp('processWithSharp_inplace')
227
+ const buff = await fn(sharp(this.buffer)).toBuffer()
228
+ getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))
229
229
  this.updateBuffer(new Uint8Array(buff))
230
230
  return this
231
231
  }
@@ -241,22 +241,10 @@ export class MediaImage {
241
241
  /** where to save the resulting image */
242
242
  path?: AbsolutePath,
243
243
  ): Promise<MediaImage> => {
244
- const res: Sharp = fn(sharp(this.absPath))
244
+ const sharp = await importSharp('processWithSharp')
245
245
  path ??= this.absPath + `.processed-${Date.now()}` + this.extension
246
- await res.toFile(path)
247
- const buffer = await res.toBuffer()
246
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer())
247
+ getComfyStorage().writeBytes(path, buffer)
248
248
  return new MediaImage({ path, buffer })
249
249
  }
250
-
251
- generatePreview = async (targetPath: string): Promise<void> => {
252
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true })
253
- mkdirSync(dirname(targetPath), { recursive: true })
254
- await img.toFile(targetPath)
255
- }
256
-
257
- generateMiniPreview = async (): Promise<string> => {
258
- const image2 = await sharp(this.absPath).resize(32, 32, { fit: 'inside' }).webp({ quality: 1 }).toBuffer()
259
- const x = image2.toString('base64')
260
- return x
261
- }
262
250
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * local output naming, relative to `.comfy-ts/outputs/` (his repro
3
+ * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
4
+ * `_00001_` counter every run, so trusting it overwrote the same file — and
5
+ * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
6
+ * prefix. Local names are ours: dir from the prompt's own filename_prefix
7
+ * (or an explicit saveFormat.prefix override), then
8
+ * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
9
+ * per stem and nothing ever collides.
10
+ */
11
+ export const localOutputPath = (p: {
12
+ /** explicit local dir override (ImageSaveFormat.prefix) — wins when set */
13
+ localDir?: string
14
+ /** the SaveImage node's own filename_prefix as sent in the prompt */
15
+ filenamePrefix?: string
16
+ /** server-reported subfolder (fallback when no prefix is known) */
17
+ subfolder: string
18
+ /** server-reported filename, e.g. krea_00001_.png */
19
+ filename: string
20
+ /** run timestamp, YYYYMMDD-HHmmss */
21
+ timestamp: string
22
+ }): string => {
23
+ // server name → stem / counter / extension: `krea_00001_.png`
24
+ const dot = p.filename.lastIndexOf('.')
25
+ const ext = dot === -1 ? '' : p.filename.slice(dot)
26
+ const base = dot === -1 ? p.filename : p.filename.slice(0, dot)
27
+ const counterMatch = /_(\d+)_$/.exec(base)
28
+ const counter = counterMatch?.[1]
29
+ const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base
30
+
31
+ // directory + stem intent: explicit local dir > prompt prefix > server
32
+ // layout. The stem SURVIVES a localDir override — identity keeps sorting
33
+ let dir: string
34
+ let stem: string
35
+ if (p.filenamePrefix != null && p.filenamePrefix !== '') {
36
+ const slash = p.filenamePrefix.lastIndexOf('/')
37
+ dir = slash === -1 ? '' : p.filenamePrefix.slice(0, slash)
38
+ stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1)
39
+ } else {
40
+ dir = p.subfolder
41
+ stem = serverStem
42
+ }
43
+ if (p.localDir != null) dir = p.localDir
44
+
45
+ const name = [stem === '' ? null : stem, p.timestamp, counter].filter((x) => x != null).join('_') + ext
46
+ return dir === '' ? name : `${dir}/${name}`
47
+ }
48
+
49
+ /**
50
+ * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
51
+ * was already CLAIMED by a still-downloading retrieval (two same-second runs
52
+ * on a counter-resetting cloud host compute the same name — reviewer catch).
53
+ * The chosen path is claimed before returning.
54
+ */
55
+ export const uniquifyOutputPath = (p: {
56
+ path: string
57
+ exists: (path: string) => boolean
58
+ claimed: Set<string>
59
+ }): string => {
60
+ let out = p.path
61
+ if (p.exists(out) || p.claimed.has(out)) {
62
+ const dot = out.lastIndexOf('.')
63
+ const stem = dot === -1 ? out : out.slice(0, dot)
64
+ const ext = dot === -1 ? '' : out.slice(dot)
65
+ for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`
66
+ }
67
+ p.claimed.add(out)
68
+ return out
69
+ }
70
+
71
+ /** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */
72
+ export const runTimestamp = (d: Date): string => {
73
+ const pad = (n: number): string => String(n).padStart(2, '0')
74
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
75
+ }
@@ -1,4 +1,4 @@
1
- import crypto from 'node:crypto'
1
+ import { sha1HexOfString } from 'src/utils/sha1.ts'
2
2
  import { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'
3
3
  import { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'
4
4
  import { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
@@ -280,7 +280,7 @@ export class ComfySchema {
280
280
  enumValues.length === 0 //
281
281
  ? `[[empty]]`
282
282
  : enumValues.sort().join('|')
283
- const hash = crypto.createHash('sha1').update(hashContent).digest('hex').slice(0, 8)
283
+ const hash = sha1HexOfString(hashContent).slice(0, 8)
284
284
 
285
285
  // 3. retrieve or create an EnumInfo
286
286
  let unionInfo: Maybe<ComfyUnionInfo> = this.knownUnionByHash.get(hash)