comfy-ts 1.3.0 → 2.0.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 (115) hide show
  1. package/README.md +106 -6
  2. package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-CqNE_kgR.js} +67 -14
  3. package/dist/DefinedWorkflow-CqNE_kgR.js.map +1 -0
  4. package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-Da4DZUP7.js} +2 -2
  5. package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-Da4DZUP7.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +548 -239
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +164 -116
  10. package/dist/index.d.ts +165 -117
  11. package/dist/index.js +540 -230
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-Bn6yIJB0.js → run-serve-BqeXtf8P.js} +9 -7
  14. package/dist/run-serve-BqeXtf8P.js.map +1 -0
  15. package/dist/{run-tui-BtjaOXRh.js → run-tui-CiB7TbYv.js} +18 -13
  16. package/dist/run-tui-CiB7TbYv.js.map +1 -0
  17. package/dist/{state-DKCPy105.js → state-C1g_B8zR.js} +398 -201
  18. package/dist/state-C1g_B8zR.js.map +1 -0
  19. package/dist/web.d.ts +17335 -0
  20. package/dist/web.js +5715 -0
  21. package/dist/web.js.map +1 -0
  22. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +1 -0
  23. package/examples/comfy-cloud/anima-t2i.cflow.ts +2 -3
  24. package/examples/comfy-cloud/boogu-i2i.cflow.ts +2 -5
  25. package/examples/comfy-cloud/capybara-i2i.cflow.ts +2 -2
  26. package/examples/comfy-cloud/capybara-i2v.cflow.ts +1 -0
  27. package/examples/comfy-cloud/capybara-t2i.cflow.ts +2 -2
  28. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +1 -0
  29. package/examples/comfy-cloud/chroma-t2i.cflow.ts +2 -5
  30. package/examples/comfy-cloud/ernie-t2i.cflow.ts +2 -3
  31. package/examples/comfy-cloud/firered-i2i.cflow.ts +2 -2
  32. package/examples/comfy-cloud/flux1-i2i.cflow.ts +2 -2
  33. package/examples/comfy-cloud/flux1-t2i.cflow.ts +2 -2
  34. package/examples/comfy-cloud/flux2-i2i.cflow.ts +2 -5
  35. package/examples/comfy-cloud/flux2-t2i.cflow.ts +2 -5
  36. package/examples/comfy-cloud/hidream-i2i.cflow.ts +2 -5
  37. package/examples/comfy-cloud/hidream-t2i.cflow.ts +2 -2
  38. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +1 -0
  39. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +1 -0
  40. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +2 -3
  41. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +1 -0
  42. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +2 -2
  43. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +1 -0
  44. package/examples/comfy-cloud/krea2-t2i.cflow.ts +2 -3
  45. package/examples/comfy-cloud/lens-t2i.cflow.ts +2 -3
  46. package/examples/comfy-cloud/longcat-i2i.cflow.ts +2 -2
  47. package/examples/comfy-cloud/longcat-t2i.cflow.ts +2 -5
  48. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +1 -0
  49. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +1 -0
  50. package/examples/comfy-cloud/newbie-t2i.cflow.ts +2 -5
  51. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +2 -5
  52. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +2 -5
  53. package/examples/comfy-cloud/ovis-t2i.cflow.ts +2 -5
  54. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +2 -5
  55. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +2 -2
  56. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +2 -2
  57. package/examples/comfy-cloud/sd35-t2i.cflow.ts +2 -2
  58. package/examples/comfy-cloud/sdk.d.ts +13251 -11458
  59. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +2 -2
  60. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +1 -0
  61. package/examples/comfy-cloud/svd-i2v.cflow.ts +1 -0
  62. package/examples/comfy-cloud/wan21-i2v.cflow.ts +1 -0
  63. package/examples/comfy-cloud/wan21-t2v.cflow.ts +1 -0
  64. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +1 -0
  65. package/examples/comfy-cloud/wan22-i2v.cflow.ts +1 -0
  66. package/examples/comfy-cloud/wan22-t2v.cflow.ts +1 -0
  67. package/examples/comfy-cloud/z-image-t2i.cflow.ts +2 -5
  68. package/examples/rvion/01-txt2img.cflow.ts +5 -3
  69. package/examples/rvion/02-img2img-upload.cflow.ts +5 -4
  70. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +6 -7
  71. package/examples/rvion/05-comfy-cloud.cflow.ts +4 -2
  72. package/examples/rvion/06-qwen-image-edit.cflow.ts +2 -3
  73. package/examples/web/example.ts +78 -0
  74. package/examples/web/index.html +77 -0
  75. package/examples/web/serve.ts +42 -0
  76. package/examples/web/tsconfig.json +15 -0
  77. package/package.json +8 -2
  78. package/src/cli/serve/ServeApp.ts +9 -6
  79. package/src/cli/tui/state/ExecSt.ts +14 -2
  80. package/src/coreExports.ts +118 -0
  81. package/src/host/ComfyHost.ts +56 -24
  82. package/src/host/ResilientWebsocket.ts +93 -47
  83. package/src/host/hostUrl.ts +2 -1
  84. package/src/host/loraManagerApi.ts +6 -7
  85. package/src/index.ts +8 -107
  86. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  87. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  88. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  89. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  90. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  91. package/src/runner/ComfyExecution.ts +168 -77
  92. package/src/runner/ComfyWorkflow.ts +25 -3
  93. package/src/runner/ComfyWsApi.ts +6 -0
  94. package/src/runner/MediaImage.ts +73 -38
  95. package/src/runner/ephemeral.ts +21 -0
  96. package/src/runner/outputPath.ts +2 -2
  97. package/src/sdk-generator/ComfySchema.ts +2 -2
  98. package/src/sdk-generator/_pythonModuleToNamespace.ts +3 -0
  99. package/src/state.ts +13 -9
  100. package/src/storage/ComfyStorage.ts +144 -0
  101. package/src/storage/nodeStorage.ts +9 -0
  102. package/src/types/index.ts +6 -2
  103. package/src/utils/downloadFile.ts +11 -69
  104. package/src/utils/hashArrayBuffer.ts +3 -4
  105. package/src/utils/lazySharp.ts +25 -0
  106. package/src/utils/sha1.ts +69 -0
  107. package/src/vars/ComfyVars.ts +5 -6
  108. package/src/vars/DefinedWorkflow.ts +3 -1
  109. package/src/vars/loraKeywords.ts +6 -6
  110. package/src/web.ts +13 -0
  111. package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
  112. package/dist/run-serve-Bn6yIJB0.js.map +0 -1
  113. package/dist/run-tui-BtjaOXRh.js.map +0 -1
  114. package/dist/state-DKCPy105.js.map +0 -1
  115. package/src/utils/writeFile.ts +0 -16
package/dist/index.js CHANGED
@@ -1,18 +1,116 @@
1
- import fs, { existsSync, mkdirSync, readFileSync, statSync, writeFile, writeFileSync } from "node:fs";
1
+ import * as fs from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import * as os from "node:os";
2
4
  import { basename, dirname, isAbsolute, join, resolve } from "pathe";
3
5
  import { scope, type } from "arktype";
4
6
  import { nanoid } from "nanoid";
5
- import sharp from "sharp";
6
7
  import { imageMeta } from "image-meta";
7
- import crypto from "node:crypto";
8
- import WebSocket from "ws";
9
- import { homedir } from "node:os";
10
8
  import { action, makeObservable, observable, runInAction } from "mobx";
11
- import https from "node:https";
12
- import { stdout } from "node:process";
13
9
  import { fileURLToPath } from "node:url";
10
+ //#region src/storage/ComfyStorage.ts
11
+ function dirnameOf(path) {
12
+ const ix = path.lastIndexOf("/");
13
+ return ix <= 0 ? "/" : path.slice(0, ix);
14
+ }
15
+ /** node backend built from INJECTED modules: nodeStorage.ts passes its static
16
+ * imports, the autodetect below passes process.getBuiltinModule results */
17
+ function createNodeStorageFrom(fs, os) {
18
+ return {
19
+ kind: "node",
20
+ readText: (p) => fs.readFileSync(p, "utf8"),
21
+ readTextIfExists: (p) => fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null,
22
+ readBytes: (p) => new Uint8Array(fs.readFileSync(p)),
23
+ writeText: (p, text) => {
24
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
25
+ fs.writeFileSync(p, text);
26
+ },
27
+ writeBytes: (p, bytes) => {
28
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
29
+ fs.writeFileSync(p, bytes);
30
+ },
31
+ exists: (p) => fs.existsSync(p),
32
+ mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
33
+ mtimeMs: (p) => fs.existsSync(p) ? fs.statSync(p).mtimeMs : null,
34
+ homedir: () => os.homedir(),
35
+ cwd: () => process.cwd()
36
+ };
37
+ }
38
+ /** in-memory backend: the web default, also handy for hermetic tests.
39
+ * Paths are LITERAL keys (no normalization — core callers resolve through
40
+ * pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp
41
+ * dirs only, never implicit parents. Bytes are copied in AND out so neither
42
+ * side can mutate the store. */
43
+ function createMemoryStorage(p = {}) {
44
+ const files = /* @__PURE__ */ new Map();
45
+ const mtimes = /* @__PURE__ */ new Map();
46
+ const dirs = /* @__PURE__ */ new Set();
47
+ const td = new TextDecoder();
48
+ const te = new TextEncoder();
49
+ const write = (path, bytes) => {
50
+ files.set(path, bytes.slice());
51
+ mtimes.set(path, Date.now());
52
+ };
53
+ return {
54
+ kind: "memory",
55
+ readText: (path) => {
56
+ const hit = files.get(path);
57
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
58
+ return td.decode(hit);
59
+ },
60
+ readTextIfExists: (path) => {
61
+ const hit = files.get(path);
62
+ return hit == null ? null : td.decode(hit);
63
+ },
64
+ readBytes: (path) => {
65
+ const hit = files.get(path);
66
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
67
+ return hit.slice();
68
+ },
69
+ writeText: (path, text) => write(path, te.encode(text)),
70
+ writeBytes: write,
71
+ exists: (path) => files.has(path) || dirs.has(path),
72
+ mkdirp: (path) => void dirs.add(path),
73
+ mtimeMs: (path) => mtimes.get(path) ?? null,
74
+ homedir: () => p.homedir ?? "/home/web",
75
+ cwd: () => p.cwd ?? "/"
76
+ };
77
+ }
78
+ let installedDefault = null;
79
+ /** entries call this at import time: index.ts installs node, web.ts memory */
80
+ function setDefaultComfyStorage(storage) {
81
+ installedDefault = storage;
82
+ }
83
+ function autodetectNodeStorage() {
84
+ const get = globalThis.process?.getBuiltinModule;
85
+ if (typeof get !== "function") return null;
86
+ const fs = get("node:fs");
87
+ const os = get("node:os");
88
+ if (fs == null || os == null) return null;
89
+ return createNodeStorageFrom(fs, os);
90
+ }
91
+ function resolveComfyStorage(explicit) {
92
+ if (explicit != null) return explicit;
93
+ if (installedDefault != null) return installedDefault;
94
+ const detected = autodetectNodeStorage();
95
+ if (detected != null) {
96
+ installedDefault = detected;
97
+ return detected;
98
+ }
99
+ throw new Error(`no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`);
100
+ }
101
+ /** the ONE accessor call sites use: the instance's storage when the global
102
+ * exists, the resolved default otherwise (vars constructed before create()) */
103
+ function getComfyStorage() {
104
+ return globalThis.comfyts?.storage ?? resolveComfyStorage();
105
+ }
106
+ //#endregion
107
+ //#region src/storage/nodeStorage.ts
108
+ function createNodeStorage() {
109
+ return createNodeStorageFrom(fs, os);
110
+ }
111
+ //#endregion
14
112
  //#region package.json
15
- var version = "1.3.0";
113
+ var version = "2.0.0";
16
114
  //#endregion
17
115
  //#region src/litegraph/LiteGraphLinkID.ts
18
116
  const asLiteGraphLinkID = (id) => id;
@@ -1564,7 +1662,7 @@ var LiteGraphCtx = class {
1564
1662
  * `_00001_` counter every run, so trusting it overwrote the same file — and
1565
1663
  * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
1566
1664
  * prefix. Local names are ours: dir from the prompt's own filename_prefix
1567
- * (or an explicit saveFormat.prefix override), then
1665
+ * (or an explicit save.prefix override), then
1568
1666
  * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
1569
1667
  * per stem and nothing ever collides.
1570
1668
  */
@@ -1616,6 +1714,32 @@ const runTimestamp = (d) => {
1616
1714
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
1617
1715
  };
1618
1716
  //#endregion
1717
+ //#region src/utils/extractErrorMessage.ts
1718
+ /** Extracts an error message from an exception stuff. */
1719
+ const extractErrorMessage = (error) => {
1720
+ if (error instanceof Error) return error.message;
1721
+ if (error === null) return "null";
1722
+ if (typeof error === "string") return error;
1723
+ if (typeof error === "object") {
1724
+ if ("message" in error && typeof error.message === "string") return error.message;
1725
+ return JSON.stringify(error);
1726
+ }
1727
+ return String(error);
1728
+ };
1729
+ //#endregion
1730
+ //#region src/utils/lazySharp.ts
1731
+ let cached = null;
1732
+ async function importSharp(reason) {
1733
+ if (cached != null) return cached;
1734
+ const specifier = "sharp";
1735
+ try {
1736
+ cached = (await import(specifier)).default;
1737
+ return cached;
1738
+ } catch (e) {
1739
+ throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
1740
+ }
1741
+ }
1742
+ //#endregion
1619
1743
  //#region src/types/index.ts
1620
1744
  const asAbsolutePath = (path) => path;
1621
1745
  const asRelativePath = (path) => path;
@@ -1665,10 +1789,78 @@ function exhaust(x) {
1665
1789
  return x;
1666
1790
  }
1667
1791
  //#endregion
1792
+ //#region src/utils/sha1.ts
1793
+ function sha1Hex(data) {
1794
+ const ml = data.length;
1795
+ const total = Math.ceil((ml + 1 + 8) / 64) * 64;
1796
+ const bytes = new Uint8Array(total);
1797
+ bytes.set(data);
1798
+ bytes[ml] = 128;
1799
+ const dv = new DataView(bytes.buffer);
1800
+ const bitLen = ml * 8;
1801
+ dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32));
1802
+ dv.setUint32(total - 4, bitLen >>> 0);
1803
+ let h0 = 1732584193;
1804
+ let h1 = 4023233417;
1805
+ let h2 = 2562383102;
1806
+ let h3 = 271733878;
1807
+ let h4 = 3285377520;
1808
+ const w = /* @__PURE__ */ new Uint32Array(80);
1809
+ for (let i = 0; i < total; i += 64) {
1810
+ for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
1811
+ for (let j = 16; j < 80; j++) {
1812
+ const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0);
1813
+ w[j] = n << 1 | n >>> 31;
1814
+ }
1815
+ let a = h0;
1816
+ let b = h1;
1817
+ let c = h2;
1818
+ let d = h3;
1819
+ let e = h4;
1820
+ for (let j = 0; j < 80; j++) {
1821
+ let f;
1822
+ let k;
1823
+ if (j < 20) {
1824
+ f = b & c | ~b & d;
1825
+ k = 1518500249;
1826
+ } else if (j < 40) {
1827
+ f = b ^ c ^ d;
1828
+ k = 1859775393;
1829
+ } else if (j < 60) {
1830
+ f = b & c | b & d | c & d;
1831
+ k = 2400959708;
1832
+ } else {
1833
+ f = b ^ c ^ d;
1834
+ k = 3395469782;
1835
+ }
1836
+ const temp = (a << 5 | a >>> 27) + f + e + k + (w[j] ?? 0) >>> 0;
1837
+ e = d;
1838
+ d = c;
1839
+ c = b << 30 | b >>> 2;
1840
+ b = a;
1841
+ a = temp;
1842
+ }
1843
+ h0 = h0 + a >>> 0;
1844
+ h1 = h1 + b >>> 0;
1845
+ h2 = h2 + c >>> 0;
1846
+ h3 = h3 + d >>> 0;
1847
+ h4 = h4 + e >>> 0;
1848
+ }
1849
+ return [
1850
+ h0,
1851
+ h1,
1852
+ h2,
1853
+ h3,
1854
+ h4
1855
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
1856
+ }
1857
+ function sha1HexOfString(s) {
1858
+ return sha1Hex(new TextEncoder().encode(s));
1859
+ }
1860
+ //#endregion
1668
1861
  //#region src/utils/hashArrayBuffer.ts
1669
1862
  const hashArrayBuffer = (buffer) => {
1670
- const data = Buffer.from(buffer);
1671
- return crypto.createHash("sha1").update(data).digest("hex");
1863
+ return sha1Hex(buffer);
1672
1864
  };
1673
1865
  //#endregion
1674
1866
  //#region src/graph/ComfyNodeID.ts
@@ -1800,6 +1992,21 @@ const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
1800
1992
  const WsMsg_ark = types$1.WsMsg;
1801
1993
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
1802
1994
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
1995
+ //#endregion
1996
+ //#region src/runner/MediaImage.ts
1997
+ /** base64 image loader nodes we know how to wire, in preference order — each
1998
+ * verified against a real object_info dump before entering the table */
1999
+ const BASE64_IMAGE_LOADERS = [{
2000
+ nameInComfy: "ETN_LoadImageBase64",
2001
+ inputs: (b64) => ({ image: b64 })
2002
+ }, {
2003
+ nameInComfy: "easy loadImageBase64",
2004
+ inputs: (b64) => ({
2005
+ base64_data: b64,
2006
+ image_output: "Hide",
2007
+ save_prefix: ""
2008
+ })
2009
+ }];
1803
2010
  type({
1804
2011
  comfyHostHttpURL: "string",
1805
2012
  comfyImageInfo: ComfyImageInfo_ark
@@ -1828,8 +2035,19 @@ var MediaImage = class MediaImage {
1828
2035
  channel
1829
2036
  });
1830
2037
  };
2038
+ this.loadInWorkflow_viaBase64Node = (workflow) => {
2039
+ const schema = workflow.host.schema;
2040
+ const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy));
2041
+ if (entry == null) throw new Error(`❌ host '${workflow.host.data.id}' has no base64 image loader node (looked for: ${BASE64_IMAGE_LOADERS.map((t) => `'${t.nameInComfy}'`).join(", ")}). Install one (e.g. comfyui-tooling-nodes) or fall back to loadInWorkflow_viaLoadImageNode (uploads persist server-side).`);
2042
+ return new ComfyNode(workflow, (workflow._uidNumber++).toString(), {
2043
+ class_type: entry.nameInComfy,
2044
+ inputs: entry.inputs(this.getBase64Payload())
2045
+ }, {});
2046
+ };
1831
2047
  this._buffer = null;
1832
- this.freeBuffer = () => void (this._buffer = null);
2048
+ this.freeBuffer = () => {
2049
+ if (this.absPath != null) this._buffer = null;
2050
+ };
1833
2051
  this.updateBuffer = (buff) => {
1834
2052
  this._buffer = buff;
1835
2053
  this._metadata = null;
@@ -1844,41 +2062,35 @@ var MediaImage = class MediaImage {
1844
2062
  this._metadata = null;
1845
2063
  this._hash = null;
1846
2064
  this.processWithSharp_inplace = async (fn) => {
1847
- const buff = await fn(sharp(this.absPath)).toBuffer();
1848
- writeFileSync(this.absPath, buff);
2065
+ const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
2066
+ if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
1849
2067
  this.updateBuffer(new Uint8Array(buff));
1850
2068
  return this;
1851
2069
  };
1852
2070
  this.processWithSharp = async (fn, path) => {
1853
- const res = fn(sharp(this.absPath));
1854
- path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
1855
- await res.toFile(path);
1856
- const buffer = await res.toBuffer();
2071
+ const sharp = await importSharp("processWithSharp");
2072
+ path ??= this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : void 0;
2073
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
2074
+ if (path != null) getComfyStorage().writeBytes(path, buffer);
1857
2075
  return new MediaImage({
1858
2076
  path,
1859
2077
  buffer
1860
2078
  });
1861
2079
  };
1862
- this.generatePreview = async (targetPath) => {
1863
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
1864
- mkdirSync(dirname(targetPath), { recursive: true });
1865
- await img.toFile(targetPath);
1866
- };
1867
- this.generateMiniPreview = async () => {
1868
- return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
1869
- };
1870
- this.absPath = data.path;
2080
+ this.absPath = data.path ?? null;
1871
2081
  this.execution = data.execution;
1872
2082
  this.promptNodeID = data.promptNodeID;
2083
+ if (data.path == null && data.buffer == null) throw new Error("❌ MediaImage: an in-memory image (no path) requires a buffer");
1873
2084
  if (data.buffer != null) this.updateBuffer(data.buffer);
1874
2085
  }
1875
2086
  /** the image as a Blob, e.g. to feed FormData uploads */
1876
2087
  getAsBlob() {
1877
2088
  return new Blob([this.buffer], { type: `image/${this.metadata.type ?? "png"}` });
1878
2089
  }
1879
- /** return the image filename */
2090
+ /** return the image filename (in-memory images get a stable hash-derived name) */
1880
2091
  get filename() {
1881
- return basename(this.absPath);
2092
+ if (this.absPath != null) return basename(this.absPath);
2093
+ return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? "png"}`;
1882
2094
  }
1883
2095
  get baseNameWithoutExtension() {
1884
2096
  const fname = this.filename;
@@ -1936,26 +2148,25 @@ var MediaImage = class MediaImage {
1936
2148
  * does not includes the prefix `data:image/png;base64,`
1937
2149
  */
1938
2150
  getBase64Payload() {
1939
- return Buffer.from(this.buffer).toString("base64");
2151
+ const bytes = this.buffer;
2152
+ let bin = "";
2153
+ const chunk = 32768;
2154
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
2155
+ return btoa(bin);
1940
2156
  }
1941
2157
  get buffer() {
1942
2158
  if (this._buffer != null) return this._buffer;
1943
- const buff = readFileSync(this.absPath);
1944
- const uint8arr = new Uint8Array(buff);
1945
- this._buffer = uint8arr;
2159
+ this._buffer = getComfyStorage().readBytes(bang(this.absPath, "in-memory MediaImage lost its buffer"));
1946
2160
  return this._buffer;
1947
2161
  }
1948
2162
  get metadata() {
1949
2163
  if (this._metadata != null) return this._metadata;
1950
- const buff = readFileSync(this.absPath);
1951
- const uint8arr = new Uint8Array(buff);
1952
- this._metadata = imageMeta(uint8arr);
2164
+ this._metadata = imageMeta(this.buffer);
1953
2165
  return this._metadata;
1954
2166
  }
1955
2167
  get hash() {
1956
2168
  if (this._hash != null) return this._hash;
1957
- const buff = readFileSync(this.absPath);
1958
- this._hash = hashArrayBuffer(new Uint8Array(buff));
2169
+ this._hash = hashArrayBuffer(this.buffer);
1959
2170
  return this._hash;
1960
2171
  }
1961
2172
  };
@@ -1971,7 +2182,9 @@ var ComfyExecution = class {
1971
2182
  constructor(workflow, data, init = {}) {
1972
2183
  this.workflow = workflow;
1973
2184
  this.data = data;
1974
- this.saveFormat = null;
2185
+ this.save = null;
2186
+ this.scrubHistory = false;
2187
+ this.ephemeral = false;
1975
2188
  this.snapshot = null;
1976
2189
  this.onProgress = null;
1977
2190
  this.logProgress = false;
@@ -1982,6 +2195,13 @@ var ComfyExecution = class {
1982
2195
  });
1983
2196
  this.onPromptRelatedMessage = (msg) => {
1984
2197
  const graph = this.workflow;
2198
+ if (msg.type === "binary_preview_frame") {
2199
+ if (this.wsOutputNodeExecuting) this.onWsImageOutput({
2200
+ bytes: msg.bytes,
2201
+ mime: msg.mime
2202
+ });
2203
+ return;
2204
+ }
1985
2205
  if (msg.type === "execution_start") return;
1986
2206
  else if (msg.type === "execution_cached") graph.onExecutionCached(msg);
1987
2207
  else if (msg.type === "executing") this.onExecuting(msg);
@@ -2025,70 +2245,104 @@ var ComfyExecution = class {
2025
2245
  this.imageErrors = [];
2026
2246
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
2027
2247
  const promptNode = this.workflow.data.apiJson?.[promptNodeID];
2028
- const promptMeta = this.workflow.data.metadata?.[promptNodeID];
2029
2248
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
2030
2249
  const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
2031
- const sf = this.saveFormat;
2250
+ const response = await this.host.fetchFile(imgRoute);
2251
+ const bytes = new Uint8Array(await response.arrayBuffer());
2252
+ const comfyUIInfos = {
2253
+ comfyImageInfo,
2254
+ comfyHostHttpURL: this.host.getServerHostHTTP()
2255
+ };
2256
+ const sf = this.save;
2257
+ if (sf == null) return this.pushImage(new MediaImage({
2258
+ buffer: bytes,
2259
+ execution: this,
2260
+ promptNodeID,
2261
+ comfyUIInfos
2262
+ }), promptNodeID);
2032
2263
  const promptPrefix = promptNode.inputs["filename_prefix"];
2033
- let absPath = comfyts.resolveFromOutput(localOutputPath({
2034
- localDir: sf?.prefix,
2264
+ const written = await this.encodeAndWrite({
2265
+ bytes,
2266
+ sf,
2035
2267
  filenamePrefix: typeof promptPrefix === "string" ? promptPrefix : void 0,
2036
2268
  subfolder: comfyImageInfo.subfolder,
2037
- filename: comfyImageInfo.filename,
2038
- timestamp: runTimestamp(new Date(this.startedAt))
2039
- }));
2040
- if (sf?.format && sf.format !== "raw") {
2041
- const extension = sf.format.split("/")[1];
2042
- absPath += "." + extension;
2043
- }
2044
- absPath = uniquifyOutputPath({
2045
- path: absPath,
2046
- exists: existsSync,
2047
- claimed: CLAIMED_OUTPUT_PATHS
2269
+ filename: comfyImageInfo.filename
2048
2270
  });
2049
- mkdirSync(dirname(absPath), { recursive: true });
2050
- let img;
2051
- if (sf && sf.format !== "raw") {
2052
- const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2271
+ this.pushImage(new MediaImage({
2272
+ path: written.path,
2273
+ buffer: written.bytes,
2274
+ execution: this,
2275
+ promptNodeID,
2276
+ comfyUIInfos
2277
+ }), promptNodeID);
2278
+ };
2279
+ this.encodeAndWrite = async (p) => {
2280
+ let bytes = p.bytes;
2281
+ const reencode = p.sf.format != null && p.sf.format !== "raw";
2282
+ if (reencode) {
2053
2283
  let textChunk = {};
2054
2284
  try {
2055
- const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
2285
+ const res = getPngMetadataFromUint8Array(p.bytes);
2056
2286
  if (res.success) textChunk = res.value;
2057
2287
  } catch {}
2058
2288
  const format = (() => {
2059
- if (sf.format === "image/jpeg") return "jpeg";
2060
- if (sf.format === "image/png") return "png";
2061
- if (sf.format === "image/webp") return "webp";
2289
+ if (p.sf.format === "image/jpeg") return "jpeg";
2290
+ if (p.sf.format === "image/webp") return "webp";
2062
2291
  return "png";
2063
2292
  })();
2064
- await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
2065
- img = new MediaImage({
2066
- path: asAbsolutePath(absPath),
2067
- execution: this,
2068
- promptNodeID,
2069
- comfyUIInfos: {
2070
- comfyImageInfo,
2071
- comfyHostHttpURL: this.host.getServerHostHTTP()
2072
- }
2073
- });
2074
- } else {
2075
- const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2076
- const uint8arr = new Uint8Array(buff);
2077
- writeFileSync(absPath, uint8arr);
2078
- img = new MediaImage({
2079
- path: asAbsolutePath(absPath),
2080
- buffer: uint8arr,
2081
- execution: this,
2082
- promptNodeID,
2083
- comfyUIInfos: {
2084
- comfyImageInfo,
2085
- comfyHostHttpURL: this.host.getServerHostHTTP()
2086
- }
2087
- });
2293
+ const encoded = await (await importSharp(`save format '${p.sf.format}' re-encoding`))(p.bytes).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, p.sf.quality ? { quality: Math.round(p.sf.quality * 100) } : void 0).toBuffer();
2294
+ bytes = new Uint8Array(encoded);
2088
2295
  }
2089
- if (promptMeta?.tag) img.tags.push(promptMeta.tag);
2090
- if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
2091
- this.images.push(img);
2296
+ let absPath = comfyts.resolveFromOutput(localOutputPath({
2297
+ localDir: p.sf.prefix,
2298
+ filenamePrefix: p.filenamePrefix,
2299
+ subfolder: p.subfolder,
2300
+ filename: p.filename,
2301
+ timestamp: runTimestamp(new Date(this.startedAt))
2302
+ }));
2303
+ if (reencode) absPath += "." + bang(p.sf.format).split("/")[1];
2304
+ const storage = getComfyStorage();
2305
+ absPath = uniquifyOutputPath({
2306
+ path: absPath,
2307
+ exists: (x) => storage.exists(x),
2308
+ claimed: CLAIMED_OUTPUT_PATHS
2309
+ });
2310
+ storage.writeBytes(asAbsolutePath(absPath), bytes);
2311
+ return {
2312
+ path: asAbsolutePath(absPath),
2313
+ bytes
2314
+ };
2315
+ };
2316
+ this.onWsImageOutput = (p) => {
2317
+ const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
2318
+ this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
2319
+ console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
2320
+ this.imageErrors.push({
2321
+ image: null,
2322
+ error: e
2323
+ });
2324
+ }));
2325
+ };
2326
+ this.storeWsImage = async (p, promptNodeID) => {
2327
+ const sf = this.save;
2328
+ if (sf == null) return this.pushImage(new MediaImage({
2329
+ buffer: p.bytes,
2330
+ execution: this,
2331
+ promptNodeID
2332
+ }), promptNodeID);
2333
+ const ext = p.mime === "image/jpeg" ? "jpg" : p.mime.split("/")[1] ?? "png";
2334
+ const written = await this.encodeAndWrite({
2335
+ bytes: p.bytes,
2336
+ sf,
2337
+ subfolder: "",
2338
+ filename: `${this.workflow.id}.${ext}`
2339
+ });
2340
+ this.pushImage(new MediaImage({
2341
+ path: written.path,
2342
+ buffer: written.bytes,
2343
+ execution: this,
2344
+ promptNodeID
2345
+ }), promptNodeID);
2092
2346
  };
2093
2347
  this.images = [];
2094
2348
  this.alreadyDone = false;
@@ -2102,11 +2356,20 @@ var ComfyExecution = class {
2102
2356
  await Promise.all(this.pendingPromises);
2103
2357
  this.host.executions.delete(this.data.id);
2104
2358
  this.host._pendingMsgs.delete(this.data.id);
2359
+ if (this.ephemeral) {
2360
+ const classTypes = Object.values(this.snapshot?.apiJson ?? {}).map((n) => n.class_type);
2361
+ if (classTypes.includes("LoadImage") || classTypes.includes("LoadImageMask")) console.warn(`🟡 ephemeral run ${this.data.id}: outputs never touched the server disk, but the graph's LoadImage nodes reference files in the host's input/ folder (uploads persist — ComfyUI has no delete API). Use MediaImage.loadInWorkflow_viaBase64Node to keep inputs off the server too.`);
2362
+ }
2363
+ if (this.scrubHistory) await this.host.deleteHistory(this.data.id).catch((e) => {
2364
+ console.error(`🔴 failed to scrub history entry ${this.data.id} on host ${this.host.data.id}:`, e);
2365
+ });
2105
2366
  this.finishProgressLine();
2106
2367
  this._resolve(this);
2107
2368
  };
2108
2369
  this.snapshot = init.snapshot ?? null;
2109
- this.saveFormat = init.saveFormat ?? null;
2370
+ this.save = init.save === true ? {} : init.save === false ? null : init.save ?? null;
2371
+ this.scrubHistory = init.scrubHistory ?? false;
2372
+ this.ephemeral = init.ephemeral ?? false;
2110
2373
  this.onProgress = init.onProgress ?? null;
2111
2374
  this.logProgress = init.logProgress ?? false;
2112
2375
  this.host.executions.set(data.id, this);
@@ -2131,14 +2394,14 @@ var ComfyExecution = class {
2131
2394
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2132
2395
  if (line === this._lastLoggedLine) return;
2133
2396
  this._lastLoggedLine = line;
2134
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2397
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2135
2398
  else console.log(line);
2136
2399
  }
2137
2400
  finishProgressLine() {
2138
2401
  if (!this.logProgress) return;
2139
2402
  const p = this.progress;
2140
2403
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2141
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2404
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2142
2405
  else console.log(line);
2143
2406
  }
2144
2407
  log(...args) {
@@ -2164,11 +2427,47 @@ var ComfyExecution = class {
2164
2427
  get status() {
2165
2428
  return this.data.status ?? "New";
2166
2429
  }
2430
+ /** accumulate an output on the prompt; tags from node metadata ride along */
2431
+ pushImage(img, promptNodeID) {
2432
+ const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
2433
+ if (promptMeta?.tag) img.tags.push(promptMeta.tag);
2434
+ if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
2435
+ this.images.push(img);
2436
+ }
2437
+ /** true while the currently executing node is a SaveImageWebsocket in the
2438
+ * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the
2439
+ * live graph may still say SaveImage) — binary frames are then OUTPUTS */
2440
+ get wsOutputNodeExecuting() {
2441
+ const uid = this.workflow.currentExecutingNode?.uid;
2442
+ if (uid == null) return false;
2443
+ return (this.snapshot?.apiJson ?? this.workflow.apiJson)[uid]?.class_type === "SaveImageWebsocket";
2444
+ }
2167
2445
  update(data) {
2168
2446
  Object.assign(this.data, data);
2169
2447
  }
2170
2448
  };
2171
2449
  //#endregion
2450
+ //#region src/runner/ephemeral.ts
2451
+ /**
2452
+ * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage
2453
+ * node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`
2454
+ * input only), so outputs stream over the ws and never touch the server disk.
2455
+ * Mutates the given apiJson IN PLACE — callers pass the run's deep-copied
2456
+ * snapshot, never the live graph. Returns how many nodes were rewritten so
2457
+ * callers can warn when a graph had nothing to rewrite.
2458
+ */
2459
+ function rewriteSaveNodesToWebsocket(apiJson) {
2460
+ let rewritten = 0;
2461
+ for (const node of Object.values(apiJson)) {
2462
+ if (node.class_type !== "SaveImage") continue;
2463
+ const images = node.inputs["images"];
2464
+ node.class_type = "SaveImageWebsocket";
2465
+ node.inputs = images == null ? {} : { images };
2466
+ rewritten++;
2467
+ }
2468
+ return rewritten;
2469
+ }
2470
+ //#endregion
2172
2471
  //#region src/utils/deepCopyNaive.ts
2173
2472
  const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
2174
2473
  //#endregion
@@ -2435,6 +2734,11 @@ var ComfyWorkflow = class {
2435
2734
  apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
2436
2735
  workflowJson: await this.toWorkflowJson()
2437
2736
  };
2737
+ if (p.ephemeral) {
2738
+ const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson);
2739
+ const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === "SaveImageWebsocket");
2740
+ if (rewritten === 0 && !hasWsSaver) console.warn(`🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`);
2741
+ }
2438
2742
  const out = {
2439
2743
  client_id: this.host.comfySessionId,
2440
2744
  prompt: snapshot.apiJson,
@@ -2457,7 +2761,9 @@ var ComfyWorkflow = class {
2457
2761
  graphID: this.id
2458
2762
  }, {
2459
2763
  snapshot,
2460
- saveFormat: p.saveFormat,
2764
+ save: p.save,
2765
+ ephemeral: p.ephemeral ?? false,
2766
+ scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,
2461
2767
  onProgress: p.onProgress,
2462
2768
  logProgress: p.log ?? false
2463
2769
  });
@@ -2551,6 +2857,7 @@ function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
2551
2857
  function pythonModuleToPrefix(pythonModule) {
2552
2858
  if (pythonModule === "nodes") return "";
2553
2859
  if (pythonModule.startsWith("comfy_extras.")) return "";
2860
+ if (pythonModule === "custom_nodes.websocket_image_save") return "";
2554
2861
  if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
2555
2862
  if (pythonModule.startsWith("custom_nodes.")) return pythonModule.replace(/^custom_nodes\./i, "").replace(/^comfyui[-_]/i, "").replace(/[-_]comfyui$/i, "").replace(/^comfy[-_]/i, "").replace(/[-_]comfy$/i, "").replace(/^nodes[-_]/i, "").replace(/[-_]node[-_]suite$/i, "") + ".";
2556
2863
  console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
@@ -2887,7 +3194,7 @@ var ComfySchema = class {
2887
3194
  else if (typeof enumValue === "number") enumValues.push(enumValue);
2888
3195
  else enumValues.push(enumValue.content);
2889
3196
  const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
2890
- const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
3197
+ const hash = sha1HexOfString(hashContent).slice(0, 8);
2891
3198
  let unionInfo = this.knownUnionByHash.get(hash);
2892
3199
  if (unionInfo == null) {
2893
3200
  const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
@@ -3171,19 +3478,6 @@ types.ComfyInputType;
3171
3478
  types.ComfyEnumDef;
3172
3479
  types.ComfyInputOpts;
3173
3480
  //#endregion
3174
- //#region src/utils/extractErrorMessage.ts
3175
- /** Extracts an error message from an exception stuff. */
3176
- const extractErrorMessage = (error) => {
3177
- if (error instanceof Error) return error.message;
3178
- if (error === null) return "null";
3179
- if (typeof error === "string") return error;
3180
- if (typeof error === "object") {
3181
- if ("message" in error && typeof error.message === "string") return error.message;
3182
- return JSON.stringify(error);
3183
- }
3184
- return String(error);
3185
- };
3186
- //#endregion
3187
3481
  //#region src/utils/stringifyReadable.ts
3188
3482
  const tab = " ";
3189
3483
  function readableStringify(obj, maxLevel = 3, level = 0) {
@@ -3211,17 +3505,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3211
3505
  return result;
3212
3506
  }
3213
3507
  //#endregion
3214
- //#region src/utils/writeFile.ts
3215
- const writeFileAsync = async (path, data, fmt) => {
3216
- return new Promise((resolve, reject) => {
3217
- logInfo(`writing file: ${ansi.blue(path)}`);
3218
- writeFile(path, data, fmt, (err) => {
3219
- if (err) reject(err);
3220
- else resolve();
3221
- });
3222
- });
3223
- };
3224
- //#endregion
3225
3508
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3226
3509
  const ComfyManagerAPIModelList_ark = type({ models: type({
3227
3510
  name: type.string.as(),
@@ -3459,7 +3742,8 @@ function parseHostBase(p) {
3459
3742
  function renderHttpBase(p) {
3460
3743
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3461
3744
  }
3462
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3745
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
3746
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
3463
3747
  function renderWsUrl(p) {
3464
3748
  return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3465
3749
  }
@@ -3469,6 +3753,27 @@ function renderPort(p) {
3469
3753
  }
3470
3754
  //#endregion
3471
3755
  //#region src/host/ResilientWebsocket.ts
3756
+ let transportPromise = null;
3757
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
3758
+ function resolveWsTransport() {
3759
+ transportPromise ??= (async () => {
3760
+ const specifier = "ws";
3761
+ try {
3762
+ return {
3763
+ ctor: (await import(specifier)).default,
3764
+ supportsHeaders: true
3765
+ };
3766
+ } catch {
3767
+ const native = globalThis.WebSocket;
3768
+ if (native != null) return {
3769
+ ctor: native,
3770
+ supportsHeaders: false
3771
+ };
3772
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
3773
+ }
3774
+ })();
3775
+ return transportPromise;
3776
+ }
3472
3777
  var ResilientWebSocketClient = class {
3473
3778
  addInfo(msg) {
3474
3779
  this.debugMessages.push({
@@ -3503,7 +3808,17 @@ var ResilientWebSocketClient = class {
3503
3808
  this.currentWS = null;
3504
3809
  this.isOpen = false;
3505
3810
  }
3506
- connect() {
3811
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
3812
+ headerlessUrl(headers) {
3813
+ const rest = { ...headers };
3814
+ const apiKey = rest["X-API-Key"];
3815
+ delete rest["X-API-Key"];
3816
+ const extra = Object.keys(rest);
3817
+ if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
3818
+ if (apiKey == null) return this.url;
3819
+ return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
3820
+ }
3821
+ async connect() {
3507
3822
  this.isOpen = false;
3508
3823
  const prevWS = this.currentWS;
3509
3824
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
@@ -3512,13 +3827,24 @@ var ResilientWebSocketClient = class {
3512
3827
  this.addInfo("Previous WebSocket discarded");
3513
3828
  prevWS.close();
3514
3829
  }
3515
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
3830
+ let ws;
3831
+ try {
3832
+ const transport = await resolveWsTransport();
3833
+ if (this.permanentlyClosed) return;
3834
+ const headers = this.options.headers?.() ?? {};
3835
+ ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
3836
+ } catch (e) {
3837
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
3838
+ this.permanentlyClosed = true;
3839
+ this.options.onTransportDead?.(e);
3840
+ return;
3841
+ }
3516
3842
  ws.binaryType = "arraybuffer";
3517
3843
  this.currentWS = ws;
3518
- if (this.options.onMessage) ws.onmessage = (event) => {
3844
+ ws.onmessage = (event) => {
3519
3845
  this.options.onMessage(event);
3520
3846
  };
3521
- ws.onopen = (_event) => {
3847
+ ws.onopen = () => {
3522
3848
  if (ws !== this.currentWS) return;
3523
3849
  this.addInfo("✅ WebSocket connected to " + this.url);
3524
3850
  this.isOpen = true;
@@ -3532,7 +3858,7 @@ var ResilientWebSocketClient = class {
3532
3858
  if (this.permanentlyClosed) return;
3533
3859
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3534
3860
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3535
- this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
3861
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3536
3862
  };
3537
3863
  ws.onerror = (event) => {
3538
3864
  if (ws !== this.currentWS) return;
@@ -3550,14 +3876,6 @@ var ResilientWebSocketClient = class {
3550
3876
  this.currentWS?.send(message);
3551
3877
  }
3552
3878
  }
3553
- /** forward WebSocket add event listeners to the current WebSocket instance */
3554
- addEventListener(type, listener, options) {
3555
- this.currentWS?.addEventListener(type, listener, options);
3556
- }
3557
- /** forward WebSocket remove event listeners to the current WebSocket instance */
3558
- removeEventListener(type, listener) {
3559
- this.currentWS?.removeEventListener(type, listener);
3560
- }
3561
3879
  };
3562
3880
  //#endregion
3563
3881
  //#region src/vars/loraKeywords.ts
@@ -3577,9 +3895,10 @@ function loadOnce() {
3577
3895
  if (loaded) return;
3578
3896
  loaded = true;
3579
3897
  const path = filePath();
3580
- if (!existsSync(path)) return;
3898
+ const text = getComfyStorage().readTextIfExists(path);
3899
+ if (text == null) return;
3581
3900
  try {
3582
- const raw = JSON.parse(readFileSync(path, "utf8"));
3901
+ const raw = JSON.parse(text);
3583
3902
  if (raw == null || typeof raw !== "object") return;
3584
3903
  runInAction(() => {
3585
3904
  for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
@@ -3602,8 +3921,7 @@ function setLoraKeyword(name, keyword) {
3602
3921
  });
3603
3922
  const path = filePath();
3604
3923
  try {
3605
- mkdirSync(dirname(path), { recursive: true });
3606
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3924
+ getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3607
3925
  } catch (e) {
3608
3926
  logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
3609
3927
  }
@@ -4047,7 +4365,7 @@ var SizeVar = class extends ComfyVar {
4047
4365
  if (iv == null || iv.value === "") return null;
4048
4366
  try {
4049
4367
  const abs = iv.absPath();
4050
- const meta = imageMeta(new Uint8Array(readFileSync(abs)));
4368
+ const meta = imageMeta(getComfyStorage().readBytes(abs));
4051
4369
  if (meta.width == null || meta.height == null) return null;
4052
4370
  return {
4053
4371
  width: meta.width,
@@ -4101,7 +4419,7 @@ var ImageVarEmptyError = class extends Error {
4101
4419
  /** trim + expand a leading `~/` — every ImageVar write funnels through this */
4102
4420
  function expandUserPath(raw) {
4103
4421
  const trimmed = raw.trim();
4104
- return trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
4422
+ return trimmed.startsWith("~/") ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed;
4105
4423
  }
4106
4424
  /**
4107
4425
  * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
@@ -4137,7 +4455,7 @@ var ImageVar = class extends ComfyVar {
4137
4455
  absPath() {
4138
4456
  if (!this.isSet()) throw this.emptyError();
4139
4457
  if (isAbsolute(this.value)) return this.value;
4140
- return resolve(this.opts.folder ?? process.cwd(), this.value);
4458
+ return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value);
4141
4459
  }
4142
4460
  /** empty = unset: the build fails LOUD here (varValues calls outValue) */
4143
4461
  outValue() {
@@ -4146,7 +4464,7 @@ var ImageVar = class extends ComfyVar {
4146
4464
  }
4147
4465
  display() {
4148
4466
  if (!this.isSet()) return "(unset) pick a file";
4149
- const home = homedir();
4467
+ const home = getComfyStorage().homedir();
4150
4468
  return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
4151
4469
  }
4152
4470
  };
@@ -4221,7 +4539,9 @@ var DefinedWorkflow = class {
4221
4539
  advance: true,
4222
4540
  host
4223
4541
  })).run({
4224
- saveFormat: settings.saveFormat,
4542
+ save: settings.save,
4543
+ ephemeral: settings.ephemeral,
4544
+ scrubHistory: settings.scrubHistory,
4225
4545
  idMode: settings.idMode,
4226
4546
  log: settings.log,
4227
4547
  onProgress: settings.onProgress
@@ -4409,6 +4729,12 @@ var ComfyHost = class {
4409
4729
  this.interrupt = () => {
4410
4730
  return this.postJSON_("/interrupt", {});
4411
4731
  };
4732
+ this.deleteHistory = (promptId) => {
4733
+ return this.postJSON_("/history", { delete: [promptId] });
4734
+ };
4735
+ this.clearHistory = () => {
4736
+ return this.postJSON_("/history", { clear: true });
4737
+ };
4412
4738
  this.fetchRawLogs = async () => {
4413
4739
  const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
4414
4740
  if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
@@ -4444,11 +4770,11 @@ var ComfyHost = class {
4444
4770
  this.isUpdatingSchema = true;
4445
4771
  const object_info_json = await this.fetchJSON_("/object_info");
4446
4772
  const object_info_str = readableStringify(object_info_json, 4);
4447
- writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
4773
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
4448
4774
  const res = ComfySchemaJSON_ark(object_info_json);
4449
4775
  if (res instanceof type.errors) printArkResultInConsole(res);
4450
4776
  const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
4451
- writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
4777
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
4452
4778
  this.schema.update({
4453
4779
  spec: object_info_json,
4454
4780
  embeddings: embeddings_json
@@ -4465,7 +4791,7 @@ var ComfyHost = class {
4465
4791
  };
4466
4792
  console.error(error);
4467
4793
  console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
4468
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4794
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4469
4795
  this.markFailed(error);
4470
4796
  } finally {
4471
4797
  this.isUpdatingSchema = false;
@@ -4486,9 +4812,10 @@ var ComfyHost = class {
4486
4812
  this.base = parseHostBase(this.data);
4487
4813
  /** folder where file related to the host config will be cached */
4488
4814
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
4489
- if (!existsSync(this.cacheFolder)) {
4815
+ const storage = getComfyStorage();
4816
+ if (!storage.exists(this.cacheFolder)) {
4490
4817
  console.log("🟢 creating folder", this.cacheFolder);
4491
- mkdirSync(this.cacheFolder, { recursive: true });
4818
+ storage.mkdirp(this.cacheFolder);
4492
4819
  }
4493
4820
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
4494
4821
  this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
@@ -4538,19 +4865,20 @@ var ComfyHost = class {
4538
4865
  }
4539
4866
  async writeSDKToDisk() {
4540
4867
  if (this.data.sdkAutoWrite === false) return;
4868
+ const storage = getComfyStorage();
4541
4869
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
4542
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
4543
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
4870
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
4871
+ storage.writeText(this.sdkDTSPath, comfySchemaTs);
4544
4872
  }
4545
4873
  shouldUseSchemaCache() {
4546
4874
  if (this._schemaStrategy === "refresh") return false;
4547
- const exists = existsSync(this.comfyJSONPath);
4875
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
4548
4876
  if (this._schemaStrategy === "cache") {
4549
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4877
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4550
4878
  return true;
4551
4879
  }
4552
- if (!exists) return false;
4553
- return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
4880
+ if (mtimeMs == null) return false;
4881
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs;
4554
4882
  }
4555
4883
  waitForSession(timeoutMs = 5e3) {
4556
4884
  if (this.comfySessionId !== "temp") return Promise.resolve();
@@ -4585,6 +4913,7 @@ var ComfyHost = class {
4585
4913
  onMessage: (e) => this.onMessage(e),
4586
4914
  url: () => this.getWSUrl(),
4587
4915
  headers: () => this.authHeaders(),
4916
+ onTransportDead: (e) => this.markFailed(e),
4588
4917
  onClose: () => {
4589
4918
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
4590
4919
  }
@@ -4604,7 +4933,7 @@ var ComfyHost = class {
4604
4933
  * examples must still open in the TUI; run() fetches the real schema through
4605
4934
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
4606
4935
  loadSchemaFromCache() {
4607
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
4936
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
4608
4937
  logError(`no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`);
4609
4938
  return Promise.resolve();
4610
4939
  }
@@ -4616,7 +4945,7 @@ var ComfyHost = class {
4616
4945
  embeddings: embeddings_json
4617
4946
  });
4618
4947
  this.schema.RUN_BASIC_CHECKS();
4619
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4948
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4620
4949
  })().catch((e) => {
4621
4950
  this._schemaFromCache = null;
4622
4951
  throw e;
@@ -4641,6 +4970,22 @@ var ComfyHost = class {
4641
4970
  if (e.data instanceof ArrayBuffer) {
4642
4971
  const frame = parseBinaryWsFrame(e.data);
4643
4972
  if (frame.kind === "preview") {
4973
+ const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null;
4974
+ if (activeExec?.wsOutputNodeExecuting) {
4975
+ activeExec.onWsImageOutput({
4976
+ bytes: frame.bytes,
4977
+ mime: frame.mime
4978
+ });
4979
+ return;
4980
+ }
4981
+ if (this.activePromptID != null) {
4982
+ const pending = this._pendingMsgs.get(this.activePromptID);
4983
+ if (pending != null) pending.push({
4984
+ type: "binary_preview_frame",
4985
+ bytes: frame.bytes,
4986
+ mime: frame.mime
4987
+ });
4988
+ }
4644
4989
  const imageBlob = new Blob([frame.bytes], { type: frame.mime });
4645
4990
  this.latentPreview = {
4646
4991
  blob: imageBlob,
@@ -4708,55 +5053,13 @@ var ComfyHost = class {
4708
5053
  };
4709
5054
  //#endregion
4710
5055
  //#region src/utils/downloadFile.ts
4711
- /** Usage example
4712
- * | ;(async () => {
4713
- * | try {
4714
- * | await downloadFile('https://example.com/file', 'folder/filename')
4715
- * | console.log('Download completed successfully')
4716
- * | } catch (error) {
4717
- * | console.error('Download failed:', error)
4718
- * | }
4719
- * | })()
4720
- * |
4721
- */
4722
- function downloadFile(url, outputPath, logPrefix = " - ") {
4723
- mkdirSync(dirname(outputPath), { recursive: true });
4724
- return new Promise((resolve, reject) => {
4725
- https.get(url, (response) => {
4726
- if (response.statusCode === 302 || response.statusCode === 301) {
4727
- const newUrl = response.headers.location;
4728
- console.log(`Redirected to ${newUrl}`);
4729
- resolve(downloadFile(newUrl, outputPath));
4730
- return;
4731
- }
4732
- if (response.statusCode !== 200) {
4733
- reject(`Failed to download file: Status Code ${response.statusCode}`);
4734
- return;
4735
- }
4736
- const rawLen = response.headers["content-length"];
4737
- if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
4738
- else {
4739
- const totalSize = parseInt(rawLen, 10);
4740
- let downloaded = 0;
4741
- let lastLoggedPercentage = 0;
4742
- response.on("data", (chunk) => {
4743
- downloaded += chunk.length;
4744
- const percentage = Math.round(downloaded / totalSize * 100);
4745
- if (percentage >= lastLoggedPercentage + 1) {
4746
- stdout.write(`\r${logPrefix}${percentage}% downloaded`);
4747
- lastLoggedPercentage = percentage;
4748
- }
4749
- });
4750
- }
4751
- const fileStream = fs.createWriteStream(outputPath);
4752
- response.pipe(fileStream);
4753
- fileStream.on("finish", () => {
4754
- console.log(` (DONE)`);
4755
- fileStream.close();
4756
- resolve(true);
4757
- });
4758
- }).on("error", (err) => reject(err));
4759
- });
5056
+ async function downloadFile(url, outputPath, logPrefix = " - ") {
5057
+ const res = await fetch(url);
5058
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
5059
+ const bytes = new Uint8Array(await res.arrayBuffer());
5060
+ getComfyStorage().writeBytes(outputPath, bytes);
5061
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
5062
+ return true;
4760
5063
  }
4761
5064
  //#endregion
4762
5065
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
@@ -4877,7 +5180,7 @@ const ComfyManagerRawPluginInfo_ark = type({
4877
5180
  const _getKnownPlugins = (DB) => {
4878
5181
  const counter = DB.report.file("custom-node-list.json");
4879
5182
  let totalFileSeen = 0;
4880
- const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
5183
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
4881
5184
  if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4882
5185
  const canonical = [];
4883
5186
  for (const row of root.custom_nodes) {
@@ -4915,7 +5218,7 @@ const _getKnownPlugins = (DB) => {
4915
5218
  }
4916
5219
  out1 += "\n";
4917
5220
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
4918
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5221
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4919
5222
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4920
5223
  let out2 = "";
4921
5224
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -4923,7 +5226,7 @@ const _getKnownPlugins = (DB) => {
4923
5226
  out2 += "export type KnownComfyPluginURL =\n";
4924
5227
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
4925
5228
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
4926
- writeFileSync(out2Path, out2, "utf-8");
5229
+ getComfyStorage().writeText(out2Path, out2);
4927
5230
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4928
5231
  }
4929
5232
  if (DB.opts.check) {
@@ -4969,7 +5272,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNod
4969
5272
  const _getCustomNodeRegistry = (DB) => {
4970
5273
  const counter = DB.report.file("extension-node-map.json");
4971
5274
  let totalCustomNodeSeen = 0;
4972
- const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
5275
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
4973
5276
  const root = type("Record<string, unknown>")(raw);
4974
5277
  if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4975
5278
  for (const [url, value] of Object.entries(root)) {
@@ -5005,7 +5308,7 @@ const _getCustomNodeRegistry = (DB) => {
5005
5308
  for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
5006
5309
  out += "\n";
5007
5310
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
5008
- writeFileSync(outPath, out + "\n", "utf-8");
5311
+ getComfyStorage().writeText(outPath, out + "\n");
5009
5312
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
5010
5313
  }
5011
5314
  if (DB.opts.check) {
@@ -5060,7 +5363,7 @@ const ComfyManagerModelInfo_ark = type({
5060
5363
  //#region src/manager/loaders/step4_model-list-loader.ts
5061
5364
  const _getKnownModels = (DB) => {
5062
5365
  const counter = DB.report.file("model-list.json");
5063
- const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
5366
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
5064
5367
  if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
5065
5368
  const canonical = [];
5066
5369
  for (const row of root.models) {
@@ -5089,7 +5392,7 @@ const _getKnownModels = (DB) => {
5089
5392
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
5090
5393
  out1 += "]\n";
5091
5394
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
5092
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5395
+ getComfyStorage().writeText(out1Path, out1 + "\n");
5093
5396
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
5094
5397
  let out4 = "";
5095
5398
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -5105,7 +5408,7 @@ const _getKnownModels = (DB) => {
5105
5408
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
5106
5409
  out4 += "]\n";
5107
5410
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
5108
- writeFileSync(out4Path, out4 + "\n", "utf-8");
5411
+ getComfyStorage().writeText(out4Path, out4 + "\n");
5109
5412
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
5110
5413
  let out2 = "";
5111
5414
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -5122,7 +5425,7 @@ const _getKnownModels = (DB) => {
5122
5425
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
5123
5426
  out2 += "]\n";
5124
5427
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
5125
- writeFileSync(out2Path, out2 + "\n", "utf-8");
5428
+ getComfyStorage().writeText(out2Path, out2 + "\n");
5126
5429
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
5127
5430
  let out3 = "";
5128
5431
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -5137,7 +5440,7 @@ const _getKnownModels = (DB) => {
5137
5440
  }
5138
5441
  out3 += "\n";
5139
5442
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
5140
- writeFileSync(out3Path, out3 + "\n", "utf-8");
5443
+ getComfyStorage().writeText(out3Path, out3 + "\n");
5141
5444
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
5142
5445
  let out99 = "";
5143
5446
  out99 += `// prettier-ignore\n`;
@@ -5151,7 +5454,7 @@ const _getKnownModels = (DB) => {
5151
5454
  }
5152
5455
  out99 += "\n";
5153
5456
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
5154
- writeFileSync(out99Path, out99 + "\n", "utf-8");
5457
+ getComfyStorage().writeText(out99Path, out99 + "\n");
5155
5458
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
5156
5459
  }
5157
5460
  if (DB.opts.check) {
@@ -5172,7 +5475,7 @@ const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
5172
5475
  //#region src/manager/loaders/step5_alter-list-loader.ts
5173
5476
  const _getAlterList = (DB) => {
5174
5477
  const counter = DB.report.file("alter-list.json");
5175
- const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
5478
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
5176
5479
  if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
5177
5480
  const canonical = [];
5178
5481
  for (const row of root.items) {
@@ -5197,7 +5500,7 @@ const ComfyManagerGithubStatEntry_ark = type({
5197
5500
  //#region src/manager/loaders/step6_github-stats-loader.ts
5198
5501
  const _getGithubStats = (DB) => {
5199
5502
  const counter = DB.report.file("github-stats.json");
5200
- const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
5503
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
5201
5504
  const root = type("Record<string, unknown>")(raw);
5202
5505
  if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
5203
5506
  for (const [url, value] of Object.entries(root)) {
@@ -5312,13 +5615,12 @@ var ComfyTS = class ComfyTS {
5312
5615
  this.version = version;
5313
5616
  this.hosts = /* @__PURE__ */ new Map();
5314
5617
  this._registry = null;
5315
- this.rootPath = asAbsolutePath(process.cwd());
5316
5618
  this.readJSON_ = (absPath, def) => {
5317
- if (!existsSync(absPath)) {
5619
+ const str = this.storage.readTextIfExists(absPath);
5620
+ if (str == null) {
5318
5621
  if (def != null) return def;
5319
5622
  throw new Error(`file does not exist ${absPath}`);
5320
5623
  }
5321
- const str = readFileSync(absPath, "utf8");
5322
5624
  return JSON.parse(str);
5323
5625
  };
5324
5626
  this.autolayoutOpts = {
@@ -5329,7 +5631,8 @@ var ComfyTS = class ComfyTS {
5329
5631
  const globalHack = globalThis;
5330
5632
  if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
5331
5633
  globalHack.comfyts = this;
5332
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
5634
+ this.storage = resolveComfyStorage(p.storage);
5635
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
5333
5636
  this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
5334
5637
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
5335
5638
  this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
@@ -5393,6 +5696,18 @@ var ComfyTS = class ComfyTS {
5393
5696
  }
5394
5697
  };
5395
5698
  //#endregion
5699
+ //#region src/utils/loraTag.ts
5700
+ /**
5701
+ * build a LoraManager-style lora tag: `<lora:name:strength>` or
5702
+ * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5703
+ * autocomplete + validation:
5704
+ *
5705
+ * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5706
+ */
5707
+ function loraTag(name, strength = 1, clipStrength) {
5708
+ return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5709
+ }
5710
+ //#endregion
5396
5711
  //#region src/exampleAssets.ts
5397
5712
  /**
5398
5713
  * the examples/ folder shipped in the npm tarball, resolved from THIS module's
@@ -5445,18 +5760,13 @@ function isTuiActive() {
5445
5760
  return process.env[COMFY_TS_TUI_ENV] === "1";
5446
5761
  }
5447
5762
  //#endregion
5448
- //#region src/utils/loraTag.ts
5763
+ //#region src/index.ts
5449
5764
  /**
5450
- * build a LoraManager-style lora tag: `<lora:name:strength>` or
5451
- * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5452
- * autocomplete + validation:
5453
- *
5454
- * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5765
+ * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)
5766
+ * @packageDocumentation
5455
5767
  */
5456
- function loraTag(name, strength = 1, clipStrength) {
5457
- return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5458
- }
5768
+ setDefaultComfyStorage(createNodeStorage());
5459
5769
  //#endregion
5460
- export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, exampleImagePath, getLoraKeyword, hostIdToNamespace, isTuiActive, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setLoraKeyword, v };
5770
+ export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, exampleImagePath, getComfyStorage, getLoraKeyword, hostIdToNamespace, isTuiActive, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, v };
5461
5771
 
5462
5772
  //# sourceMappingURL=index.js.map