comfy-ts 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +66 -0
  2. package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/DraftsSt-DcOTn0QR.js +434 -0
  5. package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +476 -202
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +98 -40
  11. package/dist/index.d.ts +117 -59
  12. package/dist/index.js +468 -193
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-CN0DhrsA.js +638 -0
  15. package/dist/run-serve-CN0DhrsA.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
  17. package/dist/run-tui-bN2hSD5i.js.map +1 -0
  18. package/dist/state-COlKYipO.js +4743 -0
  19. package/dist/state-COlKYipO.js.map +1 -0
  20. package/dist/web.d.ts +17340 -0
  21. package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
  22. package/dist/web.js.map +1 -0
  23. package/examples/web/example.ts +71 -0
  24. package/examples/web/index.html +77 -0
  25. package/examples/web/serve.ts +42 -0
  26. package/examples/web/tsconfig.json +15 -0
  27. package/package.json +10 -3
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/StatusBar.tsx +1 -0
  34. package/src/cli/tui/components/TreePanel.tsx +17 -3
  35. package/src/cli/tui/components/TuiApp.tsx +7 -2
  36. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  37. package/src/cli/tui/imageClipboard.ts +39 -0
  38. package/src/cli/tui/listWindow.ts +36 -0
  39. package/src/cli/tui/state/ExecSt.ts +48 -0
  40. package/src/cli/tui/state/TreeSt.ts +25 -0
  41. package/src/cli/tui/state/TuiSt.ts +34 -0
  42. package/src/coreExports.ts +118 -0
  43. package/src/host/ComfyHost.ts +23 -23
  44. package/src/host/ResilientWebsocket.ts +93 -47
  45. package/src/host/hostUrl.ts +2 -1
  46. package/src/host/loraManagerApi.ts +6 -7
  47. package/src/index.ts +8 -107
  48. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  49. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  50. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  51. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  52. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  53. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  54. package/src/runner/ComfyExecution.ts +32 -12
  55. package/src/runner/MediaImage.ts +18 -30
  56. package/src/runner/outputPath.ts +75 -0
  57. package/src/sdk-generator/ComfySchema.ts +2 -2
  58. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  59. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  60. package/src/state.ts +13 -9
  61. package/src/storage/ComfyStorage.ts +144 -0
  62. package/src/storage/nodeStorage.ts +9 -0
  63. package/src/utils/downloadFile.ts +11 -69
  64. package/src/utils/hashArrayBuffer.ts +3 -4
  65. package/src/utils/lazySharp.ts +25 -0
  66. package/src/utils/sha1.ts +69 -0
  67. package/src/vars/ComfyVars.ts +13 -6
  68. package/src/vars/loraKeywords.ts +6 -6
  69. package/src/web.ts +13 -0
  70. package/dist/run-tui-BAdizWsO.js.map +0 -1
  71. package/dist/state-BYbxDgfr.js.map +0 -1
  72. package/src/utils/writeFile.ts +0 -16
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.2.0";
113
+ var version = "1.4.0";
16
114
  //#endregion
17
115
  //#region src/litegraph/LiteGraphLinkID.ts
18
116
  const asLiteGraphLinkID = (id) => id;
@@ -726,6 +824,25 @@ const containerInstanceSlotType = (opts) => {
726
824
  if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
727
825
  return first.type;
728
826
  };
827
+ /**
828
+ * frontend-registered widgets whose object_info opts carry NO config signal —
829
+ * the one exception to config-only classification (architecture.md rule 8).
830
+ * Every entry must quote the frontend widget-creation source.
831
+ *
832
+ * LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified
833
+ * 2026-07-31): the LOAD_3D custom widget handler runs
834
+ * node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)
835
+ * node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)
836
+ * node.addWidget('button', 'clear', 'clear', …)
837
+ * THEN creates the scene widget, so the serialized run is
838
+ * [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved
839
+ * files, an {image, mask, normal, camera_info, …} dict at queue time.
840
+ */
841
+ const EMPTY_CONFIG_FRONTEND_WIDGETS = { LOAD_3D: { prefixValues: [
842
+ "upload3dmodel",
843
+ "uploadExtraResources",
844
+ "clear"
845
+ ] } };
729
846
  const classifyWidgetInput = (p) => {
730
847
  const o = isRecord(p.opts) ? p.opts : null;
731
848
  if (o?.["forceInput"] === true) return { kind: "slot" };
@@ -734,7 +851,8 @@ const classifyWidgetInput = (p) => {
734
851
  return {
735
852
  kind: "widget",
736
853
  consumes: controlConsumes(o, tn, p.name),
737
- strictValues: true
854
+ strictValues: true,
855
+ prefixValues: []
738
856
  };
739
857
  }
740
858
  if (typeof p.type !== "string") return { kind: "slot" };
@@ -742,7 +860,8 @@ const classifyWidgetInput = (p) => {
742
860
  if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
743
861
  kind: "widget",
744
862
  consumes: controlConsumes(o, widgetTypeName, p.name),
745
- strictValues: true
863
+ strictValues: true,
864
+ prefixValues: []
746
865
  };
747
866
  const options = o?.["options"];
748
867
  if (Array.isArray(options)) {
@@ -759,7 +878,8 @@ const classifyWidgetInput = (p) => {
759
878
  return {
760
879
  kind: "widget",
761
880
  consumes: controlConsumes(o, p.type, p.name),
762
- strictValues: true
881
+ strictValues: true,
882
+ prefixValues: []
763
883
  };
764
884
  }
765
885
  const template = o?.["template"];
@@ -770,7 +890,15 @@ const classifyWidgetInput = (p) => {
770
890
  if (o?.["socketless"] === true) return {
771
891
  kind: "widget",
772
892
  consumes: 1,
773
- strictValues: false
893
+ strictValues: false,
894
+ prefixValues: []
895
+ };
896
+ const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName];
897
+ if (emptyConfigEntry != null) return {
898
+ kind: "widget",
899
+ consumes: emptyConfigEntry.prefixValues.length + 1,
900
+ strictValues: false,
901
+ prefixValues: emptyConfigEntry.prefixValues
774
902
  };
775
903
  return { kind: "slot" };
776
904
  };
@@ -780,11 +908,6 @@ const classifySchemaInput = (input) => classifyWidgetInput({
780
908
  opts: input.opts,
781
909
  isEnumUnion: input.isEnum
782
910
  });
783
- /** how many widgets_values entries this schema input consumes (export path + positional walks) */
784
- const howManyWidgetValuesForThisSchemaType = (input) => {
785
- const kind = classifySchemaInput(input);
786
- return kind.kind === "widget" ? kind.consumes : 0;
787
- };
788
911
  /**
789
912
  * what ComfyUI's frontend gives a widget created with no serialized value
790
913
  * (`getWidgetDefaultValue` semantics), used when a positional array is
@@ -886,15 +1009,15 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
886
1009
  if (!p.strict && isRecord(value)) return value;
887
1010
  throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
888
1011
  };
889
- /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
1012
+ /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */
890
1013
  const resolveWidgetValue = (p) => {
891
1014
  let value;
892
1015
  let has = false;
893
1016
  if (Object.hasOwn(named, p.promptName)) {
894
1017
  value = named[p.promptName];
895
1018
  has = true;
896
- } else if (offset < positional.length) {
897
- value = positional[offset];
1019
+ } else if (offset + p.prefixLen < positional.length) {
1020
+ value = positional[offset + p.prefixLen];
898
1021
  has = true;
899
1022
  }
900
1023
  if (positional.length > 0) offset += p.consumes;
@@ -906,7 +1029,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
906
1029
  const consumePlainWidget = (p) => {
907
1030
  const r = resolveWidgetValue({
908
1031
  promptName: p.promptName,
909
- consumes: p.consumes
1032
+ consumes: p.consumes,
1033
+ prefixLen: p.prefixLen
910
1034
  });
911
1035
  const raw = r.filled ? defaultValueForWidget({
912
1036
  type: p.typeName,
@@ -925,7 +1049,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
925
1049
  const consumeDynamicCombo = (p) => {
926
1050
  const r = resolveWidgetValue({
927
1051
  promptName: p.path,
928
- consumes: 1
1052
+ consumes: 1,
1053
+ prefixLen: 0
929
1054
  });
930
1055
  const key = r.filled ? p.defaultKey : r.value;
931
1056
  if (typeof key !== "string") throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): dynamic combo "${p.path}" key is not a string: ${JSON.stringify(key)}`, node);
@@ -953,6 +1078,7 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
953
1078
  typeName: typeof sub.type === "string" ? sub.type : "COMBO",
954
1079
  opts: sub.opts,
955
1080
  consumes: kind.consumes,
1081
+ prefixLen: kind.prefixValues.length,
956
1082
  strict: kind.strictValues,
957
1083
  enumValues: inlineEnum,
958
1084
  linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
@@ -964,13 +1090,15 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
964
1090
  if (kind.kind === "slot" && input?.widgetName != null) kind = {
965
1091
  kind: "widget",
966
1092
  consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
967
- strictValues: true
1093
+ strictValues: true,
1094
+ prefixValues: []
968
1095
  };
969
1096
  if (kind.kind === "widget") consumePlainWidget({
970
1097
  promptName: field.nameInComfy,
971
1098
  typeName: field.typeName,
972
1099
  opts: field.opts,
973
1100
  consumes: kind.consumes,
1101
+ prefixLen: kind.prefixValues.length,
974
1102
  strict: kind.strictValues,
975
1103
  linkedInput: input
976
1104
  });
@@ -1470,7 +1598,7 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
1470
1598
  const widgets_values = [];
1471
1599
  for (const ipt of node.$schema.inputs) {
1472
1600
  const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1473
- const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0;
1601
+ const kind = classifySchemaInput(ipt);
1474
1602
  if (_isLink(raw)) {
1475
1603
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber, `link target node "${raw[0]}" not found in graph`);
1476
1604
  inputs.push({
@@ -1478,9 +1606,10 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
1478
1606
  type: ipt.typeName,
1479
1607
  link: ctx.allocateLink(nodeUidNumber, raw[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), ipt.typeName)
1480
1608
  });
1481
- } else if (isWidget) {
1482
- widgets_values.push(raw);
1483
- if (ipt.typeName === "INT" && (ipt.nameInComfy === "seed" || ipt.nameInComfy === "noise_seed")) widgets_values.push(false);
1609
+ } else if (kind.kind === "widget") {
1610
+ widgets_values.push(...kind.prefixValues, raw);
1611
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1612
+ for (let i = 0; i < phantoms; i++) widgets_values.push(false);
1484
1613
  } else inputs.push({
1485
1614
  name: ipt.nameInComfy,
1486
1615
  type: ipt.typeName,
@@ -1526,6 +1655,91 @@ var LiteGraphCtx = class {
1526
1655
  }
1527
1656
  };
1528
1657
  //#endregion
1658
+ //#region src/runner/outputPath.ts
1659
+ /**
1660
+ * local output naming, relative to `.comfy-ts/outputs/` (his repro
1661
+ * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
1662
+ * `_00001_` counter every run, so trusting it overwrote the same file — and
1663
+ * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
1664
+ * prefix. Local names are ours: dir from the prompt's own filename_prefix
1665
+ * (or an explicit saveFormat.prefix override), then
1666
+ * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
1667
+ * per stem and nothing ever collides.
1668
+ */
1669
+ const localOutputPath = (p) => {
1670
+ const dot = p.filename.lastIndexOf(".");
1671
+ const ext = dot === -1 ? "" : p.filename.slice(dot);
1672
+ const base = dot === -1 ? p.filename : p.filename.slice(0, dot);
1673
+ const counterMatch = /_(\d+)_$/.exec(base);
1674
+ const counter = counterMatch?.[1];
1675
+ const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base;
1676
+ let dir;
1677
+ let stem;
1678
+ if (p.filenamePrefix != null && p.filenamePrefix !== "") {
1679
+ const slash = p.filenamePrefix.lastIndexOf("/");
1680
+ dir = slash === -1 ? "" : p.filenamePrefix.slice(0, slash);
1681
+ stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1);
1682
+ } else {
1683
+ dir = p.subfolder;
1684
+ stem = serverStem;
1685
+ }
1686
+ if (p.localDir != null) dir = p.localDir;
1687
+ const name = [
1688
+ stem === "" ? null : stem,
1689
+ p.timestamp,
1690
+ counter
1691
+ ].filter((x) => x != null).join("_") + ext;
1692
+ return dir === "" ? name : `${dir}/${name}`;
1693
+ };
1694
+ /**
1695
+ * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
1696
+ * was already CLAIMED by a still-downloading retrieval (two same-second runs
1697
+ * on a counter-resetting cloud host compute the same name — reviewer catch).
1698
+ * The chosen path is claimed before returning.
1699
+ */
1700
+ const uniquifyOutputPath = (p) => {
1701
+ let out = p.path;
1702
+ if (p.exists(out) || p.claimed.has(out)) {
1703
+ const dot = out.lastIndexOf(".");
1704
+ const stem = dot === -1 ? out : out.slice(0, dot);
1705
+ const ext = dot === -1 ? "" : out.slice(dot);
1706
+ for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`;
1707
+ }
1708
+ p.claimed.add(out);
1709
+ return out;
1710
+ };
1711
+ /** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */
1712
+ const runTimestamp = (d) => {
1713
+ const pad = (n) => String(n).padStart(2, "0");
1714
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
1715
+ };
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
1529
1743
  //#region src/types/index.ts
1530
1744
  const asAbsolutePath = (path) => path;
1531
1745
  const asRelativePath = (path) => path;
@@ -1575,10 +1789,78 @@ function exhaust(x) {
1575
1789
  return x;
1576
1790
  }
1577
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
1578
1861
  //#region src/utils/hashArrayBuffer.ts
1579
1862
  const hashArrayBuffer = (buffer) => {
1580
- const data = Buffer.from(buffer);
1581
- return crypto.createHash("sha1").update(data).digest("hex");
1863
+ return sha1Hex(buffer);
1582
1864
  };
1583
1865
  //#endregion
1584
1866
  //#region src/graph/ComfyNodeID.ts
@@ -1754,29 +2036,21 @@ var MediaImage = class MediaImage {
1754
2036
  this._metadata = null;
1755
2037
  this._hash = null;
1756
2038
  this.processWithSharp_inplace = async (fn) => {
1757
- const buff = await fn(sharp(this.absPath)).toBuffer();
1758
- writeFileSync(this.absPath, buff);
2039
+ const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
2040
+ getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
1759
2041
  this.updateBuffer(new Uint8Array(buff));
1760
2042
  return this;
1761
2043
  };
1762
2044
  this.processWithSharp = async (fn, path) => {
1763
- const res = fn(sharp(this.absPath));
2045
+ const sharp = await importSharp("processWithSharp");
1764
2046
  path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
1765
- await res.toFile(path);
1766
- const buffer = await res.toBuffer();
2047
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
2048
+ getComfyStorage().writeBytes(path, buffer);
1767
2049
  return new MediaImage({
1768
2050
  path,
1769
2051
  buffer
1770
2052
  });
1771
2053
  };
1772
- this.generatePreview = async (targetPath) => {
1773
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
1774
- mkdirSync(dirname(targetPath), { recursive: true });
1775
- await img.toFile(targetPath);
1776
- };
1777
- this.generateMiniPreview = async () => {
1778
- return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
1779
- };
1780
2054
  this.absPath = data.path;
1781
2055
  this.execution = data.execution;
1782
2056
  this.promptNodeID = data.promptNodeID;
@@ -1846,31 +2120,33 @@ var MediaImage = class MediaImage {
1846
2120
  * does not includes the prefix `data:image/png;base64,`
1847
2121
  */
1848
2122
  getBase64Payload() {
1849
- return Buffer.from(this.buffer).toString("base64");
2123
+ const bytes = this.buffer;
2124
+ let bin = "";
2125
+ const chunk = 32768;
2126
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
2127
+ return btoa(bin);
1850
2128
  }
1851
2129
  get buffer() {
1852
2130
  if (this._buffer != null) return this._buffer;
1853
- const buff = readFileSync(this.absPath);
1854
- const uint8arr = new Uint8Array(buff);
1855
- this._buffer = uint8arr;
2131
+ this._buffer = getComfyStorage().readBytes(this.absPath);
1856
2132
  return this._buffer;
1857
2133
  }
1858
2134
  get metadata() {
1859
2135
  if (this._metadata != null) return this._metadata;
1860
- const buff = readFileSync(this.absPath);
1861
- const uint8arr = new Uint8Array(buff);
1862
- this._metadata = imageMeta(uint8arr);
2136
+ this._metadata = imageMeta(this.buffer);
1863
2137
  return this._metadata;
1864
2138
  }
1865
2139
  get hash() {
1866
2140
  if (this._hash != null) return this._hash;
1867
- const buff = readFileSync(this.absPath);
1868
- this._hash = hashArrayBuffer(new Uint8Array(buff));
2141
+ this._hash = hashArrayBuffer(this.buffer);
1869
2142
  return this._hash;
1870
2143
  }
1871
2144
  };
1872
2145
  //#endregion
1873
2146
  //#region src/runner/ComfyExecution.ts
2147
+ /** paths claimed by in-flight retrievals: two same-second runs on a
2148
+ * counter-resetting cloud host compute the same name before either writes */
2149
+ const CLAIMED_OUTPUT_PATHS = /* @__PURE__ */ new Set();
1874
2150
  var ComfyExecution = class {
1875
2151
  get host() {
1876
2152
  return this.workflow.host;
@@ -1936,12 +2212,24 @@ var ComfyExecution = class {
1936
2212
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
1937
2213
  const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
1938
2214
  const sf = this.saveFormat;
1939
- let absPath = comfyts.resolveFromOutput(join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
2215
+ const promptPrefix = promptNode.inputs["filename_prefix"];
2216
+ let absPath = comfyts.resolveFromOutput(localOutputPath({
2217
+ localDir: sf?.prefix,
2218
+ filenamePrefix: typeof promptPrefix === "string" ? promptPrefix : void 0,
2219
+ subfolder: comfyImageInfo.subfolder,
2220
+ filename: comfyImageInfo.filename,
2221
+ timestamp: runTimestamp(new Date(this.startedAt))
2222
+ }));
1940
2223
  if (sf?.format && sf.format !== "raw") {
1941
2224
  const extension = sf.format.split("/")[1];
1942
2225
  absPath += "." + extension;
1943
2226
  }
1944
- mkdirSync(dirname(absPath), { recursive: true });
2227
+ const storage = getComfyStorage();
2228
+ absPath = uniquifyOutputPath({
2229
+ path: absPath,
2230
+ exists: (p) => storage.exists(p),
2231
+ claimed: CLAIMED_OUTPUT_PATHS
2232
+ });
1945
2233
  let img;
1946
2234
  if (sf && sf.format !== "raw") {
1947
2235
  const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
@@ -1956,9 +2244,11 @@ var ComfyExecution = class {
1956
2244
  if (sf.format === "image/webp") return "webp";
1957
2245
  return "png";
1958
2246
  })();
1959
- await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
2247
+ 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();
2248
+ storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded));
1960
2249
  img = new MediaImage({
1961
2250
  path: asAbsolutePath(absPath),
2251
+ buffer: new Uint8Array(encoded),
1962
2252
  execution: this,
1963
2253
  promptNodeID,
1964
2254
  comfyUIInfos: {
@@ -1969,7 +2259,7 @@ var ComfyExecution = class {
1969
2259
  } else {
1970
2260
  const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1971
2261
  const uint8arr = new Uint8Array(buff);
1972
- writeFileSync(absPath, uint8arr);
2262
+ storage.writeBytes(asAbsolutePath(absPath), uint8arr);
1973
2263
  img = new MediaImage({
1974
2264
  path: asAbsolutePath(absPath),
1975
2265
  buffer: uint8arr,
@@ -2026,14 +2316,14 @@ var ComfyExecution = class {
2026
2316
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2027
2317
  if (line === this._lastLoggedLine) return;
2028
2318
  this._lastLoggedLine = line;
2029
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2319
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2030
2320
  else console.log(line);
2031
2321
  }
2032
2322
  finishProgressLine() {
2033
2323
  if (!this.logProgress) return;
2034
2324
  const p = this.progress;
2035
2325
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2036
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2326
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2037
2327
  else console.log(line);
2038
2328
  }
2039
2329
  log(...args) {
@@ -2782,7 +3072,7 @@ var ComfySchema = class {
2782
3072
  else if (typeof enumValue === "number") enumValues.push(enumValue);
2783
3073
  else enumValues.push(enumValue.content);
2784
3074
  const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
2785
- const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
3075
+ const hash = sha1HexOfString(hashContent).slice(0, 8);
2786
3076
  let unionInfo = this.knownUnionByHash.get(hash);
2787
3077
  if (unionInfo == null) {
2788
3078
  const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
@@ -3066,19 +3356,6 @@ types.ComfyInputType;
3066
3356
  types.ComfyEnumDef;
3067
3357
  types.ComfyInputOpts;
3068
3358
  //#endregion
3069
- //#region src/utils/extractErrorMessage.ts
3070
- /** Extracts an error message from an exception stuff. */
3071
- const extractErrorMessage = (error) => {
3072
- if (error instanceof Error) return error.message;
3073
- if (error === null) return "null";
3074
- if (typeof error === "string") return error;
3075
- if (typeof error === "object") {
3076
- if ("message" in error && typeof error.message === "string") return error.message;
3077
- return JSON.stringify(error);
3078
- }
3079
- return String(error);
3080
- };
3081
- //#endregion
3082
3359
  //#region src/utils/stringifyReadable.ts
3083
3360
  const tab = " ";
3084
3361
  function readableStringify(obj, maxLevel = 3, level = 0) {
@@ -3106,17 +3383,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3106
3383
  return result;
3107
3384
  }
3108
3385
  //#endregion
3109
- //#region src/utils/writeFile.ts
3110
- const writeFileAsync = async (path, data, fmt) => {
3111
- return new Promise((resolve, reject) => {
3112
- logInfo(`writing file: ${ansi.blue(path)}`);
3113
- writeFile(path, data, fmt, (err) => {
3114
- if (err) reject(err);
3115
- else resolve();
3116
- });
3117
- });
3118
- };
3119
- //#endregion
3120
3386
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3121
3387
  const ComfyManagerAPIModelList_ark = type({ models: type({
3122
3388
  name: type.string.as(),
@@ -3354,7 +3620,8 @@ function parseHostBase(p) {
3354
3620
  function renderHttpBase(p) {
3355
3621
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3356
3622
  }
3357
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3623
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
3624
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
3358
3625
  function renderWsUrl(p) {
3359
3626
  return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3360
3627
  }
@@ -3364,6 +3631,27 @@ function renderPort(p) {
3364
3631
  }
3365
3632
  //#endregion
3366
3633
  //#region src/host/ResilientWebsocket.ts
3634
+ let transportPromise = null;
3635
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
3636
+ function resolveWsTransport() {
3637
+ transportPromise ??= (async () => {
3638
+ const specifier = "ws";
3639
+ try {
3640
+ return {
3641
+ ctor: (await import(specifier)).default,
3642
+ supportsHeaders: true
3643
+ };
3644
+ } catch {
3645
+ const native = globalThis.WebSocket;
3646
+ if (native != null) return {
3647
+ ctor: native,
3648
+ supportsHeaders: false
3649
+ };
3650
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
3651
+ }
3652
+ })();
3653
+ return transportPromise;
3654
+ }
3367
3655
  var ResilientWebSocketClient = class {
3368
3656
  addInfo(msg) {
3369
3657
  this.debugMessages.push({
@@ -3398,7 +3686,17 @@ var ResilientWebSocketClient = class {
3398
3686
  this.currentWS = null;
3399
3687
  this.isOpen = false;
3400
3688
  }
3401
- connect() {
3689
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
3690
+ headerlessUrl(headers) {
3691
+ const rest = { ...headers };
3692
+ const apiKey = rest["X-API-Key"];
3693
+ delete rest["X-API-Key"];
3694
+ const extra = Object.keys(rest);
3695
+ if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
3696
+ if (apiKey == null) return this.url;
3697
+ return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
3698
+ }
3699
+ async connect() {
3402
3700
  this.isOpen = false;
3403
3701
  const prevWS = this.currentWS;
3404
3702
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
@@ -3407,13 +3705,24 @@ var ResilientWebSocketClient = class {
3407
3705
  this.addInfo("Previous WebSocket discarded");
3408
3706
  prevWS.close();
3409
3707
  }
3410
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
3708
+ let ws;
3709
+ try {
3710
+ const transport = await resolveWsTransport();
3711
+ if (this.permanentlyClosed) return;
3712
+ const headers = this.options.headers?.() ?? {};
3713
+ ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
3714
+ } catch (e) {
3715
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
3716
+ this.permanentlyClosed = true;
3717
+ this.options.onTransportDead?.(e);
3718
+ return;
3719
+ }
3411
3720
  ws.binaryType = "arraybuffer";
3412
3721
  this.currentWS = ws;
3413
- if (this.options.onMessage) ws.onmessage = (event) => {
3722
+ ws.onmessage = (event) => {
3414
3723
  this.options.onMessage(event);
3415
3724
  };
3416
- ws.onopen = (_event) => {
3725
+ ws.onopen = () => {
3417
3726
  if (ws !== this.currentWS) return;
3418
3727
  this.addInfo("✅ WebSocket connected to " + this.url);
3419
3728
  this.isOpen = true;
@@ -3427,7 +3736,7 @@ var ResilientWebSocketClient = class {
3427
3736
  if (this.permanentlyClosed) return;
3428
3737
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3429
3738
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3430
- this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
3739
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3431
3740
  };
3432
3741
  ws.onerror = (event) => {
3433
3742
  if (ws !== this.currentWS) return;
@@ -3445,14 +3754,6 @@ var ResilientWebSocketClient = class {
3445
3754
  this.currentWS?.send(message);
3446
3755
  }
3447
3756
  }
3448
- /** forward WebSocket add event listeners to the current WebSocket instance */
3449
- addEventListener(type, listener, options) {
3450
- this.currentWS?.addEventListener(type, listener, options);
3451
- }
3452
- /** forward WebSocket remove event listeners to the current WebSocket instance */
3453
- removeEventListener(type, listener) {
3454
- this.currentWS?.removeEventListener(type, listener);
3455
- }
3456
3757
  };
3457
3758
  //#endregion
3458
3759
  //#region src/vars/loraKeywords.ts
@@ -3472,9 +3773,10 @@ function loadOnce() {
3472
3773
  if (loaded) return;
3473
3774
  loaded = true;
3474
3775
  const path = filePath();
3475
- if (!existsSync(path)) return;
3776
+ const text = getComfyStorage().readTextIfExists(path);
3777
+ if (text == null) return;
3476
3778
  try {
3477
- const raw = JSON.parse(readFileSync(path, "utf8"));
3779
+ const raw = JSON.parse(text);
3478
3780
  if (raw == null || typeof raw !== "object") return;
3479
3781
  runInAction(() => {
3480
3782
  for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
@@ -3497,8 +3799,7 @@ function setLoraKeyword(name, keyword) {
3497
3799
  });
3498
3800
  const path = filePath();
3499
3801
  try {
3500
- mkdirSync(dirname(path), { recursive: true });
3501
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3802
+ getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3502
3803
  } catch (e) {
3503
3804
  logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
3504
3805
  }
@@ -3694,6 +3995,12 @@ var SeedVar = class extends ComfyVar {
3694
3995
  afterRun() {
3695
3996
  this.advance();
3696
3997
  }
3998
+ /** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive
3999
+ * ('=' is the construction default; drafts restore their own mode via loadJSON) */
4000
+ reset() {
4001
+ this.setMode("=");
4002
+ return super.reset();
4003
+ }
3697
4004
  /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
3698
4005
  parse(raw) {
3699
4006
  const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
@@ -3936,7 +4243,7 @@ var SizeVar = class extends ComfyVar {
3936
4243
  if (iv == null || iv.value === "") return null;
3937
4244
  try {
3938
4245
  const abs = iv.absPath();
3939
- const meta = imageMeta(new Uint8Array(readFileSync(abs)));
4246
+ const meta = imageMeta(getComfyStorage().readBytes(abs));
3940
4247
  if (meta.width == null || meta.height == null) return null;
3941
4248
  return {
3942
4249
  width: meta.width,
@@ -3990,7 +4297,7 @@ var ImageVarEmptyError = class extends Error {
3990
4297
  /** trim + expand a leading `~/` — every ImageVar write funnels through this */
3991
4298
  function expandUserPath(raw) {
3992
4299
  const trimmed = raw.trim();
3993
- return trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
4300
+ return trimmed.startsWith("~/") ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed;
3994
4301
  }
3995
4302
  /**
3996
4303
  * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
@@ -4026,7 +4333,7 @@ var ImageVar = class extends ComfyVar {
4026
4333
  absPath() {
4027
4334
  if (!this.isSet()) throw this.emptyError();
4028
4335
  if (isAbsolute(this.value)) return this.value;
4029
- return resolve(this.opts.folder ?? process.cwd(), this.value);
4336
+ return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value);
4030
4337
  }
4031
4338
  /** empty = unset: the build fails LOUD here (varValues calls outValue) */
4032
4339
  outValue() {
@@ -4035,7 +4342,7 @@ var ImageVar = class extends ComfyVar {
4035
4342
  }
4036
4343
  display() {
4037
4344
  if (!this.isSet()) return "(unset) pick a file";
4038
- const home = homedir();
4345
+ const home = getComfyStorage().homedir();
4039
4346
  return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
4040
4347
  }
4041
4348
  };
@@ -4333,11 +4640,11 @@ var ComfyHost = class {
4333
4640
  this.isUpdatingSchema = true;
4334
4641
  const object_info_json = await this.fetchJSON_("/object_info");
4335
4642
  const object_info_str = readableStringify(object_info_json, 4);
4336
- writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
4643
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
4337
4644
  const res = ComfySchemaJSON_ark(object_info_json);
4338
4645
  if (res instanceof type.errors) printArkResultInConsole(res);
4339
4646
  const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
4340
- writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
4647
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
4341
4648
  this.schema.update({
4342
4649
  spec: object_info_json,
4343
4650
  embeddings: embeddings_json
@@ -4354,7 +4661,7 @@ var ComfyHost = class {
4354
4661
  };
4355
4662
  console.error(error);
4356
4663
  console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
4357
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4664
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4358
4665
  this.markFailed(error);
4359
4666
  } finally {
4360
4667
  this.isUpdatingSchema = false;
@@ -4375,9 +4682,10 @@ var ComfyHost = class {
4375
4682
  this.base = parseHostBase(this.data);
4376
4683
  /** folder where file related to the host config will be cached */
4377
4684
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
4378
- if (!existsSync(this.cacheFolder)) {
4685
+ const storage = getComfyStorage();
4686
+ if (!storage.exists(this.cacheFolder)) {
4379
4687
  console.log("🟢 creating folder", this.cacheFolder);
4380
- mkdirSync(this.cacheFolder, { recursive: true });
4688
+ storage.mkdirp(this.cacheFolder);
4381
4689
  }
4382
4690
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
4383
4691
  this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
@@ -4427,19 +4735,20 @@ var ComfyHost = class {
4427
4735
  }
4428
4736
  async writeSDKToDisk() {
4429
4737
  if (this.data.sdkAutoWrite === false) return;
4738
+ const storage = getComfyStorage();
4430
4739
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
4431
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
4432
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
4740
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
4741
+ storage.writeText(this.sdkDTSPath, comfySchemaTs);
4433
4742
  }
4434
4743
  shouldUseSchemaCache() {
4435
4744
  if (this._schemaStrategy === "refresh") return false;
4436
- const exists = existsSync(this.comfyJSONPath);
4745
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
4437
4746
  if (this._schemaStrategy === "cache") {
4438
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4747
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4439
4748
  return true;
4440
4749
  }
4441
- if (!exists) return false;
4442
- return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
4750
+ if (mtimeMs == null) return false;
4751
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs;
4443
4752
  }
4444
4753
  waitForSession(timeoutMs = 5e3) {
4445
4754
  if (this.comfySessionId !== "temp") return Promise.resolve();
@@ -4474,6 +4783,7 @@ var ComfyHost = class {
4474
4783
  onMessage: (e) => this.onMessage(e),
4475
4784
  url: () => this.getWSUrl(),
4476
4785
  headers: () => this.authHeaders(),
4786
+ onTransportDead: (e) => this.markFailed(e),
4477
4787
  onClose: () => {
4478
4788
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
4479
4789
  }
@@ -4493,7 +4803,7 @@ var ComfyHost = class {
4493
4803
  * examples must still open in the TUI; run() fetches the real schema through
4494
4804
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
4495
4805
  loadSchemaFromCache() {
4496
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
4806
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
4497
4807
  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`);
4498
4808
  return Promise.resolve();
4499
4809
  }
@@ -4505,7 +4815,7 @@ var ComfyHost = class {
4505
4815
  embeddings: embeddings_json
4506
4816
  });
4507
4817
  this.schema.RUN_BASIC_CHECKS();
4508
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4818
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4509
4819
  })().catch((e) => {
4510
4820
  this._schemaFromCache = null;
4511
4821
  throw e;
@@ -4597,55 +4907,13 @@ var ComfyHost = class {
4597
4907
  };
4598
4908
  //#endregion
4599
4909
  //#region src/utils/downloadFile.ts
4600
- /** Usage example
4601
- * | ;(async () => {
4602
- * | try {
4603
- * | await downloadFile('https://example.com/file', 'folder/filename')
4604
- * | console.log('Download completed successfully')
4605
- * | } catch (error) {
4606
- * | console.error('Download failed:', error)
4607
- * | }
4608
- * | })()
4609
- * |
4610
- */
4611
- function downloadFile(url, outputPath, logPrefix = " - ") {
4612
- mkdirSync(dirname(outputPath), { recursive: true });
4613
- return new Promise((resolve, reject) => {
4614
- https.get(url, (response) => {
4615
- if (response.statusCode === 302 || response.statusCode === 301) {
4616
- const newUrl = response.headers.location;
4617
- console.log(`Redirected to ${newUrl}`);
4618
- resolve(downloadFile(newUrl, outputPath));
4619
- return;
4620
- }
4621
- if (response.statusCode !== 200) {
4622
- reject(`Failed to download file: Status Code ${response.statusCode}`);
4623
- return;
4624
- }
4625
- const rawLen = response.headers["content-length"];
4626
- if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
4627
- else {
4628
- const totalSize = parseInt(rawLen, 10);
4629
- let downloaded = 0;
4630
- let lastLoggedPercentage = 0;
4631
- response.on("data", (chunk) => {
4632
- downloaded += chunk.length;
4633
- const percentage = Math.round(downloaded / totalSize * 100);
4634
- if (percentage >= lastLoggedPercentage + 1) {
4635
- stdout.write(`\r${logPrefix}${percentage}% downloaded`);
4636
- lastLoggedPercentage = percentage;
4637
- }
4638
- });
4639
- }
4640
- const fileStream = fs.createWriteStream(outputPath);
4641
- response.pipe(fileStream);
4642
- fileStream.on("finish", () => {
4643
- console.log(` (DONE)`);
4644
- fileStream.close();
4645
- resolve(true);
4646
- });
4647
- }).on("error", (err) => reject(err));
4648
- });
4910
+ async function downloadFile(url, outputPath, logPrefix = " - ") {
4911
+ const res = await fetch(url);
4912
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
4913
+ const bytes = new Uint8Array(await res.arrayBuffer());
4914
+ getComfyStorage().writeBytes(outputPath, bytes);
4915
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
4916
+ return true;
4649
4917
  }
4650
4918
  //#endregion
4651
4919
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
@@ -4766,7 +5034,7 @@ const ComfyManagerRawPluginInfo_ark = type({
4766
5034
  const _getKnownPlugins = (DB) => {
4767
5035
  const counter = DB.report.file("custom-node-list.json");
4768
5036
  let totalFileSeen = 0;
4769
- const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
5037
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
4770
5038
  if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4771
5039
  const canonical = [];
4772
5040
  for (const row of root.custom_nodes) {
@@ -4804,7 +5072,7 @@ const _getKnownPlugins = (DB) => {
4804
5072
  }
4805
5073
  out1 += "\n";
4806
5074
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
4807
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5075
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4808
5076
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4809
5077
  let out2 = "";
4810
5078
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -4812,7 +5080,7 @@ const _getKnownPlugins = (DB) => {
4812
5080
  out2 += "export type KnownComfyPluginURL =\n";
4813
5081
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
4814
5082
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
4815
- writeFileSync(out2Path, out2, "utf-8");
5083
+ getComfyStorage().writeText(out2Path, out2);
4816
5084
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4817
5085
  }
4818
5086
  if (DB.opts.check) {
@@ -4858,7 +5126,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNod
4858
5126
  const _getCustomNodeRegistry = (DB) => {
4859
5127
  const counter = DB.report.file("extension-node-map.json");
4860
5128
  let totalCustomNodeSeen = 0;
4861
- const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
5129
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
4862
5130
  const root = type("Record<string, unknown>")(raw);
4863
5131
  if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4864
5132
  for (const [url, value] of Object.entries(root)) {
@@ -4894,7 +5162,7 @@ const _getCustomNodeRegistry = (DB) => {
4894
5162
  for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
4895
5163
  out += "\n";
4896
5164
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
4897
- writeFileSync(outPath, out + "\n", "utf-8");
5165
+ getComfyStorage().writeText(outPath, out + "\n");
4898
5166
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
4899
5167
  }
4900
5168
  if (DB.opts.check) {
@@ -4949,7 +5217,7 @@ const ComfyManagerModelInfo_ark = type({
4949
5217
  //#region src/manager/loaders/step4_model-list-loader.ts
4950
5218
  const _getKnownModels = (DB) => {
4951
5219
  const counter = DB.report.file("model-list.json");
4952
- const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
5220
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
4953
5221
  if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
4954
5222
  const canonical = [];
4955
5223
  for (const row of root.models) {
@@ -4978,7 +5246,7 @@ const _getKnownModels = (DB) => {
4978
5246
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4979
5247
  out1 += "]\n";
4980
5248
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
4981
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5249
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4982
5250
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4983
5251
  let out4 = "";
4984
5252
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -4994,7 +5262,7 @@ const _getKnownModels = (DB) => {
4994
5262
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
4995
5263
  out4 += "]\n";
4996
5264
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
4997
- writeFileSync(out4Path, out4 + "\n", "utf-8");
5265
+ getComfyStorage().writeText(out4Path, out4 + "\n");
4998
5266
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
4999
5267
  let out2 = "";
5000
5268
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -5011,7 +5279,7 @@ const _getKnownModels = (DB) => {
5011
5279
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
5012
5280
  out2 += "]\n";
5013
5281
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
5014
- writeFileSync(out2Path, out2 + "\n", "utf-8");
5282
+ getComfyStorage().writeText(out2Path, out2 + "\n");
5015
5283
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
5016
5284
  let out3 = "";
5017
5285
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -5026,7 +5294,7 @@ const _getKnownModels = (DB) => {
5026
5294
  }
5027
5295
  out3 += "\n";
5028
5296
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
5029
- writeFileSync(out3Path, out3 + "\n", "utf-8");
5297
+ getComfyStorage().writeText(out3Path, out3 + "\n");
5030
5298
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
5031
5299
  let out99 = "";
5032
5300
  out99 += `// prettier-ignore\n`;
@@ -5040,7 +5308,7 @@ const _getKnownModels = (DB) => {
5040
5308
  }
5041
5309
  out99 += "\n";
5042
5310
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
5043
- writeFileSync(out99Path, out99 + "\n", "utf-8");
5311
+ getComfyStorage().writeText(out99Path, out99 + "\n");
5044
5312
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
5045
5313
  }
5046
5314
  if (DB.opts.check) {
@@ -5061,7 +5329,7 @@ const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
5061
5329
  //#region src/manager/loaders/step5_alter-list-loader.ts
5062
5330
  const _getAlterList = (DB) => {
5063
5331
  const counter = DB.report.file("alter-list.json");
5064
- const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
5332
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
5065
5333
  if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
5066
5334
  const canonical = [];
5067
5335
  for (const row of root.items) {
@@ -5086,7 +5354,7 @@ const ComfyManagerGithubStatEntry_ark = type({
5086
5354
  //#region src/manager/loaders/step6_github-stats-loader.ts
5087
5355
  const _getGithubStats = (DB) => {
5088
5356
  const counter = DB.report.file("github-stats.json");
5089
- const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
5357
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
5090
5358
  const root = type("Record<string, unknown>")(raw);
5091
5359
  if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
5092
5360
  for (const [url, value] of Object.entries(root)) {
@@ -5201,13 +5469,12 @@ var ComfyTS = class ComfyTS {
5201
5469
  this.version = version;
5202
5470
  this.hosts = /* @__PURE__ */ new Map();
5203
5471
  this._registry = null;
5204
- this.rootPath = asAbsolutePath(process.cwd());
5205
5472
  this.readJSON_ = (absPath, def) => {
5206
- if (!existsSync(absPath)) {
5473
+ const str = this.storage.readTextIfExists(absPath);
5474
+ if (str == null) {
5207
5475
  if (def != null) return def;
5208
5476
  throw new Error(`file does not exist ${absPath}`);
5209
5477
  }
5210
- const str = readFileSync(absPath, "utf8");
5211
5478
  return JSON.parse(str);
5212
5479
  };
5213
5480
  this.autolayoutOpts = {
@@ -5218,7 +5485,8 @@ var ComfyTS = class ComfyTS {
5218
5485
  const globalHack = globalThis;
5219
5486
  if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
5220
5487
  globalHack.comfyts = this;
5221
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
5488
+ this.storage = resolveComfyStorage(p.storage);
5489
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
5222
5490
  this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
5223
5491
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
5224
5492
  this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
@@ -5282,6 +5550,18 @@ var ComfyTS = class ComfyTS {
5282
5550
  }
5283
5551
  };
5284
5552
  //#endregion
5553
+ //#region src/utils/loraTag.ts
5554
+ /**
5555
+ * build a LoraManager-style lora tag: `<lora:name:strength>` or
5556
+ * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5557
+ * autocomplete + validation:
5558
+ *
5559
+ * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5560
+ */
5561
+ function loraTag(name, strength = 1, clipStrength) {
5562
+ return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5563
+ }
5564
+ //#endregion
5285
5565
  //#region src/exampleAssets.ts
5286
5566
  /**
5287
5567
  * the examples/ folder shipped in the npm tarball, resolved from THIS module's
@@ -5334,18 +5614,13 @@ function isTuiActive() {
5334
5614
  return process.env[COMFY_TS_TUI_ENV] === "1";
5335
5615
  }
5336
5616
  //#endregion
5337
- //#region src/utils/loraTag.ts
5617
+ //#region src/index.ts
5338
5618
  /**
5339
- * build a LoraManager-style lora tag: `<lora:name:strength>` or
5340
- * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5341
- * autocomplete + validation:
5342
- *
5343
- * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5619
+ * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)
5620
+ * @packageDocumentation
5344
5621
  */
5345
- function loraTag(name, strength = 1, clipStrength) {
5346
- return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5347
- }
5622
+ setDefaultComfyStorage(createNodeStorage());
5348
5623
  //#endregion
5349
- 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 };
5624
+ 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 };
5350
5625
 
5351
5626
  //# sourceMappingURL=index.js.map