comfy-ts 1.3.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 (53) hide show
  1. package/README.md +26 -0
  2. package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-C_QAxKr3.js} +64 -13
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-DcOTn0QR.js} +2 -2
  5. package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-DcOTn0QR.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +346 -183
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +93 -40
  10. package/dist/index.d.ts +94 -41
  11. package/dist/index.js +338 -174
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-Bn6yIJB0.js → run-serve-CN0DhrsA.js} +3 -3
  14. package/dist/{run-serve-Bn6yIJB0.js.map → run-serve-CN0DhrsA.js.map} +1 -1
  15. package/dist/{run-tui-BtjaOXRh.js → run-tui-bN2hSD5i.js} +10 -11
  16. package/dist/{run-tui-BtjaOXRh.js.map → run-tui-bN2hSD5i.js.map} +1 -1
  17. package/dist/{state-DKCPy105.js → state-COlKYipO.js} +199 -146
  18. package/dist/state-COlKYipO.js.map +1 -0
  19. package/dist/web.d.ts +17340 -0
  20. package/dist/web.js +5569 -0
  21. package/dist/web.js.map +1 -0
  22. package/examples/web/example.ts +71 -0
  23. package/examples/web/index.html +77 -0
  24. package/examples/web/serve.ts +42 -0
  25. package/examples/web/tsconfig.json +15 -0
  26. package/package.json +8 -2
  27. package/src/coreExports.ts +118 -0
  28. package/src/host/ComfyHost.ts +23 -23
  29. package/src/host/ResilientWebsocket.ts +93 -47
  30. package/src/host/hostUrl.ts +2 -1
  31. package/src/host/loraManagerApi.ts +6 -7
  32. package/src/index.ts +8 -107
  33. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  34. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  35. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  36. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  37. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  38. package/src/runner/ComfyExecution.ts +14 -11
  39. package/src/runner/MediaImage.ts +18 -30
  40. package/src/sdk-generator/ComfySchema.ts +2 -2
  41. package/src/state.ts +13 -9
  42. package/src/storage/ComfyStorage.ts +144 -0
  43. package/src/storage/nodeStorage.ts +9 -0
  44. package/src/utils/downloadFile.ts +11 -69
  45. package/src/utils/hashArrayBuffer.ts +3 -4
  46. package/src/utils/lazySharp.ts +25 -0
  47. package/src/utils/sha1.ts +69 -0
  48. package/src/vars/ComfyVars.ts +5 -6
  49. package/src/vars/loraKeywords.ts +6 -6
  50. package/src/web.ts +13 -0
  51. package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
  52. package/dist/state-DKCPy105.js.map +0 -1
  53. package/src/utils/writeFile.ts +0 -16
@@ -1,14 +1,77 @@
1
- import { _ as logError, g as isQuiet, h as extractErrorMessage, t as DefinedWorkflow, v as logInfo, y as logSuccess } from "./DefinedWorkflow-gpknV-5f.js";
2
- import fs, { existsSync, mkdirSync, readFileSync, statSync, writeFile, writeFileSync } from "node:fs";
3
- import { basename, dirname, join } from "pathe";
4
- import crypto from "node:crypto";
1
+ import { _ as resolveComfyStorage, b as logInfo, g as getComfyStorage, h as extractErrorMessage, t as DefinedWorkflow, v as isQuiet, x as logSuccess, y as logError } from "./DefinedWorkflow-C_QAxKr3.js";
2
+ import { basename, join } from "pathe";
5
3
  import { scope, type } from "arktype";
6
4
  import { nanoid } from "nanoid";
7
- import sharp from "sharp";
8
5
  import { imageMeta } from "image-meta";
9
- import WebSocket from "ws";
10
- import https from "node:https";
11
- import { stdout } from "node:process";
6
+ //#region src/utils/sha1.ts
7
+ function sha1Hex(data) {
8
+ const ml = data.length;
9
+ const total = Math.ceil((ml + 1 + 8) / 64) * 64;
10
+ const bytes = new Uint8Array(total);
11
+ bytes.set(data);
12
+ bytes[ml] = 128;
13
+ const dv = new DataView(bytes.buffer);
14
+ const bitLen = ml * 8;
15
+ dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32));
16
+ dv.setUint32(total - 4, bitLen >>> 0);
17
+ let h0 = 1732584193;
18
+ let h1 = 4023233417;
19
+ let h2 = 2562383102;
20
+ let h3 = 271733878;
21
+ let h4 = 3285377520;
22
+ const w = /* @__PURE__ */ new Uint32Array(80);
23
+ for (let i = 0; i < total; i += 64) {
24
+ for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
25
+ for (let j = 16; j < 80; j++) {
26
+ const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0);
27
+ w[j] = n << 1 | n >>> 31;
28
+ }
29
+ let a = h0;
30
+ let b = h1;
31
+ let c = h2;
32
+ let d = h3;
33
+ let e = h4;
34
+ for (let j = 0; j < 80; j++) {
35
+ let f;
36
+ let k;
37
+ if (j < 20) {
38
+ f = b & c | ~b & d;
39
+ k = 1518500249;
40
+ } else if (j < 40) {
41
+ f = b ^ c ^ d;
42
+ k = 1859775393;
43
+ } else if (j < 60) {
44
+ f = b & c | b & d | c & d;
45
+ k = 2400959708;
46
+ } else {
47
+ f = b ^ c ^ d;
48
+ k = 3395469782;
49
+ }
50
+ const temp = (a << 5 | a >>> 27) + f + e + k + (w[j] ?? 0) >>> 0;
51
+ e = d;
52
+ d = c;
53
+ c = b << 30 | b >>> 2;
54
+ b = a;
55
+ a = temp;
56
+ }
57
+ h0 = h0 + a >>> 0;
58
+ h1 = h1 + b >>> 0;
59
+ h2 = h2 + c >>> 0;
60
+ h3 = h3 + d >>> 0;
61
+ h4 = h4 + e >>> 0;
62
+ }
63
+ return [
64
+ h0,
65
+ h1,
66
+ h2,
67
+ h3,
68
+ h4
69
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
70
+ }
71
+ function sha1HexOfString(s) {
72
+ return sha1Hex(new TextEncoder().encode(s));
73
+ }
74
+ //#endregion
12
75
  //#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
13
76
  /** having a bunch of sensible default will help slightly */
14
77
  function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
@@ -603,7 +666,7 @@ var ComfySchema = class {
603
666
  else if (typeof enumValue === "number") enumValues.push(enumValue);
604
667
  else enumValues.push(enumValue.content);
605
668
  const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
606
- const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
669
+ const hash = sha1HexOfString(hashContent).slice(0, 8);
607
670
  let unionInfo = this.knownUnionByHash.get(hash);
608
671
  if (unionInfo == null) {
609
672
  const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
@@ -820,7 +883,7 @@ var ComfySchema = class {
820
883
  };
821
884
  //#endregion
822
885
  //#region package.json
823
- var version = "1.3.0";
886
+ var version = "1.4.0";
824
887
  //#endregion
825
888
  //#region src/litegraph/LiteGraphLinkID.ts
826
889
  const asLiteGraphLinkID = (id) => id;
@@ -2191,6 +2254,19 @@ const runTimestamp = (d) => {
2191
2254
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
2192
2255
  };
2193
2256
  //#endregion
2257
+ //#region src/utils/lazySharp.ts
2258
+ let cached = null;
2259
+ async function importSharp(reason) {
2260
+ if (cached != null) return cached;
2261
+ const specifier = "sharp";
2262
+ try {
2263
+ cached = (await import(specifier)).default;
2264
+ return cached;
2265
+ } catch (e) {
2266
+ throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
2267
+ }
2268
+ }
2269
+ //#endregion
2194
2270
  //#region src/types/index.ts
2195
2271
  const asAbsolutePath = (path) => path;
2196
2272
  const resultSuccess = (value) => ({
@@ -2229,8 +2305,7 @@ function exhaust(x) {
2229
2305
  //#endregion
2230
2306
  //#region src/utils/hashArrayBuffer.ts
2231
2307
  const hashArrayBuffer = (buffer) => {
2232
- const data = Buffer.from(buffer);
2233
- return crypto.createHash("sha1").update(data).digest("hex");
2308
+ return sha1Hex(buffer);
2234
2309
  };
2235
2310
  //#endregion
2236
2311
  //#region src/graph/ComfyNodeID.ts
@@ -2406,29 +2481,21 @@ var MediaImage = class MediaImage {
2406
2481
  this._metadata = null;
2407
2482
  this._hash = null;
2408
2483
  this.processWithSharp_inplace = async (fn) => {
2409
- const buff = await fn(sharp(this.absPath)).toBuffer();
2410
- writeFileSync(this.absPath, buff);
2484
+ const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
2485
+ getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
2411
2486
  this.updateBuffer(new Uint8Array(buff));
2412
2487
  return this;
2413
2488
  };
2414
2489
  this.processWithSharp = async (fn, path) => {
2415
- const res = fn(sharp(this.absPath));
2490
+ const sharp = await importSharp("processWithSharp");
2416
2491
  path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
2417
- await res.toFile(path);
2418
- const buffer = await res.toBuffer();
2492
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
2493
+ getComfyStorage().writeBytes(path, buffer);
2419
2494
  return new MediaImage({
2420
2495
  path,
2421
2496
  buffer
2422
2497
  });
2423
2498
  };
2424
- this.generatePreview = async (targetPath) => {
2425
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
2426
- mkdirSync(dirname(targetPath), { recursive: true });
2427
- await img.toFile(targetPath);
2428
- };
2429
- this.generateMiniPreview = async () => {
2430
- return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
2431
- };
2432
2499
  this.absPath = data.path;
2433
2500
  this.execution = data.execution;
2434
2501
  this.promptNodeID = data.promptNodeID;
@@ -2498,26 +2565,25 @@ var MediaImage = class MediaImage {
2498
2565
  * does not includes the prefix `data:image/png;base64,`
2499
2566
  */
2500
2567
  getBase64Payload() {
2501
- return Buffer.from(this.buffer).toString("base64");
2568
+ const bytes = this.buffer;
2569
+ let bin = "";
2570
+ const chunk = 32768;
2571
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
2572
+ return btoa(bin);
2502
2573
  }
2503
2574
  get buffer() {
2504
2575
  if (this._buffer != null) return this._buffer;
2505
- const buff = readFileSync(this.absPath);
2506
- const uint8arr = new Uint8Array(buff);
2507
- this._buffer = uint8arr;
2576
+ this._buffer = getComfyStorage().readBytes(this.absPath);
2508
2577
  return this._buffer;
2509
2578
  }
2510
2579
  get metadata() {
2511
2580
  if (this._metadata != null) return this._metadata;
2512
- const buff = readFileSync(this.absPath);
2513
- const uint8arr = new Uint8Array(buff);
2514
- this._metadata = imageMeta(uint8arr);
2581
+ this._metadata = imageMeta(this.buffer);
2515
2582
  return this._metadata;
2516
2583
  }
2517
2584
  get hash() {
2518
2585
  if (this._hash != null) return this._hash;
2519
- const buff = readFileSync(this.absPath);
2520
- this._hash = hashArrayBuffer(new Uint8Array(buff));
2586
+ this._hash = hashArrayBuffer(this.buffer);
2521
2587
  return this._hash;
2522
2588
  }
2523
2589
  };
@@ -2603,12 +2669,12 @@ var ComfyExecution = class {
2603
2669
  const extension = sf.format.split("/")[1];
2604
2670
  absPath += "." + extension;
2605
2671
  }
2672
+ const storage = getComfyStorage();
2606
2673
  absPath = uniquifyOutputPath({
2607
2674
  path: absPath,
2608
- exists: existsSync,
2675
+ exists: (p) => storage.exists(p),
2609
2676
  claimed: CLAIMED_OUTPUT_PATHS
2610
2677
  });
2611
- mkdirSync(dirname(absPath), { recursive: true });
2612
2678
  let img;
2613
2679
  if (sf && sf.format !== "raw") {
2614
2680
  const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
@@ -2623,9 +2689,11 @@ var ComfyExecution = class {
2623
2689
  if (sf.format === "image/webp") return "webp";
2624
2690
  return "png";
2625
2691
  })();
2626
- await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
2692
+ const encoded = await (await importSharp(`saveFormat '${sf.format}' re-encoding`))(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toBuffer();
2693
+ storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded));
2627
2694
  img = new MediaImage({
2628
2695
  path: asAbsolutePath(absPath),
2696
+ buffer: new Uint8Array(encoded),
2629
2697
  execution: this,
2630
2698
  promptNodeID,
2631
2699
  comfyUIInfos: {
@@ -2636,7 +2704,7 @@ var ComfyExecution = class {
2636
2704
  } else {
2637
2705
  const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2638
2706
  const uint8arr = new Uint8Array(buff);
2639
- writeFileSync(absPath, uint8arr);
2707
+ storage.writeBytes(asAbsolutePath(absPath), uint8arr);
2640
2708
  img = new MediaImage({
2641
2709
  path: asAbsolutePath(absPath),
2642
2710
  buffer: uint8arr,
@@ -2693,14 +2761,14 @@ var ComfyExecution = class {
2693
2761
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2694
2762
  if (line === this._lastLoggedLine) return;
2695
2763
  this._lastLoggedLine = line;
2696
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2764
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2697
2765
  else console.log(line);
2698
2766
  }
2699
2767
  finishProgressLine() {
2700
2768
  if (!this.logProgress) return;
2701
2769
  const p = this.progress;
2702
2770
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2703
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2771
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2704
2772
  else console.log(line);
2705
2773
  }
2706
2774
  log(...args) {
@@ -3174,17 +3242,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3174
3242
  return result;
3175
3243
  }
3176
3244
  //#endregion
3177
- //#region src/utils/writeFile.ts
3178
- const writeFileAsync = async (path, data, fmt) => {
3179
- return new Promise((resolve, reject) => {
3180
- logInfo(`writing file: ${ansi.blue(path)}`);
3181
- writeFile(path, data, fmt, (err) => {
3182
- if (err) reject(err);
3183
- else resolve();
3184
- });
3185
- });
3186
- };
3187
- //#endregion
3188
3245
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3189
3246
  const ComfyManagerAPIModelList_ark = type({ models: type({
3190
3247
  name: type.string.as(),
@@ -3422,7 +3479,8 @@ function parseHostBase(p) {
3422
3479
  function renderHttpBase(p) {
3423
3480
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3424
3481
  }
3425
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3482
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
3483
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
3426
3484
  function renderWsUrl(p) {
3427
3485
  return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3428
3486
  }
@@ -3432,6 +3490,27 @@ function renderPort(p) {
3432
3490
  }
3433
3491
  //#endregion
3434
3492
  //#region src/host/ResilientWebsocket.ts
3493
+ let transportPromise = null;
3494
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
3495
+ function resolveWsTransport() {
3496
+ transportPromise ??= (async () => {
3497
+ const specifier = "ws";
3498
+ try {
3499
+ return {
3500
+ ctor: (await import(specifier)).default,
3501
+ supportsHeaders: true
3502
+ };
3503
+ } catch {
3504
+ const native = globalThis.WebSocket;
3505
+ if (native != null) return {
3506
+ ctor: native,
3507
+ supportsHeaders: false
3508
+ };
3509
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
3510
+ }
3511
+ })();
3512
+ return transportPromise;
3513
+ }
3435
3514
  var ResilientWebSocketClient = class {
3436
3515
  addInfo(msg) {
3437
3516
  this.debugMessages.push({
@@ -3466,7 +3545,17 @@ var ResilientWebSocketClient = class {
3466
3545
  this.currentWS = null;
3467
3546
  this.isOpen = false;
3468
3547
  }
3469
- connect() {
3548
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
3549
+ headerlessUrl(headers) {
3550
+ const rest = { ...headers };
3551
+ const apiKey = rest["X-API-Key"];
3552
+ delete rest["X-API-Key"];
3553
+ const extra = Object.keys(rest);
3554
+ if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
3555
+ if (apiKey == null) return this.url;
3556
+ return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
3557
+ }
3558
+ async connect() {
3470
3559
  this.isOpen = false;
3471
3560
  const prevWS = this.currentWS;
3472
3561
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
@@ -3475,13 +3564,24 @@ var ResilientWebSocketClient = class {
3475
3564
  this.addInfo("Previous WebSocket discarded");
3476
3565
  prevWS.close();
3477
3566
  }
3478
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
3567
+ let ws;
3568
+ try {
3569
+ const transport = await resolveWsTransport();
3570
+ if (this.permanentlyClosed) return;
3571
+ const headers = this.options.headers?.() ?? {};
3572
+ ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
3573
+ } catch (e) {
3574
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
3575
+ this.permanentlyClosed = true;
3576
+ this.options.onTransportDead?.(e);
3577
+ return;
3578
+ }
3479
3579
  ws.binaryType = "arraybuffer";
3480
3580
  this.currentWS = ws;
3481
- if (this.options.onMessage) ws.onmessage = (event) => {
3581
+ ws.onmessage = (event) => {
3482
3582
  this.options.onMessage(event);
3483
3583
  };
3484
- ws.onopen = (_event) => {
3584
+ ws.onopen = () => {
3485
3585
  if (ws !== this.currentWS) return;
3486
3586
  this.addInfo("✅ WebSocket connected to " + this.url);
3487
3587
  this.isOpen = true;
@@ -3495,7 +3595,7 @@ var ResilientWebSocketClient = class {
3495
3595
  if (this.permanentlyClosed) return;
3496
3596
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3497
3597
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3498
- this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
3598
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3499
3599
  };
3500
3600
  ws.onerror = (event) => {
3501
3601
  if (ws !== this.currentWS) return;
@@ -3513,14 +3613,6 @@ var ResilientWebSocketClient = class {
3513
3613
  this.currentWS?.send(message);
3514
3614
  }
3515
3615
  }
3516
- /** forward WebSocket add event listeners to the current WebSocket instance */
3517
- addEventListener(type, listener, options) {
3518
- this.currentWS?.addEventListener(type, listener, options);
3519
- }
3520
- /** forward WebSocket remove event listeners to the current WebSocket instance */
3521
- removeEventListener(type, listener) {
3522
- this.currentWS?.removeEventListener(type, listener);
3523
- }
3524
3616
  };
3525
3617
  //#endregion
3526
3618
  //#region src/host/ComfyHost.ts
@@ -3736,11 +3828,11 @@ var ComfyHost = class {
3736
3828
  this.isUpdatingSchema = true;
3737
3829
  const object_info_json = await this.fetchJSON_("/object_info");
3738
3830
  const object_info_str = readableStringify(object_info_json, 4);
3739
- writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
3831
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
3740
3832
  const res = ComfySchemaJSON_ark(object_info_json);
3741
3833
  if (res instanceof type.errors) printArkResultInConsole(res);
3742
3834
  const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
3743
- writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
3835
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
3744
3836
  this.schema.update({
3745
3837
  spec: object_info_json,
3746
3838
  embeddings: embeddings_json
@@ -3757,7 +3849,7 @@ var ComfyHost = class {
3757
3849
  };
3758
3850
  console.error(error);
3759
3851
  console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
3760
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
3852
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
3761
3853
  this.markFailed(error);
3762
3854
  } finally {
3763
3855
  this.isUpdatingSchema = false;
@@ -3778,9 +3870,10 @@ var ComfyHost = class {
3778
3870
  this.base = parseHostBase(this.data);
3779
3871
  /** folder where file related to the host config will be cached */
3780
3872
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
3781
- if (!existsSync(this.cacheFolder)) {
3873
+ const storage = getComfyStorage();
3874
+ if (!storage.exists(this.cacheFolder)) {
3782
3875
  console.log("🟢 creating folder", this.cacheFolder);
3783
- mkdirSync(this.cacheFolder, { recursive: true });
3876
+ storage.mkdirp(this.cacheFolder);
3784
3877
  }
3785
3878
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
3786
3879
  this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
@@ -3830,19 +3923,20 @@ var ComfyHost = class {
3830
3923
  }
3831
3924
  async writeSDKToDisk() {
3832
3925
  if (this.data.sdkAutoWrite === false) return;
3926
+ const storage = getComfyStorage();
3833
3927
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
3834
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
3835
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
3928
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
3929
+ storage.writeText(this.sdkDTSPath, comfySchemaTs);
3836
3930
  }
3837
3931
  shouldUseSchemaCache() {
3838
3932
  if (this._schemaStrategy === "refresh") return false;
3839
- const exists = existsSync(this.comfyJSONPath);
3933
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
3840
3934
  if (this._schemaStrategy === "cache") {
3841
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
3935
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
3842
3936
  return true;
3843
3937
  }
3844
- if (!exists) return false;
3845
- return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
3938
+ if (mtimeMs == null) return false;
3939
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs;
3846
3940
  }
3847
3941
  waitForSession(timeoutMs = 5e3) {
3848
3942
  if (this.comfySessionId !== "temp") return Promise.resolve();
@@ -3877,6 +3971,7 @@ var ComfyHost = class {
3877
3971
  onMessage: (e) => this.onMessage(e),
3878
3972
  url: () => this.getWSUrl(),
3879
3973
  headers: () => this.authHeaders(),
3974
+ onTransportDead: (e) => this.markFailed(e),
3880
3975
  onClose: () => {
3881
3976
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
3882
3977
  }
@@ -3896,7 +3991,7 @@ var ComfyHost = class {
3896
3991
  * examples must still open in the TUI; run() fetches the real schema through
3897
3992
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
3898
3993
  loadSchemaFromCache() {
3899
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
3994
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
3900
3995
  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`);
3901
3996
  return Promise.resolve();
3902
3997
  }
@@ -3908,7 +4003,7 @@ var ComfyHost = class {
3908
4003
  embeddings: embeddings_json
3909
4004
  });
3910
4005
  this.schema.RUN_BASIC_CHECKS();
3911
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4006
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
3912
4007
  })().catch((e) => {
3913
4008
  this._schemaFromCache = null;
3914
4009
  throw e;
@@ -4000,55 +4095,13 @@ var ComfyHost = class {
4000
4095
  };
4001
4096
  //#endregion
4002
4097
  //#region src/utils/downloadFile.ts
4003
- /** Usage example
4004
- * | ;(async () => {
4005
- * | try {
4006
- * | await downloadFile('https://example.com/file', 'folder/filename')
4007
- * | console.log('Download completed successfully')
4008
- * | } catch (error) {
4009
- * | console.error('Download failed:', error)
4010
- * | }
4011
- * | })()
4012
- * |
4013
- */
4014
- function downloadFile(url, outputPath, logPrefix = " - ") {
4015
- mkdirSync(dirname(outputPath), { recursive: true });
4016
- return new Promise((resolve, reject) => {
4017
- https.get(url, (response) => {
4018
- if (response.statusCode === 302 || response.statusCode === 301) {
4019
- const newUrl = response.headers.location;
4020
- console.log(`Redirected to ${newUrl}`);
4021
- resolve(downloadFile(newUrl, outputPath));
4022
- return;
4023
- }
4024
- if (response.statusCode !== 200) {
4025
- reject(`Failed to download file: Status Code ${response.statusCode}`);
4026
- return;
4027
- }
4028
- const rawLen = response.headers["content-length"];
4029
- if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
4030
- else {
4031
- const totalSize = parseInt(rawLen, 10);
4032
- let downloaded = 0;
4033
- let lastLoggedPercentage = 0;
4034
- response.on("data", (chunk) => {
4035
- downloaded += chunk.length;
4036
- const percentage = Math.round(downloaded / totalSize * 100);
4037
- if (percentage >= lastLoggedPercentage + 1) {
4038
- stdout.write(`\r${logPrefix}${percentage}% downloaded`);
4039
- lastLoggedPercentage = percentage;
4040
- }
4041
- });
4042
- }
4043
- const fileStream = fs.createWriteStream(outputPath);
4044
- response.pipe(fileStream);
4045
- fileStream.on("finish", () => {
4046
- console.log(` (DONE)`);
4047
- fileStream.close();
4048
- resolve(true);
4049
- });
4050
- }).on("error", (err) => reject(err));
4051
- });
4098
+ async function downloadFile(url, outputPath, logPrefix = " - ") {
4099
+ const res = await fetch(url);
4100
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
4101
+ const bytes = new Uint8Array(await res.arrayBuffer());
4102
+ getComfyStorage().writeBytes(outputPath, bytes);
4103
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
4104
+ return true;
4052
4105
  }
4053
4106
  //#endregion
4054
4107
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
@@ -4169,7 +4222,7 @@ const ComfyManagerRawPluginInfo_ark = type({
4169
4222
  const _getKnownPlugins = (DB) => {
4170
4223
  const counter = DB.report.file("custom-node-list.json");
4171
4224
  let totalFileSeen = 0;
4172
- const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
4225
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
4173
4226
  if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4174
4227
  const canonical = [];
4175
4228
  for (const row of root.custom_nodes) {
@@ -4207,7 +4260,7 @@ const _getKnownPlugins = (DB) => {
4207
4260
  }
4208
4261
  out1 += "\n";
4209
4262
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
4210
- writeFileSync(out1Path, out1 + "\n", "utf-8");
4263
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4211
4264
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4212
4265
  let out2 = "";
4213
4266
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -4215,7 +4268,7 @@ const _getKnownPlugins = (DB) => {
4215
4268
  out2 += "export type KnownComfyPluginURL =\n";
4216
4269
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
4217
4270
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
4218
- writeFileSync(out2Path, out2, "utf-8");
4271
+ getComfyStorage().writeText(out2Path, out2);
4219
4272
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4220
4273
  }
4221
4274
  if (DB.opts.check) {
@@ -4261,7 +4314,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNod
4261
4314
  const _getCustomNodeRegistry = (DB) => {
4262
4315
  const counter = DB.report.file("extension-node-map.json");
4263
4316
  let totalCustomNodeSeen = 0;
4264
- const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
4317
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
4265
4318
  const root = type("Record<string, unknown>")(raw);
4266
4319
  if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4267
4320
  for (const [url, value] of Object.entries(root)) {
@@ -4297,7 +4350,7 @@ const _getCustomNodeRegistry = (DB) => {
4297
4350
  for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
4298
4351
  out += "\n";
4299
4352
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
4300
- writeFileSync(outPath, out + "\n", "utf-8");
4353
+ getComfyStorage().writeText(outPath, out + "\n");
4301
4354
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
4302
4355
  }
4303
4356
  if (DB.opts.check) {
@@ -4352,7 +4405,7 @@ const ComfyManagerModelInfo_ark = type({
4352
4405
  //#region src/manager/loaders/step4_model-list-loader.ts
4353
4406
  const _getKnownModels = (DB) => {
4354
4407
  const counter = DB.report.file("model-list.json");
4355
- const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
4408
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
4356
4409
  if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
4357
4410
  const canonical = [];
4358
4411
  for (const row of root.models) {
@@ -4381,7 +4434,7 @@ const _getKnownModels = (DB) => {
4381
4434
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4382
4435
  out1 += "]\n";
4383
4436
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
4384
- writeFileSync(out1Path, out1 + "\n", "utf-8");
4437
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4385
4438
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4386
4439
  let out4 = "";
4387
4440
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -4397,7 +4450,7 @@ const _getKnownModels = (DB) => {
4397
4450
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
4398
4451
  out4 += "]\n";
4399
4452
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
4400
- writeFileSync(out4Path, out4 + "\n", "utf-8");
4453
+ getComfyStorage().writeText(out4Path, out4 + "\n");
4401
4454
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
4402
4455
  let out2 = "";
4403
4456
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -4414,7 +4467,7 @@ const _getKnownModels = (DB) => {
4414
4467
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4415
4468
  out2 += "]\n";
4416
4469
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
4417
- writeFileSync(out2Path, out2 + "\n", "utf-8");
4470
+ getComfyStorage().writeText(out2Path, out2 + "\n");
4418
4471
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4419
4472
  let out3 = "";
4420
4473
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -4429,7 +4482,7 @@ const _getKnownModels = (DB) => {
4429
4482
  }
4430
4483
  out3 += "\n";
4431
4484
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
4432
- writeFileSync(out3Path, out3 + "\n", "utf-8");
4485
+ getComfyStorage().writeText(out3Path, out3 + "\n");
4433
4486
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
4434
4487
  let out99 = "";
4435
4488
  out99 += `// prettier-ignore\n`;
@@ -4443,7 +4496,7 @@ const _getKnownModels = (DB) => {
4443
4496
  }
4444
4497
  out99 += "\n";
4445
4498
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
4446
- writeFileSync(out99Path, out99 + "\n", "utf-8");
4499
+ getComfyStorage().writeText(out99Path, out99 + "\n");
4447
4500
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
4448
4501
  }
4449
4502
  if (DB.opts.check) {
@@ -4464,7 +4517,7 @@ const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
4464
4517
  //#region src/manager/loaders/step5_alter-list-loader.ts
4465
4518
  const _getAlterList = (DB) => {
4466
4519
  const counter = DB.report.file("alter-list.json");
4467
- const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
4520
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
4468
4521
  if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
4469
4522
  const canonical = [];
4470
4523
  for (const row of root.items) {
@@ -4489,7 +4542,7 @@ const ComfyManagerGithubStatEntry_ark = type({
4489
4542
  //#region src/manager/loaders/step6_github-stats-loader.ts
4490
4543
  const _getGithubStats = (DB) => {
4491
4544
  const counter = DB.report.file("github-stats.json");
4492
- const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
4545
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
4493
4546
  const root = type("Record<string, unknown>")(raw);
4494
4547
  if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
4495
4548
  for (const [url, value] of Object.entries(root)) {
@@ -4604,13 +4657,12 @@ var ComfyTS = class ComfyTS {
4604
4657
  this.version = version;
4605
4658
  this.hosts = /* @__PURE__ */ new Map();
4606
4659
  this._registry = null;
4607
- this.rootPath = asAbsolutePath(process.cwd());
4608
4660
  this.readJSON_ = (absPath, def) => {
4609
- if (!existsSync(absPath)) {
4661
+ const str = this.storage.readTextIfExists(absPath);
4662
+ if (str == null) {
4610
4663
  if (def != null) return def;
4611
4664
  throw new Error(`file does not exist ${absPath}`);
4612
4665
  }
4613
- const str = readFileSync(absPath, "utf8");
4614
4666
  return JSON.parse(str);
4615
4667
  };
4616
4668
  this.autolayoutOpts = {
@@ -4621,7 +4673,8 @@ var ComfyTS = class ComfyTS {
4621
4673
  const globalHack = globalThis;
4622
4674
  if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
4623
4675
  globalHack.comfyts = this;
4624
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
4676
+ this.storage = resolveComfyStorage(p.storage);
4677
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
4625
4678
  this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
4626
4679
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
4627
4680
  this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
@@ -4685,6 +4738,6 @@ var ComfyTS = class ComfyTS {
4685
4738
  }
4686
4739
  };
4687
4740
  //#endregion
4688
- export { ComfySchema as a, stripAnsi as i, settingsPathFor as n, readableStringify as r, ComfyTS as t };
4741
+ export { ComfySchema as a, stripAnsi as i, settingsPathFor as n, sha1HexOfString as o, readableStringify as r, ComfyTS as t };
4689
4742
 
4690
- //# sourceMappingURL=state-DKCPy105.js.map
4743
+ //# sourceMappingURL=state-COlKYipO.js.map